| 1 | use chatsvc::{ChatApp, InvokeRequest, InvokeResponse, TaskContent, TaskContinue, TaskResponse}; |
| 2 | use serde_json::Value; |
| 3 | |
| 4 | use crate::adaptive_card::{CardAction, task_value}; |
| 5 | use crate::engine::SyncEngine; |
| 6 | use crate::error::{Error, Result}; |
| 7 | use crate::receipts::locked; |
| 8 | use crate::remote::Remote; |
| 9 | |
| 10 | const TASK_SUBMIT_NAME: &str = "task/submit"; |
| 11 | const DEFAULT_DIALOG_WIDTH: u32 = 520; |
| 12 | const DEFAULT_DIALOG_HEIGHT: u32 = 400; |
| 13 | const MAX_FAILURE_CHARS: usize = 200; |
| 14 | |
| 15 | #[derive(Debug, Clone, PartialEq)] |
| 16 | pub enum CardActionOutcome { |
| 17 | Sent, |
| 18 | ReplaceCard(String), |
| 19 | Dialog(TaskDialog), |
| 20 | Message(String), |
| 21 | Failed(String), |
| 22 | } |
| 23 | |
| 24 | #[derive(Debug, Clone, PartialEq)] |
| 25 | pub struct TaskDialog { |
| 26 | pub title: Option<String>, |
| 27 | pub width: u32, |
| 28 | pub height: u32, |
| 29 | pub kind: TaskDialogKind, |
| 30 | } |
| 31 | |
| 32 | #[derive(Debug, Clone, PartialEq)] |
| 33 | pub enum TaskDialogKind { |
| 34 | Url { url: String, fallback_url: String }, |
| 35 | Card(String), |
| 36 | } |
| 37 | |
| 38 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 39 | pub struct DialogIdentity { |
| 40 | pub user_id: String, |
| 41 | pub display_name: String, |
| 42 | pub tenant_id: String, |
| 43 | } |
| 44 | |
| 45 | impl<R: Remote> SyncEngine<R> { |
| 46 | /// Cached per conversation after the first successful lookup. |
| 47 | pub async fn chat_apps(&self, conversation_id: &str) -> Result<Vec<ChatApp>> { |
| 48 | if let Some(cached) = locked(&self.chat_apps).get(conversation_id) { |
| 49 | return Ok(cached.clone()); |
| 50 | } |
| 51 | let apps = self.remote.chat_apps(conversation_id).await?; |
| 52 | locked(&self.chat_apps).insert(conversation_id.to_owned(), apps.clone()); |
| 53 | Ok(apps) |
| 54 | } |
| 55 | |
| 56 | pub fn cached_chat_apps(&self, conversation_id: &str) -> Option<Vec<ChatApp>> { |
| 57 | locked(&self.chat_apps).get(conversation_id).cloned() |
| 58 | } |
| 59 | |
| 60 | pub async fn dialog_identity(&self, conversation_id: &str) -> Result<DialogIdentity> { |
| 61 | let user_id = self.my_user_id().await?; |
| 62 | self.ensure_display_name().await?; |
| 63 | let tenant_id = self.my_tenant_id(conversation_id).await?; |
| 64 | Ok(DialogIdentity { |
| 65 | user_id, |
| 66 | display_name: self.me().map(|me| me.display_name).unwrap_or_default(), |
| 67 | tenant_id, |
| 68 | }) |
| 69 | } |
| 70 | |
| 71 | pub async fn card_action( |
| 72 | &self, |
| 73 | conversation_id: &str, |
| 74 | message_id: &str, |
| 75 | action: &CardAction, |
| 76 | ) -> Result<CardActionOutcome> { |
| 77 | let payload = action |
| 78 | .invoke_payload() |
| 79 | .ok_or(Error::Unsupported("this card action"))?; |
| 80 | self.invoke_card(conversation_id, message_id, payload.name, payload.value) |
| 81 | .await |
| 82 | } |
| 83 | |
| 84 | pub async fn task_submit( |
| 85 | &self, |
| 86 | conversation_id: &str, |
| 87 | message_id: &str, |
| 88 | data: Value, |
| 89 | ) -> Result<CardActionOutcome> { |
| 90 | self.invoke_card( |
| 91 | conversation_id, |
| 92 | message_id, |
| 93 | TASK_SUBMIT_NAME, |
| 94 | task_value(data), |
| 95 | ) |
| 96 | .await |
| 97 | } |
| 98 | |
| 99 | async fn invoke_card( |
| 100 | &self, |
| 101 | conversation_id: &str, |
| 102 | message_id: &str, |
| 103 | name: &str, |
| 104 | value: Value, |
| 105 | ) -> Result<CardActionOutcome> { |
| 106 | let (app, bot_id) = self.card_app(conversation_id, message_id).await?; |
| 107 | self.ensure_display_name().await?; |
| 108 | let display_name = self.me().map(|me| me.display_name).unwrap_or_default(); |
| 109 | let response = self |
| 110 | .remote |
| 111 | .invoke_card(InvokeRequest { |
| 112 | bot_id, |
| 113 | app_id: app.app_id, |
| 114 | name: name.to_owned(), |
| 115 | value, |
| 116 | display_name, |
| 117 | server_message_id: message_id.to_owned(), |
| 118 | client_message_id: None, |
| 119 | conversation_id: conversation_id.to_owned(), |
| 120 | }) |
| 121 | .await?; |
| 122 | Ok(outcome_of(response)) |
| 123 | } |
| 124 | |
| 125 | pub async fn card_app( |
| 126 | &self, |
| 127 | conversation_id: &str, |
| 128 | message_id: &str, |
| 129 | ) -> Result<(ChatApp, String)> { |
| 130 | let sender_application_id = self |
| 131 | .store |
| 132 | .messages_by_id(conversation_id, &[message_id.to_owned()])? |
| 133 | .remove(message_id) |
| 134 | .and_then(|record| record.sender_application_id); |
| 135 | let apps = self.chat_apps(conversation_id).await?; |
| 136 | let matched = sender_application_id.as_deref().and_then(|sender| { |
| 137 | apps.iter() |
| 138 | .find(|app| app.has_bot(sender) || app.app_id == sender) |
| 139 | }); |
| 140 | let mut with_bots = apps.iter().filter(|app| !app.bot_ids.is_empty()); |
| 141 | let app = match (matched, with_bots.next(), with_bots.next()) { |
| 142 | (Some(app), _, _) | (None, Some(app), None) => app, |
| 143 | _ => return Err(Error::Unsupported("a card from an unknown app")), |
| 144 | }; |
| 145 | let bot_id = sender_application_id |
| 146 | .filter(|sender| app.has_bot(sender)) |
| 147 | .or_else(|| app.bot_ids.first().cloned()) |
| 148 | .ok_or(Error::Unsupported("a card from an app without a bot"))?; |
| 149 | Ok((app.clone(), bot_id)) |
| 150 | } |
| 151 | } |
| 152 | |
| 153 | fn outcome_of(response: InvokeResponse) -> CardActionOutcome { |
| 154 | match response { |
| 155 | InvokeResponse::Empty => CardActionOutcome::Sent, |
| 156 | InvokeResponse::Card(card) => CardActionOutcome::ReplaceCard(card.to_string()), |
| 157 | InvokeResponse::Message(text) | InvokeResponse::Task(TaskResponse::Message(text)) => { |
| 158 | CardActionOutcome::Message(text) |
| 159 | } |
| 160 | InvokeResponse::Task(TaskResponse::Continue(task)) => { |
| 161 | CardActionOutcome::Dialog(dialog_of(task)) |
| 162 | } |
| 163 | InvokeResponse::Failed { |
| 164 | status_code, |
| 165 | message, |
| 166 | } => { |
| 167 | let detail: String = message.chars().take(MAX_FAILURE_CHARS).collect(); |
| 168 | CardActionOutcome::Failed(format!("The app answered {status_code}: {detail}")) |
| 169 | } |
| 170 | } |
| 171 | } |
| 172 | |
| 173 | fn dialog_of(task: TaskContinue) -> TaskDialog { |
| 174 | TaskDialog { |
| 175 | title: task.title, |
| 176 | width: task.width.unwrap_or(DEFAULT_DIALOG_WIDTH), |
| 177 | height: task.height.unwrap_or(DEFAULT_DIALOG_HEIGHT), |
| 178 | kind: match task.content { |
| 179 | TaskContent::Url { url, fallback_url } => TaskDialogKind::Url { |
| 180 | fallback_url: fallback_url.unwrap_or_else(|| url.clone()), |
| 181 | url, |
| 182 | }, |
| 183 | TaskContent::Card(card) => TaskDialogKind::Card(card.to_string()), |
| 184 | }, |
| 185 | } |
| 186 | } |