use super::types::{
as_credential_ref, ChatCredentialPublic, ChatIntegration, IntegrationStatus, Platform, Region,
};
use crate::billing::entitlements::urlencoding;
use crate::core::client::Client;
use crate::shared::{ApiResponse, Result};
use serde::Deserialize;
use serde_json::json;
use tokio_util::sync::CancellationToken;
#[derive(Debug, Clone)]
pub struct CreateIntegrationRequest {
pub app_id: String,
pub platform: Platform,
pub region: Region,
pub workspace_id: Option<String>,
pub bot_id: Option<String>,
pub config_json: Option<String>,
}
#[derive(Debug, Clone)]
pub struct StoreCredentialRequest {
pub secret_kind: String,
pub plaintext: String,
pub region: Option<Region>,
pub platform: Option<Platform>,
}
#[derive(Debug, Deserialize)]
struct ItemsWrapper<T> {
#[serde(default = "Vec::new")]
items: Vec<T>,
}
pub struct ChatBridgeClient {
client: Client,
}
impl Client {
pub fn chat_bridge(&self) -> ChatBridgeClient {
ChatBridgeClient {
client: self.clone(),
}
}
}
impl ChatBridgeClient {
pub async fn create_integration(
&self,
req: &CreateIntegrationRequest,
signal: Option<CancellationToken>,
) -> Result<ChatIntegration> {
let body_str = create_integration_wire_body(req).to_string();
self.client
.commerce_post::<ChatIntegration>("/chat-bridge/integrations", Some(&body_str), signal)
.await
}
pub async fn list_integrations(
&self,
app_id: Option<&str>,
signal: Option<CancellationToken>,
) -> Result<Vec<ChatIntegration>> {
let path = match app_id {
Some(a) => format!("/chat-bridge/integrations?app_id={}", urlencoding(a)),
None => "/chat-bridge/integrations".to_string(),
};
let w: ItemsWrapper<ChatIntegration> = self.client.commerce_get(&path, signal).await?;
Ok(w.items)
}
pub async fn get_integration(
&self,
id: &str,
signal: Option<CancellationToken>,
) -> Result<ChatIntegration> {
self.client
.commerce_get(
&format!("/chat-bridge/integrations/{}", urlencoding(id)),
signal,
)
.await
}
pub async fn update_integration_status(
&self,
id: &str,
status: IntegrationStatus,
signal: Option<CancellationToken>,
) -> Result<()> {
let body = json!({ "status": status.as_str() }).to_string();
let (env, _) = self
.client
.do_json_full::<ApiResponse<serde_json::Value>>(
reqwest::Method::PATCH,
&format!("/chat-bridge/integrations/{}/status", urlencoding(id)),
Some(&body),
signal,
)
.await?;
if let Some(env) = env {
if let Some(err) = env.business_error() {
return Err(err);
}
}
Ok(())
}
pub async fn store_credential(
&self,
integration_id: &str,
req: &StoreCredentialRequest,
signal: Option<CancellationToken>,
) -> Result<ChatCredentialPublic> {
let body_str = store_credential_wire_body(req).to_string();
let cred: ChatCredentialPublic = self
.client
.commerce_post(
&format!(
"/chat-bridge/integrations/{}/credentials",
urlencoding(integration_id)
),
Some(&body_str),
signal,
)
.await?;
Ok(brand_credential(cred))
}
pub async fn list_credentials(
&self,
integration_id: &str,
signal: Option<CancellationToken>,
) -> Result<Vec<ChatCredentialPublic>> {
let w: ItemsWrapper<ChatCredentialPublic> = self
.client
.commerce_get(
&format!(
"/chat-bridge/integrations/{}/credentials",
urlencoding(integration_id)
),
signal,
)
.await?;
Ok(w.items.into_iter().map(brand_credential).collect())
}
pub async fn rotate_credential(
&self,
integration_id: &str,
secret_kind: &str,
new_plaintext: &str,
signal: Option<CancellationToken>,
) -> Result<ChatCredentialPublic> {
let body = json!({
"secret_kind": secret_kind,
"new_plaintext": new_plaintext,
})
.to_string();
let cred: ChatCredentialPublic = self
.client
.commerce_post(
&format!(
"/chat-bridge/integrations/{}/credentials/rotate",
urlencoding(integration_id)
),
Some(&body),
signal,
)
.await?;
Ok(brand_credential(cred))
}
pub async fn revoke_credential(
&self,
credential_ref: &str,
signal: Option<CancellationToken>,
) -> Result<()> {
self.client
.commerce_post_discard(
&format!(
"/chat-bridge/credentials/{}/revoke",
urlencoding(credential_ref)
),
Some("{}"),
signal,
)
.await
}
}
fn brand_credential(mut c: ChatCredentialPublic) -> ChatCredentialPublic {
c.credential_ref = as_credential_ref(c.credential_ref.as_str());
c
}
fn create_integration_wire_body(req: &CreateIntegrationRequest) -> serde_json::Value {
let mut body = serde_json::Map::new();
body.insert("app_id".into(), json!(req.app_id));
body.insert("platform".into(), json!(req.platform.as_str()));
body.insert("region".into(), json!(req.region.as_str()));
if let Some(w) = &req.workspace_id {
body.insert("workspace_id".into(), json!(w));
}
if let Some(b) = &req.bot_id {
body.insert("bot_id".into(), json!(b));
}
if let Some(c) = &req.config_json {
body.insert("config_json".into(), json!(c));
}
serde_json::Value::Object(body)
}
fn store_credential_wire_body(req: &StoreCredentialRequest) -> serde_json::Value {
let mut body = serde_json::Map::new();
body.insert("secret_kind".into(), json!(req.secret_kind));
body.insert("plaintext".into(), json!(req.plaintext));
if let Some(r) = req.region {
body.insert("region".into(), json!(r.as_str()));
}
if let Some(p) = req.platform {
body.insert("platform".into(), json!(p.as_str()));
}
serde_json::Value::Object(body)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::chatbridge::types::{Platform, Region};
#[test]
fn create_integration_request_is_snake_case_wire() {
let req = CreateIntegrationRequest {
app_id: "app-1".into(),
platform: Platform::Feishu,
region: Region::Cn,
workspace_id: Some("ws-raw".into()),
bot_id: Some("bot-raw".into()),
config_json: Some("{\"rate\":1}".into()),
};
let body = create_integration_wire_body(&req);
assert_eq!(body["app_id"], "app-1");
assert_eq!(body["workspace_id"], "ws-raw");
assert_eq!(body["bot_id"], "bot-raw");
assert_eq!(body["config_json"], "{\"rate\":1}");
assert_eq!(body["platform"], "feishu");
assert_eq!(body["region"], "cn");
assert!(body.get("appId").is_none());
assert!(body.get("workspaceId").is_none());
assert!(body.get("configJson").is_none());
}
#[test]
fn store_credential_request_snake_case_plaintext_once() {
let req = StoreCredentialRequest {
secret_kind: "bot_token".into(),
plaintext: "super-secret".into(),
region: Some(Region::Intl),
platform: Some(Platform::Slack),
};
let body = store_credential_wire_body(&req);
assert_eq!(body["secret_kind"], "bot_token");
assert_eq!(body["plaintext"], "super-secret");
assert_eq!(body["region"], "intl");
assert_eq!(body["platform"], "slack");
assert!(body.get("secretKind").is_none());
let count = body
.as_object()
.unwrap()
.keys()
.filter(|k| k.contains("plaintext"))
.count();
assert_eq!(count, 1);
}
#[test]
fn optional_fields_omitted_when_none() {
let req = CreateIntegrationRequest {
app_id: "a".into(),
platform: Platform::Wecom,
region: Region::Cn,
workspace_id: None,
bot_id: None,
config_json: None,
};
let body = create_integration_wire_body(&req);
let obj = body.as_object().unwrap();
assert!(!obj.contains_key("workspace_id"));
assert!(!obj.contains_key("bot_id"));
assert!(!obj.contains_key("config_json"));
}
}