1use std::ops::Deref;
2
3use serde::{Deserialize, Serialize};
4use serde_json::{Value, json};
5
6use crate::authentification::CredentialsOrApiKey;
7use crate::error::Result;
8use crate::http::{client, encode, ok};
9use crate::parrot::chat::ChatSummary;
10use crate::parrot::generative::Author;
11
12#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
15#[serde(rename_all = "lowercase")]
16pub enum OwnerKind {
17 Group,
18 Friend,
19 Partnership,
20}
21
22#[derive(Debug, Clone, Serialize, Deserialize)]
24pub struct OwnerGroup {
25 pub id: String,
26 pub name: String,
27}
28
29#[derive(Debug, Clone, Serialize, Deserialize)]
31pub struct Owner {
32 pub kind: OwnerKind,
33 pub id: String,
35 pub name: String,
37 #[serde(default)]
40 pub trust: Option<f64>,
41 #[serde(default, skip_serializing_if = "Option::is_none")]
43 pub group: Option<OwnerGroup>,
44}
45
46#[derive(Debug, Clone, Serialize)]
49pub struct Chat {
50 #[serde(flatten)]
51 pub summary: ChatSummary,
52 pub owner: Owner,
53}
54
55impl Deref for Chat {
56 type Target = ChatSummary;
57
58 fn deref(&self) -> &ChatSummary {
59 &self.summary
60 }
61}
62
63impl Chat {
64 pub fn from_json(json: &Value) -> Option<Chat> {
65 Some(Chat {
66 summary: ChatSummary::from_json(json),
67 owner: serde_json::from_value(json["owner"].clone()).ok()?,
68 })
69 }
70}
71
72impl<'de> Deserialize<'de> for Chat {
73 fn deserialize<D: serde::Deserializer<'de>>(
74 deserializer: D,
75 ) -> std::result::Result<Self, D::Error> {
76 Chat::from_json(&Value::deserialize(deserializer)?)
77 .ok_or_else(|| serde::de::Error::custom("a shared chat needs its owner"))
78 }
79}
80
81#[derive(Debug, Clone, Serialize, Deserialize)]
83pub struct Message {
84 pub position: u32,
85 pub role: String,
86 pub text: String,
87 #[serde(default, skip_serializing_if = "Option::is_none")]
88 pub author: Option<Author>,
89 pub created: i64,
91}
92
93#[derive(Debug, Clone, Serialize, Deserialize)]
95pub struct Unread {
96 pub total: u32,
97 #[serde(default)]
98 pub chats: Vec<Chat>,
99}
100
101#[derive(Debug, Clone, Serialize, Deserialize)]
103pub struct CaughtUpChat {
104 pub id: String,
105 pub name: String,
106 #[serde(default)]
107 pub human: bool,
108 pub owner: Owner,
109 pub updated: i64,
110 #[serde(default)]
111 pub messages: Vec<Message>,
112}
113
114#[derive(Debug, Clone, Serialize, Deserialize)]
115pub struct CaughtUp {
116 #[serde(default)]
117 pub chats: Vec<CaughtUpChat>,
118 pub more: bool,
120 pub unread: u32,
122}
123
124#[derive(Debug, Clone, Serialize, Deserialize)]
126pub struct ChatReference {
127 pub id: String,
128 pub name: String,
129 pub owner: Owner,
130}
131
132#[derive(Debug, Clone, Serialize, Deserialize)]
133pub struct Found {
134 pub chat: ChatReference,
135 pub message: Message,
136}
137
138#[derive(Debug, Clone, Copy, Default)]
140pub struct UnreadOptions {
141 pub min_trust: Option<f64>,
143}
144
145#[derive(Debug, Clone, Copy, Default)]
147pub struct CatchUpOptions {
148 pub min_trust: Option<f64>,
150 pub max: Option<u32>,
152}
153
154#[derive(Debug, Clone, Copy, Default)]
156pub struct SearchOptions {
157 pub cursor: Option<u32>,
159 pub max: Option<u32>,
161}
162
163pub async fn list(authorization: &CredentialsOrApiKey) -> Result<Vec<Chat>> {
167 let response = client()
168 .get(format!("{}/chats/shared", crate::get_url()))
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 let rows: Vec<Value> = ok(response).await?.json().await?;
181 Ok(rows.iter().filter_map(Chat::from_json).collect())
182}
183
184pub async fn unread(authorization: &CredentialsOrApiKey, options: UnreadOptions) -> Result<Unread> {
187 let query = options
188 .min_trust
189 .map(|min_trust| format!("?minTrust={}", encode(&min_trust.to_string())))
190 .unwrap_or_default();
191 let response = client()
192 .get(format!("{}/chats/unread{}", crate::get_url(), query))
193 .header(
194 "Authorization",
195 match authorization {
196 CredentialsOrApiKey::Credentials(credentials) => {
197 format!("Token {}", credentials.token)
198 }
199 CredentialsOrApiKey::ApiKey(key) => format!("ApiKey {}", key.id),
200 },
201 )
202 .send()
203 .await?;
204 let json: Value = ok(response).await?.json().await?;
205 Ok(Unread {
206 total: json["total"].as_u64().unwrap_or_default() as u32,
207 chats: json["chats"]
208 .as_array()
209 .into_iter()
210 .flatten()
211 .filter_map(Chat::from_json)
212 .collect(),
213 })
214}
215
216pub async fn catch_up(
221 authorization: &CredentialsOrApiKey,
222 options: CatchUpOptions,
223) -> Result<CaughtUp> {
224 let response = client()
225 .post(format!("{}/chats/catch-up", crate::get_url()))
226 .header(
227 "Authorization",
228 match authorization {
229 CredentialsOrApiKey::Credentials(credentials) => {
230 format!("Token {}", credentials.token)
231 }
232 CredentialsOrApiKey::ApiKey(key) => format!("ApiKey {}", key.id),
233 },
234 )
235 .json(&json!({ "minTrust": options.min_trust, "max": options.max }))
236 .send()
237 .await?;
238 Ok(ok(response).await?.json().await?)
239}
240
241pub async fn search(
245 authorization: &CredentialsOrApiKey,
246 query: &str,
247 options: SearchOptions,
248) -> Result<Vec<Found>> {
249 let response = client()
250 .post(format!("{}/chats/search", crate::get_url()))
251 .header(
252 "Authorization",
253 match authorization {
254 CredentialsOrApiKey::Credentials(credentials) => {
255 format!("Token {}", credentials.token)
256 }
257 CredentialsOrApiKey::ApiKey(key) => format!("ApiKey {}", key.id),
258 },
259 )
260 .json(&json!({ "query": query, "cursor": options.cursor, "max": options.max }))
261 .send()
262 .await?;
263 Ok(ok(response).await?.json().await?)
264}
265
266pub async fn post(authorization: &CredentialsOrApiKey, chat: &str, text: &str) -> Result<()> {
271 let opened = client()
272 .post(format!("{}/chat/live/open", crate::parrot::get_url()))
273 .header(
274 "Authorization",
275 match authorization {
276 CredentialsOrApiKey::Credentials(credentials) => {
277 format!("Token {}", credentials.token)
278 }
279 CredentialsOrApiKey::ApiKey(key) => format!("ApiKey {}", key.id),
280 },
281 )
282 .json(&json!({ "chatId": chat }))
283 .send()
284 .await?;
285 ok(opened).await?;
286 let response = client()
287 .post(format!("{}/chat/live/append", crate::parrot::get_url()))
288 .header(
289 "Authorization",
290 match authorization {
291 CredentialsOrApiKey::Credentials(credentials) => {
292 format!("Token {}", credentials.token)
293 }
294 CredentialsOrApiKey::ApiKey(key) => format!("ApiKey {}", key.id),
295 },
296 )
297 .header("Server", format!("parrot:chat:{chat}"))
298 .json(&json!({ "role": "USER", "parts": [{ "type": "TEXT", "text": text }] }))
299 .send()
300 .await?;
301 ok(response).await?;
302 Ok(())
303}