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#[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#[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#[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 pub admins: Vec<String>,
84 pub people: Vec<String>,
86 pub groups: Vec<GroupRef>,
88 pub members: Vec<GroupMember>,
91 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#[derive(Debug, Clone, Serialize, Deserialize)]
117#[serde(rename_all = "camelCase")]
118pub struct JoinLink {
119 pub code: String,
120 #[serde(default)]
122 pub uses: u32,
123 #[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#[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#[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#[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#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
212#[serde(rename_all = "lowercase")]
213pub enum NestSide {
214 Parent,
215 Child,
216}
217
218#[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 #[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#[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#[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#[derive(Debug, Clone, Copy, Default)]
297pub struct InviteOptions {
298 pub notify: Option<bool>,
299}
300
301#[derive(Debug, Clone, Copy, Default)]
303pub struct LinkOptions {
304 pub max_uses: Option<u32>,
305}
306
307#[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
323pub 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
335pub 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
355pub 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
379pub 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
403pub 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
422pub 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
434pub 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
447pub 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
468pub 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
481pub 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
499pub 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
510pub 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
526pub 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
544pub 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
561pub 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
577pub 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
594pub 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
610pub 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
630pub 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
654pub 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
676pub 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
689pub 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
701pub 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#[derive(Debug, Clone, Serialize, Deserialize)]
721pub struct Partnership {
722 pub id: String,
723 pub group: String,
724 pub partner: GroupSummary,
725 pub hidden: bool,
728 #[serde(default)]
729 pub chats: Vec<ChatSummary>,
730 pub created: DateTime<Utc>,
731}
732
733#[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
745pub 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
771pub 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
792pub 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
812pub 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
832pub 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
846pub 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}