1use chrono::{DateTime, Utc};
2use serde::{Deserialize, Serialize};
3use serde_json::{Map, Value, json};
4
5use super::generative::{Content, File as FilePart, Function, Part};
6use super::room::RoomMessage;
7use crate::authentification::{Credentials, CredentialsOrApiKey, Profile};
8use crate::billing::PageQuery;
9use crate::drive::{self, DriveAuthorization};
10use crate::error::Result;
11use crate::http::{client, ok};
12
13#[derive(Debug, Clone, PartialEq, Eq)]
16pub enum ChatTarget {
17 Code { code: String },
18 Reference { reference: String },
19}
20
21#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
23#[serde(rename_all = "camelCase")]
24pub struct MovedChat {
25 pub chat_id: String,
26 pub group_id: String,
27}
28
29pub async fn move_chat_to_group(
30 credentials: &Credentials,
31 chat_id: &str,
32 group_id: &str,
33) -> Result<MovedChat> {
34 let response = client()
35 .post(format!("{}/chat/move", super::get_url()))
36 .header("Authorization", format!("Token {}", credentials.token))
37 .json(&json!({ "chatId": chat_id, "groupId": group_id }))
38 .send()
39 .await?;
40 Ok(ok(response).await?.json().await?)
41}
42
43#[derive(Debug, Clone, Default)]
45pub struct OpenRoomOptions {
46 pub share: Option<bool>,
47 pub write: Option<bool>,
48}
49
50#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
52#[serde(rename_all = "camelCase")]
53pub struct OpenedRoom {
54 pub reference: String,
55 pub room_id: String,
56 #[serde(default, skip_serializing_if = "Option::is_none")]
57 pub code: Option<String>,
58}
59
60pub async fn open_room(
66 authorization: &CredentialsOrApiKey,
67 chat_id: &str,
68 options: OpenRoomOptions,
69) -> Result<OpenedRoom> {
70 let mut body = Map::new();
71 body.insert("chatId".to_string(), Value::from(chat_id));
72 insert(&mut body, "share", options.share.map(Value::from));
73 insert(&mut body, "write", options.write.map(Value::from));
74 let response = client()
75 .post(format!("{}/chat/live/open", super::get_url()))
76 .header(
77 "Authorization",
78 match authorization {
79 CredentialsOrApiKey::Credentials(credentials) => {
80 format!("Token {}", credentials.token)
81 }
82 CredentialsOrApiKey::ApiKey(key) => format!("ApiKey {}", key.id),
83 },
84 )
85 .json(&body)
86 .send()
87 .await?;
88 let json: Value = ok(response).await?.json().await?;
89 Ok(OpenedRoom {
90 reference: text(&json["reference"]),
91 room_id: text(&json["roomId"]),
92 code: json["code"].as_str().map(str::to_string),
93 })
94}
95
96fn insert(body: &mut Map<String, Value>, key: &str, value: Option<Value>) {
97 if let Some(value) = value {
98 body.insert(key.to_string(), value);
99 }
100}
101
102fn text(value: &Value) -> String {
103 match value {
104 Value::String(value) => value.clone(),
105 Value::Null => String::new(),
106 value => value.to_string(),
107 }
108}
109
110pub(crate) fn room_parts(
112 parts: &Value,
113 authorization: &CredentialsOrApiKey,
114 target: &ChatTarget,
115) -> Vec<Part> {
116 parts
117 .as_array()
118 .into_iter()
119 .flatten()
120 .filter_map(|part| {
121 if part["type"] != "FILE" {
122 return Part::from_json(part);
123 }
124 let mut meta = part.clone();
125 meta["name"] = Value::from(part["name"].as_str().unwrap_or("file"));
126 meta["contentType"] = Value::from(
127 part["contentType"]
128 .as_str()
129 .unwrap_or("application/octet-stream"),
130 );
131 let nonempty = |key: &str| part[key].as_str().filter(|value| !value.is_empty());
132 let authorization = authorization.clone();
133 let file_authorization = if let Some(access_code) = nonempty("accessCode") {
134 DriveAuthorization::AccessCode {
135 authorization,
136 access_code: access_code.to_string(),
137 }
138 } else if let Some(path) = nonempty("path") {
139 DriveAuthorization::Path {
140 authorization,
141 path: path.to_string(),
142 group: part["group"].as_str().map(str::to_string),
143 }
144 } else if let ChatTarget::Code { code } = target {
145 DriveAuthorization::AccessCode {
146 authorization,
147 access_code: code.clone(),
148 }
149 } else if let Some(reference) = nonempty("ref") {
150 DriveAuthorization::Path {
151 authorization,
152 path: reference.to_string(),
153 group: None,
154 }
155 } else {
156 DriveAuthorization::AccessCode {
157 authorization,
158 access_code: String::new(),
159 }
160 };
161 Some(Part::File(FilePart {
162 file: drive::File::from_json(&meta, file_authorization),
163 }))
164 })
165 .collect()
166}
167
168fn target_headers(
169 request: reqwest::RequestBuilder,
170 target: &ChatTarget,
171) -> reqwest::RequestBuilder {
172 match target {
173 ChatTarget::Code { code } => request.header("Access-Code", code),
174 ChatTarget::Reference { reference } => request.header("Server", reference),
175 }
176}
177
178pub async fn page_messages(
181 authorization: &CredentialsOrApiKey,
182 target: &ChatTarget,
183 query: PageQuery,
184) -> Result<Vec<RoomMessage>> {
185 let request = client()
186 .get(format!(
187 "{}/chat/live/messages?cursor={}&max={}",
188 super::get_url(),
189 query.cursor,
190 query.max
191 ))
192 .header(
193 "Authorization",
194 match authorization {
195 CredentialsOrApiKey::Credentials(credentials) => {
196 format!("Token {}", credentials.token)
197 }
198 CredentialsOrApiKey::ApiKey(key) => format!("ApiKey {}", key.id),
199 },
200 );
201 let response = target_headers(request, target).send().await?;
202 let json: Value = ok(response).await?.json().await?;
203 Ok(json
204 .as_array()
205 .into_iter()
206 .flatten()
207 .map(|message| RoomMessage::from_json(message, authorization, target))
208 .collect())
209}
210
211#[derive(Debug, Clone, PartialEq, Eq)]
214pub enum AppendResult {
215 Sent { id: Option<String> },
216 Queued { queue_id: Option<String> },
217}
218
219impl AppendResult {
220 pub(crate) fn from_json(json: &Value) -> AppendResult {
221 if json["queued"] == true {
222 AppendResult::Queued {
223 queue_id: json["queueId"].as_str().map(str::to_string),
224 }
225 } else {
226 AppendResult::Sent {
227 id: json["id"].as_str().map(str::to_string),
228 }
229 }
230 }
231}
232
233#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
236#[serde(untagged)]
237#[allow(clippy::large_enum_variant)]
238pub enum FunctionOrFunctions {
239 Function(Function),
240 Functions(Vec<Function>),
241}
242
243#[derive(Debug, Clone, Default)]
245pub struct AppendOptions {
246 pub reply_to: Option<String>,
247 pub model: Option<String>,
248 pub reasoning: Option<String>,
249 pub tools: Option<FunctionOrFunctions>,
251 pub seat: Option<String>,
253}
254
255pub async fn append_room_message(
262 authorization: &CredentialsOrApiKey,
263 target: &ChatTarget,
264 message: &Content,
265 options: AppendOptions,
266) -> Result<AppendResult> {
267 let serialized_parts: Vec<Value> = message.parts.iter().map(Part::wire).collect();
268
269 let mut body = Map::new();
270 body.insert("role".to_string(), serde_json::to_value(message.role)?);
271 body.insert("parts".to_string(), Value::Array(serialized_parts));
272 insert(&mut body, "replyTo", options.reply_to.map(Value::from));
273 insert(&mut body, "model", options.model.map(Value::from));
274 insert(&mut body, "reasoning", options.reasoning.map(Value::from));
275 insert(
276 &mut body,
277 "tools",
278 options.tools.map(serde_json::to_value).transpose()?,
279 );
280 insert(&mut body, "seat", options.seat.map(Value::from));
281
282 let request = client()
283 .post(format!("{}/chat/live/append", super::get_url()))
284 .header(
285 "Authorization",
286 match authorization {
287 CredentialsOrApiKey::Credentials(credentials) => {
288 format!("Token {}", credentials.token)
289 }
290 CredentialsOrApiKey::ApiKey(key) => format!("ApiKey {}", key.id),
291 },
292 );
293 let response = target_headers(request, target).json(&body).send().await?;
294 let response = ok(response).await?;
295 let json: Value = response.json().await.unwrap_or(Value::Null);
296 Ok(AppendResult::from_json(&json))
297}
298
299#[derive(Debug, Clone)]
301pub struct Attachment {
302 pub file: drive::File,
303 pub chat: String,
305 pub r#ref: String,
306 pub message: Option<u32>,
308 pub author: Option<Profile>,
309 pub created_at: DateTime<Utc>,
310}
311
312impl Attachment {
313 pub fn from_json(json: &Value, authorization: &CredentialsOrApiKey) -> Attachment {
314 let name = json["name"]
315 .as_str()
316 .or_else(|| json["ref"].as_str())
317 .unwrap_or("file");
318 let meta = json!({
319 "name": name,
320 "contentType": json["contentType"].as_str().unwrap_or("application/octet-stream"),
321 "contentLength": json["contentLength"].as_f64().unwrap_or_default(),
322 });
323 Attachment {
324 file: drive::File::from_json(
325 &meta,
326 DriveAuthorization::AccessCode {
327 authorization: authorization.clone(),
328 access_code: text(&json["accessCode"]),
329 },
330 ),
331 chat: text(&json["chat"]),
332 r#ref: text(&json["ref"]),
333 message: json["message"].as_f64().map(|message| message as u32),
334 author: if json["author"].is_object() {
335 serde_json::from_value(json["author"].clone()).ok()
336 } else {
337 None
338 },
339 created_at: crate::tickets::parse_date(&json["created"]).unwrap_or_else(Utc::now),
340 }
341 }
342}
343
344pub async fn list_room_attachments(
346 authorization: &CredentialsOrApiKey,
347 target: &ChatTarget,
348) -> Result<Vec<Attachment>> {
349 let request = client()
350 .get(format!("{}/chat/live/attachments", super::get_url()))
351 .header(
352 "Authorization",
353 match authorization {
354 CredentialsOrApiKey::Credentials(credentials) => {
355 format!("Token {}", credentials.token)
356 }
357 CredentialsOrApiKey::ApiKey(key) => format!("ApiKey {}", key.id),
358 },
359 );
360 let response = target_headers(request, target).send().await?;
361 let json: Value = ok(response).await?.json().await?;
362 Ok(json
363 .as_array()
364 .into_iter()
365 .flatten()
366 .map(|row| Attachment::from_json(row, authorization))
367 .collect())
368}
369
370pub async fn set_room_repository(
373 authorization: &CredentialsOrApiKey,
374 target: &ChatTarget,
375 repository: Option<u64>,
376) -> Result<()> {
377 let request = client()
378 .post(format!("{}/chat/repository", super::get_url()))
379 .header(
380 "Authorization",
381 match authorization {
382 CredentialsOrApiKey::Credentials(credentials) => {
383 format!("Token {}", credentials.token)
384 }
385 CredentialsOrApiKey::ApiKey(key) => format!("ApiKey {}", key.id),
386 },
387 );
388 let response = target_headers(request, target)
389 .json(&json!({ "repository": repository }))
390 .send()
391 .await?;
392 ok(response).await?;
393 Ok(())
394}
395
396pub async fn unqueue_room_message(
400 authorization: &CredentialsOrApiKey,
401 target: &ChatTarget,
402 queue_id: &str,
403) -> Result<()> {
404 let request = client()
405 .post(format!("{}/chat/live/unqueue", super::get_url()))
406 .header(
407 "Authorization",
408 match authorization {
409 CredentialsOrApiKey::Credentials(credentials) => {
410 format!("Token {}", credentials.token)
411 }
412 CredentialsOrApiKey::ApiKey(key) => format!("ApiKey {}", key.id),
413 },
414 );
415 let response = target_headers(request, target)
416 .json(&json!({ "queueId": queue_id }))
417 .send()
418 .await?;
419 ok(response).await?;
420 Ok(())
421}
422
423#[derive(Debug, Clone, Default)]
425pub struct SteerOptions {
426 pub queue_id: Option<String>,
427 pub all: Option<bool>,
428 pub stop: Option<bool>,
429 pub model: Option<String>,
430 pub reasoning: Option<String>,
431}
432
433pub async fn steer_room(
440 authorization: &CredentialsOrApiKey,
441 target: &ChatTarget,
442 options: SteerOptions,
443) -> Result<()> {
444 let mut body = Map::new();
445 insert(&mut body, "queueId", options.queue_id.map(Value::from));
446 insert(&mut body, "all", options.all.map(Value::from));
447 insert(&mut body, "stop", options.stop.map(Value::from));
448 insert(&mut body, "model", options.model.map(Value::from));
449 insert(&mut body, "reasoning", options.reasoning.map(Value::from));
450 let request = client()
451 .post(format!("{}/chat/live/steer", super::get_url()))
452 .header(
453 "Authorization",
454 match authorization {
455 CredentialsOrApiKey::Credentials(credentials) => {
456 format!("Token {}", credentials.token)
457 }
458 CredentialsOrApiKey::ApiKey(key) => format!("ApiKey {}", key.id),
459 },
460 );
461 let response = target_headers(request, target).json(&body).send().await?;
462 ok(response).await?;
463 Ok(())
464}
465
466#[cfg(test)]
467mod tests {
468 use super::AppendResult;
469 use serde_json::json;
470
471 #[test]
472 fn append_results_say_whether_the_send_queued() {
473 assert_eq!(
474 AppendResult::from_json(&json!({ "queued": false, "id": "42" })),
475 AppendResult::Sent {
476 id: Some("42".to_string())
477 }
478 );
479 assert_eq!(
480 AppendResult::from_json(&json!({ "queued": true, "queueId": "7" })),
481 AppendResult::Queued {
482 queue_id: Some("7".to_string())
483 }
484 );
485 assert_eq!(
486 AppendResult::from_json(&json!({})),
487 AppendResult::Sent { id: None }
488 );
489 }
490}