Skip to main content

fauna_api/
chats.rs

1use serde::{Deserialize, Serialize};
2use serde_json::json;
3
4use crate::authentification::{CredentialsOrApiKey, Profile};
5use crate::error::Result;
6use crate::http::{client, encode, ok};
7use crate::parrot::chat::LastMessage;
8
9/// Whose chat it is: one of your groups, a friendship, or a partnership of one
10/// of your groups.
11#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
12#[serde(rename_all = "lowercase")]
13pub enum OwnerKind {
14    Group,
15    Friend,
16    Partnership,
17}
18
19/// For a partnership: your group in it.
20#[derive(Debug, Clone, Serialize, Deserialize)]
21pub struct OwnerGroup {
22    pub id: String,
23    pub name: String,
24}
25
26/// Who a chat belongs to, and how much you trust it.
27#[derive(Debug, Clone, Serialize, Deserialize)]
28pub struct Owner {
29    pub kind: OwnerKind,
30    /// The group, friendship or partnership id.
31    pub id: String,
32    /// The group's name, your friend's name, or the partner group's name.
33    pub name: String,
34    /// Your trust in your friend, or your group's trust in the partner group, in
35    /// [0, 1). `None` for your own groups, which always count.
36    #[serde(default)]
37    pub trust: Option<f64>,
38    /// For a partnership: your group in it.
39    #[serde(default, skip_serializing_if = "Option::is_none")]
40    pub group: Option<OwnerGroup>,
41}
42
43/// A chat you share with others.
44#[derive(Debug, Clone, Serialize, Deserialize)]
45pub struct Chat {
46    pub id: String,
47    pub name: String,
48    /// People only: sends never start a model reply.
49    #[serde(default)]
50    pub human: bool,
51    pub owner: Owner,
52    /// Messages you haven't read. Signed in with an API key, the key keeps its
53    /// own place.
54    #[serde(default)]
55    pub unread: u32,
56    /// Milliseconds since the epoch.
57    pub updated: i64,
58    #[serde(default)]
59    pub last: Option<LastMessage>,
60}
61
62/// A message as plain text: mentions as names, files as `[file: name]`.
63#[derive(Debug, Clone, Serialize, Deserialize)]
64pub struct Message {
65    pub position: u32,
66    pub role: String,
67    pub text: String,
68    #[serde(default, skip_serializing_if = "Option::is_none")]
69    pub author: Option<Profile>,
70    /// The name of the API key an agent posted it with.
71    #[serde(default, skip_serializing_if = "Option::is_none")]
72    pub via: Option<String>,
73    /// Milliseconds since the epoch.
74    pub created: i64,
75}
76
77/// What you haven't read, in chats that pass a trust threshold.
78#[derive(Debug, Clone, Serialize, Deserialize)]
79pub struct Unread {
80    pub total: u32,
81    #[serde(default)]
82    pub chats: Vec<Chat>,
83}
84
85/// A chat in a catch up, with what you hadn't read, oldest first.
86#[derive(Debug, Clone, Serialize, Deserialize)]
87pub struct CaughtUpChat {
88    pub id: String,
89    pub name: String,
90    #[serde(default)]
91    pub human: bool,
92    pub owner: Owner,
93    pub updated: i64,
94    #[serde(default)]
95    pub messages: Vec<Message>,
96}
97
98#[derive(Debug, Clone, Serialize, Deserialize)]
99pub struct CaughtUp {
100    #[serde(default)]
101    pub chats: Vec<CaughtUpChat>,
102    /// More unread is waiting: catch up again for the next batch.
103    pub more: bool,
104    /// Unread left in chats that pass, after this batch.
105    pub unread: u32,
106}
107
108/// The chat a search found a message in.
109#[derive(Debug, Clone, Serialize, Deserialize)]
110pub struct ChatReference {
111    pub id: String,
112    pub name: String,
113    pub owner: Owner,
114}
115
116#[derive(Debug, Clone, Serialize, Deserialize)]
117pub struct Found {
118    pub chat: ChatReference,
119    pub message: Message,
120}
121
122/// The `options` argument of `unread`.
123#[derive(Debug, Clone, Copy, Default)]
124pub struct UnreadOptions {
125    /// Chats you trust at least this much, in [0, 1]. Defaults to 0.1.
126    pub min_trust: Option<f64>,
127}
128
129/// The `options` argument of `catch_up`.
130#[derive(Debug, Clone, Copy, Default)]
131pub struct CatchUpOptions {
132    /// Chats you trust at least this much, in [0, 1]. Defaults to 0.1.
133    pub min_trust: Option<f64>,
134    /// Most messages to return, 1 to 500. Defaults to 100.
135    pub max: Option<u32>,
136}
137
138/// The `options` argument of `search`.
139#[derive(Debug, Clone, Copy, Default)]
140pub struct SearchOptions {
141    /// Matches to skip from the newest.
142    pub cursor: Option<u32>,
143    /// Page size, 1 to 100. Defaults to 20.
144    pub max: Option<u32>,
145}
146
147/// Every chat you share with others, newest first: your groups', your friends'
148/// and your groups' partnerships', each with its owner, your trust in it and
149/// what you haven't read.
150pub async fn list(authorization: &CredentialsOrApiKey) -> Result<Vec<Chat>> {
151    let response = client()
152        .get(format!("{}/chats/shared", crate::get_url()))
153        .header(
154            "Authorization",
155            match authorization {
156                CredentialsOrApiKey::Credentials(credentials) => {
157                    format!("Token {}", credentials.token)
158                }
159                CredentialsOrApiKey::ApiKey(key) => format!("ApiKey {}", key.id),
160            },
161        )
162        .send()
163        .await?;
164    Ok(ok(response).await?.json().await?)
165}
166
167/// What you haven't read in chats you trust at least `min_trust` (default 0.1).
168/// Your own groups' chats always count.
169pub async fn unread(authorization: &CredentialsOrApiKey, options: UnreadOptions) -> Result<Unread> {
170    let query = options
171        .min_trust
172        .map(|min_trust| format!("?minTrust={}", encode(&min_trust.to_string())))
173        .unwrap_or_default();
174    let response = client()
175        .get(format!("{}/chats/unread{}", crate::get_url(), query))
176        .header(
177            "Authorization",
178            match authorization {
179                CredentialsOrApiKey::Credentials(credentials) => {
180                    format!("Token {}", credentials.token)
181                }
182                CredentialsOrApiKey::ApiKey(key) => format!("ApiKey {}", key.id),
183            },
184        )
185        .send()
186        .await?;
187    Ok(ok(response).await?.json().await?)
188}
189
190/// Everything you haven't read in chats you trust at least `min_trust` (default
191/// 0.1), oldest first within each chat, at most `max` messages (default 100),
192/// read as it's returned. Call again while `more` is true. A reader that never
193/// opened a chat starts with its newest 20.
194pub async fn catch_up(
195    authorization: &CredentialsOrApiKey,
196    options: CatchUpOptions,
197) -> Result<CaughtUp> {
198    let response = client()
199        .post(format!("{}/chats/catch-up", crate::get_url()))
200        .header(
201            "Authorization",
202            match authorization {
203                CredentialsOrApiKey::Credentials(credentials) => {
204                    format!("Token {}", credentials.token)
205                }
206                CredentialsOrApiKey::ApiKey(key) => format!("ApiKey {}", key.id),
207            },
208        )
209        .json(&json!({ "minTrust": options.min_trust, "max": options.max }))
210        .send()
211        .await?;
212    Ok(ok(response).await?.json().await?)
213}
214
215/// Messages holding every word of `query` across every chat you share with
216/// others, newest first. `cursor` skips that many matches from the newest; `max`
217/// is the page size (default 20).
218pub async fn search(
219    authorization: &CredentialsOrApiKey,
220    query: &str,
221    options: SearchOptions,
222) -> Result<Vec<Found>> {
223    let response = client()
224        .post(format!("{}/chats/search", crate::get_url()))
225        .header(
226            "Authorization",
227            match authorization {
228                CredentialsOrApiKey::Credentials(credentials) => {
229                    format!("Token {}", credentials.token)
230                }
231                CredentialsOrApiKey::ApiKey(key) => format!("ApiKey {}", key.id),
232            },
233        )
234        .json(&json!({ "query": query, "cursor": options.cursor, "max": options.max }))
235        .send()
236        .await?;
237    Ok(ok(response).await?.json().await?)
238}
239
240/// Post `text` in a chat, as you. Everyone in it sees it live, its webhooks fire
241/// and it counts toward memories, like any message. Signed in with an API key,
242/// the message records the key's name (`via`) and never moves trust. In a chat
243/// that isn't people only, it starts a model reply as any message does.
244pub async fn post(authorization: &CredentialsOrApiKey, chat: &str, text: &str) -> Result<()> {
245    let opened = client()
246        .post(format!("{}/chat/live/open", crate::parrot::get_url()))
247        .header(
248            "Authorization",
249            match authorization {
250                CredentialsOrApiKey::Credentials(credentials) => {
251                    format!("Token {}", credentials.token)
252                }
253                CredentialsOrApiKey::ApiKey(key) => format!("ApiKey {}", key.id),
254            },
255        )
256        .json(&json!({ "chatId": chat }))
257        .send()
258        .await?;
259    ok(opened).await?;
260    let response = client()
261        .post(format!("{}/chat/live/append", crate::parrot::get_url()))
262        .header(
263            "Authorization",
264            match authorization {
265                CredentialsOrApiKey::Credentials(credentials) => {
266                    format!("Token {}", credentials.token)
267                }
268                CredentialsOrApiKey::ApiKey(key) => format!("ApiKey {}", key.id),
269            },
270        )
271        .header("Server", format!("parrot:chat:{chat}"))
272        .json(&json!({ "role": "USER", "parts": [{ "type": "TEXT", "text": text }] }))
273        .send()
274        .await?;
275    ok(response).await?;
276    Ok(())
277}