Skip to main content

fauna_api/
chats.rs

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/// Whose chat it is: one of your groups, a friendship, or a partnership of one
13/// of your groups.
14#[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/// For a partnership: your group in it.
23#[derive(Debug, Clone, Serialize, Deserialize)]
24pub struct OwnerGroup {
25    pub id: String,
26    pub name: String,
27}
28
29/// Who a chat belongs to, and how much you trust it.
30#[derive(Debug, Clone, Serialize, Deserialize)]
31pub struct Owner {
32    pub kind: OwnerKind,
33    /// The group, friendship or partnership id.
34    pub id: String,
35    /// The group's name, your friend's name, or the partner group's name.
36    pub name: String,
37    /// Your trust in your friend, or your group's trust in the partner group, in
38    /// [0, 1). `None` for your own groups, which always count.
39    #[serde(default)]
40    pub trust: Option<f64>,
41    /// For a partnership: your group in it.
42    #[serde(default, skip_serializing_if = "Option::is_none")]
43    pub group: Option<OwnerGroup>,
44}
45
46/// A chat you share with others: the Parrot chat, and whose it is. Signed in with an API key,
47/// its `unread` is the key's own place.
48#[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/// A message as plain text: mentions as names, files as `[file: name]`.
82#[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    /// Milliseconds since the epoch.
90    pub created: i64,
91}
92
93/// What you haven't read, in chats that pass a trust threshold.
94#[derive(Debug, Clone, Serialize, Deserialize)]
95pub struct Unread {
96    pub total: u32,
97    #[serde(default)]
98    pub chats: Vec<Chat>,
99}
100
101/// A chat in a catch up, with what you hadn't read, oldest first.
102#[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    /// More unread is waiting: catch up again for the next batch.
119    pub more: bool,
120    /// Unread left in chats that pass, after this batch.
121    pub unread: u32,
122}
123
124/// The chat a search found a message in.
125#[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/// The `options` argument of `unread`.
139#[derive(Debug, Clone, Copy, Default)]
140pub struct UnreadOptions {
141    /// Chats you trust at least this much, in [0, 1]. Defaults to 0.1.
142    pub min_trust: Option<f64>,
143}
144
145/// The `options` argument of `catch_up`.
146#[derive(Debug, Clone, Copy, Default)]
147pub struct CatchUpOptions {
148    /// Chats you trust at least this much, in [0, 1]. Defaults to 0.1.
149    pub min_trust: Option<f64>,
150    /// Most messages to return, 1 to 500. Defaults to 100.
151    pub max: Option<u32>,
152}
153
154/// The `options` argument of `search`.
155#[derive(Debug, Clone, Copy, Default)]
156pub struct SearchOptions {
157    /// Matches to skip from the newest.
158    pub cursor: Option<u32>,
159    /// Page size, 1 to 100. Defaults to 20.
160    pub max: Option<u32>,
161}
162
163/// Every chat you share with others, newest first: your groups', your friends'
164/// and your groups' partnerships', each with its owner, your trust in it and
165/// what you haven't read.
166pub 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
184/// What you haven't read in chats you trust at least `min_trust` (default 0.1).
185/// Your own groups' chats always count.
186pub 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
216/// Everything you haven't read in chats you trust at least `min_trust` (default
217/// 0.1), oldest first within each chat, at most `max` messages (default 100),
218/// read as it's returned. Call again while `more` is true. A reader that never
219/// opened a chat starts with its newest 20.
220pub 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
241/// Messages holding every word of `query` across every chat you share with
242/// others, newest first. `cursor` skips that many matches from the newest; `max`
243/// is the page size (default 20).
244pub 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
266/// Post `text` in a chat, as you. Everyone in it sees it live, its webhooks fire
267/// and it counts toward memories, like any message. Signed in with an API key,
268/// the message is authored by the key, by its name, and never moves trust. In a chat
269/// that isn't people only, it starts a model reply as any message does.
270pub 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}