| 1 | use std::collections::HashMap; |
| 2 | |
| 3 | use chatsvc::{ConversationRef, EmotionReaction, MessageEmotions}; |
| 4 | use chrono::{DateTime, Utc}; |
| 5 | use store::MessageRecord; |
| 6 | |
| 7 | use crate::engine::{Conversation, SyncEngine}; |
| 8 | use crate::remote::Remote; |
| 9 | use crate::stored::{ReactionInfo, reactions}; |
| 10 | |
| 11 | const PAGE_MARGIN: usize = 20; |
| 12 | const MAX_PAGE_SIZE: usize = 200; |
| 13 | const MAX_GROUPS: usize = 10; |
| 14 | |
| 15 | impl<R: Remote> SyncEngine<R> { |
| 16 | /// Graph reports reactions without their skin tone; Teams reads the chat service |
| 17 | /// `emotions`, so the records take theirs from there. Failures keep the Graph reactions. |
| 18 | pub(crate) async fn apply_chat_emotions( |
| 19 | &self, |
| 20 | conversation_id: &str, |
| 21 | records: &mut [MessageRecord], |
| 22 | ) { |
| 23 | let Ok(conversation) = self.resolve_stored(conversation_id) else { |
| 24 | return; |
| 25 | }; |
| 26 | let groups = emotion_groups(conversation_id, &conversation, records); |
| 27 | for (target, members) in groups.into_iter().take(MAX_GROUPS) { |
| 28 | let Some(newest) = members |
| 29 | .iter() |
| 30 | .map(|index| &records[*index]) |
| 31 | .max_by_key(|record| record.created_at) |
| 32 | .map(|record| record.message_id.clone()) |
| 33 | else { |
| 34 | continue; |
| 35 | }; |
| 36 | let page_size = (members.len() + PAGE_MARGIN).min(MAX_PAGE_SIZE); |
| 37 | let Ok(found) = self |
| 38 | .remote |
| 39 | .message_emotions(&target, &newest, page_size) |
| 40 | .await |
| 41 | else { |
| 42 | continue; |
| 43 | }; |
| 44 | for MessageEmotions { |
| 45 | message_id, |
| 46 | reactions: found_reactions, |
| 47 | } in found |
| 48 | { |
| 49 | if let Some(index) = members |
| 50 | .iter() |
| 51 | .find(|index| records[**index].message_id == message_id) |
| 52 | { |
| 53 | let record = &mut records[*index]; |
| 54 | record.reactions_json = reactions_json(record, &found_reactions); |
| 55 | } |
| 56 | } |
| 57 | } |
| 58 | } |
| 59 | } |
| 60 | |
| 61 | fn emotion_groups( |
| 62 | conversation_id: &str, |
| 63 | conversation: &Conversation, |
| 64 | records: &[MessageRecord], |
| 65 | ) -> Vec<(ConversationRef, Vec<usize>)> { |
| 66 | let live = (0..records.len()).filter(|index| !records[*index].deleted); |
| 67 | match conversation { |
| 68 | Conversation::Chat => vec![(ConversationRef::chat(conversation_id), live.collect())], |
| 69 | Conversation::Channel { .. } => { |
| 70 | let mut groups: Vec<(ConversationRef, Vec<usize>)> = Vec::new(); |
| 71 | let mut positions: HashMap<Option<String>, usize> = HashMap::new(); |
| 72 | for index in live { |
| 73 | let root = records[index].reply_to_id.clone(); |
| 74 | let position = *positions.entry(root.clone()).or_insert_with(|| { |
| 75 | let target = match &root { |
| 76 | Some(root_id) => ConversationRef::channel_reply(conversation_id, root_id), |
| 77 | None => ConversationRef::channel_root(conversation_id), |
| 78 | }; |
| 79 | groups.push((target, Vec::new())); |
| 80 | groups.len() - 1 |
| 81 | }); |
| 82 | groups[position].1.push(index); |
| 83 | } |
| 84 | groups |
| 85 | } |
| 86 | } |
| 87 | } |
| 88 | |
| 89 | fn reactions_json(record: &MessageRecord, found: &[EmotionReaction]) -> String { |
| 90 | let names: HashMap<Option<String>, Option<String>> = reactions(record) |
| 91 | .into_iter() |
| 92 | .map(|reaction| (reaction.user_id, reaction.user_name)) |
| 93 | .collect(); |
| 94 | let converted: Vec<ReactionInfo> = found |
| 95 | .iter() |
| 96 | .map(|reaction| ReactionInfo { |
| 97 | reaction_type: chatsvc::reaction_glyph_for_key(&reaction.key) |
| 98 | .unwrap_or_else(|| reaction.key.clone()), |
| 99 | user_id: reaction.user_id.clone(), |
| 100 | user_name: names.get(&reaction.user_id).cloned().flatten(), |
| 101 | created_at: reaction |
| 102 | .time_ms |
| 103 | .and_then(DateTime::<Utc>::from_timestamp_millis), |
| 104 | }) |
| 105 | .collect(); |
| 106 | serde_json::to_string(&converted).unwrap_or_else(|_| record.reactions_json.clone()) |
| 107 | } |
| 108 | |
| 109 | #[cfg(test)] |
| 110 | mod tests { |
| 111 | use super::*; |
| 112 | |
| 113 | fn record(id: &str, reply_to: Option<&str>) -> MessageRecord { |
| 114 | MessageRecord { |
| 115 | conversation_id: "19:c".into(), |
| 116 | message_id: id.into(), |
| 117 | reply_to_id: reply_to.map(str::to_owned), |
| 118 | reactions_json: |
| 119 | r#"[{"reaction_type":"👍","user_id":"aaa","user_name":"Lea","created_at":null}]"# |
| 120 | .into(), |
| 121 | ..MessageRecord::default() |
| 122 | } |
| 123 | } |
| 124 | |
| 125 | #[test] |
| 126 | fn chat_service_keys_replace_graph_reactions_and_keep_names() { |
| 127 | let found = [EmotionReaction { |
| 128 | key: "yes-tone2".into(), |
| 129 | user_id: Some("aaa".into()), |
| 130 | time_ms: Some(1_792_135_855_841), |
| 131 | }]; |
| 132 | let json = reactions_json(&record("1", None), &found); |
| 133 | let parsed: Vec<ReactionInfo> = serde_json::from_str(&json).unwrap(); |
| 134 | assert_eq!(parsed[0].reaction_type, "👍🏼"); |
| 135 | assert_eq!(parsed[0].user_name.as_deref(), Some("Lea")); |
| 136 | assert!(parsed[0].created_at.is_some()); |
| 137 | assert_eq!(reactions_json(&record("1", None), &[]), "[]"); |
| 138 | } |
| 139 | |
| 140 | #[test] |
| 141 | fn channel_messages_group_by_thread() { |
| 142 | let records = [ |
| 143 | record("r1", None), |
| 144 | record("a", Some("r1")), |
| 145 | record("b", Some("r1")), |
| 146 | ]; |
| 147 | let groups = emotion_groups( |
| 148 | "19:c", |
| 149 | &Conversation::Channel { |
| 150 | team_id: "t".into(), |
| 151 | }, |
| 152 | &records, |
| 153 | ); |
| 154 | assert_eq!(groups.len(), 2); |
| 155 | assert_eq!(groups[0].0, ConversationRef::channel_root("19:c")); |
| 156 | assert_eq!(groups[1].0, ConversationRef::channel_reply("19:c", "r1")); |
| 157 | assert_eq!(groups[1].1, vec![1, 2]); |
| 158 | } |
| 159 | } |