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/// An email invite waiting to be accepted, as the group's admins see it.
270#[derive(Debug, Clone, Serialize, Deserialize)]
271pub struct EmailInvite {
272    pub token: String,
273    pub email: String,
274    /// Email of the admin who sent it.
275    #[serde(default, skip_serializing_if = "Option::is_none")]
276    pub by: Option<String>,
277    pub expires: DateTime<Utc>,
278}
279
280impl EmailInvite {
281    pub fn from_json(json: &Value) -> EmailInvite {
282        EmailInvite {
283            token: text(&json["token"]),
284            email: text(&json["email"]),
285            by: optional(&json["by"]),
286            expires: parse_date(&json["expires"]).unwrap_or_default(),
287        }
288    }
289}
290
291/// `Partial<Group>` in the TypeScript SDK.
292#[derive(Debug, Clone, Default, Serialize)]
293#[serde(rename_all = "camelCase")]
294pub struct PartialGroup {
295    #[serde(skip_serializing_if = "Option::is_none")]
296    pub id: Option<String>,
297    #[serde(skip_serializing_if = "Option::is_none")]
298    pub name: Option<String>,
299    #[serde(skip_serializing_if = "Option::is_none")]
300    pub icon: Option<String>,
301    #[serde(skip_serializing_if = "Option::is_none")]
302    pub balance: Option<f64>,
303    #[serde(skip_serializing_if = "Option::is_none")]
304    pub created_at: Option<DateTime<Utc>>,
305    #[serde(skip_serializing_if = "Option::is_none")]
306    pub admins: Option<Vec<String>>,
307    #[serde(skip_serializing_if = "Option::is_none")]
308    pub people: Option<Vec<String>>,
309    #[serde(skip_serializing_if = "Option::is_none")]
310    pub groups: Option<Vec<GroupRef>>,
311    #[serde(skip_serializing_if = "Option::is_none")]
312    pub members: Option<Vec<GroupMember>>,
313    #[serde(skip_serializing_if = "Option::is_none")]
314    pub through: Option<String>,
315}
316
317/// The `options` argument of `invite`, `invite_group` and `request_group`.
318#[derive(Debug, Clone, Copy, Default)]
319pub struct InviteOptions {
320    pub notify: Option<bool>,
321}
322
323/// The `options` argument of `generate_link`.
324#[derive(Debug, Clone, Copy, Default)]
325pub struct LinkOptions {
326    pub max_uses: Option<u32>,
327    /// When it stops working: in the future and at most a year out. Seven days
328    /// from now when `None`.
329    pub expires: Option<DateTime<Utc>>,
330}
331
332/// The `{ group, alreadyMember }` `accept_invite` and `join` resolve to.
333#[derive(Debug, Clone)]
334pub struct JoinResult {
335    pub group: Group,
336    pub already_member: bool,
337}
338
339impl JoinResult {
340    fn from_value(json: &Value) -> JoinResult {
341        JoinResult {
342            group: Group::from_json(&json["group"]),
343            already_member: json["alreadyMember"] == true,
344        }
345    }
346}
347
348/// Start a group. You are its first admin. Needs a subscription, and room under
349/// `fauna/groups:N`, the most groups you may administer.
350pub async fn create(credentials: &Credentials, name: &str) -> Result<Group> {
351    let response = client()
352        .post(format!("{}/groups", crate::get_url()))
353        .header("Authorization", format!("Token {}", credentials.token))
354        .json(&json!({ "name": name }))
355        .send()
356        .await?;
357    let json: Value = ok(response).await?.json().await?;
358    Ok(Group::from_json(&json))
359}
360
361/// Every group you are in, directly or through a nested group, oldest first.
362/// Each says how you are in it (`through`).
363pub async fn list(authorization: &CredentialsOrApiKey) -> Result<Vec<Group>> {
364    let response = client()
365        .get(format!("{}/groups", crate::get_url()))
366        .header(
367            "Authorization",
368            match authorization {
369                CredentialsOrApiKey::Credentials(credentials) => {
370                    format!("Token {}", credentials.token)
371                }
372                CredentialsOrApiKey::ApiKey(key) => format!("ApiKey {}", key.id),
373            },
374        )
375        .send()
376        .await?;
377    let rows: Vec<Value> = ok(response).await?.json().await?;
378    Ok(rows.iter().map(Group::from_json).collect())
379}
380
381/// People matching a partial email or name, best first, each with every group
382/// they are in and how. Only people in at least one group come back.
383pub async fn query(
384    authorization: &CredentialsOrApiKey,
385    profile: &PartialProfile,
386) -> Result<Vec<GroupMatch>> {
387    let response = client()
388        .post(format!("{}/groups/query", crate::get_url()))
389        .header(
390            "Authorization",
391            match authorization {
392                CredentialsOrApiKey::Credentials(credentials) => {
393                    format!("Token {}", credentials.token)
394                }
395                CredentialsOrApiKey::ApiKey(key) => format!("ApiKey {}", key.id),
396            },
397        )
398        .json(&json!({ "email": profile.email, "displayName": profile.display_name }))
399        .send()
400        .await?;
401    let rows: Vec<Value> = ok(response).await?.json().await?;
402    Ok(rows.iter().map(GroupMatch::from_json).collect())
403}
404
405/// Name, icon and member count of groups by id, including groups you are not
406/// in. Unknown ids are left out.
407pub async fn summaries(
408    authorization: &CredentialsOrApiKey,
409    ids: &[String],
410) -> Result<Vec<GroupSummary>> {
411    let response = client()
412        .post(format!("{}/groups/summaries", crate::get_url()))
413        .header(
414            "Authorization",
415            match authorization {
416                CredentialsOrApiKey::Credentials(credentials) => {
417                    format!("Token {}", credentials.token)
418                }
419                CredentialsOrApiKey::ApiKey(key) => format!("ApiKey {}", key.id),
420            },
421        )
422        .json(&json!({ "ids": ids }))
423        .send()
424        .await?;
425    let rows: Vec<Value> = ok(response).await?.json().await?;
426    Ok(rows.iter().map(GroupSummary::from_json).collect())
427}
428
429/// A group you are in, directly or through a nested group.
430pub async fn get(authorization: &CredentialsOrApiKey, id: &str) -> Result<Group> {
431    let response = client()
432        .get(format!("{}/groups/{}", crate::get_url(), encode(id)))
433        .header(
434            "Authorization",
435            match authorization {
436                CredentialsOrApiKey::Credentials(credentials) => {
437                    format!("Token {}", credentials.token)
438                }
439                CredentialsOrApiKey::ApiKey(key) => format!("ApiKey {}", key.id),
440            },
441        )
442        .send()
443        .await?;
444    let json: Value = ok(response).await?.json().await?;
445    Ok(Group::from_json(&json))
446}
447
448/// Change the group's name or icon. Admins only.
449pub async fn edit(credentials: &Credentials, id: &str, update: &PartialGroup) -> Result<Group> {
450    let response = client()
451        .patch(format!("{}/groups/{}", crate::get_url(), encode(id)))
452        .header("Authorization", format!("Token {}", credentials.token))
453        .json(&json!({ "update": update }))
454        .send()
455        .await?;
456    let json: Value = ok(response).await?.json().await?;
457    Ok(Group::from_json(&json))
458}
459
460/// Delete a group with its chats, files, calendar, rooms, webhooks and
461/// partnerships. It leaves every group it was in; the groups inside it stay. Its
462/// direct admins may, and so may anyone holding `fauna/groups:delete:global`.
463pub async fn remove(credentials: &Credentials, id: &str) -> Result<()> {
464    let response = client()
465        .delete(format!("{}/groups/{}", crate::get_url(), encode(id)))
466        .header("Authorization", format!("Token {}", credentials.token))
467        .send()
468        .await?;
469    ok(response).await?;
470    Ok(())
471}
472
473/// Invite an email to a group. Admins only. Nobody joins until they accept the
474/// invite with its token (`accept_invite`), whether or not the email already has
475/// a Fauna account, and the answer is the same either way. Fauna emails the
476/// invite unless `notify` is false, so an app can send its own email carrying
477/// the token. Resolves to the token.
478pub async fn invite(
479    credentials: &Credentials,
480    id: &str,
481    email: &str,
482    options: InviteOptions,
483) -> Result<String> {
484    let response = client()
485        .post(format!("{}/groups/{}/invite", crate::get_url(), encode(id)))
486        .header("Authorization", format!("Token {}", credentials.token))
487        .json(&json!({ "email": email, "notify": options.notify }))
488        .send()
489        .await?;
490    let json: Value = ok(response).await?.json().await?;
491    Ok(text(&json["token"]))
492}
493
494/// Join the group an email invite points at, using the token from the invite.
495/// `already_member` says you were directly in it already.
496pub async fn accept_invite(credentials: &Credentials, token: &str) -> Result<JoinResult> {
497    let response = client()
498        .post(format!("{}/groups/invites/accept", crate::get_url()))
499        .header("Authorization", format!("Token {}", credentials.token))
500        .json(&json!({ "token": token }))
501        .send()
502        .await?;
503    let json: Value = ok(response).await?.json().await?;
504    Ok(JoinResult::from_value(&json))
505}
506
507/// The group's email invites waiting to be accepted, newest first. Admins only.
508pub async fn invites(
509    credentials: &Credentials,
510    id: &str,
511    query: PageQuery,
512) -> Result<Vec<EmailInvite>> {
513    let response = client()
514        .get(format!(
515            "{}/groups/{}/invites?cursor={}&max={}",
516            crate::get_url(),
517            encode(id),
518            query.cursor,
519            query.max
520        ))
521        .header("Authorization", format!("Token {}", credentials.token))
522        .send()
523        .await?;
524    let rows: Vec<Value> = ok(response).await?.json().await?;
525    Ok(rows.iter().map(EmailInvite::from_json).collect())
526}
527
528/// An email invite stops working, by its token. An admin of its group, or
529/// whoever sent it.
530pub async fn revoke_invite(credentials: &Credentials, token: &str) -> Result<()> {
531    let response = client()
532        .delete(format!(
533            "{}/groups/invites/{}",
534            crate::get_url(),
535            encode(token)
536        ))
537        .header("Authorization", format!("Token {}", credentials.token))
538        .send()
539        .await?;
540    ok(response).await?;
541    Ok(())
542}
543
544/// A join code. Admins only. People join with it, and admins of other groups put
545/// their group inside this one with it. `max_uses` caps how many it lets in;
546/// without it, any number can join until it expires. It expires at `expires`, in
547/// the future and at most a year out, or in seven days without it.
548pub async fn generate_link(
549    credentials: &Credentials,
550    id: &str,
551    options: LinkOptions,
552) -> Result<String> {
553    let response = client()
554        .post(format!("{}/groups/{}/link", crate::get_url(), encode(id)))
555        .header("Authorization", format!("Token {}", credentials.token))
556        .json(&json!({ "maxUses": options.max_uses, "expires": options.expires }))
557        .send()
558        .await?;
559    let json: Value = ok(response).await?.json().await?;
560    Ok(text(&json["code"]))
561}
562
563/// The group's join links that still work, newest first. Admins only.
564pub async fn links(credentials: &Credentials, id: &str) -> Result<Vec<JoinLink>> {
565    let response = client()
566        .get(format!("{}/groups/{}/links", crate::get_url(), encode(id)))
567        .header("Authorization", format!("Token {}", credentials.token))
568        .send()
569        .await?;
570    let rows: Vec<Value> = ok(response).await?.json().await?;
571    Ok(rows.iter().map(JoinLink::from_json).collect())
572}
573
574/// A join link stops working. Admins only.
575pub async fn revoke_link(credentials: &Credentials, id: &str, code: &str) -> Result<()> {
576    let response = client()
577        .delete(format!(
578            "{}/groups/{}/links/{}",
579            crate::get_url(),
580            encode(id),
581            encode(code)
582        ))
583        .header("Authorization", format!("Token {}", credentials.token))
584        .send()
585        .await?;
586    ok(response).await?;
587    Ok(())
588}
589
590/// Join a group with a join code. With `group`, a group you administer goes
591/// inside it instead, and you are in it through that group. `already_member`
592/// says you (or `group`) were in it already.
593pub async fn join(
594    credentials: &Credentials,
595    code: &str,
596    group: Option<&str>,
597) -> Result<JoinResult> {
598    let response = client()
599        .post(format!("{}/groups/join", crate::get_url()))
600        .header("Authorization", format!("Token {}", credentials.token))
601        .json(&json!({ "code": code, "group": group }))
602        .send()
603        .await?;
604    let json: Value = ok(response).await?.json().await?;
605    Ok(JoinResult::from_value(&json))
606}
607
608/// Leave a group you are directly in. The last admin can't while anyone else is
609/// in it, directly or through a nested group: make someone else an admin, or
610/// delete the group. When nobody else is in it, leaving deletes it.
611pub async fn leave(credentials: &Credentials, id: &str) -> Result<()> {
612    let response = client()
613        .delete(format!(
614            "{}/groups/{}/membership",
615            crate::get_url(),
616            encode(id)
617        ))
618        .header("Authorization", format!("Token {}", credentials.token))
619        .send()
620        .await?;
621    ok(response).await?;
622    Ok(())
623}
624
625/// Remove a person who is directly in the group. Admins only.
626pub async fn kick(credentials: &Credentials, id: &str, email: &str) -> Result<()> {
627    let response = client()
628        .delete(format!(
629            "{}/groups/{}/members/{}",
630            crate::get_url(),
631            encode(id),
632            encode(email)
633        ))
634        .header("Authorization", format!("Token {}", credentials.token))
635        .send()
636        .await?;
637    ok(response).await?;
638    Ok(())
639}
640
641/// Make a person who is directly in the group an admin. Admins only. Someone in
642/// it only through a nested group is invited directly first. They need room under
643/// their own `fauna/groups:N`, the most groups they may administer.
644pub async fn promote(credentials: &Credentials, id: &str, email: &str) -> Result<Group> {
645    let response = client()
646        .post(format!(
647            "{}/groups/{}/admins/{}",
648            crate::get_url(),
649            encode(id),
650            encode(email)
651        ))
652        .header("Authorization", format!("Token {}", credentials.token))
653        .send()
654        .await?;
655    let json: Value = ok(response).await?.json().await?;
656    Ok(Group::from_json(&json))
657}
658
659/// Make an admin a member again. Admins only; a group keeps at least one admin.
660pub async fn demote(credentials: &Credentials, id: &str, email: &str) -> Result<Group> {
661    let response = client()
662        .delete(format!(
663            "{}/groups/{}/admins/{}",
664            crate::get_url(),
665            encode(id),
666            encode(email)
667        ))
668        .header("Authorization", format!("Token {}", credentials.token))
669        .send()
670        .await?;
671    let json: Value = ok(response).await?.json().await?;
672    Ok(Group::from_json(&json))
673}
674
675/// Invite group `child` inside group `id`; the child's admins accept with the
676/// token (`accept_nest`). Admins of `id` only. Nests at once when you administer
677/// both. Unless `notify` is false, the child's admins hear about it in their
678/// Fauna inbox. Nesting is at most 5 groups deep and never makes a loop.
679pub async fn invite_group(
680    credentials: &Credentials,
681    id: &str,
682    child: &str,
683    options: InviteOptions,
684) -> Result<NestOffer> {
685    let response = client()
686        .post(format!("{}/groups/{}/groups", crate::get_url(), encode(id)))
687        .header("Authorization", format!("Token {}", credentials.token))
688        .json(&json!({ "group": child, "notify": options.notify }))
689        .send()
690        .await?;
691    let json: Value = ok(response).await?.json().await?;
692    Ok(NestOffer::from_json(&json))
693}
694
695/// Ask to put group `id` inside group `parent`; the parent's admins approve with
696/// the token (`accept_nest`). Admins of `id` only. Nests at once when you
697/// administer both. Unless `notify` is false, the parent's admins hear about it
698/// in their Fauna inbox.
699pub async fn request_group(
700    credentials: &Credentials,
701    id: &str,
702    parent: &str,
703    options: InviteOptions,
704) -> Result<NestOffer> {
705    let response = client()
706        .post(format!(
707            "{}/groups/{}/parents",
708            crate::get_url(),
709            encode(id)
710        ))
711        .header("Authorization", format!("Token {}", credentials.token))
712        .json(&json!({ "group": parent, "notify": options.notify }))
713        .send()
714        .await?;
715    let json: Value = ok(response).await?.json().await?;
716    Ok(NestOffer::from_json(&json))
717}
718
719/// The invites and requests waiting on or from a group, newest first. Admins
720/// only.
721pub async fn nests(
722    credentials: &Credentials,
723    id: &str,
724    query: PageQuery,
725) -> Result<Vec<GroupNest>> {
726    let response = client()
727        .get(format!(
728            "{}/groups/{}/nests?cursor={}&max={}",
729            crate::get_url(),
730            encode(id),
731            query.cursor,
732            query.max
733        ))
734        .header("Authorization", format!("Token {}", credentials.token))
735        .send()
736        .await?;
737    let rows: Vec<Value> = ok(response).await?.json().await?;
738    Ok(rows.iter().map(GroupNest::from_json).collect())
739}
740
741/// Accept an invite into a group, or approve a request to join one, by its
742/// token. An admin of the side it waits on only. Resolves to the parent group.
743pub async fn accept_nest(credentials: &Credentials, token: &str) -> Result<Group> {
744    let response = client()
745        .post(format!("{}/groups/nests/accept", crate::get_url()))
746        .header("Authorization", format!("Token {}", credentials.token))
747        .json(&json!({ "token": token }))
748        .send()
749        .await?;
750    let json: Value = ok(response).await?.json().await?;
751    Ok(Group::from_json(&json))
752}
753
754/// Drop a waiting invite or request by its token. An admin of either group.
755pub async fn revoke_nest(credentials: &Credentials, token: &str) -> Result<()> {
756    let response = client()
757        .post(format!("{}/groups/nests/revoke", crate::get_url()))
758        .header("Authorization", format!("Token {}", credentials.token))
759        .json(&json!({ "token": token }))
760        .send()
761        .await?;
762    ok(response).await?;
763    Ok(())
764}
765
766/// Take group `child` out of group `id`. An admin of either group. Everyone who
767/// was in `id` only through it loses it.
768pub async fn unnest(credentials: &Credentials, id: &str, child: &str) -> Result<()> {
769    let response = client()
770        .delete(format!(
771            "{}/groups/{}/groups/{}",
772            crate::get_url(),
773            encode(id),
774            encode(child)
775        ))
776        .header("Authorization", format!("Token {}", credentials.token))
777        .send()
778        .await?;
779    ok(response).await?;
780    Ok(())
781}
782
783/// Two groups with people only chats between them. `group` is the one of yours
784/// it was listed for.
785#[derive(Debug, Clone, Serialize, Deserialize)]
786pub struct Partnership {
787    pub id: String,
788    pub group: String,
789    pub partner: GroupSummary,
790    /// Under Hidden: the partner started at no trust while you hide strangers,
791    /// and your group hasn't engaged.
792    pub hidden: bool,
793    #[serde(default)]
794    pub chats: Vec<ChatSummary>,
795    pub created: DateTime<Utc>,
796}
797
798/// The `{ partnership, chat }` `start_partnership_chat` resolves to.
799#[derive(Debug, Clone, Serialize, Deserialize)]
800pub struct StartedPartnershipChat {
801    pub partnership: Partnership,
802    pub chat: String,
803}
804
805#[derive(Deserialize)]
806struct CreatedChat {
807    id: String,
808}
809
810/// A group's partnerships, each with their chats and what you haven't read. An
811/// API key reads them too.
812pub async fn list_partnerships(
813    authorization: &CredentialsOrApiKey,
814    id: &str,
815) -> Result<Vec<Partnership>> {
816    let response = client()
817        .get(format!(
818            "{}/groups/{}/partnerships",
819            crate::get_url(),
820            encode(id)
821        ))
822        .header(
823            "Authorization",
824            match authorization {
825                CredentialsOrApiKey::Credentials(credentials) => {
826                    format!("Token {}", credentials.token)
827                }
828                CredentialsOrApiKey::ApiKey(key) => format!("ApiKey {}", key.id),
829            },
830        )
831        .send()
832        .await?;
833    Ok(ok(response).await?.json().await?)
834}
835
836/// Start a chat between your group `id` and `partner`. The first chat partners
837/// the groups.
838pub async fn start_partnership_chat(
839    credentials: &Credentials,
840    id: &str,
841    partner: &str,
842    name: Option<&str>,
843) -> Result<StartedPartnershipChat> {
844    let response = client()
845        .post(format!(
846            "{}/groups/{}/partnerships",
847            crate::get_url(),
848            encode(id)
849        ))
850        .header("Authorization", format!("Token {}", credentials.token))
851        .json(&json!({ "partner": partner, "name": name }))
852        .send()
853        .await?;
854    Ok(ok(response).await?.json().await?)
855}
856
857/// Another chat in a partnership. Resolves to its id.
858pub async fn create_partnership_chat(
859    credentials: &Credentials,
860    partnership: &str,
861    name: Option<&str>,
862) -> Result<String> {
863    let response = client()
864        .post(format!(
865            "{}/partnerships/{}/chats",
866            crate::get_url(),
867            encode(partnership)
868        ))
869        .header("Authorization", format!("Token {}", credentials.token))
870        .json(&json!({ "name": name }))
871        .send()
872        .await?;
873    let created: CreatedChat = ok(response).await?.json().await?;
874    Ok(created.id)
875}
876
877/// Delete a partnership chat, for both groups.
878pub async fn delete_partnership_chat(
879    credentials: &Credentials,
880    partnership: &str,
881    chat: &str,
882) -> Result<()> {
883    let response = client()
884        .delete(format!(
885            "{}/partnerships/{}/chats/{}",
886            crate::get_url(),
887            encode(partnership),
888            encode(chat)
889        ))
890        .header("Authorization", format!("Token {}", credentials.token))
891        .send()
892        .await?;
893    ok(response).await?;
894    Ok(())
895}
896
897/// Bring a hidden partnership out of Hidden for your group.
898pub async fn show_partnership(credentials: &Credentials, partnership: &str) -> Result<Partnership> {
899    let response = client()
900        .post(format!(
901            "{}/partnerships/{}/show",
902            crate::get_url(),
903            encode(partnership)
904        ))
905        .header("Authorization", format!("Token {}", credentials.token))
906        .send()
907        .await?;
908    Ok(ok(response).await?.json().await?)
909}
910
911/// End a partnership. Its chats and their files go with it, for both groups.
912pub async fn end_partnership(credentials: &Credentials, partnership: &str) -> Result<()> {
913    let response = client()
914        .delete(format!(
915            "{}/partnerships/{}",
916            crate::get_url(),
917            encode(partnership)
918        ))
919        .header("Authorization", format!("Token {}", credentials.token))
920        .send()
921        .await?;
922    ok(response).await?;
923    Ok(())
924}