1use super::types::{
19 as_credential_ref, ChatCredentialPublic, ChatIntegration, IntegrationStatus, Platform, Region,
20};
21use crate::billing::entitlements::urlencoding;
22use crate::core::client::Client;
23use crate::shared::{ApiResponse, Result};
24use serde::Deserialize;
25use serde_json::json;
26use tokio_util::sync::CancellationToken;
27
28#[derive(Debug, Clone)]
30pub struct CreateIntegrationRequest {
31 pub app_id: String,
33 pub platform: Platform,
34 pub region: Region,
35 pub workspace_id: Option<String>,
37 pub bot_id: Option<String>,
39 pub config_json: Option<String>,
41}
42
43#[derive(Debug, Clone)]
47pub struct StoreCredentialRequest {
48 pub secret_kind: String,
50 pub plaintext: String,
52 pub region: Option<Region>,
53 pub platform: Option<Platform>,
54}
55
56#[derive(Debug, Deserialize)]
58struct ItemsWrapper<T> {
59 #[serde(default = "Vec::new")]
60 items: Vec<T>,
61}
62
63pub struct ChatBridgeClient {
67 client: Client,
68}
69
70impl Client {
71 pub fn chat_bridge(&self) -> ChatBridgeClient {
78 ChatBridgeClient {
79 client: self.clone(),
80 }
81 }
82}
83
84impl ChatBridgeClient {
85 pub async fn create_integration(
94 &self,
95 req: &CreateIntegrationRequest,
96 signal: Option<CancellationToken>,
97 ) -> Result<ChatIntegration> {
98 let body_str = create_integration_wire_body(req).to_string();
100 self.client
101 .commerce_post::<ChatIntegration>("/chat-bridge/integrations", Some(&body_str), signal)
102 .await
103 }
104
105 pub async fn list_integrations(
107 &self,
108 app_id: Option<&str>,
109 signal: Option<CancellationToken>,
110 ) -> Result<Vec<ChatIntegration>> {
111 let path = match app_id {
112 Some(a) => format!("/chat-bridge/integrations?app_id={}", urlencoding(a)),
113 None => "/chat-bridge/integrations".to_string(),
114 };
115 let w: ItemsWrapper<ChatIntegration> = self.client.commerce_get(&path, signal).await?;
117 Ok(w.items)
118 }
119
120 pub async fn get_integration(
122 &self,
123 id: &str,
124 signal: Option<CancellationToken>,
125 ) -> Result<ChatIntegration> {
126 self.client
127 .commerce_get(
128 &format!("/chat-bridge/integrations/{}", urlencoding(id)),
129 signal,
130 )
131 .await
132 }
133
134 pub async fn update_integration_status(
137 &self,
138 id: &str,
139 status: IntegrationStatus,
140 signal: Option<CancellationToken>,
141 ) -> Result<()> {
142 let body = json!({ "status": status.as_str() }).to_string();
143 let (env, _) = self
145 .client
146 .do_json_full::<ApiResponse<serde_json::Value>>(
147 http::Method::PATCH,
148 &format!("/chat-bridge/integrations/{}/status", urlencoding(id)),
149 Some(&body),
150 signal,
151 )
152 .await?;
153 if let Some(env) = env {
154 if let Some(err) = env.business_error() {
155 return Err(err);
156 }
157 }
158 Ok(())
159 }
160
161 pub async fn store_credential(
171 &self,
172 integration_id: &str,
173 req: &StoreCredentialRequest,
174 signal: Option<CancellationToken>,
175 ) -> Result<ChatCredentialPublic> {
176 let body_str = store_credential_wire_body(req).to_string();
177 let cred: ChatCredentialPublic = self
178 .client
179 .commerce_post(
180 &format!(
181 "/chat-bridge/integrations/{}/credentials",
182 urlencoding(integration_id)
183 ),
184 Some(&body_str),
185 signal,
186 )
187 .await?;
188 Ok(brand_credential(cred))
189 }
190
191 pub async fn list_credentials(
193 &self,
194 integration_id: &str,
195 signal: Option<CancellationToken>,
196 ) -> Result<Vec<ChatCredentialPublic>> {
197 let w: ItemsWrapper<ChatCredentialPublic> = self
198 .client
199 .commerce_get(
200 &format!(
201 "/chat-bridge/integrations/{}/credentials",
202 urlencoding(integration_id)
203 ),
204 signal,
205 )
206 .await?;
207 Ok(w.items.into_iter().map(brand_credential).collect())
208 }
209
210 pub async fn rotate_credential(
214 &self,
215 integration_id: &str,
216 secret_kind: &str,
217 new_plaintext: &str,
218 signal: Option<CancellationToken>,
219 ) -> Result<ChatCredentialPublic> {
220 let body = json!({
221 "secret_kind": secret_kind,
222 "new_plaintext": new_plaintext,
223 })
224 .to_string();
225 let cred: ChatCredentialPublic = self
226 .client
227 .commerce_post(
228 &format!(
229 "/chat-bridge/integrations/{}/credentials/rotate",
230 urlencoding(integration_id)
231 ),
232 Some(&body),
233 signal,
234 )
235 .await?;
236 Ok(brand_credential(cred))
237 }
238
239 pub async fn revoke_credential(
241 &self,
242 credential_ref: &str,
243 signal: Option<CancellationToken>,
244 ) -> Result<()> {
245 self.client
246 .commerce_post_discard(
247 &format!(
248 "/chat-bridge/credentials/{}/revoke",
249 urlencoding(credential_ref)
250 ),
251 Some("{}"),
252 signal,
253 )
254 .await
255 }
256}
257
258fn brand_credential(mut c: ChatCredentialPublic) -> ChatCredentialPublic {
261 c.credential_ref = as_credential_ref(c.credential_ref.as_str());
262 c
263}
264
265fn create_integration_wire_body(req: &CreateIntegrationRequest) -> serde_json::Value {
267 let mut body = serde_json::Map::new();
268 body.insert("app_id".into(), json!(req.app_id));
269 body.insert("platform".into(), json!(req.platform.as_str()));
270 body.insert("region".into(), json!(req.region.as_str()));
271 if let Some(w) = &req.workspace_id {
272 body.insert("workspace_id".into(), json!(w));
273 }
274 if let Some(b) = &req.bot_id {
275 body.insert("bot_id".into(), json!(b));
276 }
277 if let Some(c) = &req.config_json {
278 body.insert("config_json".into(), json!(c));
279 }
280 serde_json::Value::Object(body)
281}
282
283fn store_credential_wire_body(req: &StoreCredentialRequest) -> serde_json::Value {
286 let mut body = serde_json::Map::new();
287 body.insert("secret_kind".into(), json!(req.secret_kind));
288 body.insert("plaintext".into(), json!(req.plaintext));
289 if let Some(r) = req.region {
290 body.insert("region".into(), json!(r.as_str()));
291 }
292 if let Some(p) = req.platform {
293 body.insert("platform".into(), json!(p.as_str()));
294 }
295 serde_json::Value::Object(body)
296}
297
298#[cfg(test)]
299mod tests {
300 use super::*;
301 use crate::chatbridge::types::{Platform, Region};
302
303 #[test]
304 fn create_integration_request_is_snake_case_wire() {
305 let req = CreateIntegrationRequest {
307 app_id: "app-1".into(),
308 platform: Platform::Feishu,
309 region: Region::Cn,
310 workspace_id: Some("ws-raw".into()),
311 bot_id: Some("bot-raw".into()),
312 config_json: Some("{\"rate\":1}".into()),
313 };
314 let body = create_integration_wire_body(&req);
315 assert_eq!(body["app_id"], "app-1");
316 assert_eq!(body["workspace_id"], "ws-raw");
317 assert_eq!(body["bot_id"], "bot-raw");
318 assert_eq!(body["config_json"], "{\"rate\":1}");
319 assert_eq!(body["platform"], "feishu");
320 assert_eq!(body["region"], "cn");
321 assert!(body.get("appId").is_none());
323 assert!(body.get("workspaceId").is_none());
324 assert!(body.get("configJson").is_none());
325 }
326
327 #[test]
328 fn store_credential_request_snake_case_plaintext_once() {
329 let req = StoreCredentialRequest {
330 secret_kind: "bot_token".into(),
331 plaintext: "super-secret".into(),
332 region: Some(Region::Intl),
333 platform: Some(Platform::Slack),
334 };
335 let body = store_credential_wire_body(&req);
336 assert_eq!(body["secret_kind"], "bot_token");
337 assert_eq!(body["plaintext"], "super-secret");
339 assert_eq!(body["region"], "intl");
340 assert_eq!(body["platform"], "slack");
341 assert!(body.get("secretKind").is_none());
342 let count = body
344 .as_object()
345 .unwrap()
346 .keys()
347 .filter(|k| k.contains("plaintext"))
348 .count();
349 assert_eq!(count, 1);
350 }
351
352 #[test]
353 fn optional_fields_omitted_when_none() {
354 let req = CreateIntegrationRequest {
355 app_id: "a".into(),
356 platform: Platform::Wecom,
357 region: Region::Cn,
358 workspace_id: None,
359 bot_id: None,
360 config_json: None,
361 };
362 let body = create_integration_wire_body(&req);
363 let obj = body.as_object().unwrap();
364 assert!(!obj.contains_key("workspace_id"));
365 assert!(!obj.contains_key("bot_id"));
366 assert!(!obj.contains_key("config_json"));
367 }
368}