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}
48
49#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
51#[serde(rename_all = "camelCase")]
52pub struct OpenedRoom {
53 pub reference: String,
54 pub room_id: String,
55 #[serde(default, skip_serializing_if = "Option::is_none")]
56 pub code: Option<String>,
57}
58
59pub async fn open_room(
64 authorization: &CredentialsOrApiKey,
65 chat_id: &str,
66 options: OpenRoomOptions,
67) -> Result<OpenedRoom> {
68 let mut body = Map::new();
69 body.insert("chatId".to_string(), Value::from(chat_id));
70 insert(&mut body, "share", options.share.map(Value::from));
71 let response = client()
72 .post(format!("{}/chat/live/open", super::get_url()))
73 .header(
74 "Authorization",
75 match authorization {
76 CredentialsOrApiKey::Credentials(credentials) => {
77 format!("Token {}", credentials.token)
78 }
79 CredentialsOrApiKey::ApiKey(key) => format!("ApiKey {}", key.id),
80 },
81 )
82 .json(&body)
83 .send()
84 .await?;
85 let json: Value = ok(response).await?.json().await?;
86 Ok(OpenedRoom {
87 reference: text(&json["reference"]),
88 room_id: text(&json["roomId"]),
89 code: json["code"].as_str().map(str::to_string),
90 })
91}
92
93fn insert(body: &mut Map<String, Value>, key: &str, value: Option<Value>) {
94 if let Some(value) = value {
95 body.insert(key.to_string(), value);
96 }
97}
98
99fn text(value: &Value) -> String {
100 match value {
101 Value::String(value) => value.clone(),
102 Value::Null => String::new(),
103 value => value.to_string(),
104 }
105}
106
107pub(crate) fn room_parts(
109 parts: &Value,
110 authorization: &CredentialsOrApiKey,
111 target: &ChatTarget,
112) -> Vec<Part> {
113 parts
114 .as_array()
115 .into_iter()
116 .flatten()
117 .filter_map(|part| {
118 if part["type"] != "FILE" {
119 return Part::from_json(part);
120 }
121 let mut meta = part.clone();
122 meta["name"] = Value::from(part["name"].as_str().unwrap_or("file"));
123 meta["contentType"] = Value::from(
124 part["contentType"]
125 .as_str()
126 .unwrap_or("application/octet-stream"),
127 );
128 let nonempty = |key: &str| part[key].as_str().filter(|value| !value.is_empty());
129 let authorization = authorization.clone();
130 let file_authorization = if let Some(access_code) = nonempty("accessCode") {
131 DriveAuthorization::AccessCode {
132 authorization,
133 access_code: access_code.to_string(),
134 }
135 } else if let Some(path) = nonempty("path") {
136 DriveAuthorization::Path {
137 authorization,
138 path: path.to_string(),
139 group: part["group"].as_str().map(str::to_string),
140 }
141 } else if let ChatTarget::Code { code } = target {
142 DriveAuthorization::AccessCode {
143 authorization,
144 access_code: code.clone(),
145 }
146 } else if let Some(reference) = nonempty("ref") {
147 DriveAuthorization::Path {
148 authorization,
149 path: reference.to_string(),
150 group: None,
151 }
152 } else {
153 DriveAuthorization::AccessCode {
154 authorization,
155 access_code: String::new(),
156 }
157 };
158 Some(Part::File(FilePart {
159 file: drive::File::from_json(&meta, file_authorization),
160 }))
161 })
162 .collect()
163}
164
165fn target_headers(
166 request: reqwest::RequestBuilder,
167 target: &ChatTarget,
168) -> reqwest::RequestBuilder {
169 match target {
170 ChatTarget::Code { code } => request.header("Access-Code", code),
171 ChatTarget::Reference { reference } => request.header("Server", reference),
172 }
173}
174
175pub async fn page_messages(
178 authorization: &CredentialsOrApiKey,
179 target: &ChatTarget,
180 query: PageQuery,
181) -> Result<Vec<RoomMessage>> {
182 let request = client()
183 .get(format!(
184 "{}/chat/live/messages?cursor={}&max={}",
185 super::get_url(),
186 query.cursor,
187 query.max
188 ))
189 .header(
190 "Authorization",
191 match authorization {
192 CredentialsOrApiKey::Credentials(credentials) => {
193 format!("Token {}", credentials.token)
194 }
195 CredentialsOrApiKey::ApiKey(key) => format!("ApiKey {}", key.id),
196 },
197 );
198 let response = target_headers(request, target).send().await?;
199 let json: Value = ok(response).await?.json().await?;
200 Ok(json
201 .as_array()
202 .into_iter()
203 .flatten()
204 .map(|message| RoomMessage::from_json(message, authorization, target))
205 .collect())
206}
207
208#[derive(Debug, Clone, PartialEq, Eq)]
211pub enum AppendResult {
212 Sent { id: Option<String> },
213 Queued { queue_id: Option<String> },
214}
215
216impl AppendResult {
217 pub(crate) fn from_json(json: &Value) -> AppendResult {
218 if json["queued"] == true {
219 AppendResult::Queued {
220 queue_id: json["queueId"].as_str().map(str::to_string),
221 }
222 } else {
223 AppendResult::Sent {
224 id: json["id"].as_str().map(str::to_string),
225 }
226 }
227 }
228}
229
230#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
233#[serde(untagged)]
234#[allow(clippy::large_enum_variant)]
235pub enum FunctionOrFunctions {
236 Function(Function),
237 Functions(Vec<Function>),
238}
239
240#[derive(Debug, Clone, Default)]
242pub struct AppendOptions {
243 pub reply_to: Option<String>,
244 pub model: Option<String>,
245 pub reasoning: Option<String>,
246 pub time_zone: Option<String>,
248 pub tools: Option<FunctionOrFunctions>,
250 pub seat: Option<String>,
252}
253
254pub async fn append_room_message(
261 authorization: &CredentialsOrApiKey,
262 target: &ChatTarget,
263 message: &Content,
264 options: AppendOptions,
265) -> Result<AppendResult> {
266 let serialized_parts: Vec<Value> = message.parts.iter().map(Part::wire).collect();
267
268 let mut body = Map::new();
269 body.insert("role".to_string(), serde_json::to_value(message.role)?);
270 body.insert("parts".to_string(), Value::Array(serialized_parts));
271 insert(&mut body, "replyTo", options.reply_to.map(Value::from));
272 insert(&mut body, "model", options.model.map(Value::from));
273 insert(&mut body, "reasoning", options.reasoning.map(Value::from));
274 insert(&mut body, "timeZone", options.time_zone.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 set_room_inbox(
401 authorization: &CredentialsOrApiKey,
402 target: &ChatTarget,
403 inbox: Option<&str>,
404) -> Result<()> {
405 let request = client()
406 .post(format!("{}/chat/inbox", super::get_url()))
407 .header(
408 "Authorization",
409 match authorization {
410 CredentialsOrApiKey::Credentials(credentials) => {
411 format!("Token {}", credentials.token)
412 }
413 CredentialsOrApiKey::ApiKey(key) => format!("ApiKey {}", key.id),
414 },
415 );
416 let response = target_headers(request, target)
417 .json(&json!({ "inbox": inbox }))
418 .send()
419 .await?;
420 ok(response).await?;
421 Ok(())
422}
423
424pub async fn unqueue_room_message(
428 authorization: &CredentialsOrApiKey,
429 target: &ChatTarget,
430 queue_id: &str,
431) -> Result<()> {
432 let request = client()
433 .post(format!("{}/chat/live/unqueue", super::get_url()))
434 .header(
435 "Authorization",
436 match authorization {
437 CredentialsOrApiKey::Credentials(credentials) => {
438 format!("Token {}", credentials.token)
439 }
440 CredentialsOrApiKey::ApiKey(key) => format!("ApiKey {}", key.id),
441 },
442 );
443 let response = target_headers(request, target)
444 .json(&json!({ "queueId": queue_id }))
445 .send()
446 .await?;
447 ok(response).await?;
448 Ok(())
449}
450
451#[derive(Debug, Clone, Default)]
453pub struct SteerOptions {
454 pub queue_id: Option<String>,
455 pub all: Option<bool>,
456 pub stop: Option<bool>,
457 pub model: Option<String>,
458 pub reasoning: Option<String>,
459 pub time_zone: Option<String>,
460}
461
462pub async fn steer_room(
469 authorization: &CredentialsOrApiKey,
470 target: &ChatTarget,
471 options: SteerOptions,
472) -> Result<()> {
473 let mut body = Map::new();
474 insert(&mut body, "queueId", options.queue_id.map(Value::from));
475 insert(&mut body, "all", options.all.map(Value::from));
476 insert(&mut body, "stop", options.stop.map(Value::from));
477 insert(&mut body, "model", options.model.map(Value::from));
478 insert(&mut body, "reasoning", options.reasoning.map(Value::from));
479 insert(&mut body, "timeZone", options.time_zone.map(Value::from));
480 let request = client()
481 .post(format!("{}/chat/live/steer", super::get_url()))
482 .header(
483 "Authorization",
484 match authorization {
485 CredentialsOrApiKey::Credentials(credentials) => {
486 format!("Token {}", credentials.token)
487 }
488 CredentialsOrApiKey::ApiKey(key) => format!("ApiKey {}", key.id),
489 },
490 );
491 let response = target_headers(request, target).json(&body).send().await?;
492 ok(response).await?;
493 Ok(())
494}
495
496#[cfg(test)]
497mod tests {
498 use super::AppendResult;
499 use serde_json::json;
500
501 #[test]
502 fn append_results_say_whether_the_send_queued() {
503 assert_eq!(
504 AppendResult::from_json(&json!({ "queued": false, "id": "42" })),
505 AppendResult::Sent {
506 id: Some("42".to_string())
507 }
508 );
509 assert_eq!(
510 AppendResult::from_json(&json!({ "queued": true, "queueId": "7" })),
511 AppendResult::Queued {
512 queue_id: Some("7".to_string())
513 }
514 );
515 assert_eq!(
516 AppendResult::from_json(&json!({})),
517 AppendResult::Sent { id: None }
518 );
519 }
520}