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