| 1 | use std::collections::HashMap; |
| 2 | use std::time::Duration; |
| 3 | |
| 4 | use chrono::{DateTime, Utc}; |
| 5 | use gpui_kit::*; |
| 6 | use serde_json::Value; |
| 7 | use teams_core::{ |
| 8 | Language, LanguageSettings, Translation, TranslationBehavior, TranslationStatus, |
| 9 | TranslationTrigger, authoring_patch, behavior_patch, offered_language, parse_language_settings, |
| 10 | target_patch, |
| 11 | }; |
| 12 | |
| 13 | use crate::app_state::{AppEvent, AppState}; |
| 14 | use crate::notice::short_error; |
| 15 | use crate::runtime; |
| 16 | use crate::translation::message_version; |
| 17 | |
| 18 | const SETTINGS_META_KEY: &str = "translation_settings"; |
| 19 | const LANGUAGES_META_KEY: &str = "translation_languages"; |
| 20 | const LANGUAGES_AT_META_KEY: &str = "translation_languages_at"; |
| 21 | const LANGUAGES_TTL_HOURS: i64 = 24; |
| 22 | const DEFAULT_LOCALE: &str = "en"; |
| 23 | const AUTO_DEBOUNCE: Duration = Duration::from_millis(300); |
| 24 | const STAMP_WINDOW: usize = 50; |
| 25 | const META_USER_ID: &str = "me_user_id"; |
| 26 | |
| 27 | type TranslationOutcome = Result<Vec<Translation>, String>; |
| 28 | |
| 29 | impl AppState { |
| 30 | pub fn load_cached_translation_settings(&mut self) { |
| 31 | self.translation.settings = self |
| 32 | .store |
| 33 | .meta(SETTINGS_META_KEY) |
| 34 | .ok() |
| 35 | .flatten() |
| 36 | .and_then(|text| serde_json::from_str::<Value>(&text).ok()) |
| 37 | .and_then(|value| parse_language_settings(&value).ok()); |
| 38 | self.apply_regional_format(); |
| 39 | self.translation.languages = self |
| 40 | .store |
| 41 | .meta(LANGUAGES_META_KEY) |
| 42 | .ok() |
| 43 | .flatten() |
| 44 | .and_then(|text| serde_json::from_str::<Vec<(String, String)>>(&text).ok()) |
| 45 | .map(|pairs| { |
| 46 | pairs |
| 47 | .into_iter() |
| 48 | .map(|(code, name)| Language { code, name }) |
| 49 | .collect() |
| 50 | }) |
| 51 | .unwrap_or_default(); |
| 52 | self.translation.languages_fetched_at = self |
| 53 | .store |
| 54 | .meta(LANGUAGES_AT_META_KEY) |
| 55 | .ok() |
| 56 | .flatten() |
| 57 | .and_then(|text| DateTime::parse_from_rfc3339(&text).ok()) |
| 58 | .map(|time| time.with_timezone(&Utc)); |
| 59 | } |
| 60 | |
| 61 | fn save_translation_settings(&self) { |
| 62 | if let Some(settings) = &self.translation.settings { |
| 63 | let _ = self |
| 64 | .store |
| 65 | .set_meta(SETTINGS_META_KEY, &settings.to_account_value().to_string()); |
| 66 | } |
| 67 | } |
| 68 | |
| 69 | fn save_translation_languages(&self) { |
| 70 | let pairs: Vec<(&str, &str)> = self |
| 71 | .translation |
| 72 | .languages |
| 73 | .iter() |
| 74 | .map(|language| (language.code.as_str(), language.name.as_str())) |
| 75 | .collect(); |
| 76 | let _ = self.store.set_meta( |
| 77 | LANGUAGES_META_KEY, |
| 78 | &serde_json::to_string(&pairs).unwrap_or_default(), |
| 79 | ); |
| 80 | if let Some(fetched_at) = self.translation.languages_fetched_at { |
| 81 | let _ = self |
| 82 | .store |
| 83 | .set_meta(LANGUAGES_AT_META_KEY, &fetched_at.to_rfc3339()); |
| 84 | } |
| 85 | } |
| 86 | |
| 87 | pub fn refresh_translation_settings(&mut self, cx: &mut Context<Self>) { |
| 88 | self.load_cached_translation_settings(); |
| 89 | let Some(engine) = self.engine.clone() else { |
| 90 | return; |
| 91 | }; |
| 92 | let languages_stale = self.translation.languages.is_empty() |
| 93 | || self.translation.languages_fetched_at.is_none_or(|fetched| { |
| 94 | Utc::now() - fetched > chrono::Duration::hours(LANGUAGES_TTL_HOURS) |
| 95 | }); |
| 96 | let cached_locale = self |
| 97 | .translation |
| 98 | .settings |
| 99 | .as_ref() |
| 100 | .and_then(|settings| settings.display_locale.clone()); |
| 101 | let receiver = runtime::spawn(async move { |
| 102 | let settings = engine.language_settings().await; |
| 103 | let locale = settings |
| 104 | .as_ref() |
| 105 | .ok() |
| 106 | .and_then(|settings| settings.display_locale.clone()) |
| 107 | .or(cached_locale) |
| 108 | .unwrap_or_else(|| DEFAULT_LOCALE.to_owned()); |
| 109 | let languages = if languages_stale { |
| 110 | engine.translation_languages(&locale).await.ok() |
| 111 | } else { |
| 112 | None |
| 113 | }; |
| 114 | (settings, languages) |
| 115 | }); |
| 116 | cx.spawn(async move |this, cx| { |
| 117 | let Ok((settings, languages)) = receiver.await else { |
| 118 | return; |
| 119 | }; |
| 120 | this.update(cx, |state, cx| { |
| 121 | if let Ok(settings) = settings { |
| 122 | state.translation.settings = Some(settings); |
| 123 | state.apply_regional_format(); |
| 124 | state.save_translation_settings(); |
| 125 | } |
| 126 | if let Some(languages) = languages.filter(|languages| !languages.is_empty()) { |
| 127 | state.translation.languages = languages; |
| 128 | state.translation.languages_fetched_at = Some(Utc::now()); |
| 129 | state.save_translation_languages(); |
| 130 | } |
| 131 | state.translation_changed(cx); |
| 132 | state.refresh_selected_translation(cx); |
| 133 | }) |
| 134 | .ok(); |
| 135 | }) |
| 136 | .detach(); |
| 137 | } |
| 138 | |
| 139 | fn translation_changed(&mut self, cx: &mut Context<Self>) { |
| 140 | cx.emit(AppEvent::Translation); |
| 141 | cx.notify(); |
| 142 | } |
| 143 | |
| 144 | fn refresh_selected_translation(&mut self, cx: &mut Context<Self>) { |
| 145 | let Some(selection) = self.selection.clone() else { |
| 146 | return; |
| 147 | }; |
| 148 | self.refresh_language_stamps(selection.conversation_id(), cx); |
| 149 | self.schedule_auto_translate(selection.conversation_id(), cx); |
| 150 | } |
| 151 | |
| 152 | pub fn refresh_language_stamps(&mut self, conversation_id: &str, cx: &mut Context<Self>) { |
| 153 | if self.translation.settings.is_none() |
| 154 | || self.translation.behavior() == TranslationBehavior::Never |
| 155 | { |
| 156 | return; |
| 157 | } |
| 158 | if self.mode.demo { |
| 159 | let stamps = crate::demo::language_stamps(conversation_id); |
| 160 | if self.translation.merge_stamps(conversation_id, stamps) { |
| 161 | self.translation_changed(cx); |
| 162 | } |
| 163 | self.schedule_auto_translate(conversation_id, cx); |
| 164 | return; |
| 165 | } |
| 166 | let Some(engine) = self.engine.clone() else { |
| 167 | return; |
| 168 | }; |
| 169 | let unasked = self.unasked_message_ids(conversation_id); |
| 170 | if unasked.is_empty() |
| 171 | || !self |
| 172 | .translation |
| 173 | .stamps_in_flight |
| 174 | .insert(conversation_id.to_owned()) |
| 175 | { |
| 176 | return; |
| 177 | } |
| 178 | let conversation_id = conversation_id.to_owned(); |
| 179 | let requested = conversation_id.clone(); |
| 180 | let receiver = runtime::spawn(async move { engine.language_stamps(&requested).await }); |
| 181 | cx.spawn(async move |this, cx| { |
| 182 | let outcome = receiver.await; |
| 183 | this.update(cx, |state, cx| { |
| 184 | state.translation.stamps_in_flight.remove(&conversation_id); |
| 185 | let Ok(Ok(found)) = outcome else { |
| 186 | return; |
| 187 | }; |
| 188 | state.translation.mark_asked(&conversation_id, unasked); |
| 189 | let stamps: HashMap<String, String> = found |
| 190 | .into_iter() |
| 191 | .map(|entry| (entry.message_id, entry.stamp)) |
| 192 | .collect(); |
| 193 | if state.translation.merge_stamps(&conversation_id, stamps) { |
| 194 | state.translation_changed(cx); |
| 195 | } |
| 196 | state.schedule_auto_translate(&conversation_id, cx); |
| 197 | }) |
| 198 | .ok(); |
| 199 | }) |
| 200 | .detach(); |
| 201 | } |
| 202 | |
| 203 | fn unasked_message_ids(&self, conversation_id: &str) -> Vec<String> { |
| 204 | let my_user_id = self.store.meta(META_USER_ID).ok().flatten(); |
| 205 | let records = self |
| 206 | .store |
| 207 | .messages(conversation_id, None, STAMP_WINDOW) |
| 208 | .unwrap_or_default(); |
| 209 | records |
| 210 | .into_iter() |
| 211 | .filter(|record| !record.deleted && record.sender_id != my_user_id) |
| 212 | .map(|record| record.message_id) |
| 213 | .filter(|message_id| !self.translation.was_asked(conversation_id, message_id)) |
| 214 | .collect() |
| 215 | } |
| 216 | |
| 217 | fn schedule_auto_translate(&mut self, conversation_id: &str, cx: &mut Context<Self>) { |
| 218 | if self.translation.behavior() != TranslationBehavior::Auto |
| 219 | || !self |
| 220 | .translation |
| 221 | .auto_scheduled |
| 222 | .insert(conversation_id.to_owned()) |
| 223 | { |
| 224 | return; |
| 225 | } |
| 226 | let conversation_id = conversation_id.to_owned(); |
| 227 | cx.spawn(async move |this, cx| { |
| 228 | cx.background_executor().timer(AUTO_DEBOUNCE).await; |
| 229 | this.update(cx, |state, cx| { |
| 230 | state.translation.auto_scheduled.remove(&conversation_id); |
| 231 | state.run_auto_translate(&conversation_id, cx); |
| 232 | }) |
| 233 | .ok(); |
| 234 | }) |
| 235 | .detach(); |
| 236 | } |
| 237 | |
| 238 | fn run_auto_translate(&mut self, conversation_id: &str, cx: &mut Context<Self>) { |
| 239 | if self.translation.behavior() != TranslationBehavior::Auto { |
| 240 | return; |
| 241 | } |
| 242 | let Some(stamps) = self.translation.stamps.get(conversation_id).cloned() else { |
| 243 | return; |
| 244 | }; |
| 245 | let ids: Vec<String> = stamps.keys().cloned().collect(); |
| 246 | let records = self |
| 247 | .store |
| 248 | .messages_by_id(conversation_id, &ids) |
| 249 | .unwrap_or_default(); |
| 250 | let my_user_id = self.store.meta(META_USER_ID).ok().flatten(); |
| 251 | let (target, never) = (self.translation.target(), self.translation.never_codes()); |
| 252 | let mut due: Vec<(String, i64)> = records |
| 253 | .values() |
| 254 | .filter(|record| !record.deleted && record.sender_id != my_user_id) |
| 255 | .filter(|record| { |
| 256 | let id = &record.message_id; |
| 257 | !self.translation.is_pending(conversation_id, id) |
| 258 | && !self.translation.is_failed(conversation_id, id) |
| 259 | && !self |
| 260 | .translation |
| 261 | .is_cached(conversation_id, id, message_version(record)) |
| 262 | }) |
| 263 | .filter(|record| { |
| 264 | stamps |
| 265 | .get(&record.message_id) |
| 266 | .and_then(|stamp| offered_language(stamp, &target, &never)) |
| 267 | .is_some() |
| 268 | }) |
| 269 | .map(|record| (record.message_id.clone(), message_version(record))) |
| 270 | .collect(); |
| 271 | if due.is_empty() { |
| 272 | return; |
| 273 | } |
| 274 | due.sort(); |
| 275 | let trigger = TranslationTrigger::Automatic { |
| 276 | known_languages: never, |
| 277 | }; |
| 278 | self.request_translation(conversation_id, due, trigger, cx); |
| 279 | } |
| 280 | |
| 281 | /// Offer link, menu item, retry and the See original toggle: flips a stored translation or asks for a new one. |
| 282 | pub fn translate_message( |
| 283 | &mut self, |
| 284 | conversation_id: &str, |
| 285 | message_id: &str, |
| 286 | cx: &mut Context<Self>, |
| 287 | ) { |
| 288 | let Some(record) = self.message_record(conversation_id, message_id) else { |
| 289 | return; |
| 290 | }; |
| 291 | let version = message_version(&record); |
| 292 | if self |
| 293 | .translation |
| 294 | .is_cached(conversation_id, message_id, version) |
| 295 | { |
| 296 | self.translation.toggle(conversation_id, message_id); |
| 297 | self.translation_changed(cx); |
| 298 | return; |
| 299 | } |
| 300 | let items = vec![(message_id.to_owned(), version)]; |
| 301 | self.request_translation(conversation_id, items, TranslationTrigger::OnDemand, cx); |
| 302 | } |
| 303 | |
| 304 | fn request_translation( |
| 305 | &mut self, |
| 306 | conversation_id: &str, |
| 307 | items: Vec<(String, i64)>, |
| 308 | trigger: TranslationTrigger, |
| 309 | cx: &mut Context<Self>, |
| 310 | ) { |
| 311 | let target = self.translation.target(); |
| 312 | let engine = self.engine.clone(); |
| 313 | if engine.is_none() && !self.mode.demo { |
| 314 | return; |
| 315 | } |
| 316 | for (message_id, _) in &items { |
| 317 | self.translation.start(conversation_id, message_id); |
| 318 | } |
| 319 | self.translation_changed(cx); |
| 320 | let conversation_id = conversation_id.to_owned(); |
| 321 | let Some(engine) = engine else { |
| 322 | let outcome = Ok(crate::demo::translations( |
| 323 | &items.iter().map(|(id, _)| id.clone()).collect::<Vec<_>>(), |
| 324 | )); |
| 325 | self.apply_translations(&conversation_id, &items, &target, outcome, cx); |
| 326 | return; |
| 327 | }; |
| 328 | let ids: Vec<String> = items.iter().map(|(id, _)| id.clone()).collect(); |
| 329 | let (requested_conversation, requested_target) = (conversation_id.clone(), target.clone()); |
| 330 | let receiver = runtime::spawn(async move { |
| 331 | engine |
| 332 | .translate_messages(&requested_conversation, &ids, &requested_target, &trigger) |
| 333 | .await |
| 334 | }); |
| 335 | cx.spawn(async move |this, cx| { |
| 336 | let outcome = match receiver.await { |
| 337 | Ok(Ok(translations)) => Ok(translations), |
| 338 | Ok(Err(error)) => Err(short_error(&error)), |
| 339 | Err(_) => Err("cancelled".to_owned()), |
| 340 | }; |
| 341 | this.update(cx, |state, cx| { |
| 342 | state.apply_translations(&conversation_id, &items, &target, outcome, cx) |
| 343 | }) |
| 344 | .ok(); |
| 345 | }) |
| 346 | .detach(); |
| 347 | } |
| 348 | |
| 349 | fn apply_translations( |
| 350 | &mut self, |
| 351 | conversation_id: &str, |
| 352 | items: &[(String, i64)], |
| 353 | target: &str, |
| 354 | outcome: TranslationOutcome, |
| 355 | cx: &mut Context<Self>, |
| 356 | ) { |
| 357 | let answered = outcome.unwrap_or_default(); |
| 358 | for (message_id, version) in items { |
| 359 | let html = answered |
| 360 | .iter() |
| 361 | .find(|translation| { |
| 362 | translation.message_id == *message_id |
| 363 | && translation.status == TranslationStatus::Done |
| 364 | }) |
| 365 | .and_then(|translation| translation.content_html.clone()); |
| 366 | match html { |
| 367 | Some(html) => { |
| 368 | self.translation |
| 369 | .finish(conversation_id, message_id, *version, target, html) |
| 370 | } |
| 371 | None => self.translation.fail(conversation_id, message_id), |
| 372 | } |
| 373 | } |
| 374 | self.translation_changed(cx); |
| 375 | } |
| 376 | |
| 377 | pub fn set_translation_target(&mut self, code: &str, cx: &mut Context<Self>) { |
| 378 | let Some(settings) = self.translation.settings.clone() else { |
| 379 | return; |
| 380 | }; |
| 381 | let mut updated = settings.clone(); |
| 382 | updated.target_locale = Some(code.to_owned()); |
| 383 | self.update_language_settings("Translation language", updated, target_patch(code), cx); |
| 384 | } |
| 385 | |
| 386 | pub fn set_translation_behavior( |
| 387 | &mut self, |
| 388 | behavior: TranslationBehavior, |
| 389 | cx: &mut Context<Self>, |
| 390 | ) { |
| 391 | let Some(settings) = self.translation.settings.clone() else { |
| 392 | return; |
| 393 | }; |
| 394 | let patch = behavior_patch(&settings, behavior); |
| 395 | let mut updated = settings; |
| 396 | updated.behavior = behavior; |
| 397 | updated.preferences = patch["translationPreferences"] |
| 398 | .as_object() |
| 399 | .cloned() |
| 400 | .unwrap_or_default(); |
| 401 | self.update_language_settings("Translation setting", updated, patch, cx); |
| 402 | } |
| 403 | |
| 404 | pub fn never_translate_language(&mut self, code: &str, cx: &mut Context<Self>) { |
| 405 | let Some(settings) = self.translation.settings.clone() else { |
| 406 | return; |
| 407 | }; |
| 408 | let locales = settings.with_never_translate(code); |
| 409 | self.set_never_translate_locales(settings, locales, cx); |
| 410 | } |
| 411 | |
| 412 | pub fn allow_translating_language(&mut self, code: &str, cx: &mut Context<Self>) { |
| 413 | let Some(settings) = self.translation.settings.clone() else { |
| 414 | return; |
| 415 | }; |
| 416 | let locales = settings.without_never_translate(code); |
| 417 | self.set_never_translate_locales(settings, locales, cx); |
| 418 | } |
| 419 | |
| 420 | fn set_never_translate_locales( |
| 421 | &mut self, |
| 422 | settings: LanguageSettings, |
| 423 | locales: Vec<String>, |
| 424 | cx: &mut Context<Self>, |
| 425 | ) { |
| 426 | let patch = authoring_patch(&locales); |
| 427 | let mut updated = settings; |
| 428 | updated.authoring_locales = locales; |
| 429 | self.update_language_settings("Translation setting", updated, patch, cx); |
| 430 | } |
| 431 | |
| 432 | fn update_language_settings( |
| 433 | &mut self, |
| 434 | label: &'static str, |
| 435 | updated: LanguageSettings, |
| 436 | patch: Value, |
| 437 | cx: &mut Context<Self>, |
| 438 | ) { |
| 439 | let Some(engine_or_demo) = self.chat_action_engine(cx) else { |
| 440 | return; |
| 441 | }; |
| 442 | let previous = self.translation.settings.replace(updated); |
| 443 | self.save_translation_settings(); |
| 444 | self.translation_changed(cx); |
| 445 | self.refresh_selected_translation(cx); |
| 446 | let Some(engine) = engine_or_demo else { |
| 447 | return; |
| 448 | }; |
| 449 | self.run_chat_action( |
| 450 | label, |
| 451 | async move { engine.patch_language_settings(patch).await }, |
| 452 | move |state, cx| { |
| 453 | state.translation.settings = previous; |
| 454 | state.save_translation_settings(); |
| 455 | state.translation_changed(cx); |
| 456 | }, |
| 457 | |_, _| {}, |
| 458 | cx, |
| 459 | ); |
| 460 | } |
| 461 | } |