Merge remote-tracking branch 'origin/main' into feat/popout-spellcheck
@@ -582,7 +582,7 @@ async fn speak_until_hangup(
582
582
if ticks % REACTION_EVERY_TICKS == REACTION_EVERY_TICKS / 2
583
583
&& let Some((mri, _)) = people.get((ticks / REACTION_EVERY_TICKS) as usize % people.len().max(1))
584
584
{
585
let reaction = Reaction::ALL[(ticks / REACTION_EVERY_TICKS) as usize % Reaction::ALL.len()];
585
let reaction = Reaction::ALL[(ticks / REACTION_EVERY_TICKS) as usize % Reaction::ALL.len()].clone();
586
586
control.send(CallUpdate::Reaction { mri: mri.clone(), reaction });
587
587
}
588
588
if captions_on {
@@ -582,7 +582,7 @@ async fn speak_until_hangup(582
if ticks % REACTION_EVERY_TICKS == REACTION_EVERY_TICKS / 2582
if ticks % REACTION_EVERY_TICKS == REACTION_EVERY_TICKS / 2583
&& let Some((mri, _)) = people.get((ticks / REACTION_EVERY_TICKS) as usize % people.len().max(1))583
&& let Some((mri, _)) = people.get((ticks / REACTION_EVERY_TICKS) as usize % people.len().max(1))584
{584
{585
let reaction = Reaction::ALL[(ticks / REACTION_EVERY_TICKS) as usize % Reaction::ALL.len()];585
let reaction = Reaction::ALL[(ticks / REACTION_EVERY_TICKS) as usize % Reaction::ALL.len()].clone();586
control.send(CallUpdate::Reaction { mri: mri.clone(), reaction });586
control.send(CallUpdate::Reaction { mri: mri.clone(), reaction });587
}587
}588
if captions_on {588
if captions_on {@@ -1840,13 +1840,13 @@ mod tests {
1840
1840
let reaction_at = |model: &CallModel, mri: &str, seconds: u64| {
1841
1841
model
1842
1842
.chip_of(mri, start + Duration::from_secs(seconds))
1843
.map(|chip| chip.reaction)
1843
.map(|chip| chip.reaction.clone())
1844
1844
};
1845
1845
assert_eq!(reaction_at(&model, "8:orgid:a", 2), Some(Reaction::Heart));
1846
1846
assert_eq!(
1847
1847
model
1848
1848
.own_chip(start + Duration::from_secs(2))
1849
.map(|chip| chip.reaction),
1849
.map(|chip| chip.reaction.clone()),
1850
1850
Some(Reaction::Like)
1851
1851
);
1852
1852
assert_eq!(reaction_at(&model, "8:orgid:a", 3), None);
@@ -1840,13 +1840,13 @@ mod tests {1840
let reaction_at = |model: &CallModel, mri: &str, seconds: u64| {1840
let reaction_at = |model: &CallModel, mri: &str, seconds: u64| {1841
model1841
model1842
.chip_of(mri, start + Duration::from_secs(seconds))1842
.chip_of(mri, start + Duration::from_secs(seconds))1843
.map(|chip| chip.reaction)1843
.map(|chip| chip.reaction.clone())1844
};1844
};1845
assert_eq!(reaction_at(&model, "8:orgid:a", 2), Some(Reaction::Heart));1845
assert_eq!(reaction_at(&model, "8:orgid:a", 2), Some(Reaction::Heart));1846
assert_eq!(1846
assert_eq!(1847
model1847
model1848
.own_chip(start + Duration::from_secs(2))1848
.own_chip(start + Duration::from_secs(2))1849
.map(|chip| chip.reaction),1849
.map(|chip| chip.reaction.clone()),1850
Some(Reaction::Like)1850
Some(Reaction::Like)1851
);1851
);1852
assert_eq!(reaction_at(&model, "8:orgid:a", 3), None);1852
assert_eq!(reaction_at(&model, "8:orgid:a", 3), None);@@ -798,7 +798,7 @@ impl AppState {
798
798
return;
799
799
};
800
800
if let Some(own_mri) = call.model.own_mri.clone() {
801
call.model.note_reaction(own_mri, reaction, Instant::now());
801
call.model.note_reaction(own_mri, reaction.clone(), Instant::now());
802
802
}
803
803
self.send_call_command(CallCommand::SendReaction(reaction));
804
804
cx.emit(AppEvent::Call);
@@ -798,7 +798,7 @@ impl AppState {798
return;798
return;799
};799
};800
if let Some(own_mri) = call.model.own_mri.clone() {800
if let Some(own_mri) = call.model.own_mri.clone() {801
call.model.note_reaction(own_mri, reaction, Instant::now());801
call.model.note_reaction(own_mri, reaction.clone(), Instant::now());802
}802
}803
self.send_call_command(CallCommand::SendReaction(reaction));803
self.send_call_command(CallCommand::SendReaction(reaction));804
cx.emit(AppEvent::Call);804
cx.emit(AppEvent::Call);@@ -493,6 +493,13 @@ pub fn mention_candidates(conversation_id: &str, query: &str) -> Vec<MentionCand
493
493
source: PersonSource::Member,
494
494
})
495
495
});
496
let everyone = demo_chats()
497
.into_iter()
498
.find(|chat| chat.id == conversation_id && chat.kind == "group")
499
.map(|chat| MentionCandidate::Everyone {
500
chat_id: chat.id.to_owned(),
501
})
502
.filter(|candidate| matches(candidate.display_name()));
496
503
let scope: Vec<MentionCandidate> = if conversation_id.starts_with("demo-channel") {
497
504
[
498
505
MentionCandidate::Channel {
@@ -503,6 +510,11 @@ pub fn mention_candidates(conversation_id: &str, query: &str) -> Vec<MentionCand
503
510
team_id: "demo-team-1".to_owned(),
504
511
name: "Platform".to_owned(),
505
512
},
513
MentionCandidate::Tag {
514
tag_id: "demo-tag-design".to_owned(),
515
name: "Designers".to_owned(),
516
member_count: Some(3),
517
},
506
518
]
507
519
.into_iter()
508
520
.filter(|candidate| matches(candidate.display_name()))
@@ -510,7 +522,7 @@ pub fn mention_candidates(conversation_id: &str, query: &str) -> Vec<MentionCand
510
522
} else {
511
523
Vec::new()
512
524
};
513
people.chain(scope).collect()
525
everyone.into_iter().chain(people).chain(scope).collect()
514
526
}
515
527
516
528
pub fn send_in_chat(
@@ -2409,7 +2421,18 @@ mod tests {
2409
2421
assert_eq!(chat[0].display_name(), "Mara Lindqvist");
2410
2422
let channel = mention_candidates("demo-channel-1-1", "gen");
2411
2423
assert!(matches!(channel[0], MentionCandidate::Channel { .. }));
2412
assert_eq!(mention_candidates("demo-chat-release", "").len(), 5);
2424
let all = mention_candidates("demo-chat-release", "");
2425
assert_eq!(all.len(), 6);
2426
assert!(matches!(all[0], MentionCandidate::Everyone { .. }));
2427
assert!(
2428
mention_candidates("demo-chat-mara", "")
2429
.iter()
2430
.all(|candidate| !matches!(candidate, MentionCandidate::Everyone { .. }))
2431
);
2432
assert!(matches!(
2433
mention_candidates("demo-channel-1-1", "desi")[0],
2434
MentionCandidate::Tag { .. }
2435
));
2413
2436
}
2414
2437
2415
2438
#[test]
@@ -493,6 +493,13 @@ pub fn mention_candidates(conversation_id: &str, query: &str) -> Vec<MentionCand493
source: PersonSource::Member,493
source: PersonSource::Member,494
})494
})495
});495
});496
let everyone = demo_chats()497
.into_iter()498
.find(|chat| chat.id == conversation_id && chat.kind == "group")499
.map(|chat| MentionCandidate::Everyone {500
chat_id: chat.id.to_owned(),501
})502
.filter(|candidate| matches(candidate.display_name()));496
let scope: Vec<MentionCandidate> = if conversation_id.starts_with("demo-channel") {503
let scope: Vec<MentionCandidate> = if conversation_id.starts_with("demo-channel") {497
[504
[498
MentionCandidate::Channel {505
MentionCandidate::Channel {@@ -503,6 +510,11 @@ pub fn mention_candidates(conversation_id: &str, query: &str) -> Vec<MentionCand503
team_id: "demo-team-1".to_owned(),510
team_id: "demo-team-1".to_owned(),504
name: "Platform".to_owned(),511
name: "Platform".to_owned(),505
},512
},513
MentionCandidate::Tag {514
tag_id: "demo-tag-design".to_owned(),515
name: "Designers".to_owned(),516
member_count: Some(3),517
},506
]518
]507
.into_iter()519
.into_iter()508
.filter(|candidate| matches(candidate.display_name()))520
.filter(|candidate| matches(candidate.display_name()))@@ -510,7 +522,7 @@ pub fn mention_candidates(conversation_id: &str, query: &str) -> Vec<MentionCand510
} else {522
} else {511
Vec::new()523
Vec::new()512
};524
};513
people.chain(scope).collect()525
everyone.into_iter().chain(people).chain(scope).collect()514
}526
}515
527
516
pub fn send_in_chat(528
pub fn send_in_chat(@@ -2409,7 +2421,18 @@ mod tests {2409
assert_eq!(chat[0].display_name(), "Mara Lindqvist");2421
assert_eq!(chat[0].display_name(), "Mara Lindqvist");2410
let channel = mention_candidates("demo-channel-1-1", "gen");2422
let channel = mention_candidates("demo-channel-1-1", "gen");2411
assert!(matches!(channel[0], MentionCandidate::Channel { .. }));2423
assert!(matches!(channel[0], MentionCandidate::Channel { .. }));2412
assert_eq!(mention_candidates("demo-chat-release", "").len(), 5);2424
let all = mention_candidates("demo-chat-release", "");2425
assert_eq!(all.len(), 6);2426
assert!(matches!(all[0], MentionCandidate::Everyone { .. }));2427
assert!(2428
mention_candidates("demo-chat-mara", "")2429
.iter()2430
.all(|candidate| !matches!(candidate, MentionCandidate::Everyone { .. }))2431
);2432
assert!(matches!(2433
mention_candidates("demo-channel-1-1", "desi")[0],2434
MentionCandidate::Tag { .. }2435
));2413
}2436
}2414
2437
2415
#[test]2438
#[test]@@ -45,6 +45,7 @@ pub mod scheduled;
45
45
pub mod scheduled_rows;
46
46
pub mod section_actions;
47
47
pub mod settings_section;
48
pub mod share_outlook;
48
49
pub mod sidebar_model;
49
50
pub mod sound_actions;
50
51
pub mod stored_outgoing;
@@ -45,6 +45,7 @@ pub mod scheduled;45
pub mod scheduled_rows;45
pub mod scheduled_rows;46
pub mod section_actions;46
pub mod section_actions;47
pub mod settings_section;47
pub mod settings_section;48
pub mod share_outlook;48
pub mod sidebar_model;49
pub mod sidebar_model;49
pub mod sound_actions;50
pub mod sound_actions;50
pub mod stored_outgoing;51
pub mod stored_outgoing;@@ -161,6 +161,8 @@ pub fn build_incoming(
161
161
_ => ChannelSignals::default(),
162
162
};
163
163
let chat = chat_signals(store, sidebar, &record.conversation_id, my_user_id);
164
let mentions_me = mentions_me(record, my_user_id)
165
|| (!matches!(kind, ChatKind::Channel { .. }) && teams_core::mentions_whole_chat(record));
164
166
Some(Incoming {
165
167
conversation_id: record.conversation_id.clone(),
166
168
message_id: record.message_id.clone(),
@@ -169,7 +171,7 @@ pub fn build_incoming(
169
171
sender_id: record.sender_id.clone(),
170
172
sender_name: record.sender_name.clone().unwrap_or_default(),
171
173
preview: preview_of(record),
172
mentions_me: mentions_me(record, my_user_id),
174
mentions_me,
173
175
muted: is_muted_chat(sidebar, &record.conversation_id),
174
176
signals,
175
177
chat,
@@ -593,6 +595,19 @@ mod tests {
593
595
assert!(!other.unwrap().mentions_me);
594
596
}
595
597
598
#[test]
599
fn everyone_in_a_group_chat_counts_as_a_mention_but_a_channel_mention_does_not() {
600
let store = Store::open_in_memory().unwrap();
601
let mut message = record("group", "u1", Utc::now(), "<at>Everyone</at>");
602
message.mentions_json =
603
r#"[{"user_id":null,"name":"Everyone","target_id":"group","group":true}]"#.into();
604
assert!(collect_one(message, &store).mentions_me);
605
let mut post = record("channel-open", "u1", Utc::now(), "<at>channel</at>");
606
post.mentions_json =
607
r#"[{"user_id":null,"name":"channel","target_id":"channel-open","group":true}]"#.into();
608
assert!(!collect_one(post, &store).mentions_me);
609
}
610
596
611
#[test]
597
612
fn unknown_conversation_yields_nothing() {
598
613
let message = record("nowhere", "u1", Utc::now(), "x");
@@ -161,6 +161,8 @@ pub fn build_incoming(161
_ => ChannelSignals::default(),161
_ => ChannelSignals::default(),162
};162
};163
let chat = chat_signals(store, sidebar, &record.conversation_id, my_user_id);163
let chat = chat_signals(store, sidebar, &record.conversation_id, my_user_id);164
let mentions_me = mentions_me(record, my_user_id)165
|| (!matches!(kind, ChatKind::Channel { .. }) && teams_core::mentions_whole_chat(record));164
Some(Incoming {166
Some(Incoming {165
conversation_id: record.conversation_id.clone(),167
conversation_id: record.conversation_id.clone(),166
message_id: record.message_id.clone(),168
message_id: record.message_id.clone(),@@ -169,7 +171,7 @@ pub fn build_incoming(169
sender_id: record.sender_id.clone(),171
sender_id: record.sender_id.clone(),170
sender_name: record.sender_name.clone().unwrap_or_default(),172
sender_name: record.sender_name.clone().unwrap_or_default(),171
preview: preview_of(record),173
preview: preview_of(record),172
mentions_me: mentions_me(record, my_user_id),174
mentions_me,173
muted: is_muted_chat(sidebar, &record.conversation_id),175
muted: is_muted_chat(sidebar, &record.conversation_id),174
signals,176
signals,175
chat,177
chat,@@ -593,6 +595,19 @@ mod tests {593
assert!(!other.unwrap().mentions_me);595
assert!(!other.unwrap().mentions_me);594
}596
}595
597
598
#[test]599
fn everyone_in_a_group_chat_counts_as_a_mention_but_a_channel_mention_does_not() {600
let store = Store::open_in_memory().unwrap();601
let mut message = record("group", "u1", Utc::now(), "<at>Everyone</at>");602
message.mentions_json =603
r#"[{"user_id":null,"name":"Everyone","target_id":"group","group":true}]"#.into();604
assert!(collect_one(message, &store).mentions_me);605
let mut post = record("channel-open", "u1", Utc::now(), "<at>channel</at>");606
post.mentions_json =607
r#"[{"user_id":null,"name":"channel","target_id":"channel-open","group":true}]"#.into();608
assert!(!collect_one(post, &store).mentions_me);609
}610
596
#[test]611
#[test]597
fn unknown_conversation_yields_nothing() {612
fn unknown_conversation_yields_nothing() {598
let message = record("nowhere", "u1", Utc::now(), "x");613
let message = record("nowhere", "u1", Utc::now(), "x");@@ -125,10 +125,10 @@ fn reactions_submenu(
125
125
for reaction in Reaction::ALL {
126
126
let app = app.clone();
127
127
menu = menu.item(
128
PopupMenuItem::new(format!("{} {}", reaction_glyph(reaction), reaction.name()))
128
PopupMenuItem::new(format!("{} {}", reaction_glyph(&reaction), reaction.name()))
129
129
.disabled(!can_react)
130
130
.on_click(move |_, _, cx| {
131
app.update(cx, |state, cx| state.send_call_reaction(reaction, cx))
131
app.update(cx, |state, cx| state.send_call_reaction(reaction.clone(), cx))
132
132
}),
133
133
);
134
134
}
@@ -125,10 +125,10 @@ fn reactions_submenu(125
for reaction in Reaction::ALL {125
for reaction in Reaction::ALL {126
let app = app.clone();126
let app = app.clone();127
menu = menu.item(127
menu = menu.item(128
PopupMenuItem::new(format!("{} {}", reaction_glyph(reaction), reaction.name()))128
PopupMenuItem::new(format!("{} {}", reaction_glyph(&reaction), reaction.name()))129
.disabled(!can_react)129
.disabled(!can_react)130
.on_click(move |_, _, cx| {130
.on_click(move |_, _, cx| {131
app.update(cx, |state, cx| state.send_call_reaction(reaction, cx))131
app.update(cx, |state, cx| state.send_call_reaction(reaction.clone(), cx))132
}),132
}),133
);133
);134
}134
}@@ -79,13 +79,17 @@ const MUSIC_MODE_LABEL: &str = "Music mode";
79
79
const PUSH_TO_TALK_HINT: &str = "Unmuted - release Ctrl+Space to mute";
80
80
const PUSH_TO_TALK_TOP: f32 = 12.;
81
81
82
pub fn reaction_glyph(reaction: Reaction) -> String {
82
pub fn reaction_glyph(reaction: &Reaction) -> String {
83
83
match reaction {
84
84
Reaction::Applause => "\u{1F44F}".to_owned(),
85
85
other => chat_reaction_glyph(other.name()),
86
86
}
87
87
}
88
88
89
fn is_emoji_glyph(glyph: &str) -> bool {
90
!glyph.is_ascii()
91
}
92
89
93
#[derive(Default)]
90
94
struct TileExtras {
91
95
hand: Option<usize>,
@@ -114,18 +118,22 @@ fn hand_badge(position: usize, own: bool) -> Div {
114
118
}
115
119
116
120
fn reaction_chip(reaction: Reaction, serial: u64) -> AnyElement {
121
let glyph = reaction_glyph(&reaction);
122
let emoji = is_emoji_glyph(&glyph);
117
123
div()
118
124
.absolute()
119
125
.right(px(12.))
120
126
.bottom(px(32.))
121
.size(px(36.))
127
.h(px(36.))
128
.min_w(px(36.))
129
.when(!emoji, |chip| chip.px(px(12.)))
122
130
.flex()
123
131
.items_center()
124
132
.justify_center()
125
133
.rounded_full()
126
134
.bg(theme::popup())
127
.text_size(px(20.))
128
.child(reaction_glyph(reaction))
135
.text_size(px(if emoji { 20. } else { 13. }))
136
.child(glyph)
129
137
.with_animation(
130
138
("call-reaction", serial as usize),
131
139
Animation::new(REACTION_SHOWN),
@@ -152,6 +160,7 @@ fn tile_overlays(extras: &TileExtras) -> Vec<AnyElement> {
152
160
});
153
161
let reaction = extras
154
162
.reaction
163
.clone()
155
164
.map(|(reaction, serial)| reaction_chip(reaction, serial));
156
165
badges.into_iter().chain(reaction).collect()
157
166
}
@@ -796,7 +805,7 @@ fn reactions_button(app: &Entity<AppState>, model: &CallModel) -> AnyElement {
796
805
let app = app.clone();
797
806
let popover = popover.clone();
798
807
div()
799
.id(reaction.name())
808
.id(ElementId::Name(reaction.name().to_owned().into()))
800
809
.size(px(REACTION_CELL))
801
810
.flex()
802
811
.items_center()
@@ -805,9 +814,9 @@ fn reactions_button(app: &Entity<AppState>, model: &CallModel) -> AnyElement {
805
814
.text_size(px(24.))
806
815
.cursor_pointer()
807
816
.hover(|cell| cell.bg(theme::border_strong()))
808
.child(reaction_glyph(reaction))
817
.child(reaction_glyph(&reaction))
809
818
.on_click(move |_, window, cx| {
810
app.update(cx, |state, cx| state.send_call_reaction(reaction, cx));
819
app.update(cx, |state, cx| state.send_call_reaction(reaction.clone(), cx));
811
820
popover
812
821
.update(cx, |state, cx| state.dismiss(window, cx))
813
822
.ok();
@@ -980,7 +989,7 @@ pub(super) fn plain_person_tile(
980
989
own: false,
981
990
reaction: model
982
991
.chip_of(&remote.mri, now)
983
.map(|chip| (chip.reaction, chip.serial)),
992
.map(|chip| (chip.reaction.clone(), chip.serial)),
984
993
spotlight: remote.spotlight.is_some(),
985
994
pinned: model.is_pinned(&remote.mri),
986
995
};
@@ -1069,7 +1078,7 @@ pub(super) fn plain_own_tile(
1069
1078
let extras = TileExtras {
1070
1079
hand: model.own_hand.map(|rank| model.hand_position(rank)),
1071
1080
own: true,
1072
reaction: model.own_chip(now).map(|chip| (chip.reaction, chip.serial)),
1081
reaction: model.own_chip(now).map(|chip| (chip.reaction.clone(), chip.serial)),
1073
1082
spotlight: model.own_spotlight.is_some(),
1074
1083
pinned: model.is_pinned(own_mri),
1075
1084
};
@@ -79,13 +79,17 @@ const MUSIC_MODE_LABEL: &str = "Music mode";79
const PUSH_TO_TALK_HINT: &str = "Unmuted - release Ctrl+Space to mute";79
const PUSH_TO_TALK_HINT: &str = "Unmuted - release Ctrl+Space to mute";80
const PUSH_TO_TALK_TOP: f32 = 12.;80
const PUSH_TO_TALK_TOP: f32 = 12.;81
81
82
pub fn reaction_glyph(reaction: Reaction) -> String {82
pub fn reaction_glyph(reaction: &Reaction) -> String {83
match reaction {83
match reaction {84
Reaction::Applause => "\u{1F44F}".to_owned(),84
Reaction::Applause => "\u{1F44F}".to_owned(),85
other => chat_reaction_glyph(other.name()),85
other => chat_reaction_glyph(other.name()),86
}86
}87
}87
}88
88
89
fn is_emoji_glyph(glyph: &str) -> bool {90
!glyph.is_ascii()91
}92
89
#[derive(Default)]93
#[derive(Default)]90
struct TileExtras {94
struct TileExtras {91
hand: Option<usize>,95
hand: Option<usize>,@@ -114,18 +118,22 @@ fn hand_badge(position: usize, own: bool) -> Div {114
}118
}115
119
116
fn reaction_chip(reaction: Reaction, serial: u64) -> AnyElement {120
fn reaction_chip(reaction: Reaction, serial: u64) -> AnyElement {121
let glyph = reaction_glyph(&reaction);122
let emoji = is_emoji_glyph(&glyph);117
div()123
div()118
.absolute()124
.absolute()119
.right(px(12.))125
.right(px(12.))120
.bottom(px(32.))126
.bottom(px(32.))121
.size(px(36.))127
.h(px(36.))128
.min_w(px(36.))129
.when(!emoji, |chip| chip.px(px(12.)))122
.flex()130
.flex()123
.items_center()131
.items_center()124
.justify_center()132
.justify_center()125
.rounded_full()133
.rounded_full()126
.bg(theme::popup())134
.bg(theme::popup())127
.text_size(px(20.))135
.text_size(px(if emoji { 20. } else { 13. }))128
.child(reaction_glyph(reaction))136
.child(glyph)129
.with_animation(137
.with_animation(130
("call-reaction", serial as usize),138
("call-reaction", serial as usize),131
Animation::new(REACTION_SHOWN),139
Animation::new(REACTION_SHOWN),@@ -152,6 +160,7 @@ fn tile_overlays(extras: &TileExtras) -> Vec<AnyElement> {152
});160
});153
let reaction = extras161
let reaction = extras154
.reaction162
.reaction163
.clone()155
.map(|(reaction, serial)| reaction_chip(reaction, serial));164
.map(|(reaction, serial)| reaction_chip(reaction, serial));156
badges.into_iter().chain(reaction).collect()165
badges.into_iter().chain(reaction).collect()157
}166
}@@ -796,7 +805,7 @@ fn reactions_button(app: &Entity<AppState>, model: &CallModel) -> AnyElement {796
let app = app.clone();805
let app = app.clone();797
let popover = popover.clone();806
let popover = popover.clone();798
div()807
div()799
.id(reaction.name())808
.id(ElementId::Name(reaction.name().to_owned().into()))800
.size(px(REACTION_CELL))809
.size(px(REACTION_CELL))801
.flex()810
.flex()802
.items_center()811
.items_center()@@ -805,9 +814,9 @@ fn reactions_button(app: &Entity<AppState>, model: &CallModel) -> AnyElement {805
.text_size(px(24.))814
.text_size(px(24.))806
.cursor_pointer()815
.cursor_pointer()807
.hover(|cell| cell.bg(theme::border_strong()))816
.hover(|cell| cell.bg(theme::border_strong()))808
.child(reaction_glyph(reaction))817
.child(reaction_glyph(&reaction))809
.on_click(move |_, window, cx| {818
.on_click(move |_, window, cx| {810
app.update(cx, |state, cx| state.send_call_reaction(reaction, cx));819
app.update(cx, |state, cx| state.send_call_reaction(reaction.clone(), cx));811
popover820
popover812
.update(cx, |state, cx| state.dismiss(window, cx))821
.update(cx, |state, cx| state.dismiss(window, cx))813
.ok();822
.ok();@@ -980,7 +989,7 @@ pub(super) fn plain_person_tile(980
own: false,989
own: false,981
reaction: model990
reaction: model982
.chip_of(&remote.mri, now)991
.chip_of(&remote.mri, now)983
.map(|chip| (chip.reaction, chip.serial)),992
.map(|chip| (chip.reaction.clone(), chip.serial)),984
spotlight: remote.spotlight.is_some(),993
spotlight: remote.spotlight.is_some(),985
pinned: model.is_pinned(&remote.mri),994
pinned: model.is_pinned(&remote.mri),986
};995
};@@ -1069,7 +1078,7 @@ pub(super) fn plain_own_tile(1069
let extras = TileExtras {1078
let extras = TileExtras {1070
hand: model.own_hand.map(|rank| model.hand_position(rank)),1079
hand: model.own_hand.map(|rank| model.hand_position(rank)),1071
own: true,1080
own: true,1072
reaction: model.own_chip(now).map(|chip| (chip.reaction, chip.serial)),1081
reaction: model.own_chip(now).map(|chip| (chip.reaction.clone(), chip.serial)),1073
spotlight: model.own_spotlight.is_some(),1082
spotlight: model.own_spotlight.is_some(),1074
pinned: model.is_pinned(own_mri),1083
pinned: model.is_pinned(own_mri),1075
};1084
};@@ -58,6 +58,7 @@ use super::fun_picker::{FunPicker, FunPickerEvent};
58
58
use super::link_preview::{ComposeLink, draft_link, link_preview_card, meeting_join_chip};
59
59
use super::widgets::{icon, symbol};
60
60
use crate::app_state::AppState;
61
use crate::data::Directory;
61
62
use crate::emoji;
62
63
pub use crate::outgoing::{EditPreview, Outgoing, ReplyPreview};
63
64
use crate::remote_image::RemoteImage;
@@ -309,9 +310,36 @@ fn candidate_subtitle(candidate: &MentionCandidate) -> String {
309
310
.unwrap_or_default(),
310
311
MentionCandidate::Channel { .. } => "Channel".to_owned(),
311
312
MentionCandidate::Team { .. } => "Team".to_owned(),
313
MentionCandidate::Tag { .. } => "Tag".to_owned(),
314
MentionCandidate::Everyone { .. } => String::new(),
312
315
}
313
316
}
314
317
318
fn candidate_avatar(candidate: &MentionCandidate, directory: &Directory) -> AnyElement {
319
let name = candidate.display_name();
320
match candidate {
321
MentionCandidate::Person(person) => {
322
person_avatar(directory, Some(&person.user_id), name, 28.)
323
}
324
MentionCandidate::Everyone { .. } => symbol_avatar("group", 28., 14.),
325
MentionCandidate::Tag { .. } => symbol_avatar("tag", 28., 7.),
326
other => square_avatar(name, candidate_key(other), 28., 7.).into_any_element(),
327
}
328
}
329
330
fn symbol_avatar(symbol_name: &str, size: f32, radius: f32) -> AnyElement {
331
div()
332
.size(px(size))
333
.flex_none()
334
.flex()
335
.items_center()
336
.justify_center()
337
.rounded(px(radius))
338
.bg(theme::surface_raised())
339
.child(symbol(symbol_name, 16., theme::text()))
340
.into_any_element()
341
}
342
315
343
fn step_kind(previous: &str, value: &str, cursor: usize) -> StepKind {
316
344
if let Some(typed) = emoji::typed_char(previous, value, cursor).filter(|typed| *typed != '\n') {
317
345
return StepKind::Typing {
@@ -377,6 +405,8 @@ fn candidate_key(candidate: &MentionCandidate) -> &str {
377
405
MentionCandidate::Person(person) => &person.user_id,
378
406
MentionCandidate::Channel { channel_id, .. } => channel_id,
379
407
MentionCandidate::Team { team_id, .. } => team_id,
408
MentionCandidate::Everyone { chat_id } => chat_id,
409
MentionCandidate::Tag { tag_id, .. } => tag_id,
380
410
}
381
411
}
382
412
@@ -2416,12 +2446,7 @@ impl Composer {
2416
2446
.enumerate()
2417
2447
.map(|(index, candidate)| {
2418
2448
let name = candidate.display_name().to_owned();
2419
let avatar = match candidate {
2420
MentionCandidate::Person(person) => {
2421
person_avatar(directory, Some(&person.user_id), &name, 28.)
2422
}
2423
other => square_avatar(&name, candidate_key(other), 28., 7.).into_any_element(),
2424
};
2449
let avatar = candidate_avatar(candidate, directory);
2425
2450
let subtitle = candidate_subtitle(candidate);
2426
2451
h_flex()
2427
2452
.id(ElementId::Name(format!("mention-row-{index}").into()))
@@ -58,6 +58,7 @@ use super::fun_picker::{FunPicker, FunPickerEvent};58
use super::link_preview::{ComposeLink, draft_link, link_preview_card, meeting_join_chip};58
use super::link_preview::{ComposeLink, draft_link, link_preview_card, meeting_join_chip};59
use super::widgets::{icon, symbol};59
use super::widgets::{icon, symbol};60
use crate::app_state::AppState;60
use crate::app_state::AppState;61
use crate::data::Directory;61
use crate::emoji;62
use crate::emoji;62
pub use crate::outgoing::{EditPreview, Outgoing, ReplyPreview};63
pub use crate::outgoing::{EditPreview, Outgoing, ReplyPreview};63
use crate::remote_image::RemoteImage;64
use crate::remote_image::RemoteImage;@@ -309,9 +310,36 @@ fn candidate_subtitle(candidate: &MentionCandidate) -> String {309
.unwrap_or_default(),310
.unwrap_or_default(),310
MentionCandidate::Channel { .. } => "Channel".to_owned(),311
MentionCandidate::Channel { .. } => "Channel".to_owned(),311
MentionCandidate::Team { .. } => "Team".to_owned(),312
MentionCandidate::Team { .. } => "Team".to_owned(),313
MentionCandidate::Tag { .. } => "Tag".to_owned(),314
MentionCandidate::Everyone { .. } => String::new(),312
}315
}313
}316
}314
317
318
fn candidate_avatar(candidate: &MentionCandidate, directory: &Directory) -> AnyElement {319
let name = candidate.display_name();320
match candidate {321
MentionCandidate::Person(person) => {322
person_avatar(directory, Some(&person.user_id), name, 28.)323
}324
MentionCandidate::Everyone { .. } => symbol_avatar("group", 28., 14.),325
MentionCandidate::Tag { .. } => symbol_avatar("tag", 28., 7.),326
other => square_avatar(name, candidate_key(other), 28., 7.).into_any_element(),327
}328
}329
330
fn symbol_avatar(symbol_name: &str, size: f32, radius: f32) -> AnyElement {331
div()332
.size(px(size))333
.flex_none()334
.flex()335
.items_center()336
.justify_center()337
.rounded(px(radius))338
.bg(theme::surface_raised())339
.child(symbol(symbol_name, 16., theme::text()))340
.into_any_element()341
}342
315
fn step_kind(previous: &str, value: &str, cursor: usize) -> StepKind {343
fn step_kind(previous: &str, value: &str, cursor: usize) -> StepKind {316
if let Some(typed) = emoji::typed_char(previous, value, cursor).filter(|typed| *typed != '\n') {344
if let Some(typed) = emoji::typed_char(previous, value, cursor).filter(|typed| *typed != '\n') {317
return StepKind::Typing {345
return StepKind::Typing {@@ -377,6 +405,8 @@ fn candidate_key(candidate: &MentionCandidate) -> &str {377
MentionCandidate::Person(person) => &person.user_id,405
MentionCandidate::Person(person) => &person.user_id,378
MentionCandidate::Channel { channel_id, .. } => channel_id,406
MentionCandidate::Channel { channel_id, .. } => channel_id,379
MentionCandidate::Team { team_id, .. } => team_id,407
MentionCandidate::Team { team_id, .. } => team_id,408
MentionCandidate::Everyone { chat_id } => chat_id,409
MentionCandidate::Tag { tag_id, .. } => tag_id,380
}410
}381
}411
}382
412
@@ -2416,12 +2446,7 @@ impl Composer {2416
.enumerate()2446
.enumerate()2417
.map(|(index, candidate)| {2447
.map(|(index, candidate)| {2418
let name = candidate.display_name().to_owned();2448
let name = candidate.display_name().to_owned();2419
let avatar = match candidate {2449
let avatar = candidate_avatar(candidate, directory);2420
MentionCandidate::Person(person) => {2421
person_avatar(directory, Some(&person.user_id), &name, 28.)2422
}2423
other => square_avatar(&name, candidate_key(other), 28., 7.).into_any_element(),2424
};2425
let subtitle = candidate_subtitle(candidate);2450
let subtitle = candidate_subtitle(candidate);2426
h_flex()2451
h_flex()2427
.id(ElementId::Name(format!("mention-row-{index}").into()))2452
.id(ElementId::Name(format!("mention-row-{index}").into()))@@ -3126,6 +3126,7 @@ impl ConversationView {
3126
3126
copy: action(|this, key, _, cx| this.copy_text(key, cx)),
3127
3127
translate: Some(action(|this, key, _, cx| this.translate_message(key, cx))),
3128
3128
translate_label,
3129
share_to_outlook: Some(action(|this, key, _, cx| this.share_to_outlook(key, cx))),
3129
3130
save: Some(action(|this, key, _, cx| this.toggle_saved(key, cx))),
3130
3131
saved,
3131
3132
toggle_pinned: pinnable
@@ -3126,6 +3126,7 @@ impl ConversationView {3126
copy: action(|this, key, _, cx| this.copy_text(key, cx)),3126
copy: action(|this, key, _, cx| this.copy_text(key, cx)),3127
translate: Some(action(|this, key, _, cx| this.translate_message(key, cx))),3127
translate: Some(action(|this, key, _, cx| this.translate_message(key, cx))),3128
translate_label,3128
translate_label,3129
share_to_outlook: Some(action(|this, key, _, cx| this.share_to_outlook(key, cx))),3129
save: Some(action(|this, key, _, cx| this.toggle_saved(key, cx))),3130
save: Some(action(|this, key, _, cx| this.toggle_saved(key, cx))),3130
saved,3131
saved,3131
toggle_pinned: pinnable3132
toggle_pinned: pinnable@@ -9,7 +9,7 @@ use gpui_kit::component::WindowExt as _;
9
9
use gpui_kit::component::button::{Button, ButtonVariants as _};
10
10
use gpui_kit::component::dialog::DialogFooter;
11
11
12
use crate::app_state::{AppState, Selection};
12
use crate::app_state::{AppState, Selection, selection_title};
13
13
use crate::channel_menu::post_pin_dialog;
14
14
use crate::rows::reply_excerpt;
15
15
use crate::runtime;
@@ -253,6 +253,17 @@ impl ConversationView {
253
253
}
254
254
}
255
255
256
pub(super) fn share_to_outlook(&mut self, message_id: &str, cx: &mut Context<Self>) {
257
let Some(current) = self.current.as_ref() else {
258
return;
259
};
260
let conversation_id = current.selection.conversation_id().to_owned();
261
let title = selection_title(&self.app.read(cx).sidebar, ¤t.selection);
262
self.app.update(cx, |state, cx| {
263
state.share_to_outlook(&conversation_id, message_id, &title, cx)
264
});
265
}
266
256
267
pub(super) fn toggle_saved(&mut self, message_id: &str, cx: &mut Context<Self>) {
257
268
if let Some(conversation_id) = self.conversation_id() {
258
269
self.app.update(cx, |state, cx| {
@@ -9,7 +9,7 @@ use gpui_kit::component::WindowExt as _;9
use gpui_kit::component::button::{Button, ButtonVariants as _};9
use gpui_kit::component::button::{Button, ButtonVariants as _};10
use gpui_kit::component::dialog::DialogFooter;10
use gpui_kit::component::dialog::DialogFooter;11
11
12
use crate::app_state::{AppState, Selection};12
use crate::app_state::{AppState, Selection, selection_title};13
use crate::channel_menu::post_pin_dialog;13
use crate::channel_menu::post_pin_dialog;14
use crate::rows::reply_excerpt;14
use crate::rows::reply_excerpt;15
use crate::runtime;15
use crate::runtime;@@ -253,6 +253,17 @@ impl ConversationView {253
}253
}254
}254
}255
255
256
pub(super) fn share_to_outlook(&mut self, message_id: &str, cx: &mut Context<Self>) {257
let Some(current) = self.current.as_ref() else {258
return;259
};260
let conversation_id = current.selection.conversation_id().to_owned();261
let title = selection_title(&self.app.read(cx).sidebar, ¤t.selection);262
self.app.update(cx, |state, cx| {263
state.share_to_outlook(&conversation_id, message_id, &title, cx)264
});265
}266
256
pub(super) fn toggle_saved(&mut self, message_id: &str, cx: &mut Context<Self>) {267
pub(super) fn toggle_saved(&mut self, message_id: &str, cx: &mut Context<Self>) {257
if let Some(conversation_id) = self.conversation_id() {268
if let Some(conversation_id) = self.conversation_id() {258
self.app.update(cx, |state, cx| {269
self.app.update(cx, |state, cx| {@@ -17,6 +17,7 @@ use super::toolbar_placement::{HoverChange, TOOLBAR_HEIGHT, toolbar_slot};
17
17
use super::widgets::{icon, symbol};
18
18
use crate::forward_selection::{FORWARD_LABEL, MULTIPLE_MESSAGES_LABEL, THIS_MESSAGE_LABEL};
19
19
use crate::rows::reaction_glyph;
20
use crate::share_outlook::SHARE_TO_OUTLOOK_LABEL;
20
21
use crate::theme::{self, ElevatedSurface as _};
21
22
22
23
const BAR_BUTTON: f32 = 30.;
@@ -47,6 +48,7 @@ pub struct MessageMenu {
47
48
pub copy: Action,
48
49
pub translate: Option<Action>,
49
50
pub translate_label: &'static str,
51
pub share_to_outlook: Option<Action>,
50
52
pub save: Option<Action>,
51
53
pub saved: bool,
52
54
pub toggle_pinned: Option<Action>,
@@ -199,6 +201,7 @@ fn more_button(menu: &MessageMenu, cx: &App) -> AnyElement {
199
201
delete,
200
202
mark_unread,
201
203
refresh_card,
204
share_to_outlook,
202
205
pin,
203
206
) = (
204
207
menu.reply.clone(),
@@ -212,6 +215,7 @@ fn more_button(menu: &MessageMenu, cx: &App) -> AnyElement {
212
215
menu.delete.clone(),
213
216
menu.mark_unread.clone(),
214
217
menu.refresh_card.clone(),
218
menu.share_to_outlook.clone(),
215
219
menu.pin.clone(),
216
220
);
217
221
let (saved, pinned, translate_label) = (menu.saved, menu.pinned, menu.translate_label);
@@ -266,6 +270,13 @@ fn more_button(menu: &MessageMenu, cx: &App) -> AnyElement {
266
270
if let Some(translate) = translate.clone() {
267
271
popup = popup.item(item(translate_label, IconName::Languages, translate));
268
272
}
273
if let Some(share_to_outlook) = share_to_outlook.clone() {
274
popup = popup.item(item(
275
SHARE_TO_OUTLOOK_LABEL,
276
IconName::Mail,
277
share_to_outlook,
278
));
279
}
269
280
if let Some(save) = save.clone() {
270
281
popup = popup.item(if saved {
271
282
item("Unsave message", IconName::BookmarkOff, save)
@@ -17,6 +17,7 @@ use super::toolbar_placement::{HoverChange, TOOLBAR_HEIGHT, toolbar_slot};17
use super::widgets::{icon, symbol};17
use super::widgets::{icon, symbol};18
use crate::forward_selection::{FORWARD_LABEL, MULTIPLE_MESSAGES_LABEL, THIS_MESSAGE_LABEL};18
use crate::forward_selection::{FORWARD_LABEL, MULTIPLE_MESSAGES_LABEL, THIS_MESSAGE_LABEL};19
use crate::rows::reaction_glyph;19
use crate::rows::reaction_glyph;20
use crate::share_outlook::SHARE_TO_OUTLOOK_LABEL;20
use crate::theme::{self, ElevatedSurface as _};21
use crate::theme::{self, ElevatedSurface as _};21
22
22
const BAR_BUTTON: f32 = 30.;23
const BAR_BUTTON: f32 = 30.;@@ -47,6 +48,7 @@ pub struct MessageMenu {47
pub copy: Action,48
pub copy: Action,48
pub translate: Option<Action>,49
pub translate: Option<Action>,49
pub translate_label: &'static str,50
pub translate_label: &'static str,51
pub share_to_outlook: Option<Action>,50
pub save: Option<Action>,52
pub save: Option<Action>,51
pub saved: bool,53
pub saved: bool,52
pub toggle_pinned: Option<Action>,54
pub toggle_pinned: Option<Action>,@@ -199,6 +201,7 @@ fn more_button(menu: &MessageMenu, cx: &App) -> AnyElement {199
delete,201
delete,200
mark_unread,202
mark_unread,201
refresh_card,203
refresh_card,204
share_to_outlook,202
pin,205
pin,203
) = (206
) = (204
menu.reply.clone(),207
menu.reply.clone(),@@ -212,6 +215,7 @@ fn more_button(menu: &MessageMenu, cx: &App) -> AnyElement {212
menu.delete.clone(),215
menu.delete.clone(),213
menu.mark_unread.clone(),216
menu.mark_unread.clone(),214
menu.refresh_card.clone(),217
menu.refresh_card.clone(),218
menu.share_to_outlook.clone(),215
menu.pin.clone(),219
menu.pin.clone(),216
);220
);217
let (saved, pinned, translate_label) = (menu.saved, menu.pinned, menu.translate_label);221
let (saved, pinned, translate_label) = (menu.saved, menu.pinned, menu.translate_label);@@ -266,6 +270,13 @@ fn more_button(menu: &MessageMenu, cx: &App) -> AnyElement {266
if let Some(translate) = translate.clone() {270
if let Some(translate) = translate.clone() {267
popup = popup.item(item(translate_label, IconName::Languages, translate));271
popup = popup.item(item(translate_label, IconName::Languages, translate));268
}272
}273
if let Some(share_to_outlook) = share_to_outlook.clone() {274
popup = popup.item(item(275
SHARE_TO_OUTLOOK_LABEL,276
IconName::Mail,277
share_to_outlook,278
));279
}269
if let Some(save) = save.clone() {280
if let Some(save) = save.clone() {270
popup = popup.item(if saved {281
popup = popup.item(if saved {271
item("Unsave message", IconName::BookmarkOff, save)282
item("Unsave message", IconName::BookmarkOff, save)@@ -3,33 +3,43 @@ use serde_json::{Value, json};
3
3
pub const DEFAULT_SKIN_TONE: u8 = 2;
4
4
const REACTION_TYPE: &str = "Reaction";
5
5
6
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
6
#[derive(Debug, Clone, PartialEq, Eq)]
7
7
pub enum Reaction {
8
8
Like,
9
9
Heart,
10
10
Applause,
11
11
Laugh,
12
12
Surprised,
13
Other(String),
13
14
}
14
15
15
16
impl Reaction {
16
17
pub const ALL: [Reaction; 5] = [Reaction::Like, Reaction::Heart, Reaction::Applause, Reaction::Laugh, Reaction::Surprised];
17
18
18
pub fn name(self) -> &'static str {
19
pub fn name(&self) -> &str {
19
20
match self {
20
21
Reaction::Like => "like",
21
22
Reaction::Heart => "heart",
22
23
Reaction::Applause => "applause",
23
24
Reaction::Laugh => "laugh",
24
25
Reaction::Surprised => "surprised",
26
Reaction::Other(name) => name,
25
27
}
26
28
}
27
29
28
30
pub fn from_name(name: &str) -> Option<Reaction> {
29
Reaction::ALL.into_iter().find(|reaction| reaction.name() == name)
31
if name.trim().is_empty() {
32
return None;
33
}
34
Some(
35
Reaction::ALL
36
.into_iter()
37
.find(|reaction| reaction.name() == name)
38
.unwrap_or_else(|| Reaction::Other(name.to_owned())),
39
)
30
40
}
31
41
32
fn takes_skin_tone(self) -> bool {
42
fn takes_skin_tone(&self) -> bool {
33
43
matches!(self, Reaction::Like | Reaction::Applause)
34
44
}
35
45
}
@@ -107,7 +117,8 @@ mod tests {
107
117
for reaction in Reaction::ALL {
108
118
assert_eq!(Reaction::from_name(reaction.name()), Some(reaction));
109
119
}
110
assert_eq!(Reaction::from_name("confetti"), None);
120
assert_eq!(Reaction::from_name("confetti"), Some(Reaction::Other("confetti".into())));
121
assert_eq!(Reaction::from_name(""), None);
111
122
}
112
123
113
124
#[test]
@@ -132,9 +143,10 @@ mod tests {
132
143
],
133
144
});
134
145
let events = parse_reactions(&body);
135
assert_eq!(events.len(), 2);
146
assert_eq!(events.len(), 3);
136
147
assert_eq!(events[0], ReactionEvent { mri: "8:orgid:a".into(), reaction: Reaction::Heart, count: 1 });
137
assert_eq!(events[1].mri, "8:orgid:b");
148
assert_eq!(events[1].reaction, Reaction::Other("unknown".into()));
149
assert_eq!(events[2].mri, "8:orgid:b");
138
150
}
139
151
140
152
#[test]
@@ -3,33 +3,43 @@ use serde_json::{Value, json};3
pub const DEFAULT_SKIN_TONE: u8 = 2;3
pub const DEFAULT_SKIN_TONE: u8 = 2;4
const REACTION_TYPE: &str = "Reaction";4
const REACTION_TYPE: &str = "Reaction";5
5
6
#[derive(Debug, Clone, Copy, PartialEq, Eq)]6
#[derive(Debug, Clone, PartialEq, Eq)]7
pub enum Reaction {7
pub enum Reaction {8
Like,8
Like,9
Heart,9
Heart,10
Applause,10
Applause,11
Laugh,11
Laugh,12
Surprised,12
Surprised,13
Other(String),13
}14
}14
15
15
impl Reaction {16
impl Reaction {16
pub const ALL: [Reaction; 5] = [Reaction::Like, Reaction::Heart, Reaction::Applause, Reaction::Laugh, Reaction::Surprised];17
pub const ALL: [Reaction; 5] = [Reaction::Like, Reaction::Heart, Reaction::Applause, Reaction::Laugh, Reaction::Surprised];17
18
18
pub fn name(self) -> &'static str {19
pub fn name(&self) -> &str {19
match self {20
match self {20
Reaction::Like => "like",21
Reaction::Like => "like",21
Reaction::Heart => "heart",22
Reaction::Heart => "heart",22
Reaction::Applause => "applause",23
Reaction::Applause => "applause",23
Reaction::Laugh => "laugh",24
Reaction::Laugh => "laugh",24
Reaction::Surprised => "surprised",25
Reaction::Surprised => "surprised",26
Reaction::Other(name) => name,25
}27
}26
}28
}27
29
28
pub fn from_name(name: &str) -> Option<Reaction> {30
pub fn from_name(name: &str) -> Option<Reaction> {29
Reaction::ALL.into_iter().find(|reaction| reaction.name() == name)31
if name.trim().is_empty() {32
return None;33
}34
Some(35
Reaction::ALL36
.into_iter()37
.find(|reaction| reaction.name() == name)38
.unwrap_or_else(|| Reaction::Other(name.to_owned())),39
)30
}40
}31
41
32
fn takes_skin_tone(self) -> bool {42
fn takes_skin_tone(&self) -> bool {33
matches!(self, Reaction::Like | Reaction::Applause)43
matches!(self, Reaction::Like | Reaction::Applause)34
}44
}35
}45
}@@ -107,7 +117,8 @@ mod tests {107
for reaction in Reaction::ALL {117
for reaction in Reaction::ALL {108
assert_eq!(Reaction::from_name(reaction.name()), Some(reaction));118
assert_eq!(Reaction::from_name(reaction.name()), Some(reaction));109
}119
}110
assert_eq!(Reaction::from_name("confetti"), None);120
assert_eq!(Reaction::from_name("confetti"), Some(Reaction::Other("confetti".into())));121
assert_eq!(Reaction::from_name(""), None);111
}122
}112
123
113
#[test]124
#[test]@@ -132,9 +143,10 @@ mod tests {132
],143
],133
});144
});134
let events = parse_reactions(&body);145
let events = parse_reactions(&body);135
assert_eq!(events.len(), 2);146
assert_eq!(events.len(), 3);136
assert_eq!(events[0], ReactionEvent { mri: "8:orgid:a".into(), reaction: Reaction::Heart, count: 1 });147
assert_eq!(events[0], ReactionEvent { mri: "8:orgid:a".into(), reaction: Reaction::Heart, count: 1 });137
assert_eq!(events[1].mri, "8:orgid:b");148
assert_eq!(events[1].reaction, Reaction::Other("unknown".into()));149
assert_eq!(events[2].mri, "8:orgid:b");138
}150
}139
151
140
#[test]152
#[test]@@ -14,7 +14,7 @@ use crate::events::CoreEvent;
14
14
use crate::folders::FolderSource;
15
15
use crate::links::{LinkPreview, has_stored_links};
16
16
use crate::mapping::{flatten_thread, message_record};
17
use crate::people::DirectoryCache;
17
use crate::people::{DirectoryCache, TagCache};
18
18
use crate::presence::Presence;
19
19
use crate::preview::OwnedPreview;
20
20
use crate::receipts::ReceiptCache;
@@ -123,6 +123,7 @@ pub struct SyncEngine<R: Remote = Graph> {
123
123
pub(crate) images_in_flight: Mutex<HashSet<String>>,
124
124
pub(crate) image_files: Option<ImageFileCache>,
125
125
pub(crate) directory_cache: Mutex<DirectoryCache>,
126
pub(crate) tag_cache: Mutex<TagCache>,
126
127
preview_changed: AtomicBool,
127
128
pub(crate) receipts: ReceiptCache,
128
129
pub(crate) channel_folders: Mutex<HashMap<String, DriveFolder>>,
@@ -160,6 +161,7 @@ impl<R: Remote> SyncEngine<R> {
160
161
images_in_flight: Mutex::new(HashSet::new()),
161
162
image_files: None,
162
163
directory_cache: Mutex::new(DirectoryCache::new()),
164
tag_cache: Mutex::new(TagCache::default()),
163
165
preview_changed: AtomicBool::new(false),
164
166
receipts: ReceiptCache::default(),
165
167
channel_folders: Mutex::new(HashMap::new()),
@@ -14,7 +14,7 @@ use crate::events::CoreEvent;14
use crate::folders::FolderSource;14
use crate::folders::FolderSource;15
use crate::links::{LinkPreview, has_stored_links};15
use crate::links::{LinkPreview, has_stored_links};16
use crate::mapping::{flatten_thread, message_record};16
use crate::mapping::{flatten_thread, message_record};17
use crate::people::DirectoryCache;17
use crate::people::{DirectoryCache, TagCache};18
use crate::presence::Presence;18
use crate::presence::Presence;19
use crate::preview::OwnedPreview;19
use crate::preview::OwnedPreview;20
use crate::receipts::ReceiptCache;20
use crate::receipts::ReceiptCache;@@ -123,6 +123,7 @@ pub struct SyncEngine<R: Remote = Graph> {123
pub(crate) images_in_flight: Mutex<HashSet<String>>,123
pub(crate) images_in_flight: Mutex<HashSet<String>>,124
pub(crate) image_files: Option<ImageFileCache>,124
pub(crate) image_files: Option<ImageFileCache>,125
pub(crate) directory_cache: Mutex<DirectoryCache>,125
pub(crate) directory_cache: Mutex<DirectoryCache>,126
pub(crate) tag_cache: Mutex<TagCache>,126
preview_changed: AtomicBool,127
preview_changed: AtomicBool,127
pub(crate) receipts: ReceiptCache,128
pub(crate) receipts: ReceiptCache,128
pub(crate) channel_folders: Mutex<HashMap<String, DriveFolder>>,129
pub(crate) channel_folders: Mutex<HashMap<String, DriveFolder>>,@@ -160,6 +161,7 @@ impl<R: Remote> SyncEngine<R> {160
images_in_flight: Mutex::new(HashSet::new()),161
images_in_flight: Mutex::new(HashSet::new()),161
image_files: None,162
image_files: None,162
directory_cache: Mutex::new(DirectoryCache::new()),163
directory_cache: Mutex::new(DirectoryCache::new()),164
tag_cache: Mutex::new(TagCache::default()),163
preview_changed: AtomicBool::new(false),165
preview_changed: AtomicBool::new(false),164
receipts: ReceiptCache::default(),166
receipts: ReceiptCache::default(),165
channel_folders: Mutex::new(HashMap::new()),167
channel_folders: Mutex::new(HashMap::new()),@@ -158,7 +158,7 @@ pub use meeting_join::{
158
158
pub use mentions::{MentionInput, apply_mentions, plain_mention_spans};
159
159
pub use message_link::{
160
160
ChannelAddress, ChannelLinkInput, channel_link, channel_message_link, channel_tab_link,
161
chat_message_link, team_link,
161
chat_message_link, outlook_compose_link, team_link,
162
162
};
163
163
pub use message_window::{JumpPlan, WINDOW_PAGE_SIZE, WindowPage, jump_plan, without_islands};
164
164
pub use notes_chat::{is_notes_chat, notes_chat_title};
@@ -176,7 +176,7 @@ pub use stored::{
176
176
AttachmentInfo, FileCard, FileKind, ImageKind, ImageRef, MentionInfo, PROFILE_LINK_PREFIX,
177
177
QuoteInfo, ReactionInfo, ReactionSummary, adaptive_cards, attachments, can_delete, can_edit,
178
178
card_texts, copy_text, files, images, linked_message_spans, linked_message_spans_with,
179
mentions, message_quote, message_spans, quote_html, quotes, reaction_summaries, reactions,
179
mentions, mentions_whole_chat, message_quote, message_spans, quote_html, quotes, reaction_summaries, reactions,
180
180
readable_text, translated_spans, user_mention_inputs,
181
181
};
182
182
pub use table::{Cell, PICKER_COLUMNS, PICKER_ROWS, TABLE_MARK, Table, TableEdit};
@@ -158,7 +158,7 @@ pub use meeting_join::{158
pub use mentions::{MentionInput, apply_mentions, plain_mention_spans};158
pub use mentions::{MentionInput, apply_mentions, plain_mention_spans};159
pub use message_link::{159
pub use message_link::{160
ChannelAddress, ChannelLinkInput, channel_link, channel_message_link, channel_tab_link,160
ChannelAddress, ChannelLinkInput, channel_link, channel_message_link, channel_tab_link,161
chat_message_link, team_link,161
chat_message_link, outlook_compose_link, team_link,162
};162
};163
pub use message_window::{JumpPlan, WINDOW_PAGE_SIZE, WindowPage, jump_plan, without_islands};163
pub use message_window::{JumpPlan, WINDOW_PAGE_SIZE, WindowPage, jump_plan, without_islands};164
pub use notes_chat::{is_notes_chat, notes_chat_title};164
pub use notes_chat::{is_notes_chat, notes_chat_title};@@ -176,7 +176,7 @@ pub use stored::{176
AttachmentInfo, FileCard, FileKind, ImageKind, ImageRef, MentionInfo, PROFILE_LINK_PREFIX,176
AttachmentInfo, FileCard, FileKind, ImageKind, ImageRef, MentionInfo, PROFILE_LINK_PREFIX,177
QuoteInfo, ReactionInfo, ReactionSummary, adaptive_cards, attachments, can_delete, can_edit,177
QuoteInfo, ReactionInfo, ReactionSummary, adaptive_cards, attachments, can_delete, can_edit,178
card_texts, copy_text, files, images, linked_message_spans, linked_message_spans_with,178
card_texts, copy_text, files, images, linked_message_spans, linked_message_spans_with,179
mentions, message_quote, message_spans, quote_html, quotes, reaction_summaries, reactions,179
mentions, mentions_whole_chat, message_quote, message_spans, quote_html, quotes, reaction_summaries, reactions,180
readable_text, translated_spans, user_mention_inputs,180
readable_text, translated_spans, user_mention_inputs,181
};181
};182
pub use table::{Cell, PICKER_COLUMNS, PICKER_ROWS, TABLE_MARK, Table, TableEdit};182
pub use table::{Cell, PICKER_COLUMNS, PICKER_ROWS, TABLE_MARK, Table, TableEdit};@@ -41,6 +41,24 @@ impl MentionInput {
41
41
text: text.to_owned(),
42
42
}
43
43
}
44
45
pub fn everyone(chat_id: &str, text: &str) -> Self {
46
MentionInput {
47
target: MentionTarget::Everyone {
48
chat_id: chat_id.to_owned(),
49
},
50
text: text.to_owned(),
51
}
52
}
53
54
pub fn tag(tag_id: &str, text: &str) -> Self {
55
MentionInput {
56
target: MentionTarget::Tag {
57
tag_id: tag_id.to_owned(),
58
},
59
text: text.to_owned(),
60
}
61
}
44
62
}
45
63
46
64
fn same_char(expected: char, actual: char, ignore_case: bool) -> bool {
@@ -244,11 +262,15 @@ pub fn apply_mentions(html: &str, inputs: &[MentionInput]) -> (String, Vec<Outgo
244
262
}
245
263
246
264
pub(crate) fn ensure_allowed_in_chat(inputs: &[MentionInput]) -> Result<()> {
247
if inputs
248
.iter()
249
.any(|input| !matches!(input.target, MentionTarget::User { .. }))
250
{
251
return Err(Error::Unsupported("a channel or team mention in a chat"));
265
if inputs.iter().any(|input| {
266
!matches!(
267
input.target,
268
MentionTarget::User { .. } | MentionTarget::Everyone { .. }
269
)
270
}) {
271
return Err(Error::Unsupported(
272
"a channel, team or tag mention in a chat",
273
));
252
274
}
253
275
Ok(())
254
276
}
@@ -416,6 +438,8 @@ mod tests {
416
438
#[test]
417
439
fn chats_only_take_user_mentions() {
418
440
assert!(ensure_allowed_in_chat(&[MentionInput::user("u", "A")]).is_ok());
441
assert!(ensure_allowed_in_chat(&[MentionInput::everyone("19:g", "Everyone")]).is_ok());
419
442
assert!(ensure_allowed_in_chat(&[MentionInput::team("t", "Squad")]).is_err());
443
assert!(ensure_allowed_in_chat(&[MentionInput::tag("tag-1", "Design")]).is_err());
420
444
}
421
445
}
@@ -41,6 +41,24 @@ impl MentionInput {41
text: text.to_owned(),41
text: text.to_owned(),42
}42
}43
}43
}44
45
pub fn everyone(chat_id: &str, text: &str) -> Self {46
MentionInput {47
target: MentionTarget::Everyone {48
chat_id: chat_id.to_owned(),49
},50
text: text.to_owned(),51
}52
}53
54
pub fn tag(tag_id: &str, text: &str) -> Self {55
MentionInput {56
target: MentionTarget::Tag {57
tag_id: tag_id.to_owned(),58
},59
text: text.to_owned(),60
}61
}44
}62
}45
63
46
fn same_char(expected: char, actual: char, ignore_case: bool) -> bool {64
fn same_char(expected: char, actual: char, ignore_case: bool) -> bool {@@ -244,11 +262,15 @@ pub fn apply_mentions(html: &str, inputs: &[MentionInput]) -> (String, Vec<Outgo244
}262
}245
263
246
pub(crate) fn ensure_allowed_in_chat(inputs: &[MentionInput]) -> Result<()> {264
pub(crate) fn ensure_allowed_in_chat(inputs: &[MentionInput]) -> Result<()> {247
if inputs265
if inputs.iter().any(|input| {248
.iter()266
!matches!(249
.any(|input| !matches!(input.target, MentionTarget::User { .. }))267
input.target,250
{268
MentionTarget::User { .. } | MentionTarget::Everyone { .. }251
return Err(Error::Unsupported("a channel or team mention in a chat"));269
)270
}) {271
return Err(Error::Unsupported(272
"a channel, team or tag mention in a chat",273
));252
}274
}253
Ok(())275
Ok(())254
}276
}@@ -416,6 +438,8 @@ mod tests {416
#[test]438
#[test]417
fn chats_only_take_user_mentions() {439
fn chats_only_take_user_mentions() {418
assert!(ensure_allowed_in_chat(&[MentionInput::user("u", "A")]).is_ok());440
assert!(ensure_allowed_in_chat(&[MentionInput::user("u", "A")]).is_ok());441
assert!(ensure_allowed_in_chat(&[MentionInput::everyone("19:g", "Everyone")]).is_ok());419
assert!(ensure_allowed_in_chat(&[MentionInput::team("t", "Squad")]).is_err());442
assert!(ensure_allowed_in_chat(&[MentionInput::team("t", "Squad")]).is_err());443
assert!(ensure_allowed_in_chat(&[MentionInput::tag("tag-1", "Design")]).is_err());420
}444
}421
}445
}@@ -3,6 +3,7 @@ use serde_json::json;
3
3
4
4
const LINK_HOST: &str = "https://teams.microsoft.com";
5
5
const DEEP_LINK_HOST: &str = "https://teams.cloud.microsoft";
6
const OUTLOOK_COMPOSE: &str = "https://outlook.office.com/mail/deeplink/compose";
6
7
7
8
const ENCODE_COMPONENT: &AsciiSet = &NON_ALPHANUMERIC
8
9
.remove(b'-')
@@ -31,6 +32,15 @@ fn encode(value: &str) -> String {
31
32
utf8_percent_encode(value, ENCODE_COMPONENT).to_string()
32
33
}
33
34
35
/// Outlook on the web opens a new mail with this subject and plain text body; nothing is sent.
36
pub fn outlook_compose_link(subject: &str, body: &str) -> String {
37
format!(
38
"{OUTLOOK_COMPOSE}?subject={}&body={}",
39
encode(subject),
40
encode(body)
41
)
42
}
43
34
44
/// `notes_oid` is the own object id, needed for the notes chat only.
35
45
pub fn chat_message_link(
36
46
conversation_id: &str,
@@ -113,6 +123,14 @@ mod tests {
113
123
);
114
124
}
115
125
126
#[test]
127
fn outlook_compose_link_encodes_subject_and_body() {
128
assert_eq!(
129
outlook_compose_link("Release & plan", "Ada\nhi there"),
130
"https://outlook.office.com/mail/deeplink/compose?subject=Release%20%26%20plan&body=Ada%0Ahi%20there"
131
);
132
}
133
116
134
#[test]
117
135
fn notes_link_carries_the_object_id() {
118
136
assert_eq!(
@@ -3,6 +3,7 @@ use serde_json::json;3
3
4
const LINK_HOST: &str = "https://teams.microsoft.com";4
const LINK_HOST: &str = "https://teams.microsoft.com";5
const DEEP_LINK_HOST: &str = "https://teams.cloud.microsoft";5
const DEEP_LINK_HOST: &str = "https://teams.cloud.microsoft";6
const OUTLOOK_COMPOSE: &str = "https://outlook.office.com/mail/deeplink/compose";6
7
7
const ENCODE_COMPONENT: &AsciiSet = &NON_ALPHANUMERIC8
const ENCODE_COMPONENT: &AsciiSet = &NON_ALPHANUMERIC8
.remove(b'-')9
.remove(b'-')@@ -31,6 +32,15 @@ fn encode(value: &str) -> String {31
utf8_percent_encode(value, ENCODE_COMPONENT).to_string()32
utf8_percent_encode(value, ENCODE_COMPONENT).to_string()32
}33
}33
34
35
/// Outlook on the web opens a new mail with this subject and plain text body; nothing is sent.36
pub fn outlook_compose_link(subject: &str, body: &str) -> String {37
format!(38
"{OUTLOOK_COMPOSE}?subject={}&body={}",39
encode(subject),40
encode(body)41
)42
}43
34
/// `notes_oid` is the own object id, needed for the notes chat only.44
/// `notes_oid` is the own object id, needed for the notes chat only.35
pub fn chat_message_link(45
pub fn chat_message_link(36
conversation_id: &str,46
conversation_id: &str,@@ -113,6 +123,14 @@ mod tests {113
);123
);114
}124
}115
125
126
#[test]127
fn outlook_compose_link_encodes_subject_and_body() {128
assert_eq!(129
outlook_compose_link("Release & plan", "Ada\nhi there"),130
"https://outlook.office.com/mail/deeplink/compose?subject=Release%20%26%20plan&body=Ada%0Ahi%20there"131
);132
}133
116
#[test]134
#[test]117
fn notes_link_carries_the_object_id() {135
fn notes_link_carries_the_object_id() {118
assert_eq!(136
assert_eq!(@@ -1,7 +1,7 @@
1
1
use std::collections::HashSet;
2
2
use std::time::{Duration, Instant};
3
3
4
use graph::User;
4
use graph::{Tag, User};
5
5
6
6
use crate::engine::{Conversation, META_USER_ID, SyncEngine};
7
7
use crate::error::Result;
@@ -11,6 +11,9 @@ const DIRECTORY_CACHE_TTL: Duration = Duration::from_secs(300);
11
11
const DIRECTORY_CACHE_MAX_QUERIES: usize = 64;
12
12
const DIRECTORY_MIN_QUERY_CHARS: usize = 2;
13
13
const RECENT_SENDERS_SCANNED: usize = 200;
14
const TAG_CACHE_TTL: Duration = Duration::from_secs(300);
15
const GROUP_CHAT_KIND: &str = "group";
16
pub const EVERYONE_MENTION_TEXT: &str = "Everyone";
14
17
15
18
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
16
19
pub enum PersonSource {
@@ -30,15 +33,32 @@ pub struct PersonCandidate {
30
33
#[derive(Debug, Clone, PartialEq, Eq)]
31
34
pub enum MentionCandidate {
32
35
Person(PersonCandidate),
33
Channel { channel_id: String, name: String },
34
Team { team_id: String, name: String },
36
Channel {
37
channel_id: String,
38
name: String,
39
},
40
Team {
41
team_id: String,
42
name: String,
43
},
44
Everyone {
45
chat_id: String,
46
},
47
Tag {
48
tag_id: String,
49
name: String,
50
member_count: Option<u32>,
51
},
35
52
}
36
53
37
54
impl MentionCandidate {
38
55
pub fn display_name(&self) -> &str {
39
56
match self {
40
57
MentionCandidate::Person(person) => &person.display_name,
41
MentionCandidate::Channel { name, .. } | MentionCandidate::Team { name, .. } => name,
58
MentionCandidate::Channel { name, .. }
59
| MentionCandidate::Team { name, .. }
60
| MentionCandidate::Tag { name, .. } => name,
61
MentionCandidate::Everyone { .. } => EVERYONE_MENTION_TEXT,
42
62
}
43
63
}
44
64
@@ -52,10 +72,31 @@ impl MentionCandidate {
52
72
crate::MentionInput::channel(channel_id, name)
53
73
}
54
74
MentionCandidate::Team { team_id, name } => crate::MentionInput::team(team_id, name),
75
MentionCandidate::Everyone { chat_id } => {
76
crate::MentionInput::everyone(chat_id, EVERYONE_MENTION_TEXT)
77
}
78
MentionCandidate::Tag { tag_id, name, .. } => crate::MentionInput::tag(tag_id, name),
55
79
}
56
80
}
57
81
}
58
82
83
#[derive(Default)]
84
pub(crate) struct TagCache {
85
entries: std::collections::HashMap<String, (Instant, Vec<Tag>)>,
86
}
87
88
impl TagCache {
89
fn get(&self, team_id: &str) -> Option<Vec<Tag>> {
90
let (stored_at, tags) = self.entries.get(team_id)?;
91
(stored_at.elapsed() < TAG_CACHE_TTL).then(|| tags.clone())
92
}
93
94
fn put(&mut self, team_id: &str, tags: Vec<Tag>) {
95
self.entries
96
.insert(team_id.to_owned(), (Instant::now(), tags));
97
}
98
}
99
59
100
pub(crate) struct DirectoryCache {
60
101
entries: std::collections::HashMap<String, (Instant, Vec<User>)>,
61
102
}
@@ -97,8 +138,19 @@ impl<R: Remote> SyncEngine<R> {
97
138
Ok(users)
98
139
}
99
140
100
/// Autocomplete for `@`: members of the conversation first, then (channels) the channel and its team,
101
/// then the directory. A failing directory search still returns the local part.
141
/// The team's tags, cached in memory for five minutes per team; a failed load is cached as no tags.
142
pub async fn team_tags(&self, team_id: &str) -> Result<Vec<Tag>> {
143
if let Some(cached) = self.tag_lock().get(team_id) {
144
return Ok(cached);
145
}
146
let tags = self.remote.team_tags(team_id).await;
147
self.tag_lock()
148
.put(team_id, tags.as_ref().cloned().unwrap_or_default());
149
tags
150
}
151
152
/// Autocomplete for `@`: Everyone in a group chat, members of the conversation, then (channels) the channel,
153
/// its team and the team's tags, then the directory. A failing tag or directory lookup still returns the local part.
102
154
pub async fn mention_candidates(
103
155
&self,
104
156
conversation_id: &str,
@@ -110,18 +162,23 @@ impl<R: Remote> SyncEngine<R> {
110
162
let my_user_id = self.store.meta(META_USER_ID)?.unwrap_or_default();
111
163
let mut seen: HashSet<String> = HashSet::from([my_user_id]);
112
164
113
let mut candidates: Vec<MentionCandidate> = ranked(
165
let mut candidates: Vec<MentionCandidate> =
166
ranked(self.everyone_entry(conversation_id)?.into_iter(), &query);
167
candidates.extend(ranked(
114
168
self.local_people(conversation_id)?
115
169
.into_iter()
116
170
.filter(|person| seen.insert(person.user_id.clone()))
117
171
.map(MentionCandidate::Person),
118
172
&query,
119
);
173
));
120
174
if let Conversation::Channel { team_id } = &conversation {
121
175
candidates.extend(ranked(
122
176
self.scope_entries(conversation_id, team_id)?,
123
177
&query,
124
178
));
179
if let Ok(tags) = self.team_tags(team_id).await {
180
candidates.extend(ranked(tags.into_iter().map(tag_candidate), &query));
181
}
125
182
}
126
183
let local_people = candidates
127
184
.iter()
@@ -172,6 +229,14 @@ impl<R: Remote> SyncEngine<R> {
172
229
.collect())
173
230
}
174
231
232
fn everyone_entry(&self, conversation_id: &str) -> Result<Option<MentionCandidate>> {
233
Ok(self
234
.store
235
.chat(conversation_id)?
236
.filter(|chat| chat.kind.eq_ignore_ascii_case(GROUP_CHAT_KIND))
237
.map(|chat| MentionCandidate::Everyone { chat_id: chat.id }))
238
}
239
175
240
fn scope_entries(
176
241
&self,
177
242
channel_id: &str,
@@ -194,6 +259,12 @@ impl<R: Remote> SyncEngine<R> {
194
259
Ok(channel.into_iter().chain(team))
195
260
}
196
261
262
fn tag_lock(&self) -> std::sync::MutexGuard<'_, TagCache> {
263
self.tag_cache
264
.lock()
265
.unwrap_or_else(|poisoned| poisoned.into_inner())
266
}
267
197
268
fn directory_lock(&self) -> std::sync::MutexGuard<'_, DirectoryCache> {
198
269
self.directory_cache
199
270
.lock()
@@ -201,6 +272,14 @@ impl<R: Remote> SyncEngine<R> {
201
272
}
202
273
}
203
274
275
fn tag_candidate(tag: Tag) -> MentionCandidate {
276
MentionCandidate::Tag {
277
tag_id: tag.id,
278
name: tag.display_name,
279
member_count: tag.member_count,
280
}
281
}
282
204
283
fn directory_person(user: User) -> PersonCandidate {
205
284
PersonCandidate {
206
285
display_name: user
@@ -323,6 +402,32 @@ mod tests {
323
402
name: "Squad".to_owned(),
324
403
};
325
404
assert_eq!(team.to_mention(), crate::MentionInput::team("t", "Squad"));
405
let everyone = MentionCandidate::Everyone {
406
chat_id: "19:g".to_owned(),
407
};
408
assert_eq!(
409
everyone.to_mention(),
410
crate::MentionInput::everyone("19:g", "Everyone")
411
);
412
let tag = MentionCandidate::Tag {
413
tag_id: "tag-1".to_owned(),
414
name: "Design".to_owned(),
415
member_count: Some(3),
416
};
417
assert_eq!(
418
tag.to_mention(),
419
crate::MentionInput::tag("tag-1", "Design")
420
);
421
}
422
423
#[test]
424
fn everyone_matches_its_name_like_any_candidate() {
425
let everyone = || MentionCandidate::Everyone {
426
chat_id: "19:g".to_owned(),
427
};
428
assert_eq!(ranked([everyone()].into_iter(), "ev").len(), 1);
429
assert_eq!(ranked([everyone()].into_iter(), "").len(), 1);
430
assert!(ranked([everyone()].into_iter(), "ada").is_empty());
326
431
}
327
432
328
433
#[test]
@@ -1,7 +1,7 @@1
use std::collections::HashSet;1
use std::collections::HashSet;2
use std::time::{Duration, Instant};2
use std::time::{Duration, Instant};3
3
4
use graph::User;4
use graph::{Tag, User};5
5
6
use crate::engine::{Conversation, META_USER_ID, SyncEngine};6
use crate::engine::{Conversation, META_USER_ID, SyncEngine};7
use crate::error::Result;7
use crate::error::Result;@@ -11,6 +11,9 @@ const DIRECTORY_CACHE_TTL: Duration = Duration::from_secs(300);11
const DIRECTORY_CACHE_MAX_QUERIES: usize = 64;11
const DIRECTORY_CACHE_MAX_QUERIES: usize = 64;12
const DIRECTORY_MIN_QUERY_CHARS: usize = 2;12
const DIRECTORY_MIN_QUERY_CHARS: usize = 2;13
const RECENT_SENDERS_SCANNED: usize = 200;13
const RECENT_SENDERS_SCANNED: usize = 200;14
const TAG_CACHE_TTL: Duration = Duration::from_secs(300);15
const GROUP_CHAT_KIND: &str = "group";16
pub const EVERYONE_MENTION_TEXT: &str = "Everyone";14
17
15
#[derive(Debug, Clone, Copy, PartialEq, Eq)]18
#[derive(Debug, Clone, Copy, PartialEq, Eq)]16
pub enum PersonSource {19
pub enum PersonSource {@@ -30,15 +33,32 @@ pub struct PersonCandidate {30
#[derive(Debug, Clone, PartialEq, Eq)]33
#[derive(Debug, Clone, PartialEq, Eq)]31
pub enum MentionCandidate {34
pub enum MentionCandidate {32
Person(PersonCandidate),35
Person(PersonCandidate),33
Channel { channel_id: String, name: String },36
Channel {34
Team { team_id: String, name: String },37
channel_id: String,38
name: String,39
},40
Team {41
team_id: String,42
name: String,43
},44
Everyone {45
chat_id: String,46
},47
Tag {48
tag_id: String,49
name: String,50
member_count: Option<u32>,51
},35
}52
}36
53
37
impl MentionCandidate {54
impl MentionCandidate {38
pub fn display_name(&self) -> &str {55
pub fn display_name(&self) -> &str {39
match self {56
match self {40
MentionCandidate::Person(person) => &person.display_name,57
MentionCandidate::Person(person) => &person.display_name,41
MentionCandidate::Channel { name, .. } | MentionCandidate::Team { name, .. } => name,58
MentionCandidate::Channel { name, .. }59
| MentionCandidate::Team { name, .. }60
| MentionCandidate::Tag { name, .. } => name,61
MentionCandidate::Everyone { .. } => EVERYONE_MENTION_TEXT,42
}62
}43
}63
}44
64
@@ -52,10 +72,31 @@ impl MentionCandidate {52
crate::MentionInput::channel(channel_id, name)72
crate::MentionInput::channel(channel_id, name)53
}73
}54
MentionCandidate::Team { team_id, name } => crate::MentionInput::team(team_id, name),74
MentionCandidate::Team { team_id, name } => crate::MentionInput::team(team_id, name),75
MentionCandidate::Everyone { chat_id } => {76
crate::MentionInput::everyone(chat_id, EVERYONE_MENTION_TEXT)77
}78
MentionCandidate::Tag { tag_id, name, .. } => crate::MentionInput::tag(tag_id, name),55
}79
}56
}80
}57
}81
}58
82
83
#[derive(Default)]84
pub(crate) struct TagCache {85
entries: std::collections::HashMap<String, (Instant, Vec<Tag>)>,86
}87
88
impl TagCache {89
fn get(&self, team_id: &str) -> Option<Vec<Tag>> {90
let (stored_at, tags) = self.entries.get(team_id)?;91
(stored_at.elapsed() < TAG_CACHE_TTL).then(|| tags.clone())92
}93
94
fn put(&mut self, team_id: &str, tags: Vec<Tag>) {95
self.entries96
.insert(team_id.to_owned(), (Instant::now(), tags));97
}98
}99
59
pub(crate) struct DirectoryCache {100
pub(crate) struct DirectoryCache {60
entries: std::collections::HashMap<String, (Instant, Vec<User>)>,101
entries: std::collections::HashMap<String, (Instant, Vec<User>)>,61
}102
}@@ -97,8 +138,19 @@ impl<R: Remote> SyncEngine<R> {97
Ok(users)138
Ok(users)98
}139
}99
140
100
/// Autocomplete for `@`: members of the conversation first, then (channels) the channel and its team,141
/// The team's tags, cached in memory for five minutes per team; a failed load is cached as no tags.101
/// then the directory. A failing directory search still returns the local part.142
pub async fn team_tags(&self, team_id: &str) -> Result<Vec<Tag>> {143
if let Some(cached) = self.tag_lock().get(team_id) {144
return Ok(cached);145
}146
let tags = self.remote.team_tags(team_id).await;147
self.tag_lock()148
.put(team_id, tags.as_ref().cloned().unwrap_or_default());149
tags150
}151
152
/// Autocomplete for `@`: Everyone in a group chat, members of the conversation, then (channels) the channel,153
/// its team and the team's tags, then the directory. A failing tag or directory lookup still returns the local part.102
pub async fn mention_candidates(154
pub async fn mention_candidates(103
&self,155
&self,104
conversation_id: &str,156
conversation_id: &str,@@ -110,18 +162,23 @@ impl<R: Remote> SyncEngine<R> {110
let my_user_id = self.store.meta(META_USER_ID)?.unwrap_or_default();162
let my_user_id = self.store.meta(META_USER_ID)?.unwrap_or_default();111
let mut seen: HashSet<String> = HashSet::from([my_user_id]);163
let mut seen: HashSet<String> = HashSet::from([my_user_id]);112
164
113
let mut candidates: Vec<MentionCandidate> = ranked(165
let mut candidates: Vec<MentionCandidate> =166
ranked(self.everyone_entry(conversation_id)?.into_iter(), &query);167
candidates.extend(ranked(114
self.local_people(conversation_id)?168
self.local_people(conversation_id)?115
.into_iter()169
.into_iter()116
.filter(|person| seen.insert(person.user_id.clone()))170
.filter(|person| seen.insert(person.user_id.clone()))117
.map(MentionCandidate::Person),171
.map(MentionCandidate::Person),118
&query,172
&query,119
);173
));120
if let Conversation::Channel { team_id } = &conversation {174
if let Conversation::Channel { team_id } = &conversation {121
candidates.extend(ranked(175
candidates.extend(ranked(122
self.scope_entries(conversation_id, team_id)?,176
self.scope_entries(conversation_id, team_id)?,123
&query,177
&query,124
));178
));179
if let Ok(tags) = self.team_tags(team_id).await {180
candidates.extend(ranked(tags.into_iter().map(tag_candidate), &query));181
}125
}182
}126
let local_people = candidates183
let local_people = candidates127
.iter()184
.iter()@@ -172,6 +229,14 @@ impl<R: Remote> SyncEngine<R> {172
.collect())229
.collect())173
}230
}174
231
232
fn everyone_entry(&self, conversation_id: &str) -> Result<Option<MentionCandidate>> {233
Ok(self234
.store235
.chat(conversation_id)?236
.filter(|chat| chat.kind.eq_ignore_ascii_case(GROUP_CHAT_KIND))237
.map(|chat| MentionCandidate::Everyone { chat_id: chat.id }))238
}239
175
fn scope_entries(240
fn scope_entries(176
&self,241
&self,177
channel_id: &str,242
channel_id: &str,@@ -194,6 +259,12 @@ impl<R: Remote> SyncEngine<R> {194
Ok(channel.into_iter().chain(team))259
Ok(channel.into_iter().chain(team))195
}260
}196
261
262
fn tag_lock(&self) -> std::sync::MutexGuard<'_, TagCache> {263
self.tag_cache264
.lock()265
.unwrap_or_else(|poisoned| poisoned.into_inner())266
}267
197
fn directory_lock(&self) -> std::sync::MutexGuard<'_, DirectoryCache> {268
fn directory_lock(&self) -> std::sync::MutexGuard<'_, DirectoryCache> {198
self.directory_cache269
self.directory_cache199
.lock()270
.lock()@@ -201,6 +272,14 @@ impl<R: Remote> SyncEngine<R> {201
}272
}202
}273
}203
274
275
fn tag_candidate(tag: Tag) -> MentionCandidate {276
MentionCandidate::Tag {277
tag_id: tag.id,278
name: tag.display_name,279
member_count: tag.member_count,280
}281
}282
204
fn directory_person(user: User) -> PersonCandidate {283
fn directory_person(user: User) -> PersonCandidate {205
PersonCandidate {284
PersonCandidate {206
display_name: user285
display_name: user@@ -323,6 +402,32 @@ mod tests {323
name: "Squad".to_owned(),402
name: "Squad".to_owned(),324
};403
};325
assert_eq!(team.to_mention(), crate::MentionInput::team("t", "Squad"));404
assert_eq!(team.to_mention(), crate::MentionInput::team("t", "Squad"));405
let everyone = MentionCandidate::Everyone {406
chat_id: "19:g".to_owned(),407
};408
assert_eq!(409
everyone.to_mention(),410
crate::MentionInput::everyone("19:g", "Everyone")411
);412
let tag = MentionCandidate::Tag {413
tag_id: "tag-1".to_owned(),414
name: "Design".to_owned(),415
member_count: Some(3),416
};417
assert_eq!(418
tag.to_mention(),419
crate::MentionInput::tag("tag-1", "Design")420
);421
}422
423
#[test]424
fn everyone_matches_its_name_like_any_candidate() {425
let everyone = || MentionCandidate::Everyone {426
chat_id: "19:g".to_owned(),427
};428
assert_eq!(ranked([everyone()].into_iter(), "ev").len(), 1);429
assert_eq!(ranked([everyone()].into_iter(), "").len(), 1);430
assert!(ranked([everyone()].into_iter(), "ada").is_empty());326
}431
}327
432
328
#[test]433
#[test]@@ -20,7 +20,7 @@ use chatsvc::{
20
20
use chrono::{DateTime, Utc};
21
21
use graph::{
22
22
Channel, Chat, DriveEntry, DriveFolder, Graph, Member, Message, MessageExtras, MessageTarget,
23
OutgoingMention, Photo, Presence, SharedFile, Team, UploadDestination, UploadedFile, User,
23
OutgoingMention, Photo, Presence, SharedFile, Tag, Team, UploadDestination, UploadedFile, User,
24
24
};
25
25
26
26
use crate::error::{Error, Result};
@@ -181,6 +181,10 @@ pub trait Remote {
181
181
) -> Result<Chat>;
182
182
async fn search_people(&self, query: &str) -> Result<Vec<User>>;
183
183
184
async fn team_tags(&self, _team_id: &str) -> Result<Vec<Tag>> {
185
Err(Error::Unsupported("team tags"))
186
}
187
184
188
async fn reply_with_quote(
185
189
&self,
186
190
_chat_id: &str,
@@ -917,6 +921,10 @@ impl Remote for Graph {
917
921
Ok(Graph::search_people(self, query).await?)
918
922
}
919
923
924
async fn team_tags(&self, team_id: &str) -> Result<Vec<Tag>> {
925
Ok(Graph::team_tags(self, team_id).await?)
926
}
927
920
928
async fn reply_with_quote(
921
929
&self,
922
930
chat_id: &str,
@@ -20,7 +20,7 @@ use chatsvc::{20
use chrono::{DateTime, Utc};20
use chrono::{DateTime, Utc};21
use graph::{21
use graph::{22
Channel, Chat, DriveEntry, DriveFolder, Graph, Member, Message, MessageExtras, MessageTarget,22
Channel, Chat, DriveEntry, DriveFolder, Graph, Member, Message, MessageExtras, MessageTarget,23
OutgoingMention, Photo, Presence, SharedFile, Team, UploadDestination, UploadedFile, User,23
OutgoingMention, Photo, Presence, SharedFile, Tag, Team, UploadDestination, UploadedFile, User,24
};24
};25
25
26
use crate::error::{Error, Result};26
use crate::error::{Error, Result};@@ -181,6 +181,10 @@ pub trait Remote {181
) -> Result<Chat>;181
) -> Result<Chat>;182
async fn search_people(&self, query: &str) -> Result<Vec<User>>;182
async fn search_people(&self, query: &str) -> Result<Vec<User>>;183
183
184
async fn team_tags(&self, _team_id: &str) -> Result<Vec<Tag>> {185
Err(Error::Unsupported("team tags"))186
}187
184
async fn reply_with_quote(188
async fn reply_with_quote(185
&self,189
&self,186
_chat_id: &str,190
_chat_id: &str,@@ -917,6 +921,10 @@ impl Remote for Graph {917
Ok(Graph::search_people(self, query).await?)921
Ok(Graph::search_people(self, query).await?)918
}922
}919
923
924
async fn team_tags(&self, team_id: &str) -> Result<Vec<Tag>> {925
Ok(Graph::team_tags(self, team_id).await?)926
}927
920
async fn reply_with_quote(928
async fn reply_with_quote(921
&self,929
&self,922
chat_id: &str,930
chat_id: &str,@@ -208,6 +208,13 @@ pub fn mentions(record: &MessageRecord) -> Vec<MentionInfo> {
208
208
infos
209
209
}
210
210
211
/// An @Everyone of a group chat: Graph names the chat itself as the mentioned conversation. Only meaningful in chats, a channel mention looks the same in its channel.
212
pub fn mentions_whole_chat(record: &MessageRecord) -> bool {
213
mentions(record).iter().any(|mention| {
214
mention.group && mention.target_id.as_deref() == Some(record.conversation_id.as_str())
215
})
216
}
217
211
218
pub fn quotes(record: &MessageRecord) -> Vec<QuoteInfo> {
212
219
attachments(record)
213
220
.into_iter()
@@ -208,6 +208,13 @@ pub fn mentions(record: &MessageRecord) -> Vec<MentionInfo> {208
infos208
infos209
}209
}210
210
211
/// An @Everyone of a group chat: Graph names the chat itself as the mentioned conversation. Only meaningful in chats, a channel mention looks the same in its channel.212
pub fn mentions_whole_chat(record: &MessageRecord) -> bool {213
mentions(record).iter().any(|mention| {214
mention.group && mention.target_id.as_deref() == Some(record.conversation_id.as_str())215
})216
}217
211
pub fn quotes(record: &MessageRecord) -> Vec<QuoteInfo> {218
pub fn quotes(record: &MessageRecord) -> Vec<QuoteInfo> {212
attachments(record)219
attachments(record)213
.into_iter()220
.into_iter()@@ -178,7 +178,7 @@ mod tests {
178
178
}
179
179
180
180
#[test]
181
fn channel_and_team_mentions_have_no_chatsvc_shape() {
181
fn group_mentions_have_no_chatsvc_shape() {
182
182
for target in [
183
183
MentionTarget::Channel {
184
184
channel_id: "19:c@thread.tacv2".into(),
@@ -186,6 +186,12 @@ mod tests {
186
186
MentionTarget::Team {
187
187
team_id: "team-1".into(),
188
188
},
189
MentionTarget::Everyone {
190
chat_id: "19:g@thread.v2".into(),
191
},
192
MentionTarget::Tag {
193
tag_id: "tag-1".into(),
194
},
189
195
] {
190
196
let mentions = [mention(0, target)];
191
197
assert!(quote_reply_properties("e(), &mentions, None).is_none());
@@ -178,7 +178,7 @@ mod tests {178
}178
}179
179
180
#[test]180
#[test]181
fn channel_and_team_mentions_have_no_chatsvc_shape() {181
fn group_mentions_have_no_chatsvc_shape() {182
for target in [182
for target in [183
MentionTarget::Channel {183
MentionTarget::Channel {184
channel_id: "19:c@thread.tacv2".into(),184
channel_id: "19:c@thread.tacv2".into(),@@ -186,6 +186,12 @@ mod tests {186
MentionTarget::Team {186
MentionTarget::Team {187
team_id: "team-1".into(),187
team_id: "team-1".into(),188
},188
},189
MentionTarget::Everyone {190
chat_id: "19:g@thread.v2".into(),191
},192
MentionTarget::Tag {193
tag_id: "tag-1".into(),194
},189
] {195
] {190
let mentions = [mention(0, target)];196
let mentions = [mention(0, target)];191
assert!(quote_reply_properties("e(), &mentions, None).is_none());197
assert!(quote_reply_properties("e(), &mentions, None).is_none());@@ -1084,6 +1084,16 @@ impl Remote for Handle {
1084
1084
Ok(())
1085
1085
}
1086
1086
1087
async fn team_tags(&self, team_id: &str) -> Result<Vec<graph::Tag>> {
1088
self.record(format!("tags {team_id}"));
1089
Ok(vec![
1090
serde_json::from_value(
1091
json!({"id": "tag-design", "displayName": "Designers", "memberCount": 4}),
1092
)
1093
.unwrap(),
1094
])
1095
}
1096
1087
1097
async fn search_people(&self, query: &str) -> Result<Vec<User>> {
1088
1098
self.record(format!("search {query}"));
1089
1099
let configured = self.directory_users.lock().unwrap().clone();
@@ -4023,9 +4033,14 @@ async fn people_candidates_list_members_first_then_the_directory_without_duplica
4023
4033
];
4024
4034
let engine = chat_engine(&fake, small_pages()).await;
4025
4035
4026
let everyone = engine.mention_candidates(CHAT, "", 10).await.unwrap();
4027
assert_eq!(everyone.len(), 1);
4028
assert_eq!(everyone[0].display_name(), "Ada Example");
4036
let all = engine.mention_candidates(CHAT, "", 10).await.unwrap();
4037
assert_eq!(all.len(), 2);
4038
assert!(matches!(&all[0], MentionCandidate::Everyone { chat_id } if chat_id == CHAT));
4039
assert_eq!(
4040
all[0].to_mention(),
4041
MentionInput::everyone(CHAT, "Everyone")
4042
);
4043
assert_eq!(all[1].display_name(), "Ada Example");
4029
4044
assert!(!fake.calls().iter().any(|call| call.starts_with("search")));
4030
4045
4031
4046
let found = engine.mention_candidates(CHAT, "@ada", 10).await.unwrap();
@@ -4067,12 +4082,30 @@ async fn channel_candidates_offer_recent_senders_the_channel_and_its_team() {
4067
4082
let engine = channel_engine(&fake).await;
4068
4083
engine.fetch_newer(CHANNEL).await.unwrap();
4069
4084
let all = engine.mention_candidates(CHANNEL, "", 10).await.unwrap();
4070
assert_eq!(all.len(), 3);
4085
assert_eq!(all.len(), 4);
4071
4086
assert!(matches!(&all[0], MentionCandidate::Person(person) if person.user_id == "user-ada"));
4072
4087
assert!(
4073
4088
matches!(&all[1], MentionCandidate::Channel { channel_id, .. } if channel_id == CHANNEL)
4074
4089
);
4075
4090
assert!(matches!(&all[2], MentionCandidate::Team { team_id, .. } if team_id == "team-1"));
4091
assert!(
4092
matches!(&all[3], MentionCandidate::Tag { tag_id, member_count: Some(4), .. } if tag_id == "tag-design")
4093
);
4094
let design = engine
4095
.mention_candidates(CHANNEL, "desi", 10)
4096
.await
4097
.unwrap();
4098
assert_eq!(
4099
design[0].to_mention(),
4100
MentionInput::tag("tag-design", "Designers")
4101
);
4102
engine.mention_candidates(CHANNEL, "", 10).await.unwrap();
4103
let tag_loads = fake
4104
.calls()
4105
.into_iter()
4106
.filter(|call| call.starts_with("tags"))
4107
.count();
4108
assert_eq!(tag_loads, 1);
4076
4109
let squad = engine.mention_candidates(CHANNEL, "squ", 10).await.unwrap();
4077
4110
assert_eq!(squad[0].to_mention(), MentionInput::team("team-1", "Squad"));
4078
4111
}
@@ -1084,6 +1084,16 @@ impl Remote for Handle {1084
Ok(())1084
Ok(())1085
}1085
}1086
1086
1087
async fn team_tags(&self, team_id: &str) -> Result<Vec<graph::Tag>> {1088
self.record(format!("tags {team_id}"));1089
Ok(vec![1090
serde_json::from_value(1091
json!({"id": "tag-design", "displayName": "Designers", "memberCount": 4}),1092
)1093
.unwrap(),1094
])1095
}1096
1087
async fn search_people(&self, query: &str) -> Result<Vec<User>> {1097
async fn search_people(&self, query: &str) -> Result<Vec<User>> {1088
self.record(format!("search {query}"));1098
self.record(format!("search {query}"));1089
let configured = self.directory_users.lock().unwrap().clone();1099
let configured = self.directory_users.lock().unwrap().clone();@@ -4023,9 +4033,14 @@ async fn people_candidates_list_members_first_then_the_directory_without_duplica4023
];4033
];4024
let engine = chat_engine(&fake, small_pages()).await;4034
let engine = chat_engine(&fake, small_pages()).await;4025
4035
4026
let everyone = engine.mention_candidates(CHAT, "", 10).await.unwrap();4036
let all = engine.mention_candidates(CHAT, "", 10).await.unwrap();4027
assert_eq!(everyone.len(), 1);4037
assert_eq!(all.len(), 2);4028
assert_eq!(everyone[0].display_name(), "Ada Example");4038
assert!(matches!(&all[0], MentionCandidate::Everyone { chat_id } if chat_id == CHAT));4039
assert_eq!(4040
all[0].to_mention(),4041
MentionInput::everyone(CHAT, "Everyone")4042
);4043
assert_eq!(all[1].display_name(), "Ada Example");4029
assert!(!fake.calls().iter().any(|call| call.starts_with("search")));4044
assert!(!fake.calls().iter().any(|call| call.starts_with("search")));4030
4045
4031
let found = engine.mention_candidates(CHAT, "@ada", 10).await.unwrap();4046
let found = engine.mention_candidates(CHAT, "@ada", 10).await.unwrap();@@ -4067,12 +4082,30 @@ async fn channel_candidates_offer_recent_senders_the_channel_and_its_team() {4067
let engine = channel_engine(&fake).await;4082
let engine = channel_engine(&fake).await;4068
engine.fetch_newer(CHANNEL).await.unwrap();4083
engine.fetch_newer(CHANNEL).await.unwrap();4069
let all = engine.mention_candidates(CHANNEL, "", 10).await.unwrap();4084
let all = engine.mention_candidates(CHANNEL, "", 10).await.unwrap();4070
assert_eq!(all.len(), 3);4085
assert_eq!(all.len(), 4);4071
assert!(matches!(&all[0], MentionCandidate::Person(person) if person.user_id == "user-ada"));4086
assert!(matches!(&all[0], MentionCandidate::Person(person) if person.user_id == "user-ada"));4072
assert!(4087
assert!(4073
matches!(&all[1], MentionCandidate::Channel { channel_id, .. } if channel_id == CHANNEL)4088
matches!(&all[1], MentionCandidate::Channel { channel_id, .. } if channel_id == CHANNEL)4074
);4089
);4075
assert!(matches!(&all[2], MentionCandidate::Team { team_id, .. } if team_id == "team-1"));4090
assert!(matches!(&all[2], MentionCandidate::Team { team_id, .. } if team_id == "team-1"));4091
assert!(4092
matches!(&all[3], MentionCandidate::Tag { tag_id, member_count: Some(4), .. } if tag_id == "tag-design")4093
);4094
let design = engine4095
.mention_candidates(CHANNEL, "desi", 10)4096
.await4097
.unwrap();4098
assert_eq!(4099
design[0].to_mention(),4100
MentionInput::tag("tag-design", "Designers")4101
);4102
engine.mention_candidates(CHANNEL, "", 10).await.unwrap();4103
let tag_loads = fake4104
.calls()4105
.into_iter()4106
.filter(|call| call.starts_with("tags"))4107
.count();4108
assert_eq!(tag_loads, 1);4076
let squad = engine.mention_candidates(CHANNEL, "squ", 10).await.unwrap();4109
let squad = engine.mention_candidates(CHANNEL, "squ", 10).await.unwrap();4077
assert_eq!(squad[0].to_mention(), MentionInput::team("team-1", "Squad"));4110
assert_eq!(squad[0].to_mention(), MentionInput::team("team-1", "Squad"));4078
}4111
}@@ -4,7 +4,7 @@ use serde_json::Value;
4
4
use session::{ApiResponse, GRAPH, Method, Request, Scope, Session};
5
5
6
6
use crate::error::{Error, Result};
7
use crate::models::{Channel, Chat, Member, Message, Team, User};
7
use crate::models::{Channel, Chat, Member, Message, Tag, Team, User};
8
8
use crate::page::Page;
9
9
use crate::urls;
10
10
@@ -115,6 +115,11 @@ impl Graph {
115
115
.await
116
116
}
117
117
118
pub async fn team_tags(&self, team_id: &str) -> Result<Vec<Tag>> {
119
self.get_all(&urls::team_tags(team_id), Scope::graph("TeamworkTag.Read"))
120
.await
121
}
122
118
123
pub async fn channels(&self, team_id: &str) -> Result<Vec<Channel>> {
119
124
self.get_all(
120
125
&urls::channels(team_id),
@@ -4,7 +4,7 @@ use serde_json::Value;4
use session::{ApiResponse, GRAPH, Method, Request, Scope, Session};4
use session::{ApiResponse, GRAPH, Method, Request, Scope, Session};5
5
6
use crate::error::{Error, Result};6
use crate::error::{Error, Result};7
use crate::models::{Channel, Chat, Member, Message, Team, User};7
use crate::models::{Channel, Chat, Member, Message, Tag, Team, User};8
use crate::page::Page;8
use crate::page::Page;9
use crate::urls;9
use crate::urls;10
10
@@ -115,6 +115,11 @@ impl Graph {115
.await115
.await116
}116
}117
117
118
pub async fn team_tags(&self, team_id: &str) -> Result<Vec<Tag>> {119
self.get_all(&urls::team_tags(team_id), Scope::graph("TeamworkTag.Read"))120
.await121
}122
118
pub async fn channels(&self, team_id: &str) -> Result<Vec<Channel>> {123
pub async fn channels(&self, team_id: &str) -> Result<Vec<Channel>> {119
self.get_all(124
self.get_all(120
&urls::channels(team_id),125
&urls::channels(team_id),@@ -23,7 +23,7 @@ pub use files::{
23
23
pub use library::DriveEntry;
24
24
pub use models::{
25
25
Attachment, Body, Channel, Chat, ChatViewpoint, Identity, Member, Mention, Message, Photo,
26
Presence, Reaction, Sender, Team, UNKNOWN_USER_NAME, User,
26
Presence, Reaction, Sender, Tag, Team, UNKNOWN_USER_NAME, User,
27
27
};
28
28
pub use outgoing::{
29
29
FileReference, HostedImage, KeptAttachment, MentionTarget, MessageExtras, OutgoingMention,
@@ -23,7 +23,7 @@ pub use files::{23
pub use library::DriveEntry;23
pub use library::DriveEntry;24
pub use models::{24
pub use models::{25
Attachment, Body, Channel, Chat, ChatViewpoint, Identity, Member, Mention, Message, Photo,25
Attachment, Body, Channel, Chat, ChatViewpoint, Identity, Member, Mention, Message, Photo,26
Presence, Reaction, Sender, Team, UNKNOWN_USER_NAME, User,26
Presence, Reaction, Sender, Tag, Team, UNKNOWN_USER_NAME, User,27
};27
};28
pub use outgoing::{28
pub use outgoing::{29
FileReference, HostedImage, KeptAttachment, MentionTarget, MessageExtras, OutgoingMention,29
FileReference, HostedImage, KeptAttachment, MentionTarget, MessageExtras, OutgoingMention,@@ -237,6 +237,14 @@ pub struct Team {
237
237
pub display_name: String,
238
238
}
239
239
240
#[derive(Debug, Clone, Deserialize, PartialEq)]
241
#[serde(rename_all = "camelCase")]
242
pub struct Tag {
243
pub id: String,
244
pub display_name: String,
245
pub member_count: Option<u32>,
246
}
247
240
248
#[derive(Debug, Clone, Deserialize, PartialEq)]
241
249
#[serde(rename_all = "camelCase")]
242
250
pub struct Channel {
@@ -237,6 +237,14 @@ pub struct Team {237
pub display_name: String,237
pub display_name: String,238
}238
}239
239
240
#[derive(Debug, Clone, Deserialize, PartialEq)]241
#[serde(rename_all = "camelCase")]242
pub struct Tag {243
pub id: String,244
pub display_name: String,245
pub member_count: Option<u32>,246
}247
240
#[derive(Debug, Clone, Deserialize, PartialEq)]248
#[derive(Debug, Clone, Deserialize, PartialEq)]241
#[serde(rename_all = "camelCase")]249
#[serde(rename_all = "camelCase")]242
pub struct Channel {250
pub struct Channel {@@ -10,6 +10,8 @@ pub enum MentionTarget {
10
10
User { user_id: String },
11
11
Channel { channel_id: String },
12
12
Team { team_id: String },
13
Everyone { chat_id: String },
14
Tag { tag_id: String },
13
15
}
14
16
15
17
/// `id` matches the `<at id="n">` tag in the html body.
@@ -32,6 +34,12 @@ impl OutgoingMention {
32
34
MentionTarget::Team { team_id } => json!({
33
35
"conversation": {"id": team_id, "displayName": self.text, "conversationIdentityType": "team"}
34
36
}),
37
MentionTarget::Everyone { chat_id } => json!({
38
"conversation": {"id": chat_id, "displayName": self.text, "conversationIdentityType": "chat"}
39
}),
40
MentionTarget::Tag { tag_id } => json!({
41
"tag": {"id": tag_id, "displayName": self.text}
42
}),
35
43
};
36
44
json!({"id": self.id, "mentionText": self.text, "mentioned": mentioned})
37
45
}
@@ -232,6 +240,34 @@ mod tests {
232
240
assert_eq!(team["mentioned"]["conversation"]["id"], "t");
233
241
}
234
242
243
#[test]
244
fn everyone_and_tag_mentions_match_the_documented_payload() {
245
let everyone = mention(
246
0,
247
"Everyone",
248
MentionTarget::Everyone {
249
chat_id: "19:g@thread.v2".into(),
250
},
251
)
252
.to_json();
253
assert_eq!(
254
everyone["mentioned"],
255
json!({"conversation": {"id": "19:g@thread.v2", "displayName": "Everyone", "conversationIdentityType": "chat"}})
256
);
257
let tag = mention(
258
1,
259
"Designers",
260
MentionTarget::Tag {
261
tag_id: "tag-1".into(),
262
},
263
)
264
.to_json();
265
assert_eq!(
266
tag,
267
json!({"id": 1, "mentionText": "Designers", "mentioned": {"tag": {"id": "tag-1", "displayName": "Designers"}}})
268
);
269
}
270
235
271
#[test]
236
272
fn body_without_mentions_has_no_mentions_key() {
237
273
let none = MessageExtras::default();
@@ -10,6 +10,8 @@ pub enum MentionTarget {10
User { user_id: String },10
User { user_id: String },11
Channel { channel_id: String },11
Channel { channel_id: String },12
Team { team_id: String },12
Team { team_id: String },13
Everyone { chat_id: String },14
Tag { tag_id: String },13
}15
}14
16
15
/// `id` matches the `<at id="n">` tag in the html body.17
/// `id` matches the `<at id="n">` tag in the html body.@@ -32,6 +34,12 @@ impl OutgoingMention {32
MentionTarget::Team { team_id } => json!({34
MentionTarget::Team { team_id } => json!({33
"conversation": {"id": team_id, "displayName": self.text, "conversationIdentityType": "team"}35
"conversation": {"id": team_id, "displayName": self.text, "conversationIdentityType": "team"}34
}),36
}),37
MentionTarget::Everyone { chat_id } => json!({38
"conversation": {"id": chat_id, "displayName": self.text, "conversationIdentityType": "chat"}39
}),40
MentionTarget::Tag { tag_id } => json!({41
"tag": {"id": tag_id, "displayName": self.text}42
}),35
};43
};36
json!({"id": self.id, "mentionText": self.text, "mentioned": mentioned})44
json!({"id": self.id, "mentionText": self.text, "mentioned": mentioned})37
}45
}@@ -232,6 +240,34 @@ mod tests {232
assert_eq!(team["mentioned"]["conversation"]["id"], "t");240
assert_eq!(team["mentioned"]["conversation"]["id"], "t");233
}241
}234
242
243
#[test]244
fn everyone_and_tag_mentions_match_the_documented_payload() {245
let everyone = mention(246
0,247
"Everyone",248
MentionTarget::Everyone {249
chat_id: "19:g@thread.v2".into(),250
},251
)252
.to_json();253
assert_eq!(254
everyone["mentioned"],255
json!({"conversation": {"id": "19:g@thread.v2", "displayName": "Everyone", "conversationIdentityType": "chat"}})256
);257
let tag = mention(258
1,259
"Designers",260
MentionTarget::Tag {261
tag_id: "tag-1".into(),262
},263
)264
.to_json();265
assert_eq!(266
tag,267
json!({"id": 1, "mentionText": "Designers", "mentioned": {"tag": {"id": "tag-1", "displayName": "Designers"}}})268
);269
}270
235
#[test]271
#[test]236
fn body_without_mentions_has_no_mentions_key() {272
fn body_without_mentions_has_no_mentions_key() {237
let none = MessageExtras::default();273
let none = MessageExtras::default();@@ -265,6 +265,13 @@ pub fn joined_teams() -> String {
265
265
format!("{GRAPH}/v1.0/me/joinedTeams?$select=id,displayName")
266
266
}
267
267
268
pub fn team_tags(team_id: &str) -> String {
269
format!(
270
"{GRAPH}/v1.0/teams/{}/tags?$select=id,displayName,memberCount",
271
segment(team_id)
272
)
273
}
274
268
275
pub fn channels(team_id: &str) -> String {
269
276
format!(
270
277
"{GRAPH}/v1.0/teams/{}/channels?$select=id,displayName,membershipType",
@@ -265,6 +265,13 @@ pub fn joined_teams() -> String {265
format!("{GRAPH}/v1.0/me/joinedTeams?$select=id,displayName")265
format!("{GRAPH}/v1.0/me/joinedTeams?$select=id,displayName")266
}266
}267
267
268
pub fn team_tags(team_id: &str) -> String {269
format!(270
"{GRAPH}/v1.0/teams/{}/tags?$select=id,displayName,memberCount",271
segment(team_id)272
)273
}274
268
pub fn channels(team_id: &str) -> String {275
pub fn channels(team_id: &str) -> String {269
format!(276
format!(270
"{GRAPH}/v1.0/teams/{}/channels?$select=id,displayName,membershipType",277
"{GRAPH}/v1.0/teams/{}/channels?$select=id,displayName,membershipType",