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