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