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