BlueGit

ict rusty-teams

Files

rusty-teams / crates / chatsvc / src / cards.rs

cards.rs

cards.rs 19.8 KiB Download Raw
1use serde_json::{Value, json};
2use session::{ApiResponse, Method, Request, SPACES, Scope, Session};
3
4use crate::error::{Error, Result};
5use crate::messages::{encode, messages_scope};
6use crate::pins::DEFAULT_REGION;
7
8pub const DEFAULT_MT_REGION: &str = "emea";
9pub const FALLBACK_INVOKE_REGION: &str = "de";
10const SPACES_SCOPE: &str = "user_impersonation";
11const TOKEN_PLACEHOLDER: &str = "@@rusty-teams-user-aad-token@@";
12const BOT_MRI_PREFIX: &str = "28:";
13const CARD_MESSAGE_TYPE: &str = "RichText/Media_Card";
14const ADAPTIVE_CARD_TYPE: &str = "application/vnd.microsoft.card.adaptive";
15const MESSAGE_TYPE: &str = "application/vnd.microsoft.activity.message";
16const ERROR_STATUS_FLOOR: u64 = 400;
17
18pub fn spaces_scope() -> Scope {
19 Scope::new(SPACES, SPACES_SCOPE)
20}
21
22pub fn bot_mri(bot_id: &str) -> String {
23 if bot_id.starts_with(BOT_MRI_PREFIX) {
24 bot_id.to_owned()
25 } else {
26 format!("{BOT_MRI_PREFIX}{bot_id}")
27 }
28}
29
30pub fn bot_guid(bot_id: &str) -> &str {
31 bot_id.strip_prefix(BOT_MRI_PREFIX).unwrap_or(bot_id)
32}
33
34pub trait CardTransport {
35 fn send(
36 &self,
37 request: Request,
38 scope: Scope,
39 ) -> impl std::future::Future<Output = Result<ApiResponse>>;
40}
41
42pub struct SessionCardTransport {
43 session: Session,
44}
45
46impl SessionCardTransport {
47 pub fn new(session: &Session) -> Self {
48 SessionCardTransport {
49 session: session.clone(),
50 }
51 }
52}
53
54impl CardTransport for SessionCardTransport {
55 async fn send(&self, request: Request, scope: Scope) -> Result<ApiResponse> {
56 let mut answers = self.session.batch(&[request], &scope).await?;
57 Ok(answers.remove(0))
58 }
59}
60
61#[derive(Debug, Clone, PartialEq)]
62pub struct InvokeRequest {
63 pub bot_id: String,
64 pub app_id: String,
65 pub name: String,
66 pub value: Value,
67 pub display_name: String,
68 pub server_message_id: String,
69 pub client_message_id: Option<String>,
70 pub conversation_id: String,
71}
72
73#[derive(Debug, Clone, PartialEq)]
74pub enum InvokeResponse {
75 Empty,
76 Card(Value),
77 Message(String),
78 Task(TaskResponse),
79 Failed { status_code: u16, message: String },
80}
81
82#[derive(Debug, Clone, PartialEq)]
83pub enum TaskResponse {
84 Continue(TaskContinue),
85 Message(String),
86}
87
88#[derive(Debug, Clone, PartialEq)]
89pub struct TaskContinue {
90 pub title: Option<String>,
91 pub width: Option<u32>,
92 pub height: Option<u32>,
93 pub content: TaskContent,
94}
95
96#[derive(Debug, Clone, PartialEq)]
97pub enum TaskContent {
98 Url {
99 url: String,
100 fallback_url: Option<String>,
101 },
102 Card(Value),
103}
104
105#[derive(Debug, Clone, PartialEq, Eq)]
106pub struct ChatApp {
107 pub app_id: String,
108 pub name: String,
109 pub bot_ids: Vec<String>,
110 pub small_image_url: Option<String>,
111 pub accent_color: Option<String>,
112 pub web_application_resource: Option<String>,
113}
114
115impl ChatApp {
116 pub fn has_bot(&self, bot_id: &str) -> bool {
117 self.bot_ids
118 .iter()
119 .any(|known| bot_guid(known).eq_ignore_ascii_case(bot_guid(bot_id)))
120 }
121}
122
123pub struct CardActions<T: CardTransport = SessionCardTransport> {
124 transport: T,
125 chatsvc_base: String,
126 fallback_chatsvc_base: String,
127 mt_base: String,
128}
129
130impl CardActions<SessionCardTransport> {
131 pub fn new(session: &Session) -> Self {
132 CardActions::with_transport(
133 SessionCardTransport::new(session),
134 DEFAULT_REGION,
135 DEFAULT_MT_REGION,
136 )
137 }
138}
139
140impl<T: CardTransport> CardActions<T> {
141 pub fn with_transport(transport: T, region: &str, mt_region: &str) -> Self {
142 CardActions {
143 transport,
144 chatsvc_base: chatsvc_base(region),
145 fallback_chatsvc_base: chatsvc_base(FALLBACK_INVOKE_REGION),
146 mt_base: format!("https://teams.cloud.microsoft/api/mt/{mt_region}/beta/chats"),
147 }
148 }
149
150 pub fn invoke_url(&self, bot_id: &str) -> String {
151 invoke_url(&self.chatsvc_base, bot_id)
152 }
153
154 pub fn entitlements_url(&self, chat_id: &str) -> String {
155 format!("{}/{}/apps/chatentitlements", self.mt_base, encode(chat_id))
156 }
157
158 pub async fn invoke(&self, invoke: InvokeRequest) -> Result<InvokeResponse> {
159 let body = invoke_body(&invoke);
160 let mut answer = self.post(&self.invoke_url(&invoke.bot_id), &body).await?;
161 if answer.status == 404 && self.fallback_chatsvc_base != self.chatsvc_base {
162 let url = invoke_url(&self.fallback_chatsvc_base, &invoke.bot_id);
163 answer = self.post(&url, &body).await?;
164 }
165 if !answer.is_success() {
166 return Err(Error::Session(session::Error::api(
167 answer.status,
168 "chatsvc",
169 answer.body,
170 )));
171 }
172 Ok(parse_invoke_response(&answer.body))
173 }
174
175 pub async fn chat_apps(&self, chat_id: &str) -> Result<Vec<ChatApp>> {
176 let answer = self
177 .transport
178 .send(Request::get(self.entitlements_url(chat_id)), spaces_scope())
179 .await?;
180 if !answer.is_success() {
181 return Err(Error::Session(session::Error::api(
182 answer.status,
183 "chatentitlements",
184 answer.body,
185 )));
186 }
187 parse_chat_apps(&answer.body)
188 }
189
190 async fn post(&self, url: &str, body: &Value) -> Result<ApiResponse> {
191 let mut request = Request::with_body(Method::Post, url, body.clone()).with_body_token(
192 SPACES,
193 SPACES_SCOPE,
194 TOKEN_PLACEHOLDER,
195 );
196 request.headers = vec![
197 ("x-ms-migration".to_owned(), "True".to_owned()),
198 ("behavioroverride".to_owned(), "redirectAs404".to_owned()),
199 ("content-type".to_owned(), "application/json".to_owned()),
200 ];
201 self.transport.send(request, messages_scope()).await
202 }
203}
204
205fn chatsvc_base(region: &str) -> String {
206 format!("https://teams.cloud.microsoft/api/chatsvc/{region}/v1/agents")
207}
208
209fn invoke_url(base: &str, bot_id: &str) -> String {
210 format!("{base}/{}/invoke", encode(&bot_mri(bot_id)))
211}
212
213pub fn invoke_body(invoke: &InvokeRequest) -> Value {
214 let mut body = json!({
215 "name": invoke.name,
216 "appId": invoke.app_id,
217 "messageType": CARD_MESSAGE_TYPE,
218 "value": invoke.value,
219 "imdisplayname": invoke.display_name,
220 "userAadToken": TOKEN_PLACEHOLDER,
221 "serverMessageId": invoke.server_message_id,
222 "conversation": {"id": invoke.conversation_id},
223 });
224 if let Some(client_message_id) = &invoke.client_message_id {
225 body["clientMessageId"] = json!(client_message_id);
226 }
227 body
228}
229
230pub fn parse_invoke_response(body: &Value) -> InvokeResponse {
231 let Some(object) = body.as_object() else {
232 return InvokeResponse::Empty;
233 };
234 if let Some(task) = object.get("task") {
235 return parse_task(task);
236 }
237 let status_code = object.get("statusCode").and_then(Value::as_u64);
238 let value = object.get("value");
239 if let Some(status_code) = status_code.filter(|code| *code >= ERROR_STATUS_FLOOR) {
240 return InvokeResponse::Failed {
241 status_code: status_code as u16,
242 message: value.map(text_of).unwrap_or_default(),
243 };
244 }
245 match object.get("type").and_then(Value::as_str) {
246 Some(ADAPTIVE_CARD_TYPE) => value
247 .map(|card| InvokeResponse::Card(card.clone()))
248 .unwrap_or(InvokeResponse::Empty),
249 Some(MESSAGE_TYPE) => InvokeResponse::Message(value.map(text_of).unwrap_or_default()),
250 _ => InvokeResponse::Empty,
251 }
252}
253
254fn parse_task(task: &Value) -> InvokeResponse {
255 let value = task.get("value");
256 match task.get("type").and_then(Value::as_str) {
257 Some("message") => InvokeResponse::Task(TaskResponse::Message(
258 value.map(text_of).unwrap_or_default(),
259 )),
260 Some("continue") => {
261 let Some(value) = value else {
262 return InvokeResponse::Empty;
263 };
264 let content = match value.get("card") {
265 Some(card) => TaskContent::Card(card_content(card)),
266 None => match value.get("url").and_then(Value::as_str) {
267 Some(url) => TaskContent::Url {
268 url: url.to_owned(),
269 fallback_url: value
270 .get("fallbackUrl")
271 .and_then(Value::as_str)
272 .map(str::to_owned),
273 },
274 None => return InvokeResponse::Empty,
275 },
276 };
277 InvokeResponse::Task(TaskResponse::Continue(TaskContinue {
278 title: value
279 .get("title")
280 .and_then(Value::as_str)
281 .map(str::to_owned),
282 width: dimension(value.get("width")),
283 height: dimension(value.get("height")),
284 content,
285 }))
286 }
287 _ => InvokeResponse::Empty,
288 }
289}
290
291fn dimension(value: Option<&Value>) -> Option<u32> {
292 let pixels = value?.as_u64()?;
293 u32::try_from(pixels).ok().filter(|pixels| *pixels > 0)
294}
295
296fn card_content(card: &Value) -> Value {
297 match card.get("content") {
298 Some(Value::String(text)) => serde_json::from_str(text).unwrap_or_else(|_| card.clone()),
299 Some(content) => content.clone(),
300 None => card.clone(),
301 }
302}
303
304fn text_of(value: &Value) -> String {
305 match value.as_str() {
306 Some(text) => text.to_owned(),
307 None => value.to_string(),
308 }
309}
310
311pub fn parse_chat_apps(body: &Value) -> Result<Vec<ChatApp>> {
312 let definitions = body
313 .pointer("/value/definitions")
314 .and_then(Value::as_array)
315 .ok_or_else(|| Error::UnexpectedAnswer("no app definitions".into()))?;
316 Ok(definitions
317 .iter()
318 .filter_map(|definition| {
319 let text = |key: &str| {
320 definition
321 .get(key)
322 .and_then(Value::as_str)
323 .filter(|text| !text.is_empty())
324 .map(str::to_owned)
325 };
326 Some(ChatApp {
327 app_id: text("id")?,
328 name: text("name")?,
329 bot_ids: definition
330 .get("bots")
331 .and_then(Value::as_array)
332 .into_iter()
333 .flatten()
334 .filter_map(|bot| bot.get("id")?.as_str().map(str::to_owned))
335 .collect(),
336 small_image_url: text("smallImageUrl"),
337 accent_color: text("accentColor"),
338 web_application_resource: definition
339 .pointer("/webApplicationInfo/resource")
340 .and_then(Value::as_str)
341 .map(str::to_owned),
342 })
343 })
344 .collect())
345}
346
347#[cfg(test)]
348mod tests {
349 use std::sync::Mutex;
350
351 use session::IC3;
352
353 use super::*;
354
355 struct Canned {
356 answers: Mutex<Vec<(u16, Value)>>,
357 sent: Mutex<Vec<(Request, Scope)>>,
358 }
359
360 impl CardTransport for Canned {
361 async fn send(&self, request: Request, scope: Scope) -> Result<ApiResponse> {
362 self.sent.lock().unwrap().push((request, scope));
363 let (status, body) = self.answers.lock().unwrap().remove(0);
364 Ok(ApiResponse {
365 status,
366 body,
367 retry_after: None,
368 })
369 }
370 }
371
372 fn canned(answers: Vec<(u16, Value)>) -> CardActions<Canned> {
373 CardActions::with_transport(
374 Canned {
375 answers: Mutex::new(answers),
376 sent: Mutex::new(Vec::new()),
377 },
378 "emea",
379 "emea",
380 )
381 }
382
383 fn sample_request() -> InvokeRequest {
384 InvokeRequest {
385 bot_id: "0000aaaa-0000-0000-0000-000000000001".into(),
386 app_id: "app-1".into(),
387 name: "messageback".into(),
388 value: json!({"type": "unwatch", "page": "p1"}),
389 display_name: "Test User".into(),
390 server_message_id: "1700000000001".into(),
391 client_message_id: None,
392 conversation_id: "19:chat@unq.gbl.spaces".into(),
393 }
394 }
395
396 fn entitlements() -> Value {
397 json!({"value": {"definitions": [
398 {
399 "id": "app-1",
400 "name": "Wiki Bot",
401 "smallImageUrl": "https://cdn.example/small.png",
402 "largeImageUrl": "https://cdn.example/large.png",
403 "accentColor": "#0052CC",
404 "bots": [{"id": "0000aaaa-0000-0000-0000-000000000001"}],
405 "webApplicationInfo": {"id": "web-1", "resource": "https://bot.example"}
406 },
407 {"id": "app-2", "name": "Tabs Only"},
408 {"name": "No Id"}
409 ]}})
410 }
411
412 #[tokio::test]
413 async fn invoke_posts_to_the_bot_with_the_card_body() {
414 let actions = canned(vec![(200, Value::Null)]);
415 let response = actions.invoke(sample_request()).await.unwrap();
416 assert_eq!(response, InvokeResponse::Empty);
417 let sent = actions.transport.sent.lock().unwrap();
418 let (request, scope) = &sent[0];
419 assert_eq!(
420 request.url,
421 "https://teams.cloud.microsoft/api/chatsvc/emea/v1/agents/28%3A0000aaaa-0000-0000-0000-000000000001/invoke"
422 );
423 assert_eq!(scope.resource, IC3);
424 assert!(
425 request
426 .headers
427 .contains(&("x-ms-migration".into(), "True".into()))
428 );
429 assert!(
430 request
431 .headers
432 .contains(&("behavioroverride".into(), "redirectAs404".into()))
433 );
434 assert_eq!(request.body_tokens[0].resource, SPACES);
435 let body = request.body.as_ref().unwrap();
436 assert_eq!(body["name"], "messageback");
437 assert_eq!(body["appId"], "app-1");
438 assert_eq!(body["messageType"], "RichText/Media_Card");
439 assert_eq!(body["value"]["type"], "unwatch");
440 assert_eq!(body["serverMessageId"], "1700000000001");
441 assert_eq!(body["conversation"]["id"], "19:chat@unq.gbl.spaces");
442 assert_eq!(body["userAadToken"], request.body_tokens[0].placeholder);
443 assert!(body.get("clientMessageId").is_none());
444 }
445
446 #[tokio::test]
447 async fn invoke_keeps_a_known_client_message_id() {
448 let actions = canned(vec![(200, Value::Null)]);
449 let request = InvokeRequest {
450 client_message_id: Some("client-1".into()),
451 ..sample_request()
452 };
453 actions.invoke(request).await.unwrap();
454 let sent = actions.transport.sent.lock().unwrap();
455 assert_eq!(
456 sent[0].0.body.as_ref().unwrap()["clientMessageId"],
457 "client-1"
458 );
459 }
460
461 #[tokio::test]
462 async fn invoke_retries_a_missing_route_in_the_fallback_region() {
463 let actions = canned(vec![(404, Value::Null), (200, Value::Null)]);
464 actions.invoke(sample_request()).await.unwrap();
465 let sent = actions.transport.sent.lock().unwrap();
466 assert!(sent[1].0.url.contains("/chatsvc/de/"));
467 }
468
469 #[tokio::test]
470 async fn invoke_failure_is_an_error_without_retry() {
471 let actions = canned(vec![(500, json!({"message": "boom"}))]);
472 assert!(actions.invoke(sample_request()).await.is_err());
473 assert_eq!(actions.transport.sent.lock().unwrap().len(), 1);
474 }
475
476 #[test]
477 fn empty_and_unknown_answers_are_empty() {
478 assert_eq!(parse_invoke_response(&Value::Null), InvokeResponse::Empty);
479 assert_eq!(parse_invoke_response(&json!("")), InvokeResponse::Empty);
480 assert_eq!(
481 parse_invoke_response(&json!({"other": 1})),
482 InvokeResponse::Empty
483 );
484 }
485
486 #[test]
487 fn task_with_a_url() {
488 let response = parse_invoke_response(&json!({
489 "responseType": "task",
490 "task": {"type": "continue", "value": {
491 "url": "https://bot.example/task", "fallbackUrl": "https://bot.example/fallback",
492 "height": 380, "width": 620, "title": "Settings"
493 }}
494 }));
495 assert_eq!(
496 response,
497 InvokeResponse::Task(TaskResponse::Continue(TaskContinue {
498 title: Some("Settings".into()),
499 width: Some(620),
500 height: Some(380),
501 content: TaskContent::Url {
502 url: "https://bot.example/task".into(),
503 fallback_url: Some("https://bot.example/fallback".into()),
504 },
505 }))
506 );
507 }
508
509 #[test]
510 fn task_with_a_card_attachment() {
511 let response = parse_invoke_response(&json!({
512 "task": {"type": "continue", "value": {
513 "size": "medium",
514 "card": {"contentType": "application/vnd.microsoft.card.adaptive", "content": {"type": "AdaptiveCard"}}
515 }}
516 }));
517 let InvokeResponse::Task(TaskResponse::Continue(task)) = response else {
518 panic!("expected a continue task");
519 };
520 assert_eq!(
521 task.content,
522 TaskContent::Card(json!({"type": "AdaptiveCard"}))
523 );
524 assert_eq!(task.width, None);
525 }
526
527 #[test]
528 fn task_message_and_unusable_continue() {
529 assert_eq!(
530 parse_invoke_response(&json!({"task": {"type": "message", "value": "Done"}})),
531 InvokeResponse::Task(TaskResponse::Message("Done".into()))
532 );
533 assert_eq!(
534 parse_invoke_response(&json!({"task": {"type": "continue", "value": {}}})),
535 InvokeResponse::Empty
536 );
537 }
538
539 #[test]
540 fn universal_action_answers() {
541 assert_eq!(
542 parse_invoke_response(&json!({
543 "statusCode": 200,
544 "type": "application/vnd.microsoft.card.adaptive",
545 "value": {"type": "AdaptiveCard"}
546 })),
547 InvokeResponse::Card(json!({"type": "AdaptiveCard"}))
548 );
549 assert_eq!(
550 parse_invoke_response(&json!({
551 "statusCode": 200,
552 "type": "application/vnd.microsoft.activity.message",
553 "value": "Saved"
554 })),
555 InvokeResponse::Message("Saved".into())
556 );
557 assert_eq!(
558 parse_invoke_response(&json!({"statusCode": 500, "type": "x", "value": "Broken"})),
559 InvokeResponse::Failed {
560 status_code: 500,
561 message: "Broken".into()
562 }
563 );
564 }
565
566 #[tokio::test]
567 async fn chat_apps_use_the_spaces_scope_and_parse_definitions() {
568 let actions = canned(vec![(200, entitlements())]);
569 let apps = actions.chat_apps("19:chat@unq.gbl.spaces").await.unwrap();
570 assert_eq!(apps.len(), 2);
571 let wiki = &apps[0];
572 assert_eq!(wiki.name, "Wiki Bot");
573 assert_eq!(
574 wiki.small_image_url.as_deref(),
575 Some("https://cdn.example/small.png")
576 );
577 assert_eq!(wiki.accent_color.as_deref(), Some("#0052CC"));
578 assert_eq!(
579 wiki.web_application_resource.as_deref(),
580 Some("https://bot.example")
581 );
582 assert!(wiki.has_bot("0000AAAA-0000-0000-0000-000000000001"));
583 assert!(wiki.has_bot("28:0000aaaa-0000-0000-0000-000000000001"));
584 assert!(!apps[1].has_bot("0000aaaa-0000-0000-0000-000000000001"));
585 let sent = actions.transport.sent.lock().unwrap();
586 assert_eq!(
587 sent[0].0.url,
588 "https://teams.cloud.microsoft/api/mt/emea/beta/chats/19%3Achat%40unq.gbl.spaces/apps/chatentitlements"
589 );
590 assert_eq!(sent[0].1, spaces_scope());
591 }
592
593 #[test]
594 fn entitlements_without_definitions_are_unexpected() {
595 assert!(matches!(
596 parse_chat_apps(&json!({"value": {}})),
597 Err(Error::UnexpectedAnswer(_))
598 ));
599 }
600
601 #[test]
602 fn bot_ids_convert_both_ways() {
603 assert_eq!(bot_mri("abc"), "28:abc");
604 assert_eq!(bot_mri("28:abc"), "28:abc");
605 assert_eq!(bot_guid("28:abc"), "abc");
606 }
607}