Skip to main content

fauna_api/
groups.rs

1use chrono::{DateTime, Utc};
2use serde::{Deserialize, Serialize};
3use serde_json::json;
4
5use crate::authentification::{Credentials, CredentialsOrApiKey, PartialProfile, Profile};
6use crate::error::Result;
7use crate::http::{client, encode, ok};
8use crate::parrot::chat::ChatSummary;
9
10#[derive(Debug, Clone, Serialize, Deserialize)]
11#[serde(rename_all = "camelCase")]
12pub struct Group {
13    pub id: String,
14
15    pub name: String,
16    #[serde(default, skip_serializing_if = "Option::is_none")]
17    pub icon: Option<String>,
18
19    #[serde(default)]
20    pub balance: f64,
21
22    #[serde(default)]
23    pub members: Vec<Profile>,
24
25    pub created_at: DateTime<Utc>,
26}
27
28/// A group as someone outside it sees it: no balance, no member list.
29#[derive(Debug, Clone, Serialize, Deserialize)]
30#[serde(rename_all = "camelCase")]
31pub struct GroupSummary {
32    pub id: String,
33    pub name: String,
34    #[serde(default, skip_serializing_if = "Option::is_none")]
35    pub icon: Option<String>,
36    pub member_count: u32,
37}
38
39/// A person found by `query`, with the groups they belong to.
40#[derive(Debug, Clone, Serialize, Deserialize)]
41pub struct GroupMatch {
42    pub profile: Profile,
43    pub groups: Vec<GroupSummary>,
44}
45
46/// `Partial<Group>` in the TypeScript SDK.
47#[derive(Debug, Clone, Default, Serialize)]
48#[serde(rename_all = "camelCase")]
49pub struct PartialGroup {
50    #[serde(skip_serializing_if = "Option::is_none")]
51    pub id: Option<String>,
52    #[serde(skip_serializing_if = "Option::is_none")]
53    pub name: Option<String>,
54    #[serde(skip_serializing_if = "Option::is_none")]
55    pub icon: Option<String>,
56    #[serde(skip_serializing_if = "Option::is_none")]
57    pub balance: Option<f64>,
58    #[serde(skip_serializing_if = "Option::is_none")]
59    pub members: Option<Vec<Profile>>,
60    #[serde(skip_serializing_if = "Option::is_none")]
61    pub created_at: Option<DateTime<Utc>>,
62}
63
64#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
65#[serde(rename_all = "lowercase")]
66pub enum InviteStatus {
67    Added,
68    Invited,
69}
70
71/// What `invite` resolves to: `added` when the email already had a Fauna
72/// account, `invited` with the invite token when a pending invite was stored.
73#[derive(Debug, Clone, Deserialize)]
74pub struct InviteResult {
75    pub status: InviteStatus,
76    #[serde(default)]
77    pub token: Option<String>,
78}
79
80/// The `options` argument of `invite`.
81#[derive(Debug, Clone, Copy, Default)]
82pub struct InviteOptions {
83    pub notify: Option<bool>,
84}
85
86#[derive(Debug, Clone, Deserialize)]
87#[serde(rename_all = "camelCase")]
88pub struct JoinResult {
89    pub group: Group,
90    pub already_member: bool,
91}
92
93pub async fn create(credentials: &Credentials, name: &str) -> Result<Group> {
94    let response = client()
95        .post(format!("{}/groups", crate::get_url()))
96        .header("Authorization", format!("Token {}", credentials.token))
97        .json(&json!({ "name": name }))
98        .send()
99        .await?;
100    Ok(ok(response).await?.json().await?)
101}
102
103pub async fn list(authorization: &CredentialsOrApiKey) -> Result<Vec<Group>> {
104    let response = client()
105        .get(format!("{}/groups", crate::get_url()))
106        .header(
107            "Authorization",
108            match authorization {
109                CredentialsOrApiKey::Credentials(credentials) => {
110                    format!("Token {}", credentials.token)
111                }
112                CredentialsOrApiKey::ApiKey(key) => format!("ApiKey {}", key.id),
113            },
114        )
115        .send()
116        .await?;
117    Ok(ok(response).await?.json().await?)
118}
119
120/// People matching a partial email or name, best first, each with their
121/// groups. Only people in at least one group come back.
122pub async fn query(
123    authorization: &CredentialsOrApiKey,
124    profile: &PartialProfile,
125) -> Result<Vec<GroupMatch>> {
126    let response = client()
127        .post(format!("{}/groups/query", crate::get_url()))
128        .header(
129            "Authorization",
130            match authorization {
131                CredentialsOrApiKey::Credentials(credentials) => {
132                    format!("Token {}", credentials.token)
133                }
134                CredentialsOrApiKey::ApiKey(key) => format!("ApiKey {}", key.id),
135            },
136        )
137        .json(&json!({ "email": profile.email, "displayName": profile.display_name }))
138        .send()
139        .await?;
140    Ok(ok(response).await?.json().await?)
141}
142
143/// Name, icon and member count of groups by id, including groups you are not
144/// in. Unknown ids are left out.
145pub async fn summaries(
146    authorization: &CredentialsOrApiKey,
147    ids: &[String],
148) -> Result<Vec<GroupSummary>> {
149    let response = client()
150        .post(format!("{}/groups/summaries", crate::get_url()))
151        .header(
152            "Authorization",
153            match authorization {
154                CredentialsOrApiKey::Credentials(credentials) => {
155                    format!("Token {}", credentials.token)
156                }
157                CredentialsOrApiKey::ApiKey(key) => format!("ApiKey {}", key.id),
158            },
159        )
160        .json(&json!({ "ids": ids }))
161        .send()
162        .await?;
163    Ok(ok(response).await?.json().await?)
164}
165
166pub async fn get(authorization: &CredentialsOrApiKey, id: &str) -> Result<Group> {
167    let response = client()
168        .get(format!("{}/groups/{}", crate::get_url(), encode(id)))
169        .header(
170            "Authorization",
171            match authorization {
172                CredentialsOrApiKey::Credentials(credentials) => {
173                    format!("Token {}", credentials.token)
174                }
175                CredentialsOrApiKey::ApiKey(key) => format!("ApiKey {}", key.id),
176            },
177        )
178        .send()
179        .await?;
180    Ok(ok(response).await?.json().await?)
181}
182
183pub async fn edit(credentials: &Credentials, id: &str, update: &PartialGroup) -> Result<Group> {
184    let response = client()
185        .patch(format!("{}/groups/{}", crate::get_url(), encode(id)))
186        .header("Authorization", format!("Token {}", credentials.token))
187        .json(&json!({ "update": update }))
188        .send()
189        .await?;
190    Ok(ok(response).await?.json().await?)
191}
192
193/// Add a user to a group by email. Resolves `added` if they were added directly
194/// (they have a Fauna account), or `invited` with a token if a pending invite was
195/// stored instead (no Fauna account for that email yet). Fauna emails the invite
196/// unless `notify` is false, so an app can send its own email carrying the token.
197pub async fn invite(
198    credentials: &Credentials,
199    id: &str,
200    email: &str,
201    options: InviteOptions,
202) -> Result<InviteResult> {
203    let response = client()
204        .post(format!("{}/groups/{}/invite", crate::get_url(), encode(id)))
205        .header("Authorization", format!("Token {}", credentials.token))
206        .json(&json!({ "email": email, "notify": options.notify }))
207        .send()
208        .await?;
209    Ok(ok(response).await?.json().await?)
210}
211
212/// Join the group an email invite points at, using the token from the invite.
213pub async fn accept_invite(credentials: &Credentials, token: &str) -> Result<JoinResult> {
214    let response = client()
215        .post(format!("{}/groups/invites/accept", crate::get_url()))
216        .header("Authorization", format!("Token {}", credentials.token))
217        .json(&json!({ "token": token }))
218        .send()
219        .await?;
220    Ok(ok(response).await?.json().await?)
221}
222
223pub async fn generate_link(credentials: &Credentials, id: &str) -> Result<String> {
224    let response = client()
225        .post(format!("{}/groups/{}/link", crate::get_url(), encode(id)))
226        .header("Authorization", format!("Token {}", credentials.token))
227        .send()
228        .await?;
229    let json: serde_json::Value = ok(response).await?.json().await?;
230    Ok(json["code"].as_str().unwrap_or_default().to_string())
231}
232
233pub async fn join(credentials: &Credentials, code: &str) -> Result<JoinResult> {
234    let response = client()
235        .post(format!("{}/groups/join", crate::get_url()))
236        .header("Authorization", format!("Token {}", credentials.token))
237        .json(&json!({ "code": code }))
238        .send()
239        .await?;
240    Ok(ok(response).await?.json().await?)
241}
242
243pub async fn leave(credentials: &Credentials, id: &str) -> Result<()> {
244    let response = client()
245        .delete(format!(
246            "{}/groups/{}/membership",
247            crate::get_url(),
248            encode(id)
249        ))
250        .header("Authorization", format!("Token {}", credentials.token))
251        .send()
252        .await?;
253    ok(response).await?;
254    Ok(())
255}
256
257pub async fn kick(credentials: &Credentials, id: &str, email: &str) -> Result<()> {
258    let response = client()
259        .delete(format!(
260            "{}/groups/{}/members/{}",
261            crate::get_url(),
262            encode(id),
263            encode(email)
264        ))
265        .header("Authorization", format!("Token {}", credentials.token))
266        .send()
267        .await?;
268    ok(response).await?;
269    Ok(())
270}
271
272/// Two groups with people only chats between them. `group` is the one of yours
273/// it was listed for.
274#[derive(Debug, Clone, Serialize, Deserialize)]
275pub struct Partnership {
276    pub id: String,
277    pub group: String,
278    pub partner: GroupSummary,
279    /// Under Hidden: the partner started at no trust while you hide strangers,
280    /// and your group hasn't engaged.
281    pub hidden: bool,
282    #[serde(default)]
283    pub chats: Vec<ChatSummary>,
284    pub created: DateTime<Utc>,
285}
286
287/// The `{ partnership, chat }` `start_partnership_chat` resolves to.
288#[derive(Debug, Clone, Serialize, Deserialize)]
289pub struct StartedPartnershipChat {
290    pub partnership: Partnership,
291    pub chat: String,
292}
293
294#[derive(Deserialize)]
295struct CreatedChat {
296    id: String,
297}
298
299/// A group's partnerships, each with their chats and what you haven't read. An
300/// API key reads them too.
301pub async fn list_partnerships(
302    authorization: &CredentialsOrApiKey,
303    id: &str,
304) -> Result<Vec<Partnership>> {
305    let response = client()
306        .get(format!(
307            "{}/groups/{}/partnerships",
308            crate::get_url(),
309            encode(id)
310        ))
311        .header(
312            "Authorization",
313            match authorization {
314                CredentialsOrApiKey::Credentials(credentials) => {
315                    format!("Token {}", credentials.token)
316                }
317                CredentialsOrApiKey::ApiKey(key) => format!("ApiKey {}", key.id),
318            },
319        )
320        .send()
321        .await?;
322    Ok(ok(response).await?.json().await?)
323}
324
325/// Start a chat between your group `id` and `partner`. The first chat partners
326/// the groups.
327pub async fn start_partnership_chat(
328    credentials: &Credentials,
329    id: &str,
330    partner: &str,
331    name: Option<&str>,
332) -> Result<StartedPartnershipChat> {
333    let response = client()
334        .post(format!(
335            "{}/groups/{}/partnerships",
336            crate::get_url(),
337            encode(id)
338        ))
339        .header("Authorization", format!("Token {}", credentials.token))
340        .json(&json!({ "partner": partner, "name": name }))
341        .send()
342        .await?;
343    Ok(ok(response).await?.json().await?)
344}
345
346/// Another chat in a partnership. Resolves to its id.
347pub async fn create_partnership_chat(
348    credentials: &Credentials,
349    partnership: &str,
350    name: Option<&str>,
351) -> Result<String> {
352    let response = client()
353        .post(format!(
354            "{}/partnerships/{}/chats",
355            crate::get_url(),
356            encode(partnership)
357        ))
358        .header("Authorization", format!("Token {}", credentials.token))
359        .json(&json!({ "name": name }))
360        .send()
361        .await?;
362    let created: CreatedChat = ok(response).await?.json().await?;
363    Ok(created.id)
364}
365
366/// Delete a partnership chat, for both groups.
367pub async fn delete_partnership_chat(
368    credentials: &Credentials,
369    partnership: &str,
370    chat: &str,
371) -> Result<()> {
372    let response = client()
373        .delete(format!(
374            "{}/partnerships/{}/chats/{}",
375            crate::get_url(),
376            encode(partnership),
377            encode(chat)
378        ))
379        .header("Authorization", format!("Token {}", credentials.token))
380        .send()
381        .await?;
382    ok(response).await?;
383    Ok(())
384}
385
386/// Bring a hidden partnership out of Hidden for your group.
387pub async fn show_partnership(credentials: &Credentials, partnership: &str) -> Result<Partnership> {
388    let response = client()
389        .post(format!(
390            "{}/partnerships/{}/show",
391            crate::get_url(),
392            encode(partnership)
393        ))
394        .header("Authorization", format!("Token {}", credentials.token))
395        .send()
396        .await?;
397    Ok(ok(response).await?.json().await?)
398}
399
400/// End a partnership. Its chats and their files go with it, for both groups.
401pub async fn end_partnership(credentials: &Credentials, partnership: &str) -> Result<()> {
402    let response = client()
403        .delete(format!(
404            "{}/partnerships/{}",
405            crate::get_url(),
406            encode(partnership)
407        ))
408        .header("Authorization", format!("Token {}", credentials.token))
409        .send()
410        .await?;
411    ok(response).await?;
412    Ok(())
413}