BlueGit

ict rusty-teams

Files

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

cards.rs

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