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