use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use serde_json::json;
use crate::authentification::{Credentials, CredentialsOrApiKey, PartialProfile, Profile};
use crate::error::Result;
use crate::http::{client, encode, ok};
use crate::parrot::chat::ChatSummary;
#[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>,
#[serde(default)]
pub balance: f64,
#[serde(default)]
pub members: Vec<Profile>,
pub created_at: DateTime<Utc>,
}
#[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,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GroupMatch {
pub profile: Profile,
pub groups: Vec<GroupSummary>,
}
#[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 members: Option<Vec<Profile>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub created_at: Option<DateTime<Utc>>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum InviteStatus {
Added,
Invited,
}
#[derive(Debug, Clone, Deserialize)]
pub struct InviteResult {
pub status: InviteStatus,
#[serde(default)]
pub token: Option<String>,
}
#[derive(Debug, Clone, Copy, Default)]
pub struct InviteOptions {
pub notify: Option<bool>,
}
#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct JoinResult {
pub group: Group,
pub already_member: bool,
}
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?;
Ok(ok(response).await?.json().await?)
}
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?;
Ok(ok(response).await?.json().await?)
}
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?;
Ok(ok(response).await?.json().await?)
}
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?;
Ok(ok(response).await?.json().await?)
}
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?;
Ok(ok(response).await?.json().await?)
}
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?;
Ok(ok(response).await?.json().await?)
}
pub async fn invite(
credentials: &Credentials,
id: &str,
email: &str,
options: InviteOptions,
) -> Result<InviteResult> {
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?;
Ok(ok(response).await?.json().await?)
}
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?;
Ok(ok(response).await?.json().await?)
}
pub async fn generate_link(credentials: &Credentials, id: &str) -> Result<String> {
let response = client()
.post(format!("{}/groups/{}/link", crate::get_url(), encode(id)))
.header("Authorization", format!("Token {}", credentials.token))
.send()
.await?;
let json: serde_json::Value = ok(response).await?.json().await?;
Ok(json["code"].as_str().unwrap_or_default().to_string())
}
pub async fn join(credentials: &Credentials, code: &str) -> Result<JoinResult> {
let response = client()
.post(format!("{}/groups/join", crate::get_url()))
.header("Authorization", format!("Token {}", credentials.token))
.json(&json!({ "code": code }))
.send()
.await?;
Ok(ok(response).await?.json().await?)
}
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(())
}
#[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(())
}