use std::ops::Deref;
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
use crate::authentification::CredentialsOrApiKey;
use crate::error::Result;
use crate::http::{client, encode, ok};
use crate::parrot::chat::ChatSummary;
use crate::parrot::generative::Author;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum OwnerKind {
Group,
Friend,
Partnership,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct OwnerGroup {
pub id: String,
pub name: String,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Owner {
pub kind: OwnerKind,
pub id: String,
pub name: String,
#[serde(default)]
pub trust: Option<f64>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub group: Option<OwnerGroup>,
}
#[derive(Debug, Clone, Serialize)]
pub struct Chat {
#[serde(flatten)]
pub summary: ChatSummary,
pub owner: Owner,
}
impl Deref for Chat {
type Target = ChatSummary;
fn deref(&self) -> &ChatSummary {
&self.summary
}
}
impl Chat {
pub fn from_json(json: &Value) -> Option<Chat> {
Some(Chat {
summary: ChatSummary::from_json(json),
owner: serde_json::from_value(json["owner"].clone()).ok()?,
})
}
}
impl<'de> Deserialize<'de> for Chat {
fn deserialize<D: serde::Deserializer<'de>>(
deserializer: D,
) -> std::result::Result<Self, D::Error> {
Chat::from_json(&Value::deserialize(deserializer)?)
.ok_or_else(|| serde::de::Error::custom("a shared chat needs its owner"))
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Message {
pub position: u32,
pub role: String,
pub text: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub author: Option<Author>,
pub created: i64,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Unread {
pub total: u32,
#[serde(default)]
pub chats: Vec<Chat>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CaughtUpChat {
pub id: String,
pub name: String,
#[serde(default)]
pub human: bool,
pub owner: Owner,
pub updated: i64,
#[serde(default)]
pub messages: Vec<Message>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CaughtUp {
#[serde(default)]
pub chats: Vec<CaughtUpChat>,
pub more: bool,
pub unread: u32,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ChatReference {
pub id: String,
pub name: String,
pub owner: Owner,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Found {
pub chat: ChatReference,
pub message: Message,
}
#[derive(Debug, Clone, Copy, Default)]
pub struct UnreadOptions {
pub min_trust: Option<f64>,
}
#[derive(Debug, Clone, Copy, Default)]
pub struct CatchUpOptions {
pub min_trust: Option<f64>,
pub max: Option<u32>,
}
#[derive(Debug, Clone, Copy, Default)]
pub struct SearchOptions {
pub cursor: Option<u32>,
pub max: Option<u32>,
}
pub async fn list(authorization: &CredentialsOrApiKey) -> Result<Vec<Chat>> {
let response = client()
.get(format!("{}/chats/shared", 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().filter_map(Chat::from_json).collect())
}
pub async fn unread(authorization: &CredentialsOrApiKey, options: UnreadOptions) -> Result<Unread> {
let query = options
.min_trust
.map(|min_trust| format!("?minTrust={}", encode(&min_trust.to_string())))
.unwrap_or_default();
let response = client()
.get(format!("{}/chats/unread{}", crate::get_url(), query))
.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(Unread {
total: json["total"].as_u64().unwrap_or_default() as u32,
chats: json["chats"]
.as_array()
.into_iter()
.flatten()
.filter_map(Chat::from_json)
.collect(),
})
}
pub async fn catch_up(
authorization: &CredentialsOrApiKey,
options: CatchUpOptions,
) -> Result<CaughtUp> {
let response = client()
.post(format!("{}/chats/catch-up", crate::get_url()))
.header(
"Authorization",
match authorization {
CredentialsOrApiKey::Credentials(credentials) => {
format!("Token {}", credentials.token)
}
CredentialsOrApiKey::ApiKey(key) => format!("ApiKey {}", key.id),
},
)
.json(&json!({ "minTrust": options.min_trust, "max": options.max }))
.send()
.await?;
Ok(ok(response).await?.json().await?)
}
pub async fn search(
authorization: &CredentialsOrApiKey,
query: &str,
options: SearchOptions,
) -> Result<Vec<Found>> {
let response = client()
.post(format!("{}/chats/search", crate::get_url()))
.header(
"Authorization",
match authorization {
CredentialsOrApiKey::Credentials(credentials) => {
format!("Token {}", credentials.token)
}
CredentialsOrApiKey::ApiKey(key) => format!("ApiKey {}", key.id),
},
)
.json(&json!({ "query": query, "cursor": options.cursor, "max": options.max }))
.send()
.await?;
Ok(ok(response).await?.json().await?)
}
pub async fn post(authorization: &CredentialsOrApiKey, chat: &str, text: &str) -> Result<()> {
let opened = client()
.post(format!("{}/chat/live/open", crate::parrot::get_url()))
.header(
"Authorization",
match authorization {
CredentialsOrApiKey::Credentials(credentials) => {
format!("Token {}", credentials.token)
}
CredentialsOrApiKey::ApiKey(key) => format!("ApiKey {}", key.id),
},
)
.json(&json!({ "chatId": chat }))
.send()
.await?;
ok(opened).await?;
let response = client()
.post(format!("{}/chat/live/append", crate::parrot::get_url()))
.header(
"Authorization",
match authorization {
CredentialsOrApiKey::Credentials(credentials) => {
format!("Token {}", credentials.token)
}
CredentialsOrApiKey::ApiKey(key) => format!("ApiKey {}", key.id),
},
)
.header("Server", format!("parrot:chat:{chat}"))
.json(&json!({ "role": "USER", "parts": [{ "type": "TEXT", "text": text }] }))
.send()
.await?;
ok(response).await?;
Ok(())
}