Skip to main content

fauna_api/
groups.rs

1use chrono::{DateTime, Utc};
2use serde::{Deserialize, Serialize};
3use serde_json::{Value, json};
4
5use crate::authentification::{Credentials, CredentialsOrApiKey, PartialProfile, Profile};
6use crate::billing::PageQuery;
7use crate::error::Result;
8use crate::http::{client, encode, ok};
9use crate::parrot::chat::ChatSummary;
10use crate::tickets::{optional, parse_date};
11
12fn text(value: &Value) -> String {
13    value.as_str().unwrap_or_default().to_string()
14}
15
16fn texts(value: &Value) -> Vec<String> {
17    value
18        .as_array()
19        .map(|items| items.iter().map(text).collect())
20        .unwrap_or_default()
21}
22
23/// A group named inside another record.
24#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
25pub struct GroupRef {
26    pub id: String,
27    pub name: String,
28    #[serde(default, skip_serializing_if = "Option::is_none")]
29    pub icon: Option<String>,
30}
31
32impl GroupRef {
33    pub fn from_json(json: &Value) -> GroupRef {
34        GroupRef {
35            id: text(&json["id"]),
36            name: text(&json["name"]),
37            icon: optional(&json["icon"]),
38        }
39    }
40}
41
42/// One way someone is in a group. `through` is the group's own id when they are
43/// directly in it, else the nested group they come in through.
44#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
45#[serde(rename_all = "camelCase")]
46pub struct GroupMember {
47    pub email: String,
48    #[serde(default, skip_serializing_if = "Option::is_none")]
49    pub display_name: Option<String>,
50    #[serde(default, skip_serializing_if = "Option::is_none")]
51    pub icon: Option<String>,
52    pub through: String,
53}
54
55impl GroupMember {
56    pub fn from_json(json: &Value) -> GroupMember {
57        GroupMember {
58            email: text(&json["email"]),
59            display_name: optional(&json["displayName"]),
60            icon: optional(&json["icon"]),
61            through: text(&json["through"]),
62        }
63    }
64}
65
66/// A group as someone in it sees it. A group holds people and other groups:
67/// everyone in a nested group is in this one too, never the other way.
68#[derive(Debug, Clone, Serialize, Deserialize)]
69#[serde(rename_all = "camelCase")]
70pub struct Group {
71    pub id: String,
72
73    pub name: String,
74    #[serde(default, skip_serializing_if = "Option::is_none")]
75    pub icon: Option<String>,
76
77    pub balance: f64,
78
79    pub created_at: DateTime<Utc>,
80
81    /// Emails of its admins, who are always directly in it: they change the
82    /// group, who is in it and how people and groups join.
83    pub admins: Vec<String>,
84    /// Emails of the people directly in it, admins included.
85    pub people: Vec<String>,
86    /// The groups nested directly inside it.
87    pub groups: Vec<GroupRef>,
88    /// Everyone in it, once per way in: the people directly in it first, then
89    /// everyone who comes in through each nested group.
90    pub members: Vec<GroupMember>,
91    /// How you are in it: its own id when you are directly in it, else the nested
92    /// group you come in through.
93    pub through: String,
94}
95
96impl Group {
97    pub fn from_json(json: &Value) -> Group {
98        let list = |key: &str| json[key].as_array().cloned().unwrap_or_default();
99        Group {
100            id: text(&json["id"]),
101            name: text(&json["name"]),
102            icon: optional(&json["icon"]),
103            balance: json["balance"].as_f64().unwrap_or(0.0),
104            created_at: parse_date(&json["createdAt"]).unwrap_or_default(),
105            admins: texts(&json["admins"]),
106            people: texts(&json["people"]),
107            groups: list("groups").iter().map(GroupRef::from_json).collect(),
108            members: list("members").iter().map(GroupMember::from_json).collect(),
109            through: text(&json["through"]),
110        }
111    }
112}
113
114/// A join link, as the group's admins see it. People join with it, and admins of
115/// other groups put their group inside this one with it.
116#[derive(Debug, Clone, Serialize, Deserialize)]
117#[serde(rename_all = "camelCase")]
118pub struct JoinLink {
119    pub code: String,
120    /// How many people or groups joined with it.
121    #[serde(default)]
122    pub uses: u32,
123    /// How many it lets in before it is used up; `None` when any number can join
124    /// until it expires.
125    #[serde(default, skip_serializing_if = "Option::is_none")]
126    pub max_uses: Option<u32>,
127    pub expires: DateTime<Utc>,
128}
129
130impl JoinLink {
131    pub fn from_json(json: &Value) -> JoinLink {
132        JoinLink {
133            code: text(&json["code"]),
134            uses: json["uses"].as_u64().unwrap_or(0) as u32,
135            max_uses: json["maxUses"].as_u64().map(|uses| uses as u32),
136            expires: parse_date(&json["expires"]).unwrap_or_default(),
137        }
138    }
139}
140
141/// A group as anyone signed in may see it: no balance, no member list.
142/// `member_count` counts everyone in it, directly or through a nested group.
143#[derive(Debug, Clone, Serialize, Deserialize)]
144#[serde(rename_all = "camelCase")]
145pub struct GroupSummary {
146    pub id: String,
147    pub name: String,
148    #[serde(default, skip_serializing_if = "Option::is_none")]
149    pub icon: Option<String>,
150    pub member_count: u32,
151}
152
153impl GroupSummary {
154    pub fn from_json(json: &Value) -> GroupSummary {
155        GroupSummary {
156            id: text(&json["id"]),
157            name: text(&json["name"]),
158            icon: optional(&json["icon"]),
159            member_count: json["memberCount"].as_u64().unwrap_or(0) as u32,
160        }
161    }
162}
163
164/// A group a person found by `query` is in, and how: `through` is the group's own
165/// id when they are directly in it, else the nested group they come in through.
166#[derive(Debug, Clone, Serialize, Deserialize)]
167#[serde(rename_all = "camelCase")]
168pub struct MatchedGroup {
169    pub id: String,
170    pub name: String,
171    #[serde(default, skip_serializing_if = "Option::is_none")]
172    pub icon: Option<String>,
173    pub member_count: u32,
174    pub through: String,
175}
176
177impl MatchedGroup {
178    pub fn from_json(json: &Value) -> MatchedGroup {
179        let summary = GroupSummary::from_json(json);
180        MatchedGroup {
181            id: summary.id,
182            name: summary.name,
183            icon: summary.icon,
184            member_count: summary.member_count,
185            through: text(&json["through"]),
186        }
187    }
188}
189
190/// A person found by `query`, with every group they are in.
191#[derive(Debug, Clone, Serialize, Deserialize)]
192pub struct GroupMatch {
193    pub profile: Profile,
194    pub groups: Vec<MatchedGroup>,
195}
196
197impl GroupMatch {
198    pub fn from_json(json: &Value) -> GroupMatch {
199        GroupMatch {
200            profile: Profile::from_json(&json["profile"]).unwrap_or_default(),
201            groups: json["groups"]
202                .as_array()
203                .map(|groups| groups.iter().map(MatchedGroup::from_json).collect())
204                .unwrap_or_default(),
205        }
206    }
207}
208
209/// Which side sent a nesting: `Parent` invited the child, whose admins accept;
210/// `Child` asked to go inside the parent, whose admins approve.
211#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
212#[serde(rename_all = "lowercase")]
213pub enum NestSide {
214    Parent,
215    Child,
216}
217
218/// A group invited inside another, or asking to go inside one, waiting for the
219/// other side's admins.
220#[derive(Debug, Clone, Serialize, Deserialize)]
221pub struct GroupNest {
222    pub token: String,
223    pub parent: GroupRef,
224    pub child: GroupRef,
225    pub from: NestSide,
226    /// Email of the admin who sent it.
227    #[serde(default, skip_serializing_if = "Option::is_none")]
228    pub by: Option<String>,
229    pub expires: DateTime<Utc>,
230}
231
232impl GroupNest {
233    pub fn from_json(json: &Value) -> GroupNest {
234        GroupNest {
235            token: text(&json["token"]),
236            parent: GroupRef::from_json(&json["parent"]),
237            child: GroupRef::from_json(&json["child"]),
238            from: if json["from"] == "child" {
239                NestSide::Child
240            } else {
241                NestSide::Parent
242            },
243            by: optional(&json["by"]),
244            expires: parse_date(&json["expires"]).unwrap_or_default(),
245        }
246    }
247}
248
249/// What `invite_group` and `request_group` did: nested at once when you
250/// administer both groups, else waiting on the other side with `token`.
251#[derive(Debug, Clone, PartialEq, Eq)]
252pub enum NestOffer {
253    Nested,
254    Waiting { token: String },
255}
256
257impl NestOffer {
258    pub fn from_json(json: &Value) -> NestOffer {
259        if json["nested"] == true {
260            NestOffer::Nested
261        } else {
262            NestOffer::Waiting {
263                token: text(&json["token"]),
264            }
265        }
266    }
267}
268
269/// `Partial<Group>` in the TypeScript SDK.
270#[derive(Debug, Clone, Default, Serialize)]
271#[serde(rename_all = "camelCase")]
272pub struct PartialGroup {
273    #[serde(skip_serializing_if = "Option::is_none")]
274    pub id: Option<String>,
275    #[serde(skip_serializing_if = "Option::is_none")]
276    pub name: Option<String>,
277    #[serde(skip_serializing_if = "Option::is_none")]
278    pub icon: Option<String>,
279    #[serde(skip_serializing_if = "Option::is_none")]
280    pub balance: Option<f64>,
281    #[serde(skip_serializing_if = "Option::is_none")]
282    pub created_at: Option<DateTime<Utc>>,
283    #[serde(skip_serializing_if = "Option::is_none")]
284    pub admins: Option<Vec<String>>,
285    #[serde(skip_serializing_if = "Option::is_none")]
286    pub people: Option<Vec<String>>,
287    #[serde(skip_serializing_if = "Option::is_none")]
288    pub groups: Option<Vec<GroupRef>>,
289    #[serde(skip_serializing_if = "Option::is_none")]
290    pub members: Option<Vec<GroupMember>>,
291    #[serde(skip_serializing_if = "Option::is_none")]
292    pub through: Option<String>,
293}
294
295/// The `options` argument of `invite`, `invite_group` and `request_group`.
296#[derive(Debug, Clone, Copy, Default)]
297pub struct InviteOptions {
298    pub notify: Option<bool>,
299}
300
301/// The `options` argument of `generate_link`.
302#[derive(Debug, Clone, Copy, Default)]
303pub struct LinkOptions {
304    pub max_uses: Option<u32>,
305}
306
307/// The `{ group, alreadyMember }` `accept_invite` and `join` resolve to.
308#[derive(Debug, Clone)]
309pub struct JoinResult {
310    pub group: Group,
311    pub already_member: bool,
312}
313
314impl JoinResult {
315    fn from_value(json: &Value) -> JoinResult {
316        JoinResult {
317            group: Group::from_json(&json["group"]),
318            already_member: json["alreadyMember"] == true,
319        }
320    }
321}
322
323/// Start a group. You are its first admin. Needs a subscription.
324pub async fn create(credentials: &Credentials, name: &str) -> Result<Group> {
325    let response = client()
326        .post(format!("{}/groups", crate::get_url()))
327        .header("Authorization", format!("Token {}", credentials.token))
328        .json(&json!({ "name": name }))
329        .send()
330        .await?;
331    let json: Value = ok(response).await?.json().await?;
332    Ok(Group::from_json(&json))
333}
334
335/// Every group you are in, directly or through a nested group, oldest first.
336/// Each says how you are in it (`through`).
337pub async fn list(authorization: &CredentialsOrApiKey) -> Result<Vec<Group>> {
338    let response = client()
339        .get(format!("{}/groups", crate::get_url()))
340        .header(
341            "Authorization",
342            match authorization {
343                CredentialsOrApiKey::Credentials(credentials) => {
344                    format!("Token {}", credentials.token)
345                }
346                CredentialsOrApiKey::ApiKey(key) => format!("ApiKey {}", key.id),
347            },
348        )
349        .send()
350        .await?;
351    let rows: Vec<Value> = ok(response).await?.json().await?;
352    Ok(rows.iter().map(Group::from_json).collect())
353}
354
355/// People matching a partial email or name, best first, each with every group
356/// they are in and how. Only people in at least one group come back.
357pub async fn query(
358    authorization: &CredentialsOrApiKey,
359    profile: &PartialProfile,
360) -> Result<Vec<GroupMatch>> {
361    let response = client()
362        .post(format!("{}/groups/query", crate::get_url()))
363        .header(
364            "Authorization",
365            match authorization {
366                CredentialsOrApiKey::Credentials(credentials) => {
367                    format!("Token {}", credentials.token)
368                }
369                CredentialsOrApiKey::ApiKey(key) => format!("ApiKey {}", key.id),
370            },
371        )
372        .json(&json!({ "email": profile.email, "displayName": profile.display_name }))
373        .send()
374        .await?;
375    let rows: Vec<Value> = ok(response).await?.json().await?;
376    Ok(rows.iter().map(GroupMatch::from_json).collect())
377}
378
379/// Name, icon and member count of groups by id, including groups you are not
380/// in. Unknown ids are left out.
381pub async fn summaries(
382    authorization: &CredentialsOrApiKey,
383    ids: &[String],
384) -> Result<Vec<GroupSummary>> {
385    let response = client()
386        .post(format!("{}/groups/summaries", crate::get_url()))
387        .header(
388            "Authorization",
389            match authorization {
390                CredentialsOrApiKey::Credentials(credentials) => {
391                    format!("Token {}", credentials.token)
392                }
393                CredentialsOrApiKey::ApiKey(key) => format!("ApiKey {}", key.id),
394            },
395        )
396        .json(&json!({ "ids": ids }))
397        .send()
398        .await?;
399    let rows: Vec<Value> = ok(response).await?.json().await?;
400    Ok(rows.iter().map(GroupSummary::from_json).collect())
401}
402
403/// A group you are in, directly or through a nested group.
404pub async fn get(authorization: &CredentialsOrApiKey, id: &str) -> Result<Group> {
405    let response = client()
406        .get(format!("{}/groups/{}", crate::get_url(), encode(id)))
407        .header(
408            "Authorization",
409            match authorization {
410                CredentialsOrApiKey::Credentials(credentials) => {
411                    format!("Token {}", credentials.token)
412                }
413                CredentialsOrApiKey::ApiKey(key) => format!("ApiKey {}", key.id),
414            },
415        )
416        .send()
417        .await?;
418    let json: Value = ok(response).await?.json().await?;
419    Ok(Group::from_json(&json))
420}
421
422/// Change the group's name or icon. Admins only.
423pub async fn edit(credentials: &Credentials, id: &str, update: &PartialGroup) -> Result<Group> {
424    let response = client()
425        .patch(format!("{}/groups/{}", crate::get_url(), encode(id)))
426        .header("Authorization", format!("Token {}", credentials.token))
427        .json(&json!({ "update": update }))
428        .send()
429        .await?;
430    let json: Value = ok(response).await?.json().await?;
431    Ok(Group::from_json(&json))
432}
433
434/// Delete a group with its chats, files, calendar, rooms, webhooks and
435/// partnerships. It leaves every group it was in; the groups inside it stay. Its
436/// direct admins may, and so may anyone holding `fauna/groups:delete:global`.
437pub async fn remove(credentials: &Credentials, id: &str) -> Result<()> {
438    let response = client()
439        .delete(format!("{}/groups/{}", crate::get_url(), encode(id)))
440        .header("Authorization", format!("Token {}", credentials.token))
441        .send()
442        .await?;
443    ok(response).await?;
444    Ok(())
445}
446
447/// Invite an email to a group. Admins only. Nobody joins until they accept the
448/// invite with its token (`accept_invite`), whether or not the email already has
449/// a Fauna account, and the answer is the same either way. Fauna emails the
450/// invite unless `notify` is false, so an app can send its own email carrying
451/// the token. Resolves to the token.
452pub async fn invite(
453    credentials: &Credentials,
454    id: &str,
455    email: &str,
456    options: InviteOptions,
457) -> Result<String> {
458    let response = client()
459        .post(format!("{}/groups/{}/invite", crate::get_url(), encode(id)))
460        .header("Authorization", format!("Token {}", credentials.token))
461        .json(&json!({ "email": email, "notify": options.notify }))
462        .send()
463        .await?;
464    let json: Value = ok(response).await?.json().await?;
465    Ok(text(&json["token"]))
466}
467
468/// Join the group an email invite points at, using the token from the invite.
469/// `already_member` says you were directly in it already.
470pub async fn accept_invite(credentials: &Credentials, token: &str) -> Result<JoinResult> {
471    let response = client()
472        .post(format!("{}/groups/invites/accept", crate::get_url()))
473        .header("Authorization", format!("Token {}", credentials.token))
474        .json(&json!({ "token": token }))
475        .send()
476        .await?;
477    let json: Value = ok(response).await?.json().await?;
478    Ok(JoinResult::from_value(&json))
479}
480
481/// A join code good for seven days. Admins only. People join with it, and admins
482/// of other groups put their group inside this one with it. `max_uses` caps how
483/// many it lets in; without it, any number can join until it expires.
484pub async fn generate_link(
485    credentials: &Credentials,
486    id: &str,
487    options: LinkOptions,
488) -> Result<String> {
489    let response = client()
490        .post(format!("{}/groups/{}/link", crate::get_url(), encode(id)))
491        .header("Authorization", format!("Token {}", credentials.token))
492        .json(&json!({ "maxUses": options.max_uses }))
493        .send()
494        .await?;
495    let json: Value = ok(response).await?.json().await?;
496    Ok(text(&json["code"]))
497}
498
499/// The group's join links that still work, newest first. Admins only.
500pub async fn links(credentials: &Credentials, id: &str) -> Result<Vec<JoinLink>> {
501    let response = client()
502        .get(format!("{}/groups/{}/links", crate::get_url(), encode(id)))
503        .header("Authorization", format!("Token {}", credentials.token))
504        .send()
505        .await?;
506    let rows: Vec<Value> = ok(response).await?.json().await?;
507    Ok(rows.iter().map(JoinLink::from_json).collect())
508}
509
510/// A join link stops working. Admins only.
511pub async fn revoke_link(credentials: &Credentials, id: &str, code: &str) -> Result<()> {
512    let response = client()
513        .delete(format!(
514            "{}/groups/{}/links/{}",
515            crate::get_url(),
516            encode(id),
517            encode(code)
518        ))
519        .header("Authorization", format!("Token {}", credentials.token))
520        .send()
521        .await?;
522    ok(response).await?;
523    Ok(())
524}
525
526/// Join a group with a join code. With `group`, a group you administer goes
527/// inside it instead, and you are in it through that group. `already_member`
528/// says you (or `group`) were in it already.
529pub async fn join(
530    credentials: &Credentials,
531    code: &str,
532    group: Option<&str>,
533) -> Result<JoinResult> {
534    let response = client()
535        .post(format!("{}/groups/join", crate::get_url()))
536        .header("Authorization", format!("Token {}", credentials.token))
537        .json(&json!({ "code": code, "group": group }))
538        .send()
539        .await?;
540    let json: Value = ok(response).await?.json().await?;
541    Ok(JoinResult::from_value(&json))
542}
543
544/// Leave a group you are directly in. The last admin can't while anyone else is
545/// in it, directly or through a nested group: make someone else an admin, or
546/// delete the group. When nobody else is in it, leaving deletes it.
547pub async fn leave(credentials: &Credentials, id: &str) -> Result<()> {
548    let response = client()
549        .delete(format!(
550            "{}/groups/{}/membership",
551            crate::get_url(),
552            encode(id)
553        ))
554        .header("Authorization", format!("Token {}", credentials.token))
555        .send()
556        .await?;
557    ok(response).await?;
558    Ok(())
559}
560
561/// Remove a person who is directly in the group. Admins only.
562pub async fn kick(credentials: &Credentials, id: &str, email: &str) -> Result<()> {
563    let response = client()
564        .delete(format!(
565            "{}/groups/{}/members/{}",
566            crate::get_url(),
567            encode(id),
568            encode(email)
569        ))
570        .header("Authorization", format!("Token {}", credentials.token))
571        .send()
572        .await?;
573    ok(response).await?;
574    Ok(())
575}
576
577/// Make a person who is directly in the group an admin. Admins only. Someone in
578/// it only through a nested group is invited directly first.
579pub async fn promote(credentials: &Credentials, id: &str, email: &str) -> Result<Group> {
580    let response = client()
581        .post(format!(
582            "{}/groups/{}/admins/{}",
583            crate::get_url(),
584            encode(id),
585            encode(email)
586        ))
587        .header("Authorization", format!("Token {}", credentials.token))
588        .send()
589        .await?;
590    let json: Value = ok(response).await?.json().await?;
591    Ok(Group::from_json(&json))
592}
593
594/// Make an admin a member again. Admins only; a group keeps at least one admin.
595pub async fn demote(credentials: &Credentials, id: &str, email: &str) -> Result<Group> {
596    let response = client()
597        .delete(format!(
598            "{}/groups/{}/admins/{}",
599            crate::get_url(),
600            encode(id),
601            encode(email)
602        ))
603        .header("Authorization", format!("Token {}", credentials.token))
604        .send()
605        .await?;
606    let json: Value = ok(response).await?.json().await?;
607    Ok(Group::from_json(&json))
608}
609
610/// Invite group `child` inside group `id`; the child's admins accept with the
611/// token (`accept_nest`). Admins of `id` only. Nests at once when you administer
612/// both. Unless `notify` is false, the child's admins hear about it in their
613/// Fauna inbox. Nesting is at most 5 groups deep and never makes a loop.
614pub async fn invite_group(
615    credentials: &Credentials,
616    id: &str,
617    child: &str,
618    options: InviteOptions,
619) -> Result<NestOffer> {
620    let response = client()
621        .post(format!("{}/groups/{}/groups", crate::get_url(), encode(id)))
622        .header("Authorization", format!("Token {}", credentials.token))
623        .json(&json!({ "group": child, "notify": options.notify }))
624        .send()
625        .await?;
626    let json: Value = ok(response).await?.json().await?;
627    Ok(NestOffer::from_json(&json))
628}
629
630/// Ask to put group `id` inside group `parent`; the parent's admins approve with
631/// the token (`accept_nest`). Admins of `id` only. Nests at once when you
632/// administer both. Unless `notify` is false, the parent's admins hear about it
633/// in their Fauna inbox.
634pub async fn request_group(
635    credentials: &Credentials,
636    id: &str,
637    parent: &str,
638    options: InviteOptions,
639) -> Result<NestOffer> {
640    let response = client()
641        .post(format!(
642            "{}/groups/{}/parents",
643            crate::get_url(),
644            encode(id)
645        ))
646        .header("Authorization", format!("Token {}", credentials.token))
647        .json(&json!({ "group": parent, "notify": options.notify }))
648        .send()
649        .await?;
650    let json: Value = ok(response).await?.json().await?;
651    Ok(NestOffer::from_json(&json))
652}
653
654/// The invites and requests waiting on or from a group, newest first. Admins
655/// only.
656pub async fn nests(
657    credentials: &Credentials,
658    id: &str,
659    query: PageQuery,
660) -> Result<Vec<GroupNest>> {
661    let response = client()
662        .get(format!(
663            "{}/groups/{}/nests?cursor={}&max={}",
664            crate::get_url(),
665            encode(id),
666            query.cursor,
667            query.max
668        ))
669        .header("Authorization", format!("Token {}", credentials.token))
670        .send()
671        .await?;
672    let rows: Vec<Value> = ok(response).await?.json().await?;
673    Ok(rows.iter().map(GroupNest::from_json).collect())
674}
675
676/// Accept an invite into a group, or approve a request to join one, by its
677/// token. An admin of the side it waits on only. Resolves to the parent group.
678pub async fn accept_nest(credentials: &Credentials, token: &str) -> Result<Group> {
679    let response = client()
680        .post(format!("{}/groups/nests/accept", crate::get_url()))
681        .header("Authorization", format!("Token {}", credentials.token))
682        .json(&json!({ "token": token }))
683        .send()
684        .await?;
685    let json: Value = ok(response).await?.json().await?;
686    Ok(Group::from_json(&json))
687}
688
689/// Drop a waiting invite or request by its token. An admin of either group.
690pub async fn revoke_nest(credentials: &Credentials, token: &str) -> Result<()> {
691    let response = client()
692        .post(format!("{}/groups/nests/revoke", crate::get_url()))
693        .header("Authorization", format!("Token {}", credentials.token))
694        .json(&json!({ "token": token }))
695        .send()
696        .await?;
697    ok(response).await?;
698    Ok(())
699}
700
701/// Take group `child` out of group `id`. An admin of either group. Everyone who
702/// was in `id` only through it loses it.
703pub async fn unnest(credentials: &Credentials, id: &str, child: &str) -> Result<()> {
704    let response = client()
705        .delete(format!(
706            "{}/groups/{}/groups/{}",
707            crate::get_url(),
708            encode(id),
709            encode(child)
710        ))
711        .header("Authorization", format!("Token {}", credentials.token))
712        .send()
713        .await?;
714    ok(response).await?;
715    Ok(())
716}
717
718/// Two groups with people only chats between them. `group` is the one of yours
719/// it was listed for.
720#[derive(Debug, Clone, Serialize, Deserialize)]
721pub struct Partnership {
722    pub id: String,
723    pub group: String,
724    pub partner: GroupSummary,
725    /// Under Hidden: the partner started at no trust while you hide strangers,
726    /// and your group hasn't engaged.
727    pub hidden: bool,
728    #[serde(default)]
729    pub chats: Vec<ChatSummary>,
730    pub created: DateTime<Utc>,
731}
732
733/// The `{ partnership, chat }` `start_partnership_chat` resolves to.
734#[derive(Debug, Clone, Serialize, Deserialize)]
735pub struct StartedPartnershipChat {
736    pub partnership: Partnership,
737    pub chat: String,
738}
739
740#[derive(Deserialize)]
741struct CreatedChat {
742    id: String,
743}
744
745/// A group's partnerships, each with their chats and what you haven't read. An
746/// API key reads them too.
747pub async fn list_partnerships(
748    authorization: &CredentialsOrApiKey,
749    id: &str,
750) -> Result<Vec<Partnership>> {
751    let response = client()
752        .get(format!(
753            "{}/groups/{}/partnerships",
754            crate::get_url(),
755            encode(id)
756        ))
757        .header(
758            "Authorization",
759            match authorization {
760                CredentialsOrApiKey::Credentials(credentials) => {
761                    format!("Token {}", credentials.token)
762                }
763                CredentialsOrApiKey::ApiKey(key) => format!("ApiKey {}", key.id),
764            },
765        )
766        .send()
767        .await?;
768    Ok(ok(response).await?.json().await?)
769}
770
771/// Start a chat between your group `id` and `partner`. The first chat partners
772/// the groups.
773pub async fn start_partnership_chat(
774    credentials: &Credentials,
775    id: &str,
776    partner: &str,
777    name: Option<&str>,
778) -> Result<StartedPartnershipChat> {
779    let response = client()
780        .post(format!(
781            "{}/groups/{}/partnerships",
782            crate::get_url(),
783            encode(id)
784        ))
785        .header("Authorization", format!("Token {}", credentials.token))
786        .json(&json!({ "partner": partner, "name": name }))
787        .send()
788        .await?;
789    Ok(ok(response).await?.json().await?)
790}
791
792/// Another chat in a partnership. Resolves to its id.
793pub async fn create_partnership_chat(
794    credentials: &Credentials,
795    partnership: &str,
796    name: Option<&str>,
797) -> Result<String> {
798    let response = client()
799        .post(format!(
800            "{}/partnerships/{}/chats",
801            crate::get_url(),
802            encode(partnership)
803        ))
804        .header("Authorization", format!("Token {}", credentials.token))
805        .json(&json!({ "name": name }))
806        .send()
807        .await?;
808    let created: CreatedChat = ok(response).await?.json().await?;
809    Ok(created.id)
810}
811
812/// Delete a partnership chat, for both groups.
813pub async fn delete_partnership_chat(
814    credentials: &Credentials,
815    partnership: &str,
816    chat: &str,
817) -> Result<()> {
818    let response = client()
819        .delete(format!(
820            "{}/partnerships/{}/chats/{}",
821            crate::get_url(),
822            encode(partnership),
823            encode(chat)
824        ))
825        .header("Authorization", format!("Token {}", credentials.token))
826        .send()
827        .await?;
828    ok(response).await?;
829    Ok(())
830}
831
832/// Bring a hidden partnership out of Hidden for your group.
833pub async fn show_partnership(credentials: &Credentials, partnership: &str) -> Result<Partnership> {
834    let response = client()
835        .post(format!(
836            "{}/partnerships/{}/show",
837            crate::get_url(),
838            encode(partnership)
839        ))
840        .header("Authorization", format!("Token {}", credentials.token))
841        .send()
842        .await?;
843    Ok(ok(response).await?.json().await?)
844}
845
846/// End a partnership. Its chats and their files go with it, for both groups.
847pub async fn end_partnership(credentials: &Credentials, partnership: &str) -> Result<()> {
848    let response = client()
849        .delete(format!(
850            "{}/partnerships/{}",
851            crate::get_url(),
852            encode(partnership)
853        ))
854        .header("Authorization", format!("Token {}", credentials.token))
855        .send()
856        .await?;
857    ok(response).await?;
858    Ok(())
859}