fix(chat): reactions and skin tone work like Teams
- reactions come from the chat service emotions (yes-tone2 etc.), as Teams reads them; Graph drops skin tones and stays the fallback - every message sync path and the single-message refresh take the chat service reactions, Graph reactor names are kept - picking a tone writes preferredSkinToneIndex to the Teams account, no local-only setting - quick reactions stay untoned like Teams; clicking a reaction pill reacts in your tone - reaction pills react with one glyph, not the joined tone variants Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@@ -82,7 +82,6 @@ fn skin_tone(glyph: &str) -> Option<u32> {
82
82
}
83
83
84
84
pub const SKIN_TONE_COUNT: u8 = 5;
85
const ZERO_WIDTH_JOINER: char = '\u{200d}';
86
85
87
86
fn toneable_glyphs() -> &'static HashSet<&'static str> {
88
87
static PARSED: OnceLock<HashSet<&'static str>> = OnceLock::new();
@@ -106,20 +105,12 @@ pub fn without_tone(glyph: &str) -> String {
106
105
.collect()
107
106
}
108
107
109
/// The Teams rule: the modifier goes in once, before the first joiner, otherwise at the end;
110
/// a variation selector at that spot is dropped.
111
108
pub fn with_tone(glyph: &str, tone: u8) -> String {
112
109
let base = without_tone(glyph);
113
110
if tone == 0 || tone > SKIN_TONE_COUNT || !is_toneable(&base) {
114
111
return base;
115
112
}
116
let modifier = char::from_u32(*SKIN_TONES.start() as u32 + u32::from(tone) - 1)
117
.expect("skin tone modifier");
118
let (head, tail) = base.split_at(base.find(ZERO_WIDTH_JOINER).unwrap_or(base.len()));
119
format!(
120
"{}{modifier}{tail}",
121
head.strip_suffix(VARIATION_SELECTOR).unwrap_or(head)
122
)
113
chatsvc::insert_skin_tone(&base, tone)
123
114
}
124
115
125
116
fn base_glyph(glyph: &str) -> String {
@@ -82,7 +82,6 @@ fn skin_tone(glyph: &str) -> Option<u32> {82
}82
}83
83
84
pub const SKIN_TONE_COUNT: u8 = 5;84
pub const SKIN_TONE_COUNT: u8 = 5;85
const ZERO_WIDTH_JOINER: char = '\u{200d}';86
85
87
fn toneable_glyphs() -> &'static HashSet<&'static str> {86
fn toneable_glyphs() -> &'static HashSet<&'static str> {88
static PARSED: OnceLock<HashSet<&'static str>> = OnceLock::new();87
static PARSED: OnceLock<HashSet<&'static str>> = OnceLock::new();@@ -106,20 +105,12 @@ pub fn without_tone(glyph: &str) -> String {106
.collect()105
.collect()107
}106
}108
107
109
/// The Teams rule: the modifier goes in once, before the first joiner, otherwise at the end;110
/// a variation selector at that spot is dropped.111
pub fn with_tone(glyph: &str, tone: u8) -> String {108
pub fn with_tone(glyph: &str, tone: u8) -> String {112
let base = without_tone(glyph);109
let base = without_tone(glyph);113
if tone == 0 || tone > SKIN_TONE_COUNT || !is_toneable(&base) {110
if tone == 0 || tone > SKIN_TONE_COUNT || !is_toneable(&base) {114
return base;111
return base;115
}112
}116
let modifier = char::from_u32(*SKIN_TONES.start() as u32 + u32::from(tone) - 1)113
chatsvc::insert_skin_tone(&base, tone)117
.expect("skin tone modifier");118
let (head, tail) = base.split_at(base.find(ZERO_WIDTH_JOINER).unwrap_or(base.len()));119
format!(120
"{}{modifier}{tail}",121
head.strip_suffix(VARIATION_SELECTOR).unwrap_or(head)122
)123
}114
}124
115
125
fn base_glyph(glyph: &str) -> String {116
fn base_glyph(glyph: &str) -> String {@@ -456,6 +456,26 @@ impl AppState {
456
456
);
457
457
}
458
458
459
pub fn set_skin_tone(&mut self, tone: u8, cx: &mut Context<Self>) {
460
let Some(engine_or_demo) = self.chat_action_engine(cx) else {
461
return;
462
};
463
let previous = teams_core::skin_tone(&self.store);
464
let _ = teams_core::store_account_skin_tone(&self.store, tone);
465
let Some(engine) = engine_or_demo else {
466
return;
467
};
468
self.run_chat_action(
469
"Skin tone",
470
async move { engine.set_skin_tone(tone).await },
471
move |state, _| {
472
let _ = teams_core::store_account_skin_tone(&state.store, previous);
473
},
474
|_, _| {},
475
cx,
476
);
477
}
478
459
479
fn apply_section_settings(&mut self, settings: ChatSectionSettings, cx: &mut Context<Self>) {
460
480
self.directory.section_settings = settings;
461
481
let _ = teams_core::store_section_settings(&self.store, &settings);
@@ -456,6 +456,26 @@ impl AppState {456
);456
);457
}457
}458
458
459
pub fn set_skin_tone(&mut self, tone: u8, cx: &mut Context<Self>) {460
let Some(engine_or_demo) = self.chat_action_engine(cx) else {461
return;462
};463
let previous = teams_core::skin_tone(&self.store);464
let _ = teams_core::store_account_skin_tone(&self.store, tone);465
let Some(engine) = engine_or_demo else {466
return;467
};468
self.run_chat_action(469
"Skin tone",470
async move { engine.set_skin_tone(tone).await },471
move |state, _| {472
let _ = teams_core::store_account_skin_tone(&state.store, previous);473
},474
|_, _| {},475
cx,476
);477
}478
459
fn apply_section_settings(&mut self, settings: ChatSectionSettings, cx: &mut Context<Self>) {479
fn apply_section_settings(&mut self, settings: ChatSectionSettings, cx: &mut Context<Self>) {460
self.directory.section_settings = settings;480
self.directory.section_settings = settings;461
let _ = teams_core::store_section_settings(&self.store, &settings);481
let _ = teams_core::store_section_settings(&self.store, &settings);@@ -95,6 +95,7 @@ mod tests {
95
95
pending_reactions: HashMap::new(),
96
96
card_overrides: HashMap::new(),
97
97
translation: TranslationContext::default(),
98
skin_tone: 0,
98
99
}
99
100
}
100
101
@@ -95,6 +95,7 @@ mod tests {95
pending_reactions: HashMap::new(),95
pending_reactions: HashMap::new(),96
card_overrides: HashMap::new(),96
card_overrides: HashMap::new(),97
translation: TranslationContext::default(),97
translation: TranslationContext::default(),98
skin_tone: 0,98
}99
}99
}100
}100
101
@@ -129,6 +129,7 @@ mod tests {
129
129
ReactionChip {
130
130
reaction_type: reaction_type.to_owned(),
131
131
label: crate::rows::reaction_label(reaction_type),
132
click_glyph: crate::rows::reaction_glyph(reaction_type),
132
133
count: reactors.len(),
133
134
mine: false,
134
135
reactors,
@@ -129,6 +129,7 @@ mod tests {129
ReactionChip {129
ReactionChip {130
reaction_type: reaction_type.to_owned(),130
reaction_type: reaction_type.to_owned(),131
label: crate::rows::reaction_label(reaction_type),131
label: crate::rows::reaction_label(reaction_type),132
click_glyph: crate::rows::reaction_glyph(reaction_type),132
count: reactors.len(),133
count: reactors.len(),133
mine: false,134
mine: false,134
reactors,135
reactors,@@ -34,6 +34,7 @@ const CORNER_SERIES: f32 = 4.;
34
34
pub struct ReactionChip {
35
35
pub reaction_type: String,
36
36
pub label: String,
37
pub click_glyph: String,
37
38
pub count: usize,
38
39
pub mine: bool,
39
40
pub reactors: Vec<Reactor>,
@@ -353,19 +354,13 @@ pub fn reaction_label(reaction_type: &str) -> String {
353
354
}
354
355
355
356
pub fn reaction_glyph(reaction_type: &str) -> String {
356
if let Some((key, tone)) = reaction_type
357
.split_once(TONE_MARKER)
358
.and_then(|(key, tone)| Some((key, tone.parse::<u8>().ok()?)))
359
{
360
let base = match key {
361
"yes" => "\u{1F44D}".to_owned(),
362
other => chatsvc::emotion_glyph(other).map_or_else(|| reaction_label(other), str::to_owned),
363
};
364
return crate::emoticons::with_tone(&base, tone);
365
}
366
reaction_label(reaction_type)
367
.trim_end_matches('\u{FE0F}')
368
.to_owned()
357
let label = reaction_label(reaction_type);
358
let glyph = if label == reaction_type {
359
chatsvc::reaction_glyph_for_key(reaction_type).unwrap_or(label)
360
} else {
361
label
362
};
363
glyph.trim_end_matches('\u{FE0F}').to_owned()
369
364
}
370
365
371
366
fn same_reaction(left: &str, right: &str) -> bool {
@@ -389,7 +384,6 @@ pub fn reaction_type_for(glyph: &str) -> String {
389
384
.map_or_else(|| bare.to_owned(), str::to_owned)
390
385
}
391
386
392
const TONE_MARKER: &str = "-tone";
393
387
const MAX_TONE_VARIANTS: usize = 3;
394
388
395
389
pub type PendingReactions = HashMap<String, Vec<(String, bool)>>;
@@ -466,6 +460,7 @@ pub fn reaction_chips(reactions: &[ReactionInfo], context: &RowContext) -> Vec<R
466
460
chips.push(ReactionChip {
467
461
reaction_type: reaction.reaction_type.clone(),
468
462
label: String::new(),
463
click_glyph: crate::emoticons::with_tone(&glyph, context.skin_tone),
469
464
count: 0,
470
465
mine: false,
471
466
reactors: Vec::new(),
@@ -474,11 +469,7 @@ pub fn reaction_chips(reactions: &[ReactionInfo], context: &RowContext) -> Vec<R
474
469
chips.len() - 1
475
470
}
476
471
};
477
let label = if reaction.reaction_type.contains(TONE_MARKER) {
478
glyph
479
} else {
480
reaction_label(&reaction.reaction_type)
481
};
472
let label = glyph;
482
473
let shown = &mut variants[position];
483
474
if shown.len() < MAX_TONE_VARIANTS && !shown.contains(&label) {
484
475
shown.push(label);
@@ -576,6 +567,7 @@ pub struct RowContext {
576
567
pub pending_reactions: PendingReactions,
577
568
pub card_overrides: HashMap<String, CardOverride>,
578
569
pub translation: TranslationContext,
570
pub skin_tone: u8,
579
571
}
580
572
581
573
fn visible_reactions(record: &MessageRecord, context: &RowContext) -> Vec<ReactionInfo> {
@@ -1178,6 +1170,7 @@ mod tests {
1178
1170
pending_reactions: HashMap::new(),
1179
1171
card_overrides: HashMap::new(),
1180
1172
translation: TranslationContext::default(),
1173
skin_tone: 0,
1181
1174
}
1182
1175
}
1183
1176
@@ -1514,10 +1507,13 @@ mod tests {
1514
1507
created_at: None,
1515
1508
};
1516
1509
let kinds = ["yes-tone2", "👍🏿", "like", "👍🏻", "yes-tone2"];
1517
let chips = reaction_chips(&kinds.map(reaction), &context());
1510
let mut context = context();
1511
context.skin_tone = 3;
1512
let chips = reaction_chips(&kinds.map(reaction), &context);
1518
1513
assert_eq!(chips.len(), 1);
1519
1514
assert_eq!(chips[0].count, 5);
1520
1515
assert_eq!(chips[0].label, "👍🏼👍🏿👍");
1516
assert_eq!(chips[0].click_glyph, "👍🏽");
1521
1517
}
1522
1518
1523
1519
#[test]
@@ -34,6 +34,7 @@ const CORNER_SERIES: f32 = 4.;34
pub struct ReactionChip {34
pub struct ReactionChip {35
pub reaction_type: String,35
pub reaction_type: String,36
pub label: String,36
pub label: String,37
pub click_glyph: String,37
pub count: usize,38
pub count: usize,38
pub mine: bool,39
pub mine: bool,39
pub reactors: Vec<Reactor>,40
pub reactors: Vec<Reactor>,@@ -353,19 +354,13 @@ pub fn reaction_label(reaction_type: &str) -> String {353
}354
}354
355
355
pub fn reaction_glyph(reaction_type: &str) -> String {356
pub fn reaction_glyph(reaction_type: &str) -> String {356
if let Some((key, tone)) = reaction_type357
let label = reaction_label(reaction_type);357
.split_once(TONE_MARKER)358
let glyph = if label == reaction_type {358
.and_then(|(key, tone)| Some((key, tone.parse::<u8>().ok()?)))359
chatsvc::reaction_glyph_for_key(reaction_type).unwrap_or(label)359
{360
} else {360
let base = match key {361
label361
"yes" => "\u{1F44D}".to_owned(),362
};362
other => chatsvc::emotion_glyph(other).map_or_else(|| reaction_label(other), str::to_owned),363
glyph.trim_end_matches('\u{FE0F}').to_owned()363
};364
return crate::emoticons::with_tone(&base, tone);365
}366
reaction_label(reaction_type)367
.trim_end_matches('\u{FE0F}')368
.to_owned()369
}364
}370
365
371
fn same_reaction(left: &str, right: &str) -> bool {366
fn same_reaction(left: &str, right: &str) -> bool {@@ -389,7 +384,6 @@ pub fn reaction_type_for(glyph: &str) -> String {389
.map_or_else(|| bare.to_owned(), str::to_owned)384
.map_or_else(|| bare.to_owned(), str::to_owned)390
}385
}391
386
392
const TONE_MARKER: &str = "-tone";393
const MAX_TONE_VARIANTS: usize = 3;387
const MAX_TONE_VARIANTS: usize = 3;394
388
395
pub type PendingReactions = HashMap<String, Vec<(String, bool)>>;389
pub type PendingReactions = HashMap<String, Vec<(String, bool)>>;@@ -466,6 +460,7 @@ pub fn reaction_chips(reactions: &[ReactionInfo], context: &RowContext) -> Vec<R466
chips.push(ReactionChip {460
chips.push(ReactionChip {467
reaction_type: reaction.reaction_type.clone(),461
reaction_type: reaction.reaction_type.clone(),468
label: String::new(),462
label: String::new(),463
click_glyph: crate::emoticons::with_tone(&glyph, context.skin_tone),469
count: 0,464
count: 0,470
mine: false,465
mine: false,471
reactors: Vec::new(),466
reactors: Vec::new(),@@ -474,11 +469,7 @@ pub fn reaction_chips(reactions: &[ReactionInfo], context: &RowContext) -> Vec<R474
chips.len() - 1469
chips.len() - 1475
}470
}476
};471
};477
let label = if reaction.reaction_type.contains(TONE_MARKER) {472
let label = glyph;478
glyph479
} else {480
reaction_label(&reaction.reaction_type)481
};482
let shown = &mut variants[position];473
let shown = &mut variants[position];483
if shown.len() < MAX_TONE_VARIANTS && !shown.contains(&label) {474
if shown.len() < MAX_TONE_VARIANTS && !shown.contains(&label) {484
shown.push(label);475
shown.push(label);@@ -576,6 +567,7 @@ pub struct RowContext {576
pub pending_reactions: PendingReactions,567
pub pending_reactions: PendingReactions,577
pub card_overrides: HashMap<String, CardOverride>,568
pub card_overrides: HashMap<String, CardOverride>,578
pub translation: TranslationContext,569
pub translation: TranslationContext,570
pub skin_tone: u8,579
}571
}580
572
581
fn visible_reactions(record: &MessageRecord, context: &RowContext) -> Vec<ReactionInfo> {573
fn visible_reactions(record: &MessageRecord, context: &RowContext) -> Vec<ReactionInfo> {@@ -1178,6 +1170,7 @@ mod tests {1178
pending_reactions: HashMap::new(),1170
pending_reactions: HashMap::new(),1179
card_overrides: HashMap::new(),1171
card_overrides: HashMap::new(),1180
translation: TranslationContext::default(),1172
translation: TranslationContext::default(),1173
skin_tone: 0,1181
}1174
}1182
}1175
}1183
1176
@@ -1514,10 +1507,13 @@ mod tests {1514
created_at: None,1507
created_at: None,1515
};1508
};1516
let kinds = ["yes-tone2", "👍🏿", "like", "👍🏻", "yes-tone2"];1509
let kinds = ["yes-tone2", "👍🏿", "like", "👍🏻", "yes-tone2"];1517
let chips = reaction_chips(&kinds.map(reaction), &context());1510
let mut context = context();1511
context.skin_tone = 3;1512
let chips = reaction_chips(&kinds.map(reaction), &context);1518
assert_eq!(chips.len(), 1);1513
assert_eq!(chips.len(), 1);1519
assert_eq!(chips[0].count, 5);1514
assert_eq!(chips[0].count, 5);1520
assert_eq!(chips[0].label, "👍🏼👍🏿👍");1515
assert_eq!(chips[0].label, "👍🏼👍🏿👍");1516
assert_eq!(chips[0].click_glyph, "👍🏽");1521
}1517
}1522
1518
1523
#[test]1519
#[test]@@ -1264,6 +1264,7 @@ impl ConversationView {
1264
1264
pending_reactions: self.pending_reactions.clone(),
1265
1265
card_overrides,
1266
1266
translation,
1267
skin_tone: teams_core::skin_tone(&app.store),
1267
1268
}
1268
1269
}
1269
1270
@@ -2496,7 +2497,7 @@ impl ConversationView {
2496
2497
}
2497
2498
let skin_tone = teams_core::skin_tone(&store);
2498
2499
let wanted = if added {
2499
emoticons::with_tone(&wanted, skin_tone)
2500
wanted
2500
2501
} else {
2501
2502
let own = own_reaction_glyph(&visible, glyph, my_user_id.as_deref()).unwrap_or(wanted);
2502
2503
if emoticons::without_tone(&own) == own {
@@ -1264,6 +1264,7 @@ impl ConversationView {1264
pending_reactions: self.pending_reactions.clone(),1264
pending_reactions: self.pending_reactions.clone(),1265
card_overrides,1265
card_overrides,1266
translation,1266
translation,1267
skin_tone: teams_core::skin_tone(&app.store),1267
}1268
}1268
}1269
}1269
1270
@@ -2496,7 +2497,7 @@ impl ConversationView {2496
}2497
}2497
let skin_tone = teams_core::skin_tone(&store);2498
let skin_tone = teams_core::skin_tone(&store);2498
let wanted = if added {2499
let wanted = if added {2499
emoticons::with_tone(&wanted, skin_tone)2500
wanted2500
} else {2501
} else {2501
let own = own_reaction_glyph(&visible, glyph, my_user_id.as_deref()).unwrap_or(wanted);2502
let own = own_reaction_glyph(&visible, glyph, my_user_id.as_deref()).unwrap_or(wanted);2502
if emoticons::without_tone(&own) == own {2503
if emoticons::without_tone(&own) == own {@@ -340,7 +340,7 @@ impl FunPicker {
340
340
341
341
fn pick_tone(&mut self, glyph: &str, tone: u8, cx: &mut Context<Self>) {
342
342
self.skin_tone = tone;
343
let _ = teams_core::store_picked_skin_tone(&self.app.read(cx).store, tone);
343
self.app.update(cx, |state, cx| state.set_skin_tone(tone, cx));
344
344
self.pick_emoji(&emoticons::with_tone(glyph, tone), cx);
345
345
}
346
346
@@ -340,7 +340,7 @@ impl FunPicker {340
340
341
fn pick_tone(&mut self, glyph: &str, tone: u8, cx: &mut Context<Self>) {341
fn pick_tone(&mut self, glyph: &str, tone: u8, cx: &mut Context<Self>) {342
self.skin_tone = tone;342
self.skin_tone = tone;343
let _ = teams_core::store_picked_skin_tone(&self.app.read(cx).store, tone);343
self.app.update(cx, |state, cx| state.set_skin_tone(tone, cx));344
self.pick_emoji(&emoticons::with_tone(glyph, tone), cx);344
self.pick_emoji(&emoticons::with_tone(glyph, tone), cx);345
}345
}346
346
@@ -195,7 +195,7 @@ impl ReactionPicker {
195
195
196
196
fn pick_tone(&mut self, glyph: &str, tone: u8, window: &mut Window, cx: &mut Context<Self>) {
197
197
self.skin_tone = tone;
198
let _ = teams_core::store_picked_skin_tone(&self.app.read(cx).store, tone);
198
self.app.update(cx, |state, cx| state.set_skin_tone(tone, cx));
199
199
self.pick(&emoticons::with_tone(glyph, tone), false, window, cx);
200
200
}
201
201
@@ -195,7 +195,7 @@ impl ReactionPicker {195
195
196
fn pick_tone(&mut self, glyph: &str, tone: u8, window: &mut Window, cx: &mut Context<Self>) {196
fn pick_tone(&mut self, glyph: &str, tone: u8, window: &mut Window, cx: &mut Context<Self>) {197
self.skin_tone = tone;197
self.skin_tone = tone;198
let _ = teams_core::store_picked_skin_tone(&self.app.read(cx).store, tone);198
self.app.update(cx, |state, cx| state.set_skin_tone(tone, cx));199
self.pick(&emoticons::with_tone(glyph, tone), false, window, cx);199
self.pick(&emoticons::with_tone(glyph, tone), false, window, cx);200
}200
}201
201
@@ -114,7 +114,7 @@ fn pill(
114
114
} else {
115
115
(theme::border_strong(), theme::text_soft())
116
116
};
117
let glyph = chip.label.clone();
117
let glyph = chip.click_glyph.clone();
118
118
let tooltip_text = chip_tooltip(chip);
119
119
let toggle = controls.map(|controls| {
120
120
let is_open = controls
@@ -114,7 +114,7 @@ fn pill(114
} else {114
} else {115
(theme::border_strong(), theme::text_soft())115
(theme::border_strong(), theme::text_soft())116
};116
};117
let glyph = chip.label.clone();117
let glyph = chip.click_glyph.clone();118
let tooltip_text = chip_tooltip(chip);118
let tooltip_text = chip_tooltip(chip);119
let toggle = controls.map(|controls| {119
let toggle = controls.map(|controls| {120
let is_open = controls120
let is_open = controls@@ -0,0 +1,118 @@
1
use serde_json::Value;
2
use session::Request;
3
4
use crate::error::Result;
5
use crate::messages::{MessageTransport, Messages, ensure_success};
6
use crate::window::WindowDirection;
7
8
const ORGID_PREFIX: &str = "8:orgid:";
9
10
#[derive(Debug, Clone, PartialEq, Eq)]
11
pub struct EmotionReaction {
12
pub key: String,
13
pub user_id: Option<String>,
14
pub time_ms: Option<i64>,
15
}
16
17
#[derive(Debug, Clone, PartialEq, Eq)]
18
pub struct MessageEmotions {
19
pub message_id: String,
20
pub reactions: Vec<EmotionReaction>,
21
}
22
23
pub fn user_id_from_mri(mri: &str) -> &str {
24
mri.strip_prefix(ORGID_PREFIX).unwrap_or(mri)
25
}
26
27
fn reactions(emotions: Option<&Value>) -> Vec<EmotionReaction> {
28
emotions
29
.and_then(Value::as_array)
30
.into_iter()
31
.flatten()
32
.flat_map(|entry| {
33
let key = entry.get("key").and_then(Value::as_str).unwrap_or_default();
34
entry
35
.get("users")
36
.and_then(Value::as_array)
37
.into_iter()
38
.flatten()
39
.filter(move |_| !key.is_empty())
40
.map(move |user| EmotionReaction {
41
key: key.to_owned(),
42
user_id: user
43
.get("mri")
44
.and_then(Value::as_str)
45
.map(|mri| user_id_from_mri(mri).to_owned()),
46
time_ms: user.get("time").and_then(Value::as_i64),
47
})
48
})
49
.collect()
50
}
51
52
/// Every listed message, including those without an `emotions` property: the chat service
53
/// leaves it out when nobody reacted, and an entry whose `users` is empty means removed.
54
pub fn parse_message_emotions(body: &Value) -> Vec<MessageEmotions> {
55
body.get("messages")
56
.and_then(Value::as_array)
57
.into_iter()
58
.flatten()
59
.filter_map(|message| {
60
let message_id = match message.get("id")? {
61
Value::String(text) if !text.is_empty() => text.clone(),
62
Value::Number(number) => number.to_string(),
63
_ => return None,
64
};
65
Some(MessageEmotions {
66
message_id,
67
reactions: reactions(message.pointer("/properties/emotions")),
68
})
69
})
70
.collect()
71
}
72
73
impl<T: MessageTransport> Messages<T> {
74
pub async fn message_emotions(
75
&self,
76
conversation_id: &str,
77
newest_message_id: &str,
78
page_size: usize,
79
) -> Result<Vec<MessageEmotions>> {
80
let url = self.message_window_url(
81
conversation_id,
82
newest_message_id,
83
WindowDirection::Backward,
84
page_size,
85
);
86
let answer = self.transport.send(Request::get(url)).await?;
87
ensure_success(&answer)?;
88
Ok(parse_message_emotions(&answer.body))
89
}
90
}
91
92
#[cfg(test)]
93
mod tests {
94
use serde_json::json;
95
96
use super::*;
97
98
#[test]
99
fn emotions_expand_per_user_and_skip_removed_entries() {
100
let body = json!({"messages": [
101
{"id": "1", "properties": {"emotions": [
102
{"key": "yes-tone2", "users": [
103
{"mri": "8:orgid:aaa", "time": 1792135855841_i64, "value": "1792135855835"},
104
{"mri": "8:orgid:bbb", "time": 1792135855900_i64, "value": "1"}
105
]},
106
{"key": "heart", "users": []}
107
]}},
108
{"id": "2", "properties": {}}
109
]});
110
let parsed = parse_message_emotions(&body);
111
assert_eq!(parsed.len(), 2);
112
assert_eq!(parsed[0].reactions.len(), 2);
113
assert_eq!(parsed[0].reactions[0].key, "yes-tone2");
114
assert_eq!(parsed[0].reactions[0].user_id.as_deref(), Some("aaa"));
115
assert_eq!(parsed[0].reactions[1].time_ms, Some(1792135855900));
116
assert!(parsed[1].reactions.is_empty());
117
}
118
}
@@ -0,0 +1,118 @@1
use serde_json::Value;2
use session::Request;3
4
use crate::error::Result;5
use crate::messages::{MessageTransport, Messages, ensure_success};6
use crate::window::WindowDirection;7
8
const ORGID_PREFIX: &str = "8:orgid:";9
10
#[derive(Debug, Clone, PartialEq, Eq)]11
pub struct EmotionReaction {12
pub key: String,13
pub user_id: Option<String>,14
pub time_ms: Option<i64>,15
}16
17
#[derive(Debug, Clone, PartialEq, Eq)]18
pub struct MessageEmotions {19
pub message_id: String,20
pub reactions: Vec<EmotionReaction>,21
}22
23
pub fn user_id_from_mri(mri: &str) -> &str {24
mri.strip_prefix(ORGID_PREFIX).unwrap_or(mri)25
}26
27
fn reactions(emotions: Option<&Value>) -> Vec<EmotionReaction> {28
emotions29
.and_then(Value::as_array)30
.into_iter()31
.flatten()32
.flat_map(|entry| {33
let key = entry.get("key").and_then(Value::as_str).unwrap_or_default();34
entry35
.get("users")36
.and_then(Value::as_array)37
.into_iter()38
.flatten()39
.filter(move |_| !key.is_empty())40
.map(move |user| EmotionReaction {41
key: key.to_owned(),42
user_id: user43
.get("mri")44
.and_then(Value::as_str)45
.map(|mri| user_id_from_mri(mri).to_owned()),46
time_ms: user.get("time").and_then(Value::as_i64),47
})48
})49
.collect()50
}51
52
/// Every listed message, including those without an `emotions` property: the chat service53
/// leaves it out when nobody reacted, and an entry whose `users` is empty means removed.54
pub fn parse_message_emotions(body: &Value) -> Vec<MessageEmotions> {55
body.get("messages")56
.and_then(Value::as_array)57
.into_iter()58
.flatten()59
.filter_map(|message| {60
let message_id = match message.get("id")? {61
Value::String(text) if !text.is_empty() => text.clone(),62
Value::Number(number) => number.to_string(),63
_ => return None,64
};65
Some(MessageEmotions {66
message_id,67
reactions: reactions(message.pointer("/properties/emotions")),68
})69
})70
.collect()71
}72
73
impl<T: MessageTransport> Messages<T> {74
pub async fn message_emotions(75
&self,76
conversation_id: &str,77
newest_message_id: &str,78
page_size: usize,79
) -> Result<Vec<MessageEmotions>> {80
let url = self.message_window_url(81
conversation_id,82
newest_message_id,83
WindowDirection::Backward,84
page_size,85
);86
let answer = self.transport.send(Request::get(url)).await?;87
ensure_success(&answer)?;88
Ok(parse_message_emotions(&answer.body))89
}90
}91
92
#[cfg(test)]93
mod tests {94
use serde_json::json;95
96
use super::*;97
98
#[test]99
fn emotions_expand_per_user_and_skip_removed_entries() {100
let body = json!({"messages": [101
{"id": "1", "properties": {"emotions": [102
{"key": "yes-tone2", "users": [103
{"mri": "8:orgid:aaa", "time": 1792135855841_i64, "value": "1792135855835"},104
{"mri": "8:orgid:bbb", "time": 1792135855900_i64, "value": "1"}105
]},106
{"key": "heart", "users": []}107
]}},108
{"id": "2", "properties": {}}109
]});110
let parsed = parse_message_emotions(&body);111
assert_eq!(parsed.len(), 2);112
assert_eq!(parsed[0].reactions.len(), 2);113
assert_eq!(parsed[0].reactions[0].key, "yes-tone2");114
assert_eq!(parsed[0].reactions[0].user_id.as_deref(), Some("aaa"));115
assert_eq!(parsed[0].reactions[1].time_ms, Some(1792135855900));116
assert!(parsed[1].reactions.is_empty());117
}118
}@@ -4,6 +4,7 @@ pub mod cards;
4
4
pub mod channel_notifications;
5
5
pub mod conversations;
6
6
pub mod drafts;
7
pub mod emotions;
7
8
mod error;
8
9
pub mod forward;
9
10
pub mod gifs;
@@ -54,7 +55,8 @@ pub use presence::{
54
55
ActivityReporting, ForcedAvailability, ForcedKind, PresenceService, PresenceStatus, StatusNote, WorkLocation,
55
56
WorkLocationKind, WorkLocationSource, error_status, is_endpoint_missing,
56
57
};
57
pub use reactions::{emotion_glyph, emotion_key, emotion_keys, reaction_key, reaction_keys};
58
pub use emotions::{EmotionReaction, MessageEmotions, parse_message_emotions, user_id_from_mri};
59
pub use reactions::{emotion_glyph, insert_skin_tone, reaction_glyph_for_key, emotion_key, emotion_keys, reaction_key, reaction_keys};
58
60
pub use realtime::{
59
61
CallbackReplier, EventKind, InstanceNames, MessageEvent, PresenceUpdate, Realtime,
60
62
RealtimeConfig, RealtimeEvent, StatusEvent, StatusKind, TrouterCallback, TrouterEndpoint,
@@ -4,6 +4,7 @@ pub mod cards;4
pub mod channel_notifications;4
pub mod channel_notifications;5
pub mod conversations;5
pub mod conversations;6
pub mod drafts;6
pub mod drafts;7
pub mod emotions;7
mod error;8
mod error;8
pub mod forward;9
pub mod forward;9
pub mod gifs;10
pub mod gifs;@@ -54,7 +55,8 @@ pub use presence::{54
ActivityReporting, ForcedAvailability, ForcedKind, PresenceService, PresenceStatus, StatusNote, WorkLocation,55
ActivityReporting, ForcedAvailability, ForcedKind, PresenceService, PresenceStatus, StatusNote, WorkLocation,55
WorkLocationKind, WorkLocationSource, error_status, is_endpoint_missing,56
WorkLocationKind, WorkLocationSource, error_status, is_endpoint_missing,56
};57
};57
pub use reactions::{emotion_glyph, emotion_key, emotion_keys, reaction_key, reaction_keys};58
pub use emotions::{EmotionReaction, MessageEmotions, parse_message_emotions, user_id_from_mri};59
pub use reactions::{emotion_glyph, insert_skin_tone, reaction_glyph_for_key, emotion_key, emotion_keys, reaction_key, reaction_keys};58
pub use realtime::{60
pub use realtime::{59
CallbackReplier, EventKind, InstanceNames, MessageEvent, PresenceUpdate, Realtime,61
CallbackReplier, EventKind, InstanceNames, MessageEvent, PresenceUpdate, Realtime,60
RealtimeConfig, RealtimeEvent, StatusEvent, StatusKind, TrouterCallback, TrouterEndpoint,62
RealtimeConfig, RealtimeEvent, StatusEvent, StatusKind, TrouterCallback, TrouterEndpoint,@@ -6,6 +6,9 @@ const EMOTIONS: &str = include_str!("../assets/emotions.tsv");
6
6
const EMOTICONS: &str = include_str!("../../app/assets/emoticons.tsv");
7
7
const SKIN_TONES: std::ops::RangeInclusive<char> = '\u{1f3fb}'..='\u{1f3ff}';
8
8
const TONE_MARKER: &str = "-tone";
9
const ZERO_WIDTH_JOINER: char = '\u{200d}';
10
const VARIATION_SELECTOR: char = '\u{fe0f}';
11
const MAX_TONE: u8 = 5;
9
12
10
13
type Index = HashMap<&'static str, Vec<&'static str>>;
11
14
@@ -78,11 +81,52 @@ pub fn reaction_keys(glyph: &str) -> Vec<String> {
78
81
}
79
82
}
80
83
84
/// The Teams rule: the modifier goes in once, before the first joiner, otherwise at the end;
85
/// a variation selector at that spot is dropped.
86
pub fn insert_skin_tone(base: &str, tone: u8) -> String {
87
let Some(modifier) = (1..=MAX_TONE)
88
.contains(&tone)
89
.then(|| char::from_u32(*SKIN_TONES.start() as u32 + u32::from(tone) - 1))
90
.flatten()
91
else {
92
return base.to_owned();
93
};
94
let (head, tail) = base.split_at(base.find(ZERO_WIDTH_JOINER).unwrap_or(base.len()));
95
format!(
96
"{}{modifier}{tail}",
97
head.strip_suffix(VARIATION_SELECTOR).unwrap_or(head)
98
)
99
}
100
101
/// `yes-tone2` is 👍🏼: the chat service key of a reaction as the glyph Graph would report,
102
/// but with the tone Graph drops.
103
pub fn reaction_glyph_for_key(key: &str) -> Option<String> {
104
let (base_key, tone) = match key.rsplit_once(TONE_MARKER) {
105
Some((base, tone)) => match tone.parse::<u8>() {
106
Ok(tone) => (base, Some(tone)),
107
Err(_) => (key, None),
108
},
109
None => (key, None),
110
};
111
let base = emotion_glyph(base_key)?;
112
Some(match tone {
113
Some(tone) => insert_skin_tone(base, tone),
114
None => base.to_owned(),
115
})
116
}
117
81
118
pub fn emotion_glyph(key: &str) -> Option<&'static str> {
82
index()
83
.iter()
84
.find(|(_, keys)| keys.contains(&key))
85
.map(|(glyph, _)| *glyph)
119
static GLYPHS: OnceLock<HashMap<&'static str, &'static str>> = OnceLock::new();
120
GLYPHS
121
.get_or_init(|| {
122
EMOTIONS
123
.lines()
124
.filter_map(|line| line.split_once('\t'))
125
.flat_map(|(glyph, keys)| keys.split(' ').map(move |key| (key, glyph)))
126
.collect()
127
})
128
.get(key)
129
.copied()
86
130
}
87
131
88
132
pub fn emotion_keys(glyph: &str) -> &'static [&'static str] {
@@ -135,6 +179,16 @@ mod tests {
135
179
assert_eq!(reaction_key("❤️").as_deref(), Some("heart"));
136
180
}
137
181
182
#[test]
183
fn keys_turn_into_glyphs_with_their_tone() {
184
assert_eq!(reaction_glyph_for_key("yes-tone2").as_deref(), Some("👍🏼"));
185
assert_eq!(reaction_glyph_for_key("like").as_deref(), Some("👍"));
186
assert_eq!(reaction_glyph_for_key("heart").as_deref(), Some("❤"));
187
assert_eq!(reaction_glyph_for_key("nope"), None);
188
assert_eq!(insert_skin_tone("🤷\u{200d}♂️", 1), "🤷🏻\u{200d}♂️");
189
assert_eq!(insert_skin_tone("✌️", 3), "✌🏽");
190
}
191
138
192
#[test]
139
193
fn unknown_glyph_has_no_key() {
140
194
assert_eq!(emotion_key("x"), None);
@@ -6,6 +6,9 @@ const EMOTIONS: &str = include_str!("../assets/emotions.tsv");6
const EMOTICONS: &str = include_str!("../../app/assets/emoticons.tsv");6
const EMOTICONS: &str = include_str!("../../app/assets/emoticons.tsv");7
const SKIN_TONES: std::ops::RangeInclusive<char> = '\u{1f3fb}'..='\u{1f3ff}';7
const SKIN_TONES: std::ops::RangeInclusive<char> = '\u{1f3fb}'..='\u{1f3ff}';8
const TONE_MARKER: &str = "-tone";8
const TONE_MARKER: &str = "-tone";9
const ZERO_WIDTH_JOINER: char = '\u{200d}';10
const VARIATION_SELECTOR: char = '\u{fe0f}';11
const MAX_TONE: u8 = 5;9
12
10
type Index = HashMap<&'static str, Vec<&'static str>>;13
type Index = HashMap<&'static str, Vec<&'static str>>;11
14
@@ -78,11 +81,52 @@ pub fn reaction_keys(glyph: &str) -> Vec<String> {78
}81
}79
}82
}80
83
84
/// The Teams rule: the modifier goes in once, before the first joiner, otherwise at the end;85
/// a variation selector at that spot is dropped.86
pub fn insert_skin_tone(base: &str, tone: u8) -> String {87
let Some(modifier) = (1..=MAX_TONE)88
.contains(&tone)89
.then(|| char::from_u32(*SKIN_TONES.start() as u32 + u32::from(tone) - 1))90
.flatten()91
else {92
return base.to_owned();93
};94
let (head, tail) = base.split_at(base.find(ZERO_WIDTH_JOINER).unwrap_or(base.len()));95
format!(96
"{}{modifier}{tail}",97
head.strip_suffix(VARIATION_SELECTOR).unwrap_or(head)98
)99
}100
101
/// `yes-tone2` is 👍🏼: the chat service key of a reaction as the glyph Graph would report,102
/// but with the tone Graph drops.103
pub fn reaction_glyph_for_key(key: &str) -> Option<String> {104
let (base_key, tone) = match key.rsplit_once(TONE_MARKER) {105
Some((base, tone)) => match tone.parse::<u8>() {106
Ok(tone) => (base, Some(tone)),107
Err(_) => (key, None),108
},109
None => (key, None),110
};111
let base = emotion_glyph(base_key)?;112
Some(match tone {113
Some(tone) => insert_skin_tone(base, tone),114
None => base.to_owned(),115
})116
}117
81
pub fn emotion_glyph(key: &str) -> Option<&'static str> {118
pub fn emotion_glyph(key: &str) -> Option<&'static str> {82
index()119
static GLYPHS: OnceLock<HashMap<&'static str, &'static str>> = OnceLock::new();83
.iter()120
GLYPHS84
.find(|(_, keys)| keys.contains(&key))121
.get_or_init(|| {85
.map(|(glyph, _)| *glyph)122
EMOTIONS123
.lines()124
.filter_map(|line| line.split_once('\t'))125
.flat_map(|(glyph, keys)| keys.split(' ').map(move |key| (key, glyph)))126
.collect()127
})128
.get(key)129
.copied()86
}130
}87
131
88
pub fn emotion_keys(glyph: &str) -> &'static [&'static str] {132
pub fn emotion_keys(glyph: &str) -> &'static [&'static str] {@@ -135,6 +179,16 @@ mod tests {135
assert_eq!(reaction_key("❤️").as_deref(), Some("heart"));179
assert_eq!(reaction_key("❤️").as_deref(), Some("heart"));136
}180
}137
181
182
#[test]183
fn keys_turn_into_glyphs_with_their_tone() {184
assert_eq!(reaction_glyph_for_key("yes-tone2").as_deref(), Some("👍🏼"));185
assert_eq!(reaction_glyph_for_key("like").as_deref(), Some("👍"));186
assert_eq!(reaction_glyph_for_key("heart").as_deref(), Some("❤"));187
assert_eq!(reaction_glyph_for_key("nope"), None);188
assert_eq!(insert_skin_tone("🤷\u{200d}♂️", 1), "🤷🏻\u{200d}♂️");189
assert_eq!(insert_skin_tone("✌️", 3), "✌🏽");190
}191
138
#[test]192
#[test]139
fn unknown_glyph_has_no_key() {193
fn unknown_glyph_has_no_key() {140
assert_eq!(emotion_key("x"), None);194
assert_eq!(emotion_key("x"), None);@@ -93,6 +93,16 @@ impl<T: MessageTransport> UserSettings<T> {
93
93
ensure_success(&answer)
94
94
}
95
95
96
pub async fn set_skin_tone(&self, tone: u8) -> Result<()> {
97
let url = format!("{}?name={SKIN_TONE_KEY}", self.base_url);
98
let body = json!({ SKIN_TONE_KEY: tone.to_string() });
99
let answer = self
100
.transport
101
.send(Request::with_body(Method::Put, url, body))
102
.await?;
103
ensure_success(&answer)
104
}
105
96
106
pub async fn properties(&self) -> Result<Value> {
97
107
let answer = self.transport.send(Request::get(&self.base_url)).await?;
98
108
ensure_success(&answer)?;
@@ -93,6 +93,16 @@ impl<T: MessageTransport> UserSettings<T> {93
ensure_success(&answer)93
ensure_success(&answer)94
}94
}95
95
96
pub async fn set_skin_tone(&self, tone: u8) -> Result<()> {97
let url = format!("{}?name={SKIN_TONE_KEY}", self.base_url);98
let body = json!({ SKIN_TONE_KEY: tone.to_string() });99
let answer = self100
.transport101
.send(Request::with_body(Method::Put, url, body))102
.await?;103
ensure_success(&answer)104
}105
96
pub async fn properties(&self) -> Result<Value> {106
pub async fn properties(&self) -> Result<Value> {97
let answer = self.transport.send(Request::get(&self.base_url)).await?;107
let answer = self.transport.send(Request::get(&self.base_url)).await?;98
ensure_success(&answer)?;108
ensure_success(&answer)?;@@ -332,6 +332,8 @@ impl<R: Remote> SyncEngine<R> {
332
332
return Ok(None);
333
333
};
334
334
let mut record = record;
335
self.apply_chat_emotions(conversation_id, std::slice::from_mut(&mut record))
336
.await;
335
337
let delta = self.ingest(conversation_id, vec![record.clone()])?;
336
338
let links_changed = self.attach_links(conversation_id, &mut [&mut record]).await;
337
339
self.announce(conversation_id, !delta.is_empty() || links_changed);
@@ -332,6 +332,8 @@ impl<R: Remote> SyncEngine<R> {332
return Ok(None);332
return Ok(None);333
};333
};334
let mut record = record;334
let mut record = record;335
self.apply_chat_emotions(conversation_id, std::slice::from_mut(&mut record))336
.await;335
let delta = self.ingest(conversation_id, vec![record.clone()])?;337
let delta = self.ingest(conversation_id, vec![record.clone()])?;336
let links_changed = self.attach_links(conversation_id, &mut [&mut record]).await;338
let links_changed = self.attach_links(conversation_id, &mut [&mut record]).await;337
self.announce(conversation_id, !delta.is_empty() || links_changed);339
self.announce(conversation_id, !delta.is_empty() || links_changed);@@ -66,6 +66,8 @@ impl<R: Remote> SyncEngine<R> {
66
66
..previous.clone()
67
67
},
68
68
};
69
let mut records = records;
70
self.apply_chat_emotions(channel_id, &mut records).await;
69
71
let mut delta = self.ingest(channel_id, records)?;
70
72
self.store.set_sync_state(channel_id, &state)?;
71
73
let since = bootstrap_start(previous.newest_seen, started_at);
@@ -86,7 +88,8 @@ impl<R: Remote> SyncEngine<R> {
86
88
start: DeltaStart,
87
89
) -> Result<Delta> {
88
90
let run = self.run_delta(team_id, channel_id, start).await?;
89
let records = self.delta_records(team_id, channel_id, &run.items).await?;
91
let mut records = self.delta_records(team_id, channel_id, &run.items).await?;
92
self.apply_chat_emotions(channel_id, &mut records).await;
90
93
let newest = records.iter().map(|record| record.created_at).max();
91
94
let delta = self.ingest(channel_id, records)?;
92
95
let newest_seen = match (state.newest_seen, newest) {
@@ -198,6 +201,7 @@ impl<R: Remote> SyncEngine<R> {
198
201
.filter_map(|reply| message_record(channel_id, reply)),
199
202
);
200
203
}
204
self.apply_chat_emotions(channel_id, &mut records).await;
201
205
self.ingest(channel_id, records)
202
206
}
203
207
@@ -217,7 +221,8 @@ impl<R: Remote> SyncEngine<R> {
217
221
return Ok(Vec::new());
218
222
};
219
223
let page = self.remote.channel_messages_at(cursor).await?;
220
let records = thread_records(channel_id, &page.items);
224
let mut records = thread_records(channel_id, &page.items);
225
self.apply_chat_emotions(channel_id, &mut records).await;
221
226
self.ingest(channel_id, records.clone())?;
222
227
let page_oldest = records.iter().map(|record| record.created_at).min();
223
228
self.store.set_sync_state(
@@ -66,6 +66,8 @@ impl<R: Remote> SyncEngine<R> {66
..previous.clone()66
..previous.clone()67
},67
},68
};68
};69
let mut records = records;70
self.apply_chat_emotions(channel_id, &mut records).await;69
let mut delta = self.ingest(channel_id, records)?;71
let mut delta = self.ingest(channel_id, records)?;70
self.store.set_sync_state(channel_id, &state)?;72
self.store.set_sync_state(channel_id, &state)?;71
let since = bootstrap_start(previous.newest_seen, started_at);73
let since = bootstrap_start(previous.newest_seen, started_at);@@ -86,7 +88,8 @@ impl<R: Remote> SyncEngine<R> {86
start: DeltaStart,88
start: DeltaStart,87
) -> Result<Delta> {89
) -> Result<Delta> {88
let run = self.run_delta(team_id, channel_id, start).await?;90
let run = self.run_delta(team_id, channel_id, start).await?;89
let records = self.delta_records(team_id, channel_id, &run.items).await?;91
let mut records = self.delta_records(team_id, channel_id, &run.items).await?;92
self.apply_chat_emotions(channel_id, &mut records).await;90
let newest = records.iter().map(|record| record.created_at).max();93
let newest = records.iter().map(|record| record.created_at).max();91
let delta = self.ingest(channel_id, records)?;94
let delta = self.ingest(channel_id, records)?;92
let newest_seen = match (state.newest_seen, newest) {95
let newest_seen = match (state.newest_seen, newest) {@@ -198,6 +201,7 @@ impl<R: Remote> SyncEngine<R> {198
.filter_map(|reply| message_record(channel_id, reply)),201
.filter_map(|reply| message_record(channel_id, reply)),199
);202
);200
}203
}204
self.apply_chat_emotions(channel_id, &mut records).await;201
self.ingest(channel_id, records)205
self.ingest(channel_id, records)202
}206
}203
207
@@ -217,7 +221,8 @@ impl<R: Remote> SyncEngine<R> {217
return Ok(Vec::new());221
return Ok(Vec::new());218
};222
};219
let page = self.remote.channel_messages_at(cursor).await?;223
let page = self.remote.channel_messages_at(cursor).await?;220
let records = thread_records(channel_id, &page.items);224
let mut records = thread_records(channel_id, &page.items);225
self.apply_chat_emotions(channel_id, &mut records).await;221
self.ingest(channel_id, records.clone())?;226
self.ingest(channel_id, records.clone())?;222
let page_oldest = records.iter().map(|record| record.created_at).min();227
let page_oldest = records.iter().map(|record| record.created_at).min();223
self.store.set_sync_state(228
self.store.set_sync_state(@@ -0,0 +1,159 @@
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
}
@@ -0,0 +1,159 @@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 service17
/// `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) = members29
.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) = self38
.remote39
.message_emotions(&target, &newest, page_size)40
.await41
else {42
continue;43
};44
for MessageEmotions {45
message_id,46
reactions: found_reactions,47
} in found48
{49
if let Some(index) = members50
.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() - 181
});82
groups[position].1.push(index);83
}84
groups85
}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> = found95
.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: reaction102
.time_ms103
.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
}@@ -397,6 +397,8 @@ impl<R: Remote> SyncEngine<R> {
397
397
delta_link: None,
398
398
},
399
399
};
400
let mut collected = collected;
401
self.apply_chat_emotions(conversation_id, &mut collected).await;
400
402
let delta = self.ingest(conversation_id, collected)?;
401
403
self.store.set_sync_state(conversation_id, &state)?;
402
404
Ok(delta)
@@ -413,11 +415,12 @@ impl<R: Remote> SyncEngine<R> {
413
415
.await?;
414
416
let page_oldest = oldest_created(&page);
415
417
let has_more = page.next_link.is_some() && page_oldest.is_some();
416
let records: Vec<_> = page
418
let mut records: Vec<_> = page
417
419
.items
418
420
.iter()
419
421
.filter_map(|message| message_record(conversation_id, message))
420
422
.collect();
423
self.apply_chat_emotions(conversation_id, &mut records).await;
421
424
self.ingest(conversation_id, records.clone())?;
422
425
self.store.set_sync_state(
423
426
conversation_id,
@@ -397,6 +397,8 @@ impl<R: Remote> SyncEngine<R> {397
delta_link: None,397
delta_link: None,398
},398
},399
};399
};400
let mut collected = collected;401
self.apply_chat_emotions(conversation_id, &mut collected).await;400
let delta = self.ingest(conversation_id, collected)?;402
let delta = self.ingest(conversation_id, collected)?;401
self.store.set_sync_state(conversation_id, &state)?;403
self.store.set_sync_state(conversation_id, &state)?;402
Ok(delta)404
Ok(delta)@@ -413,11 +415,12 @@ impl<R: Remote> SyncEngine<R> {413
.await?;415
.await?;414
let page_oldest = oldest_created(&page);416
let page_oldest = oldest_created(&page);415
let has_more = page.next_link.is_some() && page_oldest.is_some();417
let has_more = page.next_link.is_some() && page_oldest.is_some();416
let records: Vec<_> = page418
let mut records: Vec<_> = page417
.items419
.items418
.iter()420
.iter()419
.filter_map(|message| message_record(conversation_id, message))421
.filter_map(|message| message_record(conversation_id, message))420
.collect();422
.collect();423
self.apply_chat_emotions(conversation_id, &mut records).await;421
self.ingest(conversation_id, records.clone())?;424
self.ingest(conversation_id, records.clone())?;422
self.store.set_sync_state(425
self.store.set_sync_state(423
conversation_id,426
conversation_id,@@ -67,6 +67,9 @@ pub trait FolderSource: Send + Sync {
67
67
fn preferred_skin_tone(&self) -> Option<u8> {
68
68
None
69
69
}
70
fn set_skin_tone(&self, _tone: u8) -> BoxFuture<'_, Result<()>> {
71
Box::pin(async { Ok(()) })
72
}
70
73
fn set_section_enabled(&self, section: ChatSection, enabled: bool)
71
74
-> BoxFuture<'_, Result<()>>;
72
75
fn set_folder_expanded<'a>(
@@ -154,6 +157,10 @@ impl FolderSource for ChatsvcFolderSource {
154
157
*self.skin_tone.lock().unwrap()
155
158
}
156
159
160
fn set_skin_tone(&self, tone: u8) -> BoxFuture<'_, Result<()>> {
161
Box::pin(async move { Ok(self.settings.set_skin_tone(tone).await?) })
162
}
163
157
164
fn teams_order(&self) -> BoxFuture<'_, Result<Vec<(String, i64)>>> {
158
165
Box::pin(async {
159
166
let cached = self.properties.lock().unwrap().take();
@@ -463,6 +470,11 @@ impl<R: Remote> SyncEngine<R> {
463
470
.await
464
471
}
465
472
473
pub async fn set_skin_tone(&self, tone: u8) -> Result<()> {
474
self.folder_source()?.set_skin_tone(tone).await?;
475
crate::skin_tone::store_account_skin_tone(&self.store, tone)
476
}
477
466
478
pub async fn set_folder_expanded(&self, folder_id: &str, expanded: bool) -> Result<()> {
467
479
self.folder_source()?
468
480
.set_folder_expanded(folder_id, expanded)
@@ -67,6 +67,9 @@ pub trait FolderSource: Send + Sync {67
fn preferred_skin_tone(&self) -> Option<u8> {67
fn preferred_skin_tone(&self) -> Option<u8> {68
None68
None69
}69
}70
fn set_skin_tone(&self, _tone: u8) -> BoxFuture<'_, Result<()>> {71
Box::pin(async { Ok(()) })72
}70
fn set_section_enabled(&self, section: ChatSection, enabled: bool)73
fn set_section_enabled(&self, section: ChatSection, enabled: bool)71
-> BoxFuture<'_, Result<()>>;74
-> BoxFuture<'_, Result<()>>;72
fn set_folder_expanded<'a>(75
fn set_folder_expanded<'a>(@@ -154,6 +157,10 @@ impl FolderSource for ChatsvcFolderSource {154
*self.skin_tone.lock().unwrap()157
*self.skin_tone.lock().unwrap()155
}158
}156
159
160
fn set_skin_tone(&self, tone: u8) -> BoxFuture<'_, Result<()>> {161
Box::pin(async move { Ok(self.settings.set_skin_tone(tone).await?) })162
}163
157
fn teams_order(&self) -> BoxFuture<'_, Result<Vec<(String, i64)>>> {164
fn teams_order(&self) -> BoxFuture<'_, Result<Vec<(String, i64)>>> {158
Box::pin(async {165
Box::pin(async {159
let cached = self.properties.lock().unwrap().take();166
let cached = self.properties.lock().unwrap().take();@@ -463,6 +470,11 @@ impl<R: Remote> SyncEngine<R> {463
.await470
.await464
}471
}465
472
473
pub async fn set_skin_tone(&self, tone: u8) -> Result<()> {474
self.folder_source()?.set_skin_tone(tone).await?;475
crate::skin_tone::store_account_skin_tone(&self.store, tone)476
}477
466
pub async fn set_folder_expanded(&self, folder_id: &str, expanded: bool) -> Result<()> {478
pub async fn set_folder_expanded(&self, folder_id: &str, expanded: bool) -> Result<()> {467
self.folder_source()?479
self.folder_source()?468
.set_folder_expanded(folder_id, expanded)480
.set_folder_expanded(folder_id, expanded)@@ -15,6 +15,7 @@ mod chat_paging;
15
15
mod download;
16
16
mod draft;
17
17
mod emoticon_tags;
18
mod emotion_sync;
18
19
mod engine;
19
20
mod error;
20
21
mod events;
@@ -136,7 +137,7 @@ pub use profile::{OrgPerson, PersonProfile};
136
137
pub use receipts::{ReceiptReader, ReceiptState};
137
138
pub use remote::{ChatsPage, DeltaPage, Remote, RemotePage};
138
139
pub use scheduled::NOTES_CHAT_ID;
139
pub use skin_tone::{skin_tone, store_picked_skin_tone};
140
pub use skin_tone::{skin_tone, store_account_skin_tone};
140
141
pub use spans::{FontSize, Span, html_to_spans};
141
142
pub use store::{ConversationHit, HIGHLIGHT_END, HIGHLIGHT_START, SearchHit};
142
143
pub use stored::{
@@ -15,6 +15,7 @@ mod chat_paging;15
mod download;15
mod download;16
mod draft;16
mod draft;17
mod emoticon_tags;17
mod emoticon_tags;18
mod emotion_sync;18
mod engine;19
mod engine;19
mod error;20
mod error;20
mod events;21
mod events;@@ -136,7 +137,7 @@ pub use profile::{OrgPerson, PersonProfile};136
pub use receipts::{ReceiptReader, ReceiptState};137
pub use receipts::{ReceiptReader, ReceiptState};137
pub use remote::{ChatsPage, DeltaPage, Remote, RemotePage};138
pub use remote::{ChatsPage, DeltaPage, Remote, RemotePage};138
pub use scheduled::NOTES_CHAT_ID;139
pub use scheduled::NOTES_CHAT_ID;139
pub use skin_tone::{skin_tone, store_picked_skin_tone};140
pub use skin_tone::{skin_tone, store_account_skin_tone};140
pub use spans::{FontSize, Span, html_to_spans};141
pub use spans::{FontSize, Span, html_to_spans};141
pub use store::{ConversationHit, HIGHLIGHT_END, HIGHLIGHT_START, SearchHit};142
pub use store::{ConversationHit, HIGHLIGHT_END, HIGHLIGHT_START, SearchHit};142
pub use stored::{143
pub use stored::{@@ -69,7 +69,8 @@ impl<R: Remote> SyncEngine<R> {
69
69
records.push(record);
70
70
}
71
71
}
72
let records = sorted(records);
72
let mut records = sorted(records);
73
self.apply_chat_emotions(chat_id, &mut records).await;
73
74
self.ingest(chat_id, records.clone())?;
74
75
self.announce(chat_id, !records.is_empty());
75
76
Ok(WindowPage {
@@ -69,7 +69,8 @@ impl<R: Remote> SyncEngine<R> {69
records.push(record);69
records.push(record);70
}70
}71
}71
}72
let records = sorted(records);72
let mut records = sorted(records);73
self.apply_chat_emotions(chat_id, &mut records).await;73
self.ingest(chat_id, records.clone())?;74
self.ingest(chat_id, records.clone())?;74
self.announce(chat_id, !records.is_empty());75
self.announce(chat_id, !records.is_empty());75
Ok(WindowPage {76
Ok(WindowPage {@@ -2,7 +2,7 @@ use chatsvc::{
2
2
CallLogEntry, CardActions, ChatApp, ConversationRef, ConversationState, Conversations,
3
3
ForcedAvailability, ForwardResult, Gif, Gifs, InvokeRequest, InvokeResponse, Language,
4
4
LanguageSettings, LanguageSettingsClient, LinkInfo, MemberHorizon, MessageLanguage,
5
MessageLinks, MessageWindow, Messages, PinnedMessage, Pins, PresenceService, PresenceStatus,
5
MessageEmotions, MessageLinks, MessageWindow, Messages, PinnedMessage, Pins, PresenceService, PresenceStatus,
6
6
Receipts, RecordingPolicy, SavedMessage, ScheduledDraft, ScheduledDrafts, StatusNote, TranslateRequest,
7
7
Translation, TranslationTrigger, Translator, WindowDirection, WorkLocationKind,
8
8
};
@@ -351,6 +351,15 @@ pub trait Remote {
351
351
Err(Error::Unsupported("link previews"))
352
352
}
353
353
354
async fn message_emotions(
355
&self,
356
_conversation: &ConversationRef,
357
_newest_message_id: &str,
358
_page_size: usize,
359
) -> Result<Vec<MessageEmotions>> {
360
Err(Error::Unsupported("chat service reactions"))
361
}
362
354
363
async fn set_message_links(&self, _target: &MessageTarget, _links_json: &str) -> Result<()> {
355
364
Err(Error::Unsupported("link previews"))
356
365
}
@@ -957,6 +966,17 @@ impl Remote for Graph {
957
966
.await?)
958
967
}
959
968
969
async fn message_emotions(
970
&self,
971
conversation: &ConversationRef,
972
newest_message_id: &str,
973
page_size: usize,
974
) -> Result<Vec<MessageEmotions>> {
975
Ok(Messages::new(self.session())
976
.message_emotions(&conversation.conversation_id(), newest_message_id, page_size)
977
.await?)
978
}
979
960
980
async fn set_message_links(&self, target: &MessageTarget, links_json: &str) -> Result<()> {
961
981
Ok(Messages::new(self.session())
962
982
.set_links(&conversation_ref(target), target.message_id(), links_json)
@@ -2,7 +2,7 @@ use chatsvc::{2
CallLogEntry, CardActions, ChatApp, ConversationRef, ConversationState, Conversations,2
CallLogEntry, CardActions, ChatApp, ConversationRef, ConversationState, Conversations,3
ForcedAvailability, ForwardResult, Gif, Gifs, InvokeRequest, InvokeResponse, Language,3
ForcedAvailability, ForwardResult, Gif, Gifs, InvokeRequest, InvokeResponse, Language,4
LanguageSettings, LanguageSettingsClient, LinkInfo, MemberHorizon, MessageLanguage,4
LanguageSettings, LanguageSettingsClient, LinkInfo, MemberHorizon, MessageLanguage,5
MessageLinks, MessageWindow, Messages, PinnedMessage, Pins, PresenceService, PresenceStatus,5
MessageEmotions, MessageLinks, MessageWindow, Messages, PinnedMessage, Pins, PresenceService, PresenceStatus,6
Receipts, RecordingPolicy, SavedMessage, ScheduledDraft, ScheduledDrafts, StatusNote, TranslateRequest,6
Receipts, RecordingPolicy, SavedMessage, ScheduledDraft, ScheduledDrafts, StatusNote, TranslateRequest,7
Translation, TranslationTrigger, Translator, WindowDirection, WorkLocationKind,7
Translation, TranslationTrigger, Translator, WindowDirection, WorkLocationKind,8
};8
};@@ -351,6 +351,15 @@ pub trait Remote {351
Err(Error::Unsupported("link previews"))351
Err(Error::Unsupported("link previews"))352
}352
}353
353
354
async fn message_emotions(355
&self,356
_conversation: &ConversationRef,357
_newest_message_id: &str,358
_page_size: usize,359
) -> Result<Vec<MessageEmotions>> {360
Err(Error::Unsupported("chat service reactions"))361
}362
354
async fn set_message_links(&self, _target: &MessageTarget, _links_json: &str) -> Result<()> {363
async fn set_message_links(&self, _target: &MessageTarget, _links_json: &str) -> Result<()> {355
Err(Error::Unsupported("link previews"))364
Err(Error::Unsupported("link previews"))356
}365
}@@ -957,6 +966,17 @@ impl Remote for Graph {957
.await?)966
.await?)958
}967
}959
968
969
async fn message_emotions(970
&self,971
conversation: &ConversationRef,972
newest_message_id: &str,973
page_size: usize,974
) -> Result<Vec<MessageEmotions>> {975
Ok(Messages::new(self.session())976
.message_emotions(&conversation.conversation_id(), newest_message_id, page_size)977
.await?)978
}979
960
async fn set_message_links(&self, target: &MessageTarget, links_json: &str) -> Result<()> {980
async fn set_message_links(&self, target: &MessageTarget, links_json: &str) -> Result<()> {961
Ok(Messages::new(self.session())981
Ok(Messages::new(self.session())962
.set_links(&conversation_ref(target), target.message_id(), links_json)982
.set_links(&conversation_ref(target), target.message_id(), links_json)@@ -3,25 +3,18 @@ use store::Store;
3
3
use crate::error::Result;
4
4
5
5
const META_ACCOUNT_SKIN_TONE: &str = "skin_tone_account";
6
const META_PICKED_SKIN_TONE: &str = "skin_tone_picked";
7
8
fn read(store: &Store, key: &str) -> Option<u8> {
9
store.meta(key).ok().flatten()?.parse().ok()
10
}
11
6
12
7
pub fn store_account_skin_tone(store: &Store, tone: u8) -> Result<()> {
13
8
Ok(store.set_meta(META_ACCOUNT_SKIN_TONE, &tone.to_string())?)
14
9
}
15
10
16
pub fn store_picked_skin_tone(store: &Store, tone: u8) -> Result<()> {
17
Ok(store.set_meta(META_PICKED_SKIN_TONE, &tone.to_string())?)
18
}
19
20
/// 0 is the default yellow, 1 to 5 light to dark. A tone picked in this app beats the
21
/// account setting, which the Teams web client only reads and never writes.
11
/// The account setting `preferredSkinToneIndex`: 0 is the default yellow, 1 to 5 light to dark.
22
12
pub fn skin_tone(store: &Store) -> u8 {
23
read(store, META_PICKED_SKIN_TONE)
24
.or_else(|| read(store, META_ACCOUNT_SKIN_TONE))
13
store
14
.meta(META_ACCOUNT_SKIN_TONE)
15
.ok()
16
.flatten()
17
.and_then(|value| value.parse().ok())
25
18
.unwrap_or(0)
26
19
}
27
20
@@ -30,12 +23,10 @@ mod tests {
30
23
use super::*;
31
24
32
25
#[test]
33
fn a_picked_tone_beats_the_account_tone() {
26
fn the_account_tone_is_stored_and_read_back() {
34
27
let store = Store::open_in_memory().unwrap();
35
28
assert_eq!(skin_tone(&store), 0);
36
29
store_account_skin_tone(&store, 2).unwrap();
37
30
assert_eq!(skin_tone(&store), 2);
38
store_picked_skin_tone(&store, 4).unwrap();
39
assert_eq!(skin_tone(&store), 4);
40
31
}
41
32
}
@@ -3,25 +3,18 @@ use store::Store;3
use crate::error::Result;3
use crate::error::Result;4
4
5
const META_ACCOUNT_SKIN_TONE: &str = "skin_tone_account";5
const META_ACCOUNT_SKIN_TONE: &str = "skin_tone_account";6
const META_PICKED_SKIN_TONE: &str = "skin_tone_picked";7
8
fn read(store: &Store, key: &str) -> Option<u8> {9
store.meta(key).ok().flatten()?.parse().ok()10
}11
6
12
pub fn store_account_skin_tone(store: &Store, tone: u8) -> Result<()> {7
pub fn store_account_skin_tone(store: &Store, tone: u8) -> Result<()> {13
Ok(store.set_meta(META_ACCOUNT_SKIN_TONE, &tone.to_string())?)8
Ok(store.set_meta(META_ACCOUNT_SKIN_TONE, &tone.to_string())?)14
}9
}15
10
16
pub fn store_picked_skin_tone(store: &Store, tone: u8) -> Result<()> {11
/// The account setting `preferredSkinToneIndex`: 0 is the default yellow, 1 to 5 light to dark.17
Ok(store.set_meta(META_PICKED_SKIN_TONE, &tone.to_string())?)18
}19
20
/// 0 is the default yellow, 1 to 5 light to dark. A tone picked in this app beats the21
/// account setting, which the Teams web client only reads and never writes.22
pub fn skin_tone(store: &Store) -> u8 {12
pub fn skin_tone(store: &Store) -> u8 {23
read(store, META_PICKED_SKIN_TONE)13
store24
.or_else(|| read(store, META_ACCOUNT_SKIN_TONE))14
.meta(META_ACCOUNT_SKIN_TONE)15
.ok()16
.flatten()17
.and_then(|value| value.parse().ok())25
.unwrap_or(0)18
.unwrap_or(0)26
}19
}27
20
@@ -30,12 +23,10 @@ mod tests {30
use super::*;23
use super::*;31
24
32
#[test]25
#[test]33
fn a_picked_tone_beats_the_account_tone() {26
fn the_account_tone_is_stored_and_read_back() {34
let store = Store::open_in_memory().unwrap();27
let store = Store::open_in_memory().unwrap();35
assert_eq!(skin_tone(&store), 0);28
assert_eq!(skin_tone(&store), 0);36
store_account_skin_tone(&store, 2).unwrap();29
store_account_skin_tone(&store, 2).unwrap();37
assert_eq!(skin_tone(&store), 2);30
assert_eq!(skin_tone(&store), 2);38
store_picked_skin_tone(&store, 4).unwrap();39
assert_eq!(skin_tone(&store), 4);40
}31
}41
}32
}