use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use serde_json::{Map, Value, json};
use super::generative::{Content, File as FilePart, Function, Part};
use super::room::RoomMessage;
use crate::authentification::{Credentials, CredentialsOrApiKey, Profile};
use crate::billing::PageQuery;
use crate::drive::{self, DriveAuthorization};
use crate::error::Result;
use crate::http::{client, ok};
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ChatTarget {
Code { code: String },
Reference { reference: String },
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct MovedChat {
pub chat_id: String,
pub group_id: String,
}
pub async fn move_chat_to_group(
credentials: &Credentials,
chat_id: &str,
group_id: &str,
) -> Result<MovedChat> {
let response = client()
.post(format!("{}/chat/move", super::get_url()))
.header("Authorization", format!("Token {}", credentials.token))
.json(&json!({ "chatId": chat_id, "groupId": group_id }))
.send()
.await?;
Ok(ok(response).await?.json().await?)
}
#[derive(Debug, Clone, Default)]
pub struct OpenRoomOptions {
pub share: Option<bool>,
pub write: Option<bool>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct OpenedRoom {
pub reference: String,
pub room_id: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub code: Option<String>,
}
pub async fn open_room(
authorization: &CredentialsOrApiKey,
chat_id: &str,
options: OpenRoomOptions,
) -> Result<OpenedRoom> {
let mut body = Map::new();
body.insert("chatId".to_string(), Value::from(chat_id));
insert(&mut body, "share", options.share.map(Value::from));
insert(&mut body, "write", options.write.map(Value::from));
let response = client()
.post(format!("{}/chat/live/open", super::get_url()))
.header(
"Authorization",
match authorization {
CredentialsOrApiKey::Credentials(credentials) => {
format!("Token {}", credentials.token)
}
CredentialsOrApiKey::ApiKey(key) => format!("ApiKey {}", key.id),
},
)
.json(&body)
.send()
.await?;
let json: Value = ok(response).await?.json().await?;
Ok(OpenedRoom {
reference: text(&json["reference"]),
room_id: text(&json["roomId"]),
code: json["code"].as_str().map(str::to_string),
})
}
fn insert(body: &mut Map<String, Value>, key: &str, value: Option<Value>) {
if let Some(value) = value {
body.insert(key.to_string(), value);
}
}
fn text(value: &Value) -> String {
match value {
Value::String(value) => value.clone(),
Value::Null => String::new(),
value => value.to_string(),
}
}
pub(crate) fn room_parts(
parts: &Value,
authorization: &CredentialsOrApiKey,
target: &ChatTarget,
) -> Vec<Part> {
parts
.as_array()
.into_iter()
.flatten()
.filter_map(|part| {
if part["type"] != "FILE" {
return Part::from_json(part);
}
let mut meta = part.clone();
meta["name"] = Value::from(part["name"].as_str().unwrap_or("file"));
meta["contentType"] = Value::from(
part["contentType"]
.as_str()
.unwrap_or("application/octet-stream"),
);
let nonempty = |key: &str| part[key].as_str().filter(|value| !value.is_empty());
let authorization = authorization.clone();
let file_authorization = if let Some(access_code) = nonempty("accessCode") {
DriveAuthorization::AccessCode {
authorization,
access_code: access_code.to_string(),
}
} else if let Some(path) = nonempty("path") {
DriveAuthorization::Path {
authorization,
path: path.to_string(),
group: part["group"].as_str().map(str::to_string),
}
} else if let ChatTarget::Code { code } = target {
DriveAuthorization::AccessCode {
authorization,
access_code: code.clone(),
}
} else if let Some(reference) = nonempty("ref") {
DriveAuthorization::Path {
authorization,
path: reference.to_string(),
group: None,
}
} else {
DriveAuthorization::AccessCode {
authorization,
access_code: String::new(),
}
};
Some(Part::File(FilePart {
file: drive::File::from_json(&meta, file_authorization),
}))
})
.collect()
}
fn target_headers(
request: reqwest::RequestBuilder,
target: &ChatTarget,
) -> reqwest::RequestBuilder {
match target {
ChatTarget::Code { code } => request.header("Access-Code", code),
ChatTarget::Reference { reference } => request.header("Server", reference),
}
}
pub async fn page_messages(
authorization: &CredentialsOrApiKey,
target: &ChatTarget,
query: PageQuery,
) -> Result<Vec<RoomMessage>> {
let request = client()
.get(format!(
"{}/chat/live/messages?cursor={}&max={}",
super::get_url(),
query.cursor,
query.max
))
.header(
"Authorization",
match authorization {
CredentialsOrApiKey::Credentials(credentials) => {
format!("Token {}", credentials.token)
}
CredentialsOrApiKey::ApiKey(key) => format!("ApiKey {}", key.id),
},
);
let response = target_headers(request, target).send().await?;
let json: Value = ok(response).await?.json().await?;
Ok(json
.as_array()
.into_iter()
.flatten()
.map(|message| RoomMessage::from_json(message, authorization, target))
.collect())
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum AppendResult {
Sent { id: Option<String> },
Queued { queue_id: Option<String> },
}
impl AppendResult {
pub(crate) fn from_json(json: &Value) -> AppendResult {
if json["queued"] == true {
AppendResult::Queued {
queue_id: json["queueId"].as_str().map(str::to_string),
}
} else {
AppendResult::Sent {
id: json["id"].as_str().map(str::to_string),
}
}
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(untagged)]
#[allow(clippy::large_enum_variant)]
pub enum FunctionOrFunctions {
Function(Function),
Functions(Vec<Function>),
}
#[derive(Debug, Clone, Default)]
pub struct AppendOptions {
pub reply_to: Option<String>,
pub model: Option<String>,
pub reasoning: Option<String>,
pub time_zone: Option<String>,
pub tools: Option<FunctionOrFunctions>,
pub seat: Option<String>,
}
pub async fn append_room_message(
authorization: &CredentialsOrApiKey,
target: &ChatTarget,
message: &Content,
options: AppendOptions,
) -> Result<AppendResult> {
let serialized_parts: Vec<Value> = message.parts.iter().map(Part::wire).collect();
let mut body = Map::new();
body.insert("role".to_string(), serde_json::to_value(message.role)?);
body.insert("parts".to_string(), Value::Array(serialized_parts));
insert(&mut body, "replyTo", options.reply_to.map(Value::from));
insert(&mut body, "model", options.model.map(Value::from));
insert(&mut body, "reasoning", options.reasoning.map(Value::from));
insert(&mut body, "timeZone", options.time_zone.map(Value::from));
insert(
&mut body,
"tools",
options.tools.map(serde_json::to_value).transpose()?,
);
insert(&mut body, "seat", options.seat.map(Value::from));
let request = client()
.post(format!("{}/chat/live/append", super::get_url()))
.header(
"Authorization",
match authorization {
CredentialsOrApiKey::Credentials(credentials) => {
format!("Token {}", credentials.token)
}
CredentialsOrApiKey::ApiKey(key) => format!("ApiKey {}", key.id),
},
);
let response = target_headers(request, target).json(&body).send().await?;
let response = ok(response).await?;
let json: Value = response.json().await.unwrap_or(Value::Null);
Ok(AppendResult::from_json(&json))
}
#[derive(Debug, Clone)]
pub struct Attachment {
pub file: drive::File,
pub chat: String,
pub r#ref: String,
pub message: Option<u32>,
pub author: Option<Profile>,
pub created_at: DateTime<Utc>,
}
impl Attachment {
pub fn from_json(json: &Value, authorization: &CredentialsOrApiKey) -> Attachment {
let name = json["name"]
.as_str()
.or_else(|| json["ref"].as_str())
.unwrap_or("file");
let meta = json!({
"name": name,
"contentType": json["contentType"].as_str().unwrap_or("application/octet-stream"),
"contentLength": json["contentLength"].as_f64().unwrap_or_default(),
});
Attachment {
file: drive::File::from_json(
&meta,
DriveAuthorization::AccessCode {
authorization: authorization.clone(),
access_code: text(&json["accessCode"]),
},
),
chat: text(&json["chat"]),
r#ref: text(&json["ref"]),
message: json["message"].as_f64().map(|message| message as u32),
author: if json["author"].is_object() {
serde_json::from_value(json["author"].clone()).ok()
} else {
None
},
created_at: crate::tickets::parse_date(&json["created"]).unwrap_or_else(Utc::now),
}
}
}
pub async fn list_room_attachments(
authorization: &CredentialsOrApiKey,
target: &ChatTarget,
) -> Result<Vec<Attachment>> {
let request = client()
.get(format!("{}/chat/live/attachments", super::get_url()))
.header(
"Authorization",
match authorization {
CredentialsOrApiKey::Credentials(credentials) => {
format!("Token {}", credentials.token)
}
CredentialsOrApiKey::ApiKey(key) => format!("ApiKey {}", key.id),
},
);
let response = target_headers(request, target).send().await?;
let json: Value = ok(response).await?.json().await?;
Ok(json
.as_array()
.into_iter()
.flatten()
.map(|row| Attachment::from_json(row, authorization))
.collect())
}
pub async fn set_room_repository(
authorization: &CredentialsOrApiKey,
target: &ChatTarget,
repository: Option<u64>,
) -> Result<()> {
let request = client()
.post(format!("{}/chat/repository", super::get_url()))
.header(
"Authorization",
match authorization {
CredentialsOrApiKey::Credentials(credentials) => {
format!("Token {}", credentials.token)
}
CredentialsOrApiKey::ApiKey(key) => format!("ApiKey {}", key.id),
},
);
let response = target_headers(request, target)
.json(&json!({ "repository": repository }))
.send()
.await?;
ok(response).await?;
Ok(())
}
pub async fn unqueue_room_message(
authorization: &CredentialsOrApiKey,
target: &ChatTarget,
queue_id: &str,
) -> Result<()> {
let request = client()
.post(format!("{}/chat/live/unqueue", super::get_url()))
.header(
"Authorization",
match authorization {
CredentialsOrApiKey::Credentials(credentials) => {
format!("Token {}", credentials.token)
}
CredentialsOrApiKey::ApiKey(key) => format!("ApiKey {}", key.id),
},
);
let response = target_headers(request, target)
.json(&json!({ "queueId": queue_id }))
.send()
.await?;
ok(response).await?;
Ok(())
}
#[derive(Debug, Clone, Default)]
pub struct SteerOptions {
pub queue_id: Option<String>,
pub all: Option<bool>,
pub stop: Option<bool>,
pub model: Option<String>,
pub reasoning: Option<String>,
pub time_zone: Option<String>,
}
pub async fn steer_room(
authorization: &CredentialsOrApiKey,
target: &ChatTarget,
options: SteerOptions,
) -> Result<()> {
let mut body = Map::new();
insert(&mut body, "queueId", options.queue_id.map(Value::from));
insert(&mut body, "all", options.all.map(Value::from));
insert(&mut body, "stop", options.stop.map(Value::from));
insert(&mut body, "model", options.model.map(Value::from));
insert(&mut body, "reasoning", options.reasoning.map(Value::from));
insert(&mut body, "timeZone", options.time_zone.map(Value::from));
let request = client()
.post(format!("{}/chat/live/steer", super::get_url()))
.header(
"Authorization",
match authorization {
CredentialsOrApiKey::Credentials(credentials) => {
format!("Token {}", credentials.token)
}
CredentialsOrApiKey::ApiKey(key) => format!("ApiKey {}", key.id),
},
);
let response = target_headers(request, target).json(&body).send().await?;
ok(response).await?;
Ok(())
}
#[cfg(test)]
mod tests {
use super::AppendResult;
use serde_json::json;
#[test]
fn append_results_say_whether_the_send_queued() {
assert_eq!(
AppendResult::from_json(&json!({ "queued": false, "id": "42" })),
AppendResult::Sent {
id: Some("42".to_string())
}
);
assert_eq!(
AppendResult::from_json(&json!({ "queued": true, "queueId": "7" })),
AppendResult::Queued {
queue_id: Some("7".to_string())
}
);
assert_eq!(
AppendResult::from_json(&json!({})),
AppendResult::Sent { id: None }
);
}
}