| 1 | use std::collections::{HashMap, HashSet}; |
| 2 | |
| 3 | use chrono::{DateTime, Utc}; |
| 4 | use store::MessageRecord; |
| 5 | use teams_core::{ |
| 6 | FALLBACK_TARGET, Language, LanguageSettings, LanguageStamp, TranslationBehavior, |
| 7 | default_target, language_name, offered_language, |
| 8 | }; |
| 9 | |
| 10 | pub type MessageKey = (String, String); |
| 11 | |
| 12 | #[derive(Debug, Clone, PartialEq)] |
| 13 | pub enum TranslationLine { |
| 14 | Offer { |
| 15 | language_code: String, |
| 16 | language: String, |
| 17 | }, |
| 18 | Working, |
| 19 | Failed, |
| 20 | Translated { |
| 21 | language: Option<String>, |
| 22 | showing_original: bool, |
| 23 | }, |
| 24 | } |
| 25 | |
| 26 | #[derive(Debug, Clone, PartialEq)] |
| 27 | pub struct CachedTranslation { |
| 28 | pub html: String, |
| 29 | pub source: Option<String>, |
| 30 | } |
| 31 | |
| 32 | #[derive(Debug, Clone, PartialEq, Eq, Hash)] |
| 33 | struct CacheKey { |
| 34 | conversation_id: String, |
| 35 | message_id: String, |
| 36 | version: i64, |
| 37 | target: String, |
| 38 | } |
| 39 | |
| 40 | #[derive(Debug, Clone, Default)] |
| 41 | pub struct TranslationContext { |
| 42 | pub enabled: bool, |
| 43 | pub target: String, |
| 44 | pub behavior: TranslationBehavior, |
| 45 | pub never: Vec<String>, |
| 46 | pub languages: Vec<Language>, |
| 47 | pub stamps: HashMap<String, String>, |
| 48 | pub cached: HashMap<(String, i64), CachedTranslation>, |
| 49 | pub shown: HashSet<String>, |
| 50 | pub working: HashSet<String>, |
| 51 | pub failed: HashSet<String>, |
| 52 | } |
| 53 | |
| 54 | #[derive(Debug, Clone, Default, PartialEq)] |
| 55 | pub struct RowTranslation { |
| 56 | pub line: Option<TranslationLine>, |
| 57 | pub translated_html: Option<String>, |
| 58 | } |
| 59 | |
| 60 | pub fn message_version(record: &MessageRecord) -> i64 { |
| 61 | record |
| 62 | .edited_at |
| 63 | .map_or(0, |edited| edited.timestamp_millis()) |
| 64 | } |
| 65 | |
| 66 | impl TranslationContext { |
| 67 | pub fn resolve(&self, record: &MessageRecord, own: bool) -> RowTranslation { |
| 68 | if !self.enabled || record.deleted { |
| 69 | return RowTranslation::default(); |
| 70 | } |
| 71 | let id = &record.message_id; |
| 72 | if self.working.contains(id) { |
| 73 | return line_only(TranslationLine::Working); |
| 74 | } |
| 75 | let version = message_version(record); |
| 76 | if let Some(cached) = self.cached.get(&(id.clone(), version)) { |
| 77 | let showing = self.shown.contains(id); |
| 78 | return RowTranslation { |
| 79 | line: Some(TranslationLine::Translated { |
| 80 | language: cached |
| 81 | .source |
| 82 | .as_deref() |
| 83 | .map(|code| language_name(code, &self.languages)), |
| 84 | showing_original: !showing, |
| 85 | }), |
| 86 | translated_html: showing.then(|| cached.html.clone()), |
| 87 | }; |
| 88 | } |
| 89 | if self.failed.contains(id) { |
| 90 | return line_only(TranslationLine::Failed); |
| 91 | } |
| 92 | if own || self.behavior != TranslationBehavior::Ask { |
| 93 | return RowTranslation::default(); |
| 94 | } |
| 95 | let offered = self |
| 96 | .stamps |
| 97 | .get(id) |
| 98 | .and_then(|stamp| offered_language(stamp, &self.target, &self.never)); |
| 99 | match offered { |
| 100 | Some(code) => line_only(TranslationLine::Offer { |
| 101 | language: language_name(&code, &self.languages), |
| 102 | language_code: code, |
| 103 | }), |
| 104 | None => RowTranslation::default(), |
| 105 | } |
| 106 | } |
| 107 | } |
| 108 | |
| 109 | fn line_only(line: TranslationLine) -> RowTranslation { |
| 110 | RowTranslation { |
| 111 | line: Some(line), |
| 112 | translated_html: None, |
| 113 | } |
| 114 | } |
| 115 | |
| 116 | #[derive(Default)] |
| 117 | pub struct TranslationState { |
| 118 | pub settings: Option<LanguageSettings>, |
| 119 | pub languages: Vec<Language>, |
| 120 | pub languages_fetched_at: Option<DateTime<Utc>>, |
| 121 | pub stamps: HashMap<String, HashMap<String, String>>, |
| 122 | pub stamps_in_flight: HashSet<String>, |
| 123 | asked: HashMap<String, HashSet<String>>, |
| 124 | pub auto_scheduled: HashSet<String>, |
| 125 | cache: HashMap<CacheKey, CachedTranslation>, |
| 126 | shown: HashSet<MessageKey>, |
| 127 | working: HashSet<MessageKey>, |
| 128 | failed: HashSet<MessageKey>, |
| 129 | } |
| 130 | |
| 131 | impl TranslationState { |
| 132 | pub fn target(&self) -> String { |
| 133 | match &self.settings { |
| 134 | Some(settings) => default_target( |
| 135 | settings.target_locale.as_deref(), |
| 136 | settings.display_locale.as_deref(), |
| 137 | &self.languages, |
| 138 | ), |
| 139 | None => FALLBACK_TARGET.to_owned(), |
| 140 | } |
| 141 | } |
| 142 | |
| 143 | pub fn behavior(&self) -> TranslationBehavior { |
| 144 | self.settings |
| 145 | .as_ref() |
| 146 | .map_or(TranslationBehavior::Ask, |settings| settings.behavior) |
| 147 | } |
| 148 | |
| 149 | /// The target counts as known, so nothing in it is ever offered. |
| 150 | pub fn never_codes(&self) -> Vec<String> { |
| 151 | let mut codes = self |
| 152 | .settings |
| 153 | .as_ref() |
| 154 | .map(LanguageSettings::never_translate_codes) |
| 155 | .unwrap_or_default(); |
| 156 | let target = self.target(); |
| 157 | if !codes.contains(&target) { |
| 158 | codes.push(target); |
| 159 | } |
| 160 | codes |
| 161 | } |
| 162 | |
| 163 | pub fn display_codes(&self) -> Vec<String> { |
| 164 | self.settings |
| 165 | .as_ref() |
| 166 | .map(LanguageSettings::never_translate_codes) |
| 167 | .unwrap_or_default() |
| 168 | } |
| 169 | |
| 170 | pub fn language_name(&self, code: &str) -> String { |
| 171 | language_name(code, &self.languages) |
| 172 | } |
| 173 | |
| 174 | pub fn context_for(&self, conversation_id: &str) -> TranslationContext { |
| 175 | let target = self.target(); |
| 176 | let of_conversation = |key: &MessageKey| (key.0 == conversation_id).then(|| key.1.clone()); |
| 177 | TranslationContext { |
| 178 | enabled: self.settings.is_some(), |
| 179 | behavior: self.behavior(), |
| 180 | never: self.never_codes(), |
| 181 | languages: self.languages.clone(), |
| 182 | stamps: self |
| 183 | .stamps |
| 184 | .get(conversation_id) |
| 185 | .cloned() |
| 186 | .unwrap_or_default(), |
| 187 | cached: self |
| 188 | .cache |
| 189 | .iter() |
| 190 | .filter(|(key, _)| key.conversation_id == conversation_id && key.target == target) |
| 191 | .map(|(key, cached)| ((key.message_id.clone(), key.version), cached.clone())) |
| 192 | .collect(), |
| 193 | shown: self.shown.iter().filter_map(of_conversation).collect(), |
| 194 | working: self.working.iter().filter_map(of_conversation).collect(), |
| 195 | failed: self.failed.iter().filter_map(of_conversation).collect(), |
| 196 | target, |
| 197 | } |
| 198 | } |
| 199 | |
| 200 | pub fn is_cached(&self, conversation_id: &str, message_id: &str, version: i64) -> bool { |
| 201 | self.cache.contains_key(&CacheKey { |
| 202 | conversation_id: conversation_id.to_owned(), |
| 203 | message_id: message_id.to_owned(), |
| 204 | version, |
| 205 | target: self.target(), |
| 206 | }) |
| 207 | } |
| 208 | |
| 209 | pub fn is_pending(&self, conversation_id: &str, message_id: &str) -> bool { |
| 210 | self.working |
| 211 | .contains(&(conversation_id.to_owned(), message_id.to_owned())) |
| 212 | } |
| 213 | |
| 214 | pub fn is_failed(&self, conversation_id: &str, message_id: &str) -> bool { |
| 215 | self.failed |
| 216 | .contains(&(conversation_id.to_owned(), message_id.to_owned())) |
| 217 | } |
| 218 | |
| 219 | pub fn start(&mut self, conversation_id: &str, message_id: &str) { |
| 220 | let key = (conversation_id.to_owned(), message_id.to_owned()); |
| 221 | self.failed.remove(&key); |
| 222 | self.working.insert(key); |
| 223 | } |
| 224 | |
| 225 | pub fn fail(&mut self, conversation_id: &str, message_id: &str) { |
| 226 | let key = (conversation_id.to_owned(), message_id.to_owned()); |
| 227 | self.working.remove(&key); |
| 228 | self.failed.insert(key); |
| 229 | } |
| 230 | |
| 231 | pub fn finish( |
| 232 | &mut self, |
| 233 | conversation_id: &str, |
| 234 | message_id: &str, |
| 235 | version: i64, |
| 236 | target: &str, |
| 237 | html: String, |
| 238 | ) { |
| 239 | let key = (conversation_id.to_owned(), message_id.to_owned()); |
| 240 | self.working.remove(&key); |
| 241 | self.failed.remove(&key); |
| 242 | let source = self |
| 243 | .stamps |
| 244 | .get(conversation_id) |
| 245 | .and_then(|stamps| stamps.get(message_id)) |
| 246 | .and_then(|stamp| LanguageStamp::parse(stamp)) |
| 247 | .and_then(|stamp| stamp.candidates.first().map(|(code, _)| code.clone())); |
| 248 | self.cache.insert( |
| 249 | CacheKey { |
| 250 | conversation_id: conversation_id.to_owned(), |
| 251 | message_id: message_id.to_owned(), |
| 252 | version, |
| 253 | target: target.to_owned(), |
| 254 | }, |
| 255 | CachedTranslation { html, source }, |
| 256 | ); |
| 257 | self.shown.insert(key); |
| 258 | } |
| 259 | |
| 260 | /// Flips between the translation and the original of a message that has a stored translation. |
| 261 | pub fn toggle(&mut self, conversation_id: &str, message_id: &str) { |
| 262 | let key = (conversation_id.to_owned(), message_id.to_owned()); |
| 263 | if !self.shown.remove(&key) { |
| 264 | self.shown.insert(key); |
| 265 | } |
| 266 | } |
| 267 | |
| 268 | pub fn mark_asked(&mut self, conversation_id: &str, message_ids: Vec<String>) { |
| 269 | self.asked |
| 270 | .entry(conversation_id.to_owned()) |
| 271 | .or_default() |
| 272 | .extend(message_ids); |
| 273 | } |
| 274 | |
| 275 | pub fn was_asked(&self, conversation_id: &str, message_id: &str) -> bool { |
| 276 | self.asked |
| 277 | .get(conversation_id) |
| 278 | .is_some_and(|asked| asked.contains(message_id)) |
| 279 | } |
| 280 | |
| 281 | pub fn merge_stamps(&mut self, conversation_id: &str, stamps: HashMap<String, String>) -> bool { |
| 282 | let known = self.stamps.entry(conversation_id.to_owned()).or_default(); |
| 283 | let before = known.len(); |
| 284 | let mut changed = false; |
| 285 | for (message_id, stamp) in stamps { |
| 286 | changed |= known.insert(message_id, stamp.clone()).as_ref() != Some(&stamp); |
| 287 | } |
| 288 | changed || known.len() != before |
| 289 | } |
| 290 | } |
| 291 | |
| 292 | #[cfg(test)] |
| 293 | mod tests { |
| 294 | use chrono::TimeZone; |
| 295 | |
| 296 | use super::*; |
| 297 | |
| 298 | const FRENCH: &str = "languages=fr:100;en:10;length:80;&detector=Bling"; |
| 299 | |
| 300 | fn record(id: &str) -> MessageRecord { |
| 301 | MessageRecord { |
| 302 | message_id: id.to_owned(), |
| 303 | conversation_id: "chat".to_owned(), |
| 304 | body_html: "<p>Bonjour</p>".to_owned(), |
| 305 | ..MessageRecord::default() |
| 306 | } |
| 307 | } |
| 308 | |
| 309 | fn state_with_stamp() -> TranslationState { |
| 310 | let mut state = TranslationState { |
| 311 | settings: Some(LanguageSettings::default()), |
| 312 | ..TranslationState::default() |
| 313 | }; |
| 314 | state.merge_stamps( |
| 315 | "chat", |
| 316 | HashMap::from([("m1".to_owned(), FRENCH.to_owned())]), |
| 317 | ); |
| 318 | state |
| 319 | } |
| 320 | |
| 321 | #[test] |
| 322 | fn a_confident_foreign_message_gets_an_offer_in_ask_mode() { |
| 323 | let context = state_with_stamp().context_for("chat"); |
| 324 | let resolved = context.resolve(&record("m1"), false); |
| 325 | assert_eq!( |
| 326 | resolved.line, |
| 327 | Some(TranslationLine::Offer { |
| 328 | language_code: "fr".into(), |
| 329 | language: "French".into() |
| 330 | }) |
| 331 | ); |
| 332 | assert_eq!(resolved.translated_html, None); |
| 333 | } |
| 334 | |
| 335 | #[test] |
| 336 | fn own_messages_and_unknown_settings_get_no_offer() { |
| 337 | let context = state_with_stamp().context_for("chat"); |
| 338 | assert_eq!( |
| 339 | context.resolve(&record("m1"), true), |
| 340 | RowTranslation::default() |
| 341 | ); |
| 342 | let mut unready = state_with_stamp(); |
| 343 | unready.settings = None; |
| 344 | assert_eq!( |
| 345 | unready.context_for("chat").resolve(&record("m1"), false), |
| 346 | RowTranslation::default() |
| 347 | ); |
| 348 | } |
| 349 | |
| 350 | #[test] |
| 351 | fn other_modes_and_the_never_list_get_no_offer() { |
| 352 | let mut state = state_with_stamp(); |
| 353 | let settings = state.settings.as_mut().unwrap(); |
| 354 | settings.behavior = TranslationBehavior::Never; |
| 355 | assert_eq!( |
| 356 | state.context_for("chat").resolve(&record("m1"), false), |
| 357 | RowTranslation::default() |
| 358 | ); |
| 359 | let settings = state.settings.as_mut().unwrap(); |
| 360 | settings.behavior = TranslationBehavior::Ask; |
| 361 | settings.authoring_locales = vec!["fr-FR".into()]; |
| 362 | assert_eq!( |
| 363 | state.context_for("chat").resolve(&record("m1"), false), |
| 364 | RowTranslation::default() |
| 365 | ); |
| 366 | } |
| 367 | |
| 368 | #[test] |
| 369 | fn a_message_without_a_stamp_gets_no_offer() { |
| 370 | let context = state_with_stamp().context_for("chat"); |
| 371 | assert_eq!( |
| 372 | context.resolve(&record("m2"), false), |
| 373 | RowTranslation::default() |
| 374 | ); |
| 375 | } |
| 376 | |
| 377 | #[test] |
| 378 | fn working_then_translated_then_toggled_back() { |
| 379 | let mut state = state_with_stamp(); |
| 380 | state.start("chat", "m1"); |
| 381 | let working = state.context_for("chat").resolve(&record("m1"), false); |
| 382 | assert_eq!(working.line, Some(TranslationLine::Working)); |
| 383 | |
| 384 | state.finish("chat", "m1", 0, "en", "<p>Hello</p>".into()); |
| 385 | let shown = state.context_for("chat").resolve(&record("m1"), false); |
| 386 | assert_eq!(shown.translated_html.as_deref(), Some("<p>Hello</p>")); |
| 387 | assert_eq!( |
| 388 | shown.line, |
| 389 | Some(TranslationLine::Translated { |
| 390 | language: Some("French".into()), |
| 391 | showing_original: false |
| 392 | }) |
| 393 | ); |
| 394 | |
| 395 | state.toggle("chat", "m1"); |
| 396 | let original = state.context_for("chat").resolve(&record("m1"), false); |
| 397 | assert_eq!(original.translated_html, None); |
| 398 | assert_eq!( |
| 399 | original.line, |
| 400 | Some(TranslationLine::Translated { |
| 401 | language: Some("French".into()), |
| 402 | showing_original: true |
| 403 | }) |
| 404 | ); |
| 405 | |
| 406 | state.toggle("chat", "m1"); |
| 407 | assert!( |
| 408 | state |
| 409 | .context_for("chat") |
| 410 | .resolve(&record("m1"), false) |
| 411 | .translated_html |
| 412 | .is_some() |
| 413 | ); |
| 414 | } |
| 415 | |
| 416 | #[test] |
| 417 | fn a_failed_request_shows_the_retry_line_until_started_again() { |
| 418 | let mut state = state_with_stamp(); |
| 419 | state.start("chat", "m1"); |
| 420 | state.fail("chat", "m1"); |
| 421 | assert_eq!( |
| 422 | state.context_for("chat").resolve(&record("m1"), false).line, |
| 423 | Some(TranslationLine::Failed) |
| 424 | ); |
| 425 | state.start("chat", "m1"); |
| 426 | assert!(!state.is_failed("chat", "m1")); |
| 427 | assert!(state.is_pending("chat", "m1")); |
| 428 | } |
| 429 | |
| 430 | #[test] |
| 431 | fn an_edit_or_a_new_target_misses_the_cache() { |
| 432 | let mut state = state_with_stamp(); |
| 433 | state.finish("chat", "m1", 0, "en", "<p>Hello</p>".into()); |
| 434 | assert!(state.is_cached("chat", "m1", 0)); |
| 435 | assert!(!state.is_cached("chat", "m1", 1)); |
| 436 | let mut edited = record("m1"); |
| 437 | edited.edited_at = Utc.timestamp_millis_opt(5_000).single(); |
| 438 | assert_eq!(message_version(&edited), 5_000); |
| 439 | assert!( |
| 440 | state |
| 441 | .context_for("chat") |
| 442 | .resolve(&edited, true) |
| 443 | .translated_html |
| 444 | .is_none() |
| 445 | ); |
| 446 | |
| 447 | state.settings.as_mut().unwrap().target_locale = Some("de".into()); |
| 448 | assert!(!state.is_cached("chat", "m1", 0)); |
| 449 | assert!(state.context_for("chat").cached.is_empty()); |
| 450 | } |
| 451 | |
| 452 | #[test] |
| 453 | fn contexts_only_carry_their_own_conversation() { |
| 454 | let mut state = state_with_stamp(); |
| 455 | state.finish("chat", "m1", 0, "en", "<p>Hello</p>".into()); |
| 456 | let other = state.context_for("other"); |
| 457 | assert!(other.cached.is_empty()); |
| 458 | assert!(other.shown.is_empty()); |
| 459 | assert!(other.stamps.is_empty()); |
| 460 | } |
| 461 | |
| 462 | #[test] |
| 463 | fn the_target_is_always_a_known_language() { |
| 464 | let state = state_with_stamp(); |
| 465 | assert_eq!(state.never_codes(), vec!["en".to_owned()]); |
| 466 | assert!(state.display_codes().is_empty()); |
| 467 | } |
| 468 | |
| 469 | #[test] |
| 470 | fn asked_messages_are_remembered_per_conversation() { |
| 471 | let mut state = TranslationState::default(); |
| 472 | state.mark_asked("chat", vec!["m1".into()]); |
| 473 | assert!(state.was_asked("chat", "m1")); |
| 474 | assert!(!state.was_asked("chat", "m2")); |
| 475 | assert!(!state.was_asked("other", "m1")); |
| 476 | } |
| 477 | |
| 478 | #[test] |
| 479 | fn merging_stamps_reports_changes_only() { |
| 480 | let mut state = TranslationState::default(); |
| 481 | let stamps = HashMap::from([("m1".to_owned(), FRENCH.to_owned())]); |
| 482 | assert!(state.merge_stamps("chat", stamps.clone())); |
| 483 | assert!(!state.merge_stamps("chat", stamps)); |
| 484 | } |
| 485 | } |