use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
use crate::authentification::{Credentials, CredentialsOrApiKey, PartialProfile, Profile};
use crate::billing::PageQuery;
use crate::error::Result;
use crate::http::{client, encode, ok};
use crate::parrot::chat::ChatSummary;
use crate::tickets::{optional, parse_date};
fn text(value: &Value) -> String {
value.as_str().unwrap_or_default().to_string()
}
fn texts(value: &Value) -> Vec<String> {
value
.as_array()
.map(|items| items.iter().map(text).collect())
.unwrap_or_default()
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct GroupRef {
pub id: String,
pub name: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub icon: Option<String>,
}
impl GroupRef {
pub fn from_json(json: &Value) -> GroupRef {
GroupRef {
id: text(&json["id"]),
name: text(&json["name"]),
icon: optional(&json["icon"]),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct GroupMember {
pub email: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub display_name: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub icon: Option<String>,
pub through: String,
}
impl GroupMember {
pub fn from_json(json: &Value) -> GroupMember {
GroupMember {
email: text(&json["email"]),
display_name: optional(&json["displayName"]),
icon: optional(&json["icon"]),
through: text(&json["through"]),
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Group {
pub id: String,
pub name: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub icon: Option<String>,
pub balance: f64,
pub created_at: DateTime<Utc>,
pub admins: Vec<String>,
pub people: Vec<String>,
pub groups: Vec<GroupRef>,
pub members: Vec<GroupMember>,
pub through: String,
}
impl Group {
pub fn from_json(json: &Value) -> Group {
let list = |key: &str| json[key].as_array().cloned().unwrap_or_default();
Group {
id: text(&json["id"]),
name: text(&json["name"]),
icon: optional(&json["icon"]),
balance: json["balance"].as_f64().unwrap_or(0.0),
created_at: parse_date(&json["createdAt"]).unwrap_or_default(),
admins: texts(&json["admins"]),
people: texts(&json["people"]),
groups: list("groups").iter().map(GroupRef::from_json).collect(),
members: list("members").iter().map(GroupMember::from_json).collect(),
through: text(&json["through"]),
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct JoinLink {
pub code: String,
#[serde(default)]
pub uses: u32,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub max_uses: Option<u32>,
pub expires: DateTime<Utc>,
}
impl JoinLink {
pub fn from_json(json: &Value) -> JoinLink {
JoinLink {
code: text(&json["code"]),
uses: json["uses"].as_u64().unwrap_or(0) as u32,
max_uses: json["maxUses"].as_u64().map(|uses| uses as u32),
expires: parse_date(&json["expires"]).unwrap_or_default(),
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct GroupSummary {
pub id: String,
pub name: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub icon: Option<String>,
pub member_count: u32,
}
impl GroupSummary {
pub fn from_json(json: &Value) -> GroupSummary {
GroupSummary {
id: text(&json["id"]),
name: text(&json["name"]),
icon: optional(&json["icon"]),
member_count: json["memberCount"].as_u64().unwrap_or(0) as u32,
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct MatchedGroup {
pub id: String,
pub name: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub icon: Option<String>,
pub member_count: u32,
pub through: String,
}
impl MatchedGroup {
pub fn from_json(json: &Value) -> MatchedGroup {
let summary = GroupSummary::from_json(json);
MatchedGroup {
id: summary.id,
name: summary.name,
icon: summary.icon,
member_count: summary.member_count,
through: text(&json["through"]),
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GroupMatch {
pub profile: Profile,
pub groups: Vec<MatchedGroup>,
}
impl GroupMatch {
pub fn from_json(json: &Value) -> GroupMatch {
GroupMatch {
profile: Profile::from_json(&json["profile"]).unwrap_or_default(),
groups: json["groups"]
.as_array()
.map(|groups| groups.iter().map(MatchedGroup::from_json).collect())
.unwrap_or_default(),
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum NestSide {
Parent,
Child,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GroupNest {
pub token: String,
pub parent: GroupRef,
pub child: GroupRef,
pub from: NestSide,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub by: Option<String>,
pub expires: DateTime<Utc>,
}
impl GroupNest {
pub fn from_json(json: &Value) -> GroupNest {
GroupNest {
token: text(&json["token"]),
parent: GroupRef::from_json(&json["parent"]),
child: GroupRef::from_json(&json["child"]),
from: if json["from"] == "child" {
NestSide::Child
} else {
NestSide::Parent
},
by: optional(&json["by"]),
expires: parse_date(&json["expires"]).unwrap_or_default(),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum NestOffer {
Nested,
Waiting { token: String },
}
impl NestOffer {
pub fn from_json(json: &Value) -> NestOffer {
if json["nested"] == true {
NestOffer::Nested
} else {
NestOffer::Waiting {
token: text(&json["token"]),
}
}
}
}
#[derive(Debug, Clone, Default, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PartialGroup {
#[serde(skip_serializing_if = "Option::is_none")]
pub id: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub icon: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub balance: Option<f64>,
#[serde(skip_serializing_if = "Option::is_none")]
pub created_at: Option<DateTime<Utc>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub admins: Option<Vec<String>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub people: Option<Vec<String>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub groups: Option<Vec<GroupRef>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub members: Option<Vec<GroupMember>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub through: Option<String>,
}
#[derive(Debug, Clone, Copy, Default)]
pub struct InviteOptions {
pub notify: Option<bool>,
}
#[derive(Debug, Clone, Copy, Default)]
pub struct LinkOptions {
pub max_uses: Option<u32>,
}
#[derive(Debug, Clone)]
pub struct JoinResult {
pub group: Group,
pub already_member: bool,
}
impl JoinResult {
fn from_value(json: &Value) -> JoinResult {
JoinResult {
group: Group::from_json(&json["group"]),
already_member: json["alreadyMember"] == true,
}
}
}
pub async fn create(credentials: &Credentials, name: &str) -> Result<Group> {
let response = client()
.post(format!("{}/groups", crate::get_url()))
.header("Authorization", format!("Token {}", credentials.token))
.json(&json!({ "name": name }))
.send()
.await?;
let json: Value = ok(response).await?.json().await?;
Ok(Group::from_json(&json))
}
pub async fn list(authorization: &CredentialsOrApiKey) -> Result<Vec<Group>> {
let response = client()
.get(format!("{}/groups", crate::get_url()))
.header(
"Authorization",
match authorization {
CredentialsOrApiKey::Credentials(credentials) => {
format!("Token {}", credentials.token)
}
CredentialsOrApiKey::ApiKey(key) => format!("ApiKey {}", key.id),
},
)
.send()
.await?;
let rows: Vec<Value> = ok(response).await?.json().await?;
Ok(rows.iter().map(Group::from_json).collect())
}
pub async fn query(
authorization: &CredentialsOrApiKey,
profile: &PartialProfile,
) -> Result<Vec<GroupMatch>> {
let response = client()
.post(format!("{}/groups/query", crate::get_url()))
.header(
"Authorization",
match authorization {
CredentialsOrApiKey::Credentials(credentials) => {
format!("Token {}", credentials.token)
}
CredentialsOrApiKey::ApiKey(key) => format!("ApiKey {}", key.id),
},
)
.json(&json!({ "email": profile.email, "displayName": profile.display_name }))
.send()
.await?;
let rows: Vec<Value> = ok(response).await?.json().await?;
Ok(rows.iter().map(GroupMatch::from_json).collect())
}
pub async fn summaries(
authorization: &CredentialsOrApiKey,
ids: &[String],
) -> Result<Vec<GroupSummary>> {
let response = client()
.post(format!("{}/groups/summaries", crate::get_url()))
.header(
"Authorization",
match authorization {
CredentialsOrApiKey::Credentials(credentials) => {
format!("Token {}", credentials.token)
}
CredentialsOrApiKey::ApiKey(key) => format!("ApiKey {}", key.id),
},
)
.json(&json!({ "ids": ids }))
.send()
.await?;
let rows: Vec<Value> = ok(response).await?.json().await?;
Ok(rows.iter().map(GroupSummary::from_json).collect())
}
pub async fn get(authorization: &CredentialsOrApiKey, id: &str) -> Result<Group> {
let response = client()
.get(format!("{}/groups/{}", crate::get_url(), encode(id)))
.header(
"Authorization",
match authorization {
CredentialsOrApiKey::Credentials(credentials) => {
format!("Token {}", credentials.token)
}
CredentialsOrApiKey::ApiKey(key) => format!("ApiKey {}", key.id),
},
)
.send()
.await?;
let json: Value = ok(response).await?.json().await?;
Ok(Group::from_json(&json))
}
pub async fn edit(credentials: &Credentials, id: &str, update: &PartialGroup) -> Result<Group> {
let response = client()
.patch(format!("{}/groups/{}", crate::get_url(), encode(id)))
.header("Authorization", format!("Token {}", credentials.token))
.json(&json!({ "update": update }))
.send()
.await?;
let json: Value = ok(response).await?.json().await?;
Ok(Group::from_json(&json))
}
pub async fn remove(credentials: &Credentials, id: &str) -> Result<()> {
let response = client()
.delete(format!("{}/groups/{}", crate::get_url(), encode(id)))
.header("Authorization", format!("Token {}", credentials.token))
.send()
.await?;
ok(response).await?;
Ok(())
}
pub async fn invite(
credentials: &Credentials,
id: &str,
email: &str,
options: InviteOptions,
) -> Result<String> {
let response = client()
.post(format!("{}/groups/{}/invite", crate::get_url(), encode(id)))
.header("Authorization", format!("Token {}", credentials.token))
.json(&json!({ "email": email, "notify": options.notify }))
.send()
.await?;
let json: Value = ok(response).await?.json().await?;
Ok(text(&json["token"]))
}
pub async fn accept_invite(credentials: &Credentials, token: &str) -> Result<JoinResult> {
let response = client()
.post(format!("{}/groups/invites/accept", crate::get_url()))
.header("Authorization", format!("Token {}", credentials.token))
.json(&json!({ "token": token }))
.send()
.await?;
let json: Value = ok(response).await?.json().await?;
Ok(JoinResult::from_value(&json))
}
pub async fn generate_link(
credentials: &Credentials,
id: &str,
options: LinkOptions,
) -> Result<String> {
let response = client()
.post(format!("{}/groups/{}/link", crate::get_url(), encode(id)))
.header("Authorization", format!("Token {}", credentials.token))
.json(&json!({ "maxUses": options.max_uses }))
.send()
.await?;
let json: Value = ok(response).await?.json().await?;
Ok(text(&json["code"]))
}
pub async fn links(credentials: &Credentials, id: &str) -> Result<Vec<JoinLink>> {
let response = client()
.get(format!("{}/groups/{}/links", crate::get_url(), encode(id)))
.header("Authorization", format!("Token {}", credentials.token))
.send()
.await?;
let rows: Vec<Value> = ok(response).await?.json().await?;
Ok(rows.iter().map(JoinLink::from_json).collect())
}
pub async fn revoke_link(credentials: &Credentials, id: &str, code: &str) -> Result<()> {
let response = client()
.delete(format!(
"{}/groups/{}/links/{}",
crate::get_url(),
encode(id),
encode(code)
))
.header("Authorization", format!("Token {}", credentials.token))
.send()
.await?;
ok(response).await?;
Ok(())
}
pub async fn join(
credentials: &Credentials,
code: &str,
group: Option<&str>,
) -> Result<JoinResult> {
let response = client()
.post(format!("{}/groups/join", crate::get_url()))
.header("Authorization", format!("Token {}", credentials.token))
.json(&json!({ "code": code, "group": group }))
.send()
.await?;
let json: Value = ok(response).await?.json().await?;
Ok(JoinResult::from_value(&json))
}
pub async fn leave(credentials: &Credentials, id: &str) -> Result<()> {
let response = client()
.delete(format!(
"{}/groups/{}/membership",
crate::get_url(),
encode(id)
))
.header("Authorization", format!("Token {}", credentials.token))
.send()
.await?;
ok(response).await?;
Ok(())
}
pub async fn kick(credentials: &Credentials, id: &str, email: &str) -> Result<()> {
let response = client()
.delete(format!(
"{}/groups/{}/members/{}",
crate::get_url(),
encode(id),
encode(email)
))
.header("Authorization", format!("Token {}", credentials.token))
.send()
.await?;
ok(response).await?;
Ok(())
}
pub async fn promote(credentials: &Credentials, id: &str, email: &str) -> Result<Group> {
let response = client()
.post(format!(
"{}/groups/{}/admins/{}",
crate::get_url(),
encode(id),
encode(email)
))
.header("Authorization", format!("Token {}", credentials.token))
.send()
.await?;
let json: Value = ok(response).await?.json().await?;
Ok(Group::from_json(&json))
}
pub async fn demote(credentials: &Credentials, id: &str, email: &str) -> Result<Group> {
let response = client()
.delete(format!(
"{}/groups/{}/admins/{}",
crate::get_url(),
encode(id),
encode(email)
))
.header("Authorization", format!("Token {}", credentials.token))
.send()
.await?;
let json: Value = ok(response).await?.json().await?;
Ok(Group::from_json(&json))
}
pub async fn invite_group(
credentials: &Credentials,
id: &str,
child: &str,
options: InviteOptions,
) -> Result<NestOffer> {
let response = client()
.post(format!("{}/groups/{}/groups", crate::get_url(), encode(id)))
.header("Authorization", format!("Token {}", credentials.token))
.json(&json!({ "group": child, "notify": options.notify }))
.send()
.await?;
let json: Value = ok(response).await?.json().await?;
Ok(NestOffer::from_json(&json))
}
pub async fn request_group(
credentials: &Credentials,
id: &str,
parent: &str,
options: InviteOptions,
) -> Result<NestOffer> {
let response = client()
.post(format!(
"{}/groups/{}/parents",
crate::get_url(),
encode(id)
))
.header("Authorization", format!("Token {}", credentials.token))
.json(&json!({ "group": parent, "notify": options.notify }))
.send()
.await?;
let json: Value = ok(response).await?.json().await?;
Ok(NestOffer::from_json(&json))
}
pub async fn nests(
credentials: &Credentials,
id: &str,
query: PageQuery,
) -> Result<Vec<GroupNest>> {
let response = client()
.get(format!(
"{}/groups/{}/nests?cursor={}&max={}",
crate::get_url(),
encode(id),
query.cursor,
query.max
))
.header("Authorization", format!("Token {}", credentials.token))
.send()
.await?;
let rows: Vec<Value> = ok(response).await?.json().await?;
Ok(rows.iter().map(GroupNest::from_json).collect())
}
pub async fn accept_nest(credentials: &Credentials, token: &str) -> Result<Group> {
let response = client()
.post(format!("{}/groups/nests/accept", crate::get_url()))
.header("Authorization", format!("Token {}", credentials.token))
.json(&json!({ "token": token }))
.send()
.await?;
let json: Value = ok(response).await?.json().await?;
Ok(Group::from_json(&json))
}
pub async fn revoke_nest(credentials: &Credentials, token: &str) -> Result<()> {
let response = client()
.post(format!("{}/groups/nests/revoke", crate::get_url()))
.header("Authorization", format!("Token {}", credentials.token))
.json(&json!({ "token": token }))
.send()
.await?;
ok(response).await?;
Ok(())
}
pub async fn unnest(credentials: &Credentials, id: &str, child: &str) -> Result<()> {
let response = client()
.delete(format!(
"{}/groups/{}/groups/{}",
crate::get_url(),
encode(id),
encode(child)
))
.header("Authorization", format!("Token {}", credentials.token))
.send()
.await?;
ok(response).await?;
Ok(())
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Partnership {
pub id: String,
pub group: String,
pub partner: GroupSummary,
pub hidden: bool,
#[serde(default)]
pub chats: Vec<ChatSummary>,
pub created: DateTime<Utc>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct StartedPartnershipChat {
pub partnership: Partnership,
pub chat: String,
}
#[derive(Deserialize)]
struct CreatedChat {
id: String,
}
pub async fn list_partnerships(
authorization: &CredentialsOrApiKey,
id: &str,
) -> Result<Vec<Partnership>> {
let response = client()
.get(format!(
"{}/groups/{}/partnerships",
crate::get_url(),
encode(id)
))
.header(
"Authorization",
match authorization {
CredentialsOrApiKey::Credentials(credentials) => {
format!("Token {}", credentials.token)
}
CredentialsOrApiKey::ApiKey(key) => format!("ApiKey {}", key.id),
},
)
.send()
.await?;
Ok(ok(response).await?.json().await?)
}
pub async fn start_partnership_chat(
credentials: &Credentials,
id: &str,
partner: &str,
name: Option<&str>,
) -> Result<StartedPartnershipChat> {
let response = client()
.post(format!(
"{}/groups/{}/partnerships",
crate::get_url(),
encode(id)
))
.header("Authorization", format!("Token {}", credentials.token))
.json(&json!({ "partner": partner, "name": name }))
.send()
.await?;
Ok(ok(response).await?.json().await?)
}
pub async fn create_partnership_chat(
credentials: &Credentials,
partnership: &str,
name: Option<&str>,
) -> Result<String> {
let response = client()
.post(format!(
"{}/partnerships/{}/chats",
crate::get_url(),
encode(partnership)
))
.header("Authorization", format!("Token {}", credentials.token))
.json(&json!({ "name": name }))
.send()
.await?;
let created: CreatedChat = ok(response).await?.json().await?;
Ok(created.id)
}
pub async fn delete_partnership_chat(
credentials: &Credentials,
partnership: &str,
chat: &str,
) -> Result<()> {
let response = client()
.delete(format!(
"{}/partnerships/{}/chats/{}",
crate::get_url(),
encode(partnership),
encode(chat)
))
.header("Authorization", format!("Token {}", credentials.token))
.send()
.await?;
ok(response).await?;
Ok(())
}
pub async fn show_partnership(credentials: &Credentials, partnership: &str) -> Result<Partnership> {
let response = client()
.post(format!(
"{}/partnerships/{}/show",
crate::get_url(),
encode(partnership)
))
.header("Authorization", format!("Token {}", credentials.token))
.send()
.await?;
Ok(ok(response).await?.json().await?)
}
pub async fn end_partnership(credentials: &Credentials, partnership: &str) -> Result<()> {
let response = client()
.delete(format!(
"{}/partnerships/{}",
crate::get_url(),
encode(partnership)
))
.header("Authorization", format!("Token {}", credentials.token))
.send()
.await?;
ok(response).await?;
Ok(())
}