Merge remote-tracking branch 'origin/main' into feat/find-filter
# Conflicts: # crates/app/src/layout_guard.rs # crates/app/src/views/conversation.rs # crates/app/src/views/sidebar.rs
@@ -218,6 +218,7 @@ mod tests {
218
218
hidden: false,
219
219
hidden_channel_ids: Vec::new(),
220
220
notifications: Default::default(),
221
mentions: Default::default(),
221
222
});
222
223
let context = build(&state, "19:chat", "reply-2").unwrap();
223
224
let texts: Vec<&str> = context
@@ -218,6 +218,7 @@ mod tests {218
hidden: false,218
hidden: false,219
hidden_channel_ids: Vec::new(),219
hidden_channel_ids: Vec::new(),220
notifications: Default::default(),220
notifications: Default::default(),221
mentions: Default::default(),221
});222
});222
let context = build(&state, "19:chat", "reply-2").unwrap();223
let context = build(&state, "19:chat", "reply-2").unwrap();223
let texts: Vec<&str> = context224
let texts: Vec<&str> = context@@ -798,6 +798,42 @@ impl AppState {
798
798
}
799
799
}
800
800
801
pub fn mark_all_channels_read(&mut self, cx: &mut Context<Self>) {
802
let Some(engine_or_demo) = self.chat_action_engine(cx) else {
803
return;
804
};
805
let previous_unread: Vec<(String, bool, Option<DateTime<Utc>>)> = self
806
.sidebar
807
.teams
808
.iter()
809
.flat_map(|team| team.channels.iter())
810
.map(|channel| (channel.id.clone(), channel.unread, None))
811
.collect();
812
let previous_mentions: Vec<(String, store::ChannelMentions)> = self
813
.sidebar
814
.teams
815
.iter()
816
.flat_map(|team| team.mentions.iter())
817
.map(|(channel_id, mentions)| (channel_id.clone(), *mentions))
818
.collect();
819
let _ = self.store.mark_all_channels_read();
820
self.reload_sidebar(cx);
821
let Some(engine) = engine_or_demo else {
822
return;
823
};
824
self.run_chat_action(
825
"Mark all as read",
826
async move { engine.mark_all_channels_read().await },
827
move |state, cx| {
828
let _ = state.store.apply_channel_read_states(&previous_unread);
829
let _ = state.store.replace_channel_mentions(&previous_mentions);
830
state.reload_sidebar(cx);
831
},
832
|_, _| {},
833
cx,
834
);
835
}
836
801
837
pub fn start_new_chat(&mut self, cx: &mut Context<Self>) {
802
838
self.new_chat = true;
803
839
self.show_call(false, cx);
@@ -1099,6 +1135,7 @@ mod tests {
1099
1135
hidden: false,
1100
1136
hidden_channel_ids: Vec::new(),
1101
1137
notifications: Default::default(),
1138
mentions: Default::default(),
1102
1139
}],
1103
1140
}
1104
1141
}
@@ -798,6 +798,42 @@ impl AppState {798
}798
}799
}799
}800
800
801
pub fn mark_all_channels_read(&mut self, cx: &mut Context<Self>) {802
let Some(engine_or_demo) = self.chat_action_engine(cx) else {803
return;804
};805
let previous_unread: Vec<(String, bool, Option<DateTime<Utc>>)> = self806
.sidebar807
.teams808
.iter()809
.flat_map(|team| team.channels.iter())810
.map(|channel| (channel.id.clone(), channel.unread, None))811
.collect();812
let previous_mentions: Vec<(String, store::ChannelMentions)> = self813
.sidebar814
.teams815
.iter()816
.flat_map(|team| team.mentions.iter())817
.map(|(channel_id, mentions)| (channel_id.clone(), *mentions))818
.collect();819
let _ = self.store.mark_all_channels_read();820
self.reload_sidebar(cx);821
let Some(engine) = engine_or_demo else {822
return;823
};824
self.run_chat_action(825
"Mark all as read",826
async move { engine.mark_all_channels_read().await },827
move |state, cx| {828
let _ = state.store.apply_channel_read_states(&previous_unread);829
let _ = state.store.replace_channel_mentions(&previous_mentions);830
state.reload_sidebar(cx);831
},832
|_, _| {},833
cx,834
);835
}836
801
pub fn start_new_chat(&mut self, cx: &mut Context<Self>) {837
pub fn start_new_chat(&mut self, cx: &mut Context<Self>) {802
self.new_chat = true;838
self.new_chat = true;803
self.show_call(false, cx);839
self.show_call(false, cx);@@ -1099,6 +1135,7 @@ mod tests {1099
hidden: false,1135
hidden: false,1100
hidden_channel_ids: Vec::new(),1136
hidden_channel_ids: Vec::new(),1101
notifications: Default::default(),1137
notifications: Default::default(),1138
mentions: Default::default(),1102
}],1139
}],1103
}1140
}1104
}1141
}@@ -1,8 +1,8 @@
1
1
use std::future::Future;
2
2
3
use chatsvc::HistoryShare;
3
4
use chrono::{DateTime, Duration, Local, Offset, Utc};
4
5
use gpui_kit::*;
5
use chatsvc::HistoryShare;
6
6
use store::{ChannelNotifications, ChatRecord, MemberRecord};
7
7
use teams_core::roster_event::{RosterChange, RosterEvent, SharedHistory, merge_members};
8
8
@@ -255,9 +255,7 @@ impl AppState {
255
255
};
256
256
let mut with_members = chat.clone();
257
257
merge_members(&mut with_members.members, &people);
258
let _ = self
259
.store
260
.upsert_chats(std::slice::from_ref(&with_members));
258
let _ = self.store.upsert_chats(std::slice::from_ref(&with_members));
261
259
self.reload_sidebar(cx);
262
260
let Some(engine) = engine_or_demo else {
263
261
self.add_demo_roster_line(chat_id, &people, share, cx);
@@ -302,19 +300,90 @@ impl AppState {
302
300
HistoryShare::Days(days) => SharedHistory::Days(days),
303
301
HistoryShare::All => SharedHistory::All,
304
302
},
303
topic: None,
305
304
};
305
self.store_demo_roster_line(chat_id, &event, cx);
306
}
307
308
fn store_demo_roster_line(
309
&mut self,
310
chat_id: &str,
311
event: &RosterEvent,
312
cx: &mut Context<Self>,
313
) {
306
314
let now = Utc::now();
307
315
let record = crate::demo::roster_record(
308
316
chat_id,
309
317
&format!("demo-roster-{}", now.timestamp_millis()),
310
318
now,
311
&event,
319
event,
312
320
);
313
321
let _ = self.store.upsert_messages(std::slice::from_ref(&record));
314
322
cx.emit(crate::app_state::AppEvent::Messages(chat_id.to_owned()));
315
323
cx.notify();
316
324
}
317
325
326
/// Teams' "Remove chat history": hidden for me only until a newer message arrives.
327
pub fn remove_chat_history(&mut self, chat_id: &str, cx: &mut Context<Self>) {
328
let Some(chat) = self.chat_record(chat_id) else {
329
return;
330
};
331
let Some(engine_or_demo) = self.chat_action_engine(cx) else {
332
return;
333
};
334
self.remove_chat_locally(chat_id, cx);
335
let Some(engine) = engine_or_demo else {
336
return;
337
};
338
let owned_id = chat_id.to_owned();
339
self.run_chat_action(
340
"Remove chat history",
341
async move { engine.remove_chat_history(&owned_id).await },
342
move |state, cx| state.restore_chat_locally(&chat, cx),
343
|_, _| {},
344
cx,
345
);
346
}
347
348
pub fn rename_chat(&mut self, chat_id: &str, topic: &str, cx: &mut Context<Self>) {
349
let Some(chat) = self.chat_record(chat_id) else {
350
return;
351
};
352
let topic = topic.trim().to_owned();
353
if topic == chat.title.trim() || chatsvc::topic_problem(&topic).is_some() {
354
return;
355
}
356
let Some(engine_or_demo) = self.chat_action_engine(cx) else {
357
return;
358
};
359
let mut renamed = chat.clone();
360
renamed.title = topic.clone();
361
let _ = self.store.upsert_chats(std::slice::from_ref(&renamed));
362
self.reload_sidebar(cx);
363
let Some(engine) = engine_or_demo else {
364
let me = self.directory.me.as_ref();
365
let event = RosterEvent {
366
change: RosterChange::Renamed,
367
initiator_id: me.map(|person| person.user_id.clone()),
368
initiator_name: me.map(|person| person.display_name.clone()),
369
member_ids: Vec::new(),
370
member_names: Vec::new(),
371
history: SharedHistory::None,
372
topic: (!topic.is_empty()).then(|| topic.clone()),
373
};
374
self.store_demo_roster_line(chat_id, &event, cx);
375
return;
376
};
377
let owned_id = chat_id.to_owned();
378
self.run_chat_action(
379
"Rename group chat",
380
async move { engine.rename_chat(&owned_id, &topic).await },
381
move |state, cx| state.restore_chat_locally(&chat, cx),
382
|_, _| {},
383
cx,
384
);
385
}
386
318
387
/// Teams turns adding people to a 1:1 into a new group chat draft with everyone.
319
388
pub fn start_group_chat_with(&mut self, people: Vec<MemberRecord>, cx: &mut Context<Self>) {
320
389
self.new_chat_people = people;
@@ -1,8 +1,8 @@1
use std::future::Future;1
use std::future::Future;2
2
3
use chatsvc::HistoryShare;3
use chrono::{DateTime, Duration, Local, Offset, Utc};4
use chrono::{DateTime, Duration, Local, Offset, Utc};4
use gpui_kit::*;5
use gpui_kit::*;5
use chatsvc::HistoryShare;6
use store::{ChannelNotifications, ChatRecord, MemberRecord};6
use store::{ChannelNotifications, ChatRecord, MemberRecord};7
use teams_core::roster_event::{RosterChange, RosterEvent, SharedHistory, merge_members};7
use teams_core::roster_event::{RosterChange, RosterEvent, SharedHistory, merge_members};8
8
@@ -255,9 +255,7 @@ impl AppState {255
};255
};256
let mut with_members = chat.clone();256
let mut with_members = chat.clone();257
merge_members(&mut with_members.members, &people);257
merge_members(&mut with_members.members, &people);258
let _ = self258
let _ = self.store.upsert_chats(std::slice::from_ref(&with_members));259
.store260
.upsert_chats(std::slice::from_ref(&with_members));261
self.reload_sidebar(cx);259
self.reload_sidebar(cx);262
let Some(engine) = engine_or_demo else {260
let Some(engine) = engine_or_demo else {263
self.add_demo_roster_line(chat_id, &people, share, cx);261
self.add_demo_roster_line(chat_id, &people, share, cx);@@ -302,19 +300,90 @@ impl AppState {302
HistoryShare::Days(days) => SharedHistory::Days(days),300
HistoryShare::Days(days) => SharedHistory::Days(days),303
HistoryShare::All => SharedHistory::All,301
HistoryShare::All => SharedHistory::All,304
},302
},303
topic: None,305
};304
};305
self.store_demo_roster_line(chat_id, &event, cx);306
}307
308
fn store_demo_roster_line(309
&mut self,310
chat_id: &str,311
event: &RosterEvent,312
cx: &mut Context<Self>,313
) {306
let now = Utc::now();314
let now = Utc::now();307
let record = crate::demo::roster_record(315
let record = crate::demo::roster_record(308
chat_id,316
chat_id,309
&format!("demo-roster-{}", now.timestamp_millis()),317
&format!("demo-roster-{}", now.timestamp_millis()),310
now,318
now,311
&event,319
event,312
);320
);313
let _ = self.store.upsert_messages(std::slice::from_ref(&record));321
let _ = self.store.upsert_messages(std::slice::from_ref(&record));314
cx.emit(crate::app_state::AppEvent::Messages(chat_id.to_owned()));322
cx.emit(crate::app_state::AppEvent::Messages(chat_id.to_owned()));315
cx.notify();323
cx.notify();316
}324
}317
325
326
/// Teams' "Remove chat history": hidden for me only until a newer message arrives.327
pub fn remove_chat_history(&mut self, chat_id: &str, cx: &mut Context<Self>) {328
let Some(chat) = self.chat_record(chat_id) else {329
return;330
};331
let Some(engine_or_demo) = self.chat_action_engine(cx) else {332
return;333
};334
self.remove_chat_locally(chat_id, cx);335
let Some(engine) = engine_or_demo else {336
return;337
};338
let owned_id = chat_id.to_owned();339
self.run_chat_action(340
"Remove chat history",341
async move { engine.remove_chat_history(&owned_id).await },342
move |state, cx| state.restore_chat_locally(&chat, cx),343
|_, _| {},344
cx,345
);346
}347
348
pub fn rename_chat(&mut self, chat_id: &str, topic: &str, cx: &mut Context<Self>) {349
let Some(chat) = self.chat_record(chat_id) else {350
return;351
};352
let topic = topic.trim().to_owned();353
if topic == chat.title.trim() || chatsvc::topic_problem(&topic).is_some() {354
return;355
}356
let Some(engine_or_demo) = self.chat_action_engine(cx) else {357
return;358
};359
let mut renamed = chat.clone();360
renamed.title = topic.clone();361
let _ = self.store.upsert_chats(std::slice::from_ref(&renamed));362
self.reload_sidebar(cx);363
let Some(engine) = engine_or_demo else {364
let me = self.directory.me.as_ref();365
let event = RosterEvent {366
change: RosterChange::Renamed,367
initiator_id: me.map(|person| person.user_id.clone()),368
initiator_name: me.map(|person| person.display_name.clone()),369
member_ids: Vec::new(),370
member_names: Vec::new(),371
history: SharedHistory::None,372
topic: (!topic.is_empty()).then(|| topic.clone()),373
};374
self.store_demo_roster_line(chat_id, &event, cx);375
return;376
};377
let owned_id = chat_id.to_owned();378
self.run_chat_action(379
"Rename group chat",380
async move { engine.rename_chat(&owned_id, &topic).await },381
move |state, cx| state.restore_chat_locally(&chat, cx),382
|_, _| {},383
cx,384
);385
}386
318
/// Teams turns adding people to a 1:1 into a new group chat draft with everyone.387
/// Teams turns adding people to a 1:1 into a new group chat draft with everyone.319
pub fn start_group_chat_with(&mut self, people: Vec<MemberRecord>, cx: &mut Context<Self>) {388
pub fn start_group_chat_with(&mut self, people: Vec<MemberRecord>, cx: &mut Context<Self>) {320
self.new_chat_people = people;389
self.new_chat_people = people;@@ -0,0 +1,127 @@
1
use gpui_kit::Context;
2
3
use crate::app_state::AppState;
4
use crate::emoticons;
5
6
pub fn quick_reaction_glyphs(reaction_ids: &[String], skin_tone: u8) -> Vec<String> {
7
reaction_ids
8
.iter()
9
.filter_map(|reaction_id| chatsvc::reaction_glyph_for_key(reaction_id))
10
.map(|glyph| emoticons::with_tone(&glyph, skin_tone))
11
.collect()
12
}
13
14
pub fn reaction_id_for_glyph(glyph: &str) -> Option<String> {
15
chatsvc::reaction_key(&emoticons::without_tone(glyph))
16
}
17
18
pub fn slots_for(reaction_ids: &[String]) -> Vec<Option<String>> {
19
let length = reaction_ids.len().max(teams_core::DEFAULT_REACTION_SLOTS);
20
(0..length)
21
.map(|index| reaction_ids.get(index).cloned())
22
.collect()
23
}
24
25
/// Teams' replace rule: an id already in another slot leaves that slot empty.
26
pub fn place_in_slot(slots: &mut [Option<String>], index: usize, reaction_id: String) {
27
for slot in slots.iter_mut() {
28
if slot.as_deref() == Some(reaction_id.as_str()) {
29
*slot = None;
30
}
31
}
32
if let Some(slot) = slots.get_mut(index) {
33
*slot = Some(reaction_id);
34
}
35
}
36
37
pub fn filled(slots: &[Option<String>]) -> Vec<String> {
38
slots.iter().flatten().cloned().collect()
39
}
40
41
impl AppState {
42
pub fn default_reactions(&self) -> Vec<String> {
43
teams_core::default_reactions(&self.store)
44
}
45
46
pub fn quick_reactions(&self) -> Vec<String> {
47
quick_reaction_glyphs(
48
&self.default_reactions(),
49
teams_core::skin_tone(&self.store),
50
)
51
}
52
53
pub fn set_default_reactions(&mut self, reaction_ids: Vec<String>, cx: &mut Context<Self>) {
54
let Some(engine_or_demo) = self.chat_action_engine(cx) else {
55
return;
56
};
57
let previous = self.default_reactions();
58
let _ = teams_core::store_account_default_reactions(&self.store, Some(&reaction_ids));
59
cx.notify();
60
let Some(engine) = engine_or_demo else {
61
return;
62
};
63
self.run_chat_action(
64
"Customising default reactions",
65
async move { engine.set_default_reactions(&reaction_ids).await },
66
move |state, cx| {
67
let _ = teams_core::store_account_default_reactions(&state.store, Some(&previous));
68
cx.notify();
69
},
70
|_, _| {},
71
cx,
72
);
73
}
74
}
75
76
#[cfg(test)]
77
mod tests {
78
use super::*;
79
80
fn ids(values: &[&str]) -> Vec<String> {
81
values.iter().map(|value| (*value).to_owned()).collect()
82
}
83
84
#[test]
85
fn teams_defaults_show_as_glyphs_and_like_takes_the_tone() {
86
let defaults = ids(&teams_core::TEAMS_DEFAULT_REACTIONS);
87
assert_eq!(
88
quick_reaction_glyphs(&defaults, 0),
89
["\u{1F44D}", "\u{2764}", "\u{1F606}", "\u{1F62E}"]
90
);
91
assert_eq!(quick_reaction_glyphs(&defaults, 2)[0], "\u{1F44D}\u{1F3FC}");
92
assert_eq!(
93
chatsvc::reaction_key(&quick_reaction_glyphs(&defaults, 2)[0]).as_deref(),
94
Some("yes-tone2")
95
);
96
}
97
98
#[test]
99
fn unknown_ids_are_left_out() {
100
assert_eq!(
101
quick_reaction_glyphs(&ids(&["heart", "custom-gone"]), 0),
102
["\u{2764}"]
103
);
104
}
105
106
#[test]
107
fn picked_glyphs_store_the_untoned_id() {
108
assert_eq!(
109
reaction_id_for_glyph("\u{1F44D}\u{1F3FC}").as_deref(),
110
Some("like")
111
);
112
assert_eq!(
113
reaction_id_for_glyph("\u{2764}\u{FE0F}").as_deref(),
114
Some("heart")
115
);
116
}
117
118
#[test]
119
fn there_are_always_five_slots_and_a_repeat_moves() {
120
let mut slots = slots_for(&ids(&["like", "heart"]));
121
assert_eq!(slots.len(), 5);
122
place_in_slot(&mut slots, 3, "like".to_owned());
123
assert_eq!(filled(&slots), ["heart", "like"]);
124
assert_eq!(slots[0], None);
125
assert_eq!(slots_for(&ids(&["a", "b", "c", "d", "e", "f"])).len(), 6);
126
}
127
}
@@ -0,0 +1,127 @@1
use gpui_kit::Context;2
3
use crate::app_state::AppState;4
use crate::emoticons;5
6
pub fn quick_reaction_glyphs(reaction_ids: &[String], skin_tone: u8) -> Vec<String> {7
reaction_ids8
.iter()9
.filter_map(|reaction_id| chatsvc::reaction_glyph_for_key(reaction_id))10
.map(|glyph| emoticons::with_tone(&glyph, skin_tone))11
.collect()12
}13
14
pub fn reaction_id_for_glyph(glyph: &str) -> Option<String> {15
chatsvc::reaction_key(&emoticons::without_tone(glyph))16
}17
18
pub fn slots_for(reaction_ids: &[String]) -> Vec<Option<String>> {19
let length = reaction_ids.len().max(teams_core::DEFAULT_REACTION_SLOTS);20
(0..length)21
.map(|index| reaction_ids.get(index).cloned())22
.collect()23
}24
25
/// Teams' replace rule: an id already in another slot leaves that slot empty.26
pub fn place_in_slot(slots: &mut [Option<String>], index: usize, reaction_id: String) {27
for slot in slots.iter_mut() {28
if slot.as_deref() == Some(reaction_id.as_str()) {29
*slot = None;30
}31
}32
if let Some(slot) = slots.get_mut(index) {33
*slot = Some(reaction_id);34
}35
}36
37
pub fn filled(slots: &[Option<String>]) -> Vec<String> {38
slots.iter().flatten().cloned().collect()39
}40
41
impl AppState {42
pub fn default_reactions(&self) -> Vec<String> {43
teams_core::default_reactions(&self.store)44
}45
46
pub fn quick_reactions(&self) -> Vec<String> {47
quick_reaction_glyphs(48
&self.default_reactions(),49
teams_core::skin_tone(&self.store),50
)51
}52
53
pub fn set_default_reactions(&mut self, reaction_ids: Vec<String>, cx: &mut Context<Self>) {54
let Some(engine_or_demo) = self.chat_action_engine(cx) else {55
return;56
};57
let previous = self.default_reactions();58
let _ = teams_core::store_account_default_reactions(&self.store, Some(&reaction_ids));59
cx.notify();60
let Some(engine) = engine_or_demo else {61
return;62
};63
self.run_chat_action(64
"Customising default reactions",65
async move { engine.set_default_reactions(&reaction_ids).await },66
move |state, cx| {67
let _ = teams_core::store_account_default_reactions(&state.store, Some(&previous));68
cx.notify();69
},70
|_, _| {},71
cx,72
);73
}74
}75
76
#[cfg(test)]77
mod tests {78
use super::*;79
80
fn ids(values: &[&str]) -> Vec<String> {81
values.iter().map(|value| (*value).to_owned()).collect()82
}83
84
#[test]85
fn teams_defaults_show_as_glyphs_and_like_takes_the_tone() {86
let defaults = ids(&teams_core::TEAMS_DEFAULT_REACTIONS);87
assert_eq!(88
quick_reaction_glyphs(&defaults, 0),89
["\u{1F44D}", "\u{2764}", "\u{1F606}", "\u{1F62E}"]90
);91
assert_eq!(quick_reaction_glyphs(&defaults, 2)[0], "\u{1F44D}\u{1F3FC}");92
assert_eq!(93
chatsvc::reaction_key(&quick_reaction_glyphs(&defaults, 2)[0]).as_deref(),94
Some("yes-tone2")95
);96
}97
98
#[test]99
fn unknown_ids_are_left_out() {100
assert_eq!(101
quick_reaction_glyphs(&ids(&["heart", "custom-gone"]), 0),102
["\u{2764}"]103
);104
}105
106
#[test]107
fn picked_glyphs_store_the_untoned_id() {108
assert_eq!(109
reaction_id_for_glyph("\u{1F44D}\u{1F3FC}").as_deref(),110
Some("like")111
);112
assert_eq!(113
reaction_id_for_glyph("\u{2764}\u{FE0F}").as_deref(),114
Some("heart")115
);116
}117
118
#[test]119
fn there_are_always_five_slots_and_a_repeat_moves() {120
let mut slots = slots_for(&ids(&["like", "heart"]));121
assert_eq!(slots.len(), 5);122
place_in_slot(&mut slots, 3, "like".to_owned());123
assert_eq!(filled(&slots), ["heart", "like"]);124
assert_eq!(slots[0], None);125
assert_eq!(slots_for(&ids(&["a", "b", "c", "d", "e", "f"])).len(), 6);126
}127
}@@ -6,8 +6,9 @@ use std::time::Instant;
6
6
use chrono::{DateTime, Duration, Local, TimeZone, Utc};
7
7
use gpui_kit::{App, Entity};
8
8
use store::{
9
ChannelLayoutRecord, ChannelNotificationLevel, ChannelNotifications, ChannelRecord,
10
ChannelTabRecord, ChatRecord, MemberRecord, MessageRecord, Store, TeamLayoutRecord, TeamRecord,
9
ChannelLayoutRecord, ChannelMentions, ChannelNotificationLevel, ChannelNotifications,
10
ChannelRecord, ChannelTabRecord, ChatRecord, MemberRecord, MessageRecord, Store,
11
TeamLayoutRecord, TeamRecord,
11
12
};
12
13
use teams_core::{
13
14
Activity, CallEvent, CallPhase, CallType, CardActionOutcome, ChatApp, Gif, Language,
@@ -134,6 +135,22 @@ const DEMO_TEAMS: [(&str, &str, [&str; 3]); 4] = [
134
135
const DEMO_TEAM_ORDER: [&str; 4] = ["demo-team-2", "demo-team-1", "demo-team-3", "demo-team-4"];
135
136
const DEMO_HIDDEN_TEAM: &str = "demo-team-4";
136
137
const DEMO_HIDDEN_CHANNEL: &str = "demo-channel-3-3";
138
const DEMO_CHANNEL_MENTIONS: [(&str, ChannelMentions); 4] = [
139
("demo-channel-1-2", mentions(2, 0, 0)),
140
("demo-channel-2-1", mentions(0, 1, 0)),
141
(DEMO_HIDDEN_CHANNEL, mentions(1, 0, 0)),
142
("demo-channel-4-2", mentions(1, 0, 1)),
143
];
144
const PINNED_CHANNEL: &str = "demo-channel-1-1";
145
const PINNED_POST: &str = "t3";
146
147
const fn mentions(personal: u32, channel: u32, team: u32) -> ChannelMentions {
148
ChannelMentions {
149
personal,
150
channel,
151
team,
152
}
153
}
137
154
const DEMO_CHANNEL_NOTIFICATIONS: [(&str, ChannelNotificationLevel, bool); 4] = [
138
155
(
139
156
"demo-channel-1-1",
@@ -808,8 +825,21 @@ pub fn seed(store: &Store) {
808
825
});
809
826
}
810
827
}
828
for channel in channels.iter_mut().filter(|channel| {
829
DEMO_CHANNEL_MENTIONS
830
.iter()
831
.any(|(id, _)| *id == channel.id)
832
}) {
833
channel.unread = true;
834
}
811
835
let _ = store.upsert_channels(&channels);
812
836
let _ = store.replace_team_layout(&demo_team_layout(&channels));
837
let _ = store.replace_channel_mentions(
838
&DEMO_CHANNEL_MENTIONS
839
.iter()
840
.map(|(id, mentions)| ((*id).to_owned(), *mentions))
841
.collect::<Vec<_>>(),
842
);
813
843
let _ = store.set_meta("me_user_id", DEMO_USER_ID);
814
844
let _ = store.set_meta("me_display_name", DEMO_USER_NAME);
815
845
let _ = store.upsert_messages(&release_messages());
@@ -986,6 +1016,14 @@ pub fn seed_directory(state: &mut AppState) {
986
1016
}
987
1017
988
1018
fn seed_message_actions(state: &mut AppState) {
1019
state.pins.insert(
1020
PINNED_CHANNEL.to_owned(),
1021
vec![PinnedMessage {
1022
message_id: PINNED_POST.to_owned(),
1023
pinned_at: Some(at(0, 9, 45)),
1024
parent_id: None,
1025
}],
1026
);
989
1027
state.pins.insert(
990
1028
RELEASE_CHAT.to_owned(),
991
1029
vec![PinnedMessage {
@@ -1386,6 +1424,7 @@ fn settings_card() -> serde_json::Value {
1386
1424
})
1387
1425
}
1388
1426
1427
pub const DEMO_TENANT_ID: &str = "demo-tenant";
1389
1428
const DEMO_MEETING_LINK: &str = "https://teams.microsoft.com/l/meetup-join/19%3ameeting_ZGVtbw%40thread.v2/0?context=%7b%22Tid%22%3a%22demo-tenant%22%2c%22Oid%22%3a%22demo-mara%22%7d";
1390
1429
1391
1430
fn meeting_link_messages() -> Vec<MessageRecord> {
@@ -6,8 +6,9 @@ use std::time::Instant;6
use chrono::{DateTime, Duration, Local, TimeZone, Utc};6
use chrono::{DateTime, Duration, Local, TimeZone, Utc};7
use gpui_kit::{App, Entity};7
use gpui_kit::{App, Entity};8
use store::{8
use store::{9
ChannelLayoutRecord, ChannelNotificationLevel, ChannelNotifications, ChannelRecord,9
ChannelLayoutRecord, ChannelMentions, ChannelNotificationLevel, ChannelNotifications,10
ChannelTabRecord, ChatRecord, MemberRecord, MessageRecord, Store, TeamLayoutRecord, TeamRecord,10
ChannelRecord, ChannelTabRecord, ChatRecord, MemberRecord, MessageRecord, Store,11
TeamLayoutRecord, TeamRecord,11
};12
};12
use teams_core::{13
use teams_core::{13
Activity, CallEvent, CallPhase, CallType, CardActionOutcome, ChatApp, Gif, Language,14
Activity, CallEvent, CallPhase, CallType, CardActionOutcome, ChatApp, Gif, Language,@@ -134,6 +135,22 @@ const DEMO_TEAMS: [(&str, &str, [&str; 3]); 4] = [134
const DEMO_TEAM_ORDER: [&str; 4] = ["demo-team-2", "demo-team-1", "demo-team-3", "demo-team-4"];135
const DEMO_TEAM_ORDER: [&str; 4] = ["demo-team-2", "demo-team-1", "demo-team-3", "demo-team-4"];135
const DEMO_HIDDEN_TEAM: &str = "demo-team-4";136
const DEMO_HIDDEN_TEAM: &str = "demo-team-4";136
const DEMO_HIDDEN_CHANNEL: &str = "demo-channel-3-3";137
const DEMO_HIDDEN_CHANNEL: &str = "demo-channel-3-3";138
const DEMO_CHANNEL_MENTIONS: [(&str, ChannelMentions); 4] = [139
("demo-channel-1-2", mentions(2, 0, 0)),140
("demo-channel-2-1", mentions(0, 1, 0)),141
(DEMO_HIDDEN_CHANNEL, mentions(1, 0, 0)),142
("demo-channel-4-2", mentions(1, 0, 1)),143
];144
const PINNED_CHANNEL: &str = "demo-channel-1-1";145
const PINNED_POST: &str = "t3";146
147
const fn mentions(personal: u32, channel: u32, team: u32) -> ChannelMentions {148
ChannelMentions {149
personal,150
channel,151
team,152
}153
}137
const DEMO_CHANNEL_NOTIFICATIONS: [(&str, ChannelNotificationLevel, bool); 4] = [154
const DEMO_CHANNEL_NOTIFICATIONS: [(&str, ChannelNotificationLevel, bool); 4] = [138
(155
(139
"demo-channel-1-1",156
"demo-channel-1-1",@@ -808,8 +825,21 @@ pub fn seed(store: &Store) {808
});825
});809
}826
}810
}827
}828
for channel in channels.iter_mut().filter(|channel| {829
DEMO_CHANNEL_MENTIONS830
.iter()831
.any(|(id, _)| *id == channel.id)832
}) {833
channel.unread = true;834
}811
let _ = store.upsert_channels(&channels);835
let _ = store.upsert_channels(&channels);812
let _ = store.replace_team_layout(&demo_team_layout(&channels));836
let _ = store.replace_team_layout(&demo_team_layout(&channels));837
let _ = store.replace_channel_mentions(838
&DEMO_CHANNEL_MENTIONS839
.iter()840
.map(|(id, mentions)| ((*id).to_owned(), *mentions))841
.collect::<Vec<_>>(),842
);813
let _ = store.set_meta("me_user_id", DEMO_USER_ID);843
let _ = store.set_meta("me_user_id", DEMO_USER_ID);814
let _ = store.set_meta("me_display_name", DEMO_USER_NAME);844
let _ = store.set_meta("me_display_name", DEMO_USER_NAME);815
let _ = store.upsert_messages(&release_messages());845
let _ = store.upsert_messages(&release_messages());@@ -986,6 +1016,14 @@ pub fn seed_directory(state: &mut AppState) {986
}1016
}987
1017
988
fn seed_message_actions(state: &mut AppState) {1018
fn seed_message_actions(state: &mut AppState) {1019
state.pins.insert(1020
PINNED_CHANNEL.to_owned(),1021
vec![PinnedMessage {1022
message_id: PINNED_POST.to_owned(),1023
pinned_at: Some(at(0, 9, 45)),1024
parent_id: None,1025
}],1026
);989
state.pins.insert(1027
state.pins.insert(990
RELEASE_CHAT.to_owned(),1028
RELEASE_CHAT.to_owned(),991
vec![PinnedMessage {1029
vec![PinnedMessage {@@ -1386,6 +1424,7 @@ fn settings_card() -> serde_json::Value {1386
})1424
})1387
}1425
}1388
1426
1427
pub const DEMO_TENANT_ID: &str = "demo-tenant";1389
const DEMO_MEETING_LINK: &str = "https://teams.microsoft.com/l/meetup-join/19%3ameeting_ZGVtbw%40thread.v2/0?context=%7b%22Tid%22%3a%22demo-tenant%22%2c%22Oid%22%3a%22demo-mara%22%7d";1428
const DEMO_MEETING_LINK: &str = "https://teams.microsoft.com/l/meetup-join/19%3ameeting_ZGVtbw%40thread.v2/0?context=%7b%22Tid%22%3a%22demo-tenant%22%2c%22Oid%22%3a%22demo-mara%22%7d";1390
1429
1391
fn meeting_link_messages() -> Vec<MessageRecord> {1430
fn meeting_link_messages() -> Vec<MessageRecord> {@@ -9,12 +9,14 @@ pub mod card_actions;
9
9
pub mod card_inputs;
10
10
pub mod card_refresh;
11
11
pub mod card_state;
12
pub mod channel_menu;
12
13
pub mod chat_actions;
13
14
pub mod chat_filter;
14
15
pub mod find_in_chat;
15
16
pub mod chat_members;
16
17
pub mod connection_banner;
17
18
pub mod data;
19
pub mod default_reactions;
18
20
pub mod demo;
19
21
pub mod demo_meetings;
20
22
pub mod demo_profiles;
@@ -9,12 +9,14 @@ pub mod card_actions;9
pub mod card_inputs;9
pub mod card_inputs;10
pub mod card_refresh;10
pub mod card_refresh;11
pub mod card_state;11
pub mod card_state;12
pub mod channel_menu;12
pub mod chat_actions;13
pub mod chat_actions;13
pub mod chat_filter;14
pub mod chat_filter;14
pub mod find_in_chat;15
pub mod find_in_chat;15
pub mod chat_members;16
pub mod chat_members;16
pub mod connection_banner;17
pub mod connection_banner;17
pub mod data;18
pub mod data;19
pub mod default_reactions;18
pub mod demo;20
pub mod demo;19
pub mod demo_meetings;21
pub mod demo_meetings;20
pub mod demo_profiles;22
pub mod demo_profiles;@@ -6,6 +6,7 @@ use store::MessageRecord;
6
6
use teams_core::{PinnedMessage, SavedMessage};
7
7
8
8
use crate::app_state::{AppEvent, AppState, Selection, selection_for};
9
use crate::channel_menu::{post_pin_failure, post_pin_notice};
9
10
use crate::format;
10
11
use crate::image_view_gallery::ViewerRequest;
11
12
use crate::notice::short_error;
@@ -229,6 +230,7 @@ impl AppState {
229
230
let Some(engine_or_demo) = self.chat_action_engine(cx) else {
230
231
return;
231
232
};
233
let channel = self.channel_name(chat_id).is_some();
232
234
let previous = self.pinned_messages(chat_id).to_vec();
233
235
let parent_id = previous
234
236
.iter()
@@ -251,6 +253,9 @@ impl AppState {
251
253
}
252
254
self.store_pins(chat_id, updated, cx);
253
255
let Some(engine) = engine_or_demo else {
256
if channel {
257
self.raise_notice(post_pin_notice(pinned).to_owned(), None, cx);
258
}
254
259
return;
255
260
};
256
261
let (owned_chat, owned_message, revert_chat) = (
@@ -258,21 +263,35 @@ impl AppState {
258
263
message_id.to_owned(),
259
264
chat_id.to_owned(),
260
265
);
261
self.run_chat_action(
262
if pinned { "Pin" } else { "Unpin" },
263
async move {
264
if pinned {
265
engine.pin_message(&owned_chat, &owned_message).await
266
} else {
267
engine
268
.unpin_message(&owned_chat, &owned_message, parent_id.as_deref())
269
.await
270
}
271
},
272
move |state, cx| state.store_pins(&revert_chat, previous, cx),
273
|_, _| {},
274
cx,
275
);
266
let call = async move {
267
if pinned {
268
engine.pin_message(&owned_chat, &owned_message).await
269
} else {
270
engine
271
.unpin_message(&owned_chat, &owned_message, parent_id.as_deref())
272
.await
273
}
274
};
275
let revert = move |state: &mut Self, cx: &mut Context<Self>| {
276
state.store_pins(&revert_chat, previous, cx)
277
};
278
if channel {
279
self.run_channel_action(
280
post_pin_failure(pinned),
281
call,
282
revert,
283
Some(post_pin_notice(pinned)),
284
cx,
285
);
286
} else {
287
self.run_chat_action(
288
if pinned { "Pin" } else { "Unpin" },
289
call,
290
revert,
291
|_, _| {},
292
cx,
293
);
294
}
276
295
}
277
296
278
297
pub fn copy_message_link(
@@ -6,6 +6,7 @@ use store::MessageRecord;6
use teams_core::{PinnedMessage, SavedMessage};6
use teams_core::{PinnedMessage, SavedMessage};7
7
8
use crate::app_state::{AppEvent, AppState, Selection, selection_for};8
use crate::app_state::{AppEvent, AppState, Selection, selection_for};9
use crate::channel_menu::{post_pin_failure, post_pin_notice};9
use crate::format;10
use crate::format;10
use crate::image_view_gallery::ViewerRequest;11
use crate::image_view_gallery::ViewerRequest;11
use crate::notice::short_error;12
use crate::notice::short_error;@@ -229,6 +230,7 @@ impl AppState {229
let Some(engine_or_demo) = self.chat_action_engine(cx) else {230
let Some(engine_or_demo) = self.chat_action_engine(cx) else {230
return;231
return;231
};232
};233
let channel = self.channel_name(chat_id).is_some();232
let previous = self.pinned_messages(chat_id).to_vec();234
let previous = self.pinned_messages(chat_id).to_vec();233
let parent_id = previous235
let parent_id = previous234
.iter()236
.iter()@@ -251,6 +253,9 @@ impl AppState {251
}253
}252
self.store_pins(chat_id, updated, cx);254
self.store_pins(chat_id, updated, cx);253
let Some(engine) = engine_or_demo else {255
let Some(engine) = engine_or_demo else {256
if channel {257
self.raise_notice(post_pin_notice(pinned).to_owned(), None, cx);258
}254
return;259
return;255
};260
};256
let (owned_chat, owned_message, revert_chat) = (261
let (owned_chat, owned_message, revert_chat) = (@@ -258,21 +263,35 @@ impl AppState {258
message_id.to_owned(),263
message_id.to_owned(),259
chat_id.to_owned(),264
chat_id.to_owned(),260
);265
);261
self.run_chat_action(266
let call = async move {262
if pinned { "Pin" } else { "Unpin" },267
if pinned {263
async move {268
engine.pin_message(&owned_chat, &owned_message).await264
if pinned {269
} else {265
engine.pin_message(&owned_chat, &owned_message).await270
engine266
} else {271
.unpin_message(&owned_chat, &owned_message, parent_id.as_deref())267
engine272
.await268
.unpin_message(&owned_chat, &owned_message, parent_id.as_deref())273
}269
.await274
};270
}275
let revert = move |state: &mut Self, cx: &mut Context<Self>| {271
},276
state.store_pins(&revert_chat, previous, cx)272
move |state, cx| state.store_pins(&revert_chat, previous, cx),277
};273
|_, _| {},278
if channel {274
cx,279
self.run_channel_action(275
);280
post_pin_failure(pinned),281
call,282
revert,283
Some(post_pin_notice(pinned)),284
cx,285
);286
} else {287
self.run_chat_action(288
if pinned { "Pin" } else { "Unpin" },289
call,290
revert,291
|_, _| {},292
cx,293
);294
}276
}295
}277
296
278
pub fn copy_message_link(297
pub fn copy_message_link(@@ -347,6 +347,7 @@ mod tests {
347
347
.map(|id| (*id).to_owned())
348
348
.collect(),
349
349
notifications: HashMap::new(),
350
mentions: Default::default(),
350
351
}
351
352
}
352
353
@@ -347,6 +347,7 @@ mod tests {347
.map(|id| (*id).to_owned())347
.map(|id| (*id).to_owned())348
.collect(),348
.collect(),349
notifications: HashMap::new(),349
notifications: HashMap::new(),350
mentions: Default::default(),350
}351
}351
}352
}352
353
@@ -68,6 +68,7 @@ mod tests {
68
68
hidden: false,
69
69
hidden_channel_ids: vec!["channel-b".into()],
70
70
notifications: Default::default(),
71
mentions: Default::default(),
71
72
}],
72
73
}
73
74
}
@@ -68,6 +68,7 @@ mod tests {68
hidden: false,68
hidden: false,69
hidden_channel_ids: vec!["channel-b".into()],69
hidden_channel_ids: vec!["channel-b".into()],70
notifications: Default::default(),70
notifications: Default::default(),71
mentions: Default::default(),71
}],72
}],72
}73
}73
}74
}@@ -120,11 +120,33 @@ impl AppState {
120
120
}
121
121
122
122
pub fn open_chat_with(&mut self, user_id: &str, cx: &mut Context<Self>) {
123
self.with_one_on_one(user_id, cx, |state, chat_id, cx| {
124
state.select(Selection::Chat(chat_id.to_owned()), cx)
125
});
126
}
127
128
/// Teams starts a 1:1 call from the profile card; the 1:1 chat is the call thread.
129
pub fn call_person(&mut self, user_id: &str, with_video: bool, cx: &mut Context<Self>) {
130
self.with_one_on_one(user_id, cx, move |state, chat_id, cx| {
131
if with_video {
132
state.start_chat_video_call(chat_id, cx);
133
} else {
134
state.start_chat_call(chat_id, cx);
135
}
136
});
137
}
138
139
fn with_one_on_one(
140
&mut self,
141
user_id: &str,
142
cx: &mut Context<Self>,
143
then: impl FnOnce(&mut Self, &str, &mut Context<Self>) + 'static,
144
) {
123
145
let existing =
124
146
existing_one_on_one(&self.sidebar.chats, self.directory.me.as_ref(), user_id)
125
147
.map(|chat| chat.id.clone());
126
148
if let Some(chat_id) = existing {
127
self.select(Selection::Chat(chat_id), cx);
149
then(self, &chat_id, cx);
128
150
return;
129
151
}
130
152
if self.mode.read_only {
@@ -149,7 +171,7 @@ impl AppState {
149
171
this.update(cx, |state, cx| match outcome {
150
172
Ok(chat_id) => {
151
173
state.reload_sidebar(cx);
152
state.select(Selection::Chat(chat_id), cx);
174
then(state, &chat_id, cx);
153
175
}
154
176
Err(reason) => {
155
177
state.raise_notice(format!("Chat could not be opened: {reason}"), None, cx)
@@ -120,11 +120,33 @@ impl AppState {120
}120
}121
121
122
pub fn open_chat_with(&mut self, user_id: &str, cx: &mut Context<Self>) {122
pub fn open_chat_with(&mut self, user_id: &str, cx: &mut Context<Self>) {123
self.with_one_on_one(user_id, cx, |state, chat_id, cx| {124
state.select(Selection::Chat(chat_id.to_owned()), cx)125
});126
}127
128
/// Teams starts a 1:1 call from the profile card; the 1:1 chat is the call thread.129
pub fn call_person(&mut self, user_id: &str, with_video: bool, cx: &mut Context<Self>) {130
self.with_one_on_one(user_id, cx, move |state, chat_id, cx| {131
if with_video {132
state.start_chat_video_call(chat_id, cx);133
} else {134
state.start_chat_call(chat_id, cx);135
}136
});137
}138
139
fn with_one_on_one(140
&mut self,141
user_id: &str,142
cx: &mut Context<Self>,143
then: impl FnOnce(&mut Self, &str, &mut Context<Self>) + 'static,144
) {123
let existing =145
let existing =124
existing_one_on_one(&self.sidebar.chats, self.directory.me.as_ref(), user_id)146
existing_one_on_one(&self.sidebar.chats, self.directory.me.as_ref(), user_id)125
.map(|chat| chat.id.clone());147
.map(|chat| chat.id.clone());126
if let Some(chat_id) = existing {148
if let Some(chat_id) = existing {127
self.select(Selection::Chat(chat_id), cx);149
then(self, &chat_id, cx);128
return;150
return;129
}151
}130
if self.mode.read_only {152
if self.mode.read_only {@@ -149,7 +171,7 @@ impl AppState {149
this.update(cx, |state, cx| match outcome {171
this.update(cx, |state, cx| match outcome {150
Ok(chat_id) => {172
Ok(chat_id) => {151
state.reload_sidebar(cx);173
state.reload_sidebar(cx);152
state.select(Selection::Chat(chat_id), cx);174
then(state, &chat_id, cx);153
}175
}154
Err(reason) => {176
Err(reason) => {155
state.raise_notice(format!("Chat could not be opened: {reason}"), None, cx)177
state.raise_notice(format!("Chat could not be opened: {reason}"), None, cx)@@ -1,9 +1,9 @@
1
1
use std::collections::{HashMap, HashSet};
2
2
3
use app_ui_kit::widgets::Unread;
3
4
use chrono::{DateTime, FixedOffset, Utc};
4
5
use store::{ChannelRecord, ChatRecord, Sidebar, SidebarTeam, is_bot_id};
5
6
use teams_core::{ChatSection, is_event_preview};
6
use app_ui_kit::widgets::Unread;
7
7
8
8
use crate::app_state::chat_title;
9
9
use crate::data::{
@@ -260,10 +260,82 @@ pub fn channel_name_style(unread: bool, shown: bool, selected: bool) -> NameStyl
260
260
}
261
261
}
262
262
263
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
264
pub enum MentionBadge {
265
Count(u32),
266
Channel,
267
Team,
268
}
269
270
/// Teams pulls a hidden channel into the list while it holds personal @mentions.
271
pub fn channel_shown(team: &SidebarTeam, channel_id: &str) -> bool {
272
!team.hidden_channel_ids.iter().any(|id| id == channel_id)
273
|| team.channel_mentions(channel_id).personal > 0
274
}
275
276
pub fn channel_hoisted(team: &SidebarTeam, channel_id: &str) -> bool {
277
team.hidden_channel_ids.iter().any(|id| id == channel_id)
278
&& team.channel_mentions(channel_id).personal > 0
279
}
280
281
pub fn team_hoisted(team: &SidebarTeam) -> bool {
282
team.hidden
283
&& team
284
.channels
285
.iter()
286
.any(|channel| channel_hoisted(team, &channel.id))
287
}
288
289
pub fn channel_badge(team: &SidebarTeam, channel_id: &str) -> Option<MentionBadge> {
290
let mentions = team.channel_mentions(channel_id);
291
if mentions.personal > 0 {
292
Some(MentionBadge::Count(mentions.personal))
293
} else if mentions.channel > 0 {
294
Some(MentionBadge::Channel)
295
} else if mentions.team > 0 {
296
Some(MentionBadge::Team)
297
} else {
298
None
299
}
300
}
301
302
/// The collapsed team row sums personal mentions of every channel, the icons only of shown channels.
303
pub fn team_badge(team: &SidebarTeam, expanded: bool) -> Option<MentionBadge> {
304
if expanded || !team_has_unread(team) {
305
return None;
306
}
307
let personal: u32 = team
308
.mentions
309
.iter()
310
.filter(|(channel_id, _)| {
311
team.channels
312
.iter()
313
.any(|channel| &channel.id == *channel_id)
314
})
315
.map(|(_, mentions)| mentions.personal)
316
.sum();
317
if personal > 0 {
318
return Some(MentionBadge::Count(personal));
319
}
320
let shown = || {
321
team.channels
322
.iter()
323
.filter(|channel| channel_shown(team, &channel.id))
324
.map(|channel| team.channel_mentions(&channel.id))
325
};
326
if shown().any(|mentions| mentions.channel > 0) {
327
Some(MentionBadge::Channel)
328
} else if shown().any(|mentions| mentions.team > 0) {
329
Some(MentionBadge::Team)
330
} else {
331
None
332
}
333
}
334
263
335
pub fn team_has_unread(team: &SidebarTeam) -> bool {
264
336
team.channels
265
337
.iter()
266
.any(|channel| channel.unread && !team.hidden_channel_ids.contains(&channel.id))
338
.any(|channel| channel.unread && channel_shown(team, &channel.id))
267
339
}
268
340
269
341
pub fn team_name_style(team: &SidebarTeam, expanded: bool) -> NameStyle {
@@ -471,40 +543,89 @@ pub fn visible_channel_ids<'a>(input: &ChannelOrderInput<'a>) -> Vec<&'a str> {
471
543
.teams
472
544
.iter()
473
545
.any(|entry| entry.hidden && holds_selection(entry));
474
let teams = input.teams.iter().filter(|entry| !entry.hidden).chain(
475
input
476
.teams
477
.iter()
478
.filter(|entry| entry.hidden && hidden_teams_shown),
479
);
480
for entry in teams {
546
let main_teams = input
547
.teams
548
.iter()
549
.filter(|entry| !entry.hidden || team_hoisted(entry))
550
.map(|entry| (entry, entry.hidden));
551
let hidden_teams = input
552
.teams
553
.iter()
554
.filter(|entry| entry.hidden && hidden_teams_shown)
555
.map(|entry| (entry, false));
556
for (entry, hoisted_only) in main_teams.chain(hidden_teams) {
481
557
if input.collapsed_teams.contains(&entry.team.id) {
482
558
continue;
483
559
}
484
let is_hidden = |channel: &ChannelRecord| entry.hidden_channel_ids.contains(&channel.id);
485
let is_selected =
486
|channel: &ChannelRecord| Some(channel.id.as_str()) == input.selected_channel;
487
let revealed = input.revealed_channel_teams.contains(&entry.team.id);
488
for channel in entry
489
.channels
490
.iter()
491
.filter(|channel| !is_hidden(channel) || is_selected(channel))
492
{
493
push(&channel.id);
494
}
495
if revealed {
496
for channel in entry
497
.channels
498
.iter()
499
.filter(|channel| is_hidden(channel) && !is_selected(channel))
500
{
501
push(&channel.id);
502
}
560
for channel_id in team_channel_ids(entry, hoisted_only, input) {
561
push(channel_id);
503
562
}
504
563
}
505
564
ids
506
565
}
507
566
567
fn team_channel_ids<'a>(
568
entry: &'a SidebarTeam,
569
hoisted_only: bool,
570
input: &ChannelOrderInput<'_>,
571
) -> Vec<&'a str> {
572
let is_selected = |channel: &ChannelRecord| Some(channel.id.as_str()) == input.selected_channel;
573
let rows = team_channel_rows(
574
entry,
575
hoisted_only,
576
input.revealed_channel_teams.contains(&entry.team.id),
577
is_selected,
578
);
579
rows.shown
580
.into_iter()
581
.chain(rows.revealed)
582
.map(|channel| channel.id.as_str())
583
.collect()
584
}
585
586
pub struct TeamChannelRows<'a> {
587
pub shown: Vec<&'a ChannelRecord>,
588
pub hidden_count: usize,
589
pub revealed: Vec<&'a ChannelRecord>,
590
}
591
592
/// `hoisted_only` is a hidden team pulled into the main list: it shows only its hoisted channels.
593
pub fn team_channel_rows<'a>(
594
entry: &'a SidebarTeam,
595
hoisted_only: bool,
596
revealed: bool,
597
is_selected: impl Fn(&ChannelRecord) -> bool,
598
) -> TeamChannelRows<'a> {
599
let shown: Vec<&ChannelRecord> = entry
600
.channels
601
.iter()
602
.filter(|channel| {
603
if hoisted_only {
604
channel_hoisted(entry, &channel.id)
605
} else {
606
is_selected(channel) || channel_shown(entry, &channel.id)
607
}
608
})
609
.collect();
610
if hoisted_only {
611
return TeamChannelRows {
612
shown,
613
hidden_count: 0,
614
revealed: Vec::new(),
615
};
616
}
617
let hidden: Vec<&ChannelRecord> = entry
618
.channels
619
.iter()
620
.filter(|channel| !shown.iter().any(|row| row.id == channel.id))
621
.collect();
622
TeamChannelRows {
623
shown,
624
hidden_count: hidden.len(),
625
revealed: if revealed { hidden } else { Vec::new() },
626
}
627
}
628
508
629
fn section(
509
630
id: String,
510
631
name: String,
@@ -746,6 +867,7 @@ mod tests {
746
867
.map(|id| (*id).to_owned())
747
868
.collect(),
748
869
notifications: HashMap::new(),
870
mentions: Default::default(),
749
871
}
750
872
}
751
873
@@ -857,6 +979,111 @@ mod tests {
857
979
);
858
980
}
859
981
982
fn with_mentions(mut entry: SidebarTeam, mentions: &[(&str, u32, u32, u32)]) -> SidebarTeam {
983
for (channel_id, personal, channel, team) in mentions {
984
entry.mentions.insert(
985
(*channel_id).to_owned(),
986
store::ChannelMentions {
987
personal: *personal,
988
channel: *channel,
989
team: *team,
990
},
991
);
992
}
993
entry
994
}
995
996
#[test]
997
fn channel_badges_prefer_the_count_then_channel_then_team() {
998
let entry = with_mentions(
999
team("t", false, &["a", "b", "c", "d"], &[]),
1000
&[("a", 2, 1, 1), ("b", 0, 3, 1), ("c", 0, 0, 1)],
1001
);
1002
assert_eq!(channel_badge(&entry, "a"), Some(MentionBadge::Count(2)));
1003
assert_eq!(channel_badge(&entry, "b"), Some(MentionBadge::Channel));
1004
assert_eq!(channel_badge(&entry, "c"), Some(MentionBadge::Team));
1005
assert_eq!(channel_badge(&entry, "d"), None);
1006
}
1007
1008
#[test]
1009
fn the_collapsed_team_sums_counts_of_all_channels_and_icons_of_shown_ones() {
1010
let entry = with_unread(
1011
with_mentions(
1012
team("t", false, &["a", "b", "c"], &["b", "c"]),
1013
&[("a", 1, 0, 0), ("b", 2, 0, 0), ("c", 0, 1, 0)],
1014
),
1015
&["a", "b", "c"],
1016
);
1017
assert_eq!(team_badge(&entry, false), Some(MentionBadge::Count(3)));
1018
assert_eq!(team_badge(&entry, true), None);
1019
let icons_only = with_unread(
1020
with_mentions(
1021
team("t", false, &["a", "c"], &["c"]),
1022
&[("a", 0, 0, 1), ("c", 0, 1, 0)],
1023
),
1024
&["a", "c"],
1025
);
1026
assert_eq!(team_badge(&icons_only, false), Some(MentionBadge::Team));
1027
let read = with_mentions(team("t", false, &["a"], &[]), &[("a", 1, 0, 0)]);
1028
assert_eq!(team_badge(&read, false), None);
1029
}
1030
1031
#[test]
1032
fn a_hidden_channel_with_a_personal_mention_is_pulled_into_the_list() {
1033
let entry = with_unread(
1034
with_mentions(
1035
team("t", false, &["a", "b", "c"], &["b", "c"]),
1036
&[("b", 1, 0, 0), ("c", 0, 1, 0)],
1037
),
1038
&["b", "c"],
1039
);
1040
assert!(channel_shown(&entry, "b"));
1041
assert!(!channel_shown(&entry, "c"));
1042
assert!(team_has_unread(&entry));
1043
let rows = team_channel_rows(&entry, false, false, |_| false);
1044
let shown: Vec<&str> = rows
1045
.shown
1046
.iter()
1047
.map(|channel| channel.id.as_str())
1048
.collect();
1049
assert_eq!(shown, ["a", "b"]);
1050
assert_eq!(rows.hidden_count, 1);
1051
assert!(rows.revealed.is_empty());
1052
}
1053
1054
#[test]
1055
fn a_hidden_team_with_a_hoisted_channel_shows_only_that_channel_in_the_main_list() {
1056
let teams = [
1057
team("t1", false, &["a"], &[]),
1058
with_mentions(team("t2", true, &["b", "c"], &["c"]), &[("c", 1, 0, 0)]),
1059
];
1060
assert!(team_hoisted(&teams[1]));
1061
assert!(!team_hoisted(&teams[0]));
1062
let rows = team_channel_rows(&teams[1], true, true, |_| true);
1063
let shown: Vec<&str> = rows
1064
.shown
1065
.iter()
1066
.map(|channel| channel.id.as_str())
1067
.collect();
1068
assert_eq!(shown, ["c"]);
1069
assert_eq!(rows.hidden_count, 0);
1070
let empty = HashSet::new();
1071
let input = ChannelOrderInput {
1072
teams: &teams,
1073
pinned_ids: &[],
1074
collapsed_teams: &empty,
1075
revealed_channel_teams: &empty,
1076
hidden_teams_open: false,
1077
selected_channel: None,
1078
};
1079
assert_eq!(visible_channel_ids(&input), ["a", "c"]);
1080
let open = ChannelOrderInput {
1081
hidden_teams_open: true,
1082
..input
1083
};
1084
assert_eq!(visible_channel_ids(&open), ["a", "c", "b"]);
1085
}
1086
860
1087
#[test]
861
1088
fn muted_chats_stay_out_of_unread_counts() {
862
1089
let mut quiet = chat("a", "group", true);
@@ -1036,7 +1263,10 @@ mod tests {
1036
1263
let group = chat_item(&chats[1], &context, None);
1037
1264
assert_eq!(group.presence_user, None);
1038
1265
assert!(matches!(group.avatar, AvatarSpec::Pair(..)));
1039
assert_eq!(avatar_for(&meeting_chat("meeting-1"), None), AvatarSpec::Meeting);
1266
assert_eq!(
1267
avatar_for(&meeting_chat("meeting-1"), None),
1268
AvatarSpec::Meeting
1269
);
1040
1270
}
1041
1271
1042
1272
#[test]
@@ -1048,7 +1278,9 @@ mod tests {
1048
1278
let collapsed = HashSet::new();
1049
1279
let mut notes = chat(teams_core::NOTES_CHAT_ID, "oneOnOne", false);
1050
1280
notes.title = "Me Myself (You)".into();
1051
notes.members.retain(|member| member.user_id.as_deref() == Some("me"));
1281
notes
1282
.members
1283
.retain(|member| member.user_id.as_deref() == Some("me"));
1052
1284
let chats = vec![notes];
1053
1285
let context = input(&chats, &directory, &collapsed);
1054
1286
let item = chat_item(&chats[0], &context, None);
@@ -1,9 +1,9 @@1
use std::collections::{HashMap, HashSet};1
use std::collections::{HashMap, HashSet};2
2
3
use app_ui_kit::widgets::Unread;3
use chrono::{DateTime, FixedOffset, Utc};4
use chrono::{DateTime, FixedOffset, Utc};4
use store::{ChannelRecord, ChatRecord, Sidebar, SidebarTeam, is_bot_id};5
use store::{ChannelRecord, ChatRecord, Sidebar, SidebarTeam, is_bot_id};5
use teams_core::{ChatSection, is_event_preview};6
use teams_core::{ChatSection, is_event_preview};6
use app_ui_kit::widgets::Unread;7
7
8
use crate::app_state::chat_title;8
use crate::app_state::chat_title;9
use crate::data::{9
use crate::data::{@@ -260,10 +260,82 @@ pub fn channel_name_style(unread: bool, shown: bool, selected: bool) -> NameStyl260
}260
}261
}261
}262
262
263
#[derive(Debug, Clone, Copy, PartialEq, Eq)]264
pub enum MentionBadge {265
Count(u32),266
Channel,267
Team,268
}269
270
/// Teams pulls a hidden channel into the list while it holds personal @mentions.271
pub fn channel_shown(team: &SidebarTeam, channel_id: &str) -> bool {272
!team.hidden_channel_ids.iter().any(|id| id == channel_id)273
|| team.channel_mentions(channel_id).personal > 0274
}275
276
pub fn channel_hoisted(team: &SidebarTeam, channel_id: &str) -> bool {277
team.hidden_channel_ids.iter().any(|id| id == channel_id)278
&& team.channel_mentions(channel_id).personal > 0279
}280
281
pub fn team_hoisted(team: &SidebarTeam) -> bool {282
team.hidden283
&& team284
.channels285
.iter()286
.any(|channel| channel_hoisted(team, &channel.id))287
}288
289
pub fn channel_badge(team: &SidebarTeam, channel_id: &str) -> Option<MentionBadge> {290
let mentions = team.channel_mentions(channel_id);291
if mentions.personal > 0 {292
Some(MentionBadge::Count(mentions.personal))293
} else if mentions.channel > 0 {294
Some(MentionBadge::Channel)295
} else if mentions.team > 0 {296
Some(MentionBadge::Team)297
} else {298
None299
}300
}301
302
/// The collapsed team row sums personal mentions of every channel, the icons only of shown channels.303
pub fn team_badge(team: &SidebarTeam, expanded: bool) -> Option<MentionBadge> {304
if expanded || !team_has_unread(team) {305
return None;306
}307
let personal: u32 = team308
.mentions309
.iter()310
.filter(|(channel_id, _)| {311
team.channels312
.iter()313
.any(|channel| &channel.id == *channel_id)314
})315
.map(|(_, mentions)| mentions.personal)316
.sum();317
if personal > 0 {318
return Some(MentionBadge::Count(personal));319
}320
let shown = || {321
team.channels322
.iter()323
.filter(|channel| channel_shown(team, &channel.id))324
.map(|channel| team.channel_mentions(&channel.id))325
};326
if shown().any(|mentions| mentions.channel > 0) {327
Some(MentionBadge::Channel)328
} else if shown().any(|mentions| mentions.team > 0) {329
Some(MentionBadge::Team)330
} else {331
None332
}333
}334
263
pub fn team_has_unread(team: &SidebarTeam) -> bool {335
pub fn team_has_unread(team: &SidebarTeam) -> bool {264
team.channels336
team.channels265
.iter()337
.iter()266
.any(|channel| channel.unread && !team.hidden_channel_ids.contains(&channel.id))338
.any(|channel| channel.unread && channel_shown(team, &channel.id))267
}339
}268
340
269
pub fn team_name_style(team: &SidebarTeam, expanded: bool) -> NameStyle {341
pub fn team_name_style(team: &SidebarTeam, expanded: bool) -> NameStyle {@@ -471,40 +543,89 @@ pub fn visible_channel_ids<'a>(input: &ChannelOrderInput<'a>) -> Vec<&'a str> {471
.teams543
.teams472
.iter()544
.iter()473
.any(|entry| entry.hidden && holds_selection(entry));545
.any(|entry| entry.hidden && holds_selection(entry));474
let teams = input.teams.iter().filter(|entry| !entry.hidden).chain(546
let main_teams = input475
input547
.teams476
.teams548
.iter()477
.iter()549
.filter(|entry| !entry.hidden || team_hoisted(entry))478
.filter(|entry| entry.hidden && hidden_teams_shown),550
.map(|entry| (entry, entry.hidden));479
);551
let hidden_teams = input480
for entry in teams {552
.teams553
.iter()554
.filter(|entry| entry.hidden && hidden_teams_shown)555
.map(|entry| (entry, false));556
for (entry, hoisted_only) in main_teams.chain(hidden_teams) {481
if input.collapsed_teams.contains(&entry.team.id) {557
if input.collapsed_teams.contains(&entry.team.id) {482
continue;558
continue;483
}559
}484
let is_hidden = |channel: &ChannelRecord| entry.hidden_channel_ids.contains(&channel.id);560
for channel_id in team_channel_ids(entry, hoisted_only, input) {485
let is_selected =561
push(channel_id);486
|channel: &ChannelRecord| Some(channel.id.as_str()) == input.selected_channel;487
let revealed = input.revealed_channel_teams.contains(&entry.team.id);488
for channel in entry489
.channels490
.iter()491
.filter(|channel| !is_hidden(channel) || is_selected(channel))492
{493
push(&channel.id);494
}495
if revealed {496
for channel in entry497
.channels498
.iter()499
.filter(|channel| is_hidden(channel) && !is_selected(channel))500
{501
push(&channel.id);502
}503
}562
}504
}563
}505
ids564
ids506
}565
}507
566
567
fn team_channel_ids<'a>(568
entry: &'a SidebarTeam,569
hoisted_only: bool,570
input: &ChannelOrderInput<'_>,571
) -> Vec<&'a str> {572
let is_selected = |channel: &ChannelRecord| Some(channel.id.as_str()) == input.selected_channel;573
let rows = team_channel_rows(574
entry,575
hoisted_only,576
input.revealed_channel_teams.contains(&entry.team.id),577
is_selected,578
);579
rows.shown580
.into_iter()581
.chain(rows.revealed)582
.map(|channel| channel.id.as_str())583
.collect()584
}585
586
pub struct TeamChannelRows<'a> {587
pub shown: Vec<&'a ChannelRecord>,588
pub hidden_count: usize,589
pub revealed: Vec<&'a ChannelRecord>,590
}591
592
/// `hoisted_only` is a hidden team pulled into the main list: it shows only its hoisted channels.593
pub fn team_channel_rows<'a>(594
entry: &'a SidebarTeam,595
hoisted_only: bool,596
revealed: bool,597
is_selected: impl Fn(&ChannelRecord) -> bool,598
) -> TeamChannelRows<'a> {599
let shown: Vec<&ChannelRecord> = entry600
.channels601
.iter()602
.filter(|channel| {603
if hoisted_only {604
channel_hoisted(entry, &channel.id)605
} else {606
is_selected(channel) || channel_shown(entry, &channel.id)607
}608
})609
.collect();610
if hoisted_only {611
return TeamChannelRows {612
shown,613
hidden_count: 0,614
revealed: Vec::new(),615
};616
}617
let hidden: Vec<&ChannelRecord> = entry618
.channels619
.iter()620
.filter(|channel| !shown.iter().any(|row| row.id == channel.id))621
.collect();622
TeamChannelRows {623
shown,624
hidden_count: hidden.len(),625
revealed: if revealed { hidden } else { Vec::new() },626
}627
}628
508
fn section(629
fn section(509
id: String,630
id: String,510
name: String,631
name: String,@@ -746,6 +867,7 @@ mod tests {746
.map(|id| (*id).to_owned())867
.map(|id| (*id).to_owned())747
.collect(),868
.collect(),748
notifications: HashMap::new(),869
notifications: HashMap::new(),870
mentions: Default::default(),749
}871
}750
}872
}751
873
@@ -857,6 +979,111 @@ mod tests {857
);979
);858
}980
}859
981
982
fn with_mentions(mut entry: SidebarTeam, mentions: &[(&str, u32, u32, u32)]) -> SidebarTeam {983
for (channel_id, personal, channel, team) in mentions {984
entry.mentions.insert(985
(*channel_id).to_owned(),986
store::ChannelMentions {987
personal: *personal,988
channel: *channel,989
team: *team,990
},991
);992
}993
entry994
}995
996
#[test]997
fn channel_badges_prefer_the_count_then_channel_then_team() {998
let entry = with_mentions(999
team("t", false, &["a", "b", "c", "d"], &[]),1000
&[("a", 2, 1, 1), ("b", 0, 3, 1), ("c", 0, 0, 1)],1001
);1002
assert_eq!(channel_badge(&entry, "a"), Some(MentionBadge::Count(2)));1003
assert_eq!(channel_badge(&entry, "b"), Some(MentionBadge::Channel));1004
assert_eq!(channel_badge(&entry, "c"), Some(MentionBadge::Team));1005
assert_eq!(channel_badge(&entry, "d"), None);1006
}1007
1008
#[test]1009
fn the_collapsed_team_sums_counts_of_all_channels_and_icons_of_shown_ones() {1010
let entry = with_unread(1011
with_mentions(1012
team("t", false, &["a", "b", "c"], &["b", "c"]),1013
&[("a", 1, 0, 0), ("b", 2, 0, 0), ("c", 0, 1, 0)],1014
),1015
&["a", "b", "c"],1016
);1017
assert_eq!(team_badge(&entry, false), Some(MentionBadge::Count(3)));1018
assert_eq!(team_badge(&entry, true), None);1019
let icons_only = with_unread(1020
with_mentions(1021
team("t", false, &["a", "c"], &["c"]),1022
&[("a", 0, 0, 1), ("c", 0, 1, 0)],1023
),1024
&["a", "c"],1025
);1026
assert_eq!(team_badge(&icons_only, false), Some(MentionBadge::Team));1027
let read = with_mentions(team("t", false, &["a"], &[]), &[("a", 1, 0, 0)]);1028
assert_eq!(team_badge(&read, false), None);1029
}1030
1031
#[test]1032
fn a_hidden_channel_with_a_personal_mention_is_pulled_into_the_list() {1033
let entry = with_unread(1034
with_mentions(1035
team("t", false, &["a", "b", "c"], &["b", "c"]),1036
&[("b", 1, 0, 0), ("c", 0, 1, 0)],1037
),1038
&["b", "c"],1039
);1040
assert!(channel_shown(&entry, "b"));1041
assert!(!channel_shown(&entry, "c"));1042
assert!(team_has_unread(&entry));1043
let rows = team_channel_rows(&entry, false, false, |_| false);1044
let shown: Vec<&str> = rows1045
.shown1046
.iter()1047
.map(|channel| channel.id.as_str())1048
.collect();1049
assert_eq!(shown, ["a", "b"]);1050
assert_eq!(rows.hidden_count, 1);1051
assert!(rows.revealed.is_empty());1052
}1053
1054
#[test]1055
fn a_hidden_team_with_a_hoisted_channel_shows_only_that_channel_in_the_main_list() {1056
let teams = [1057
team("t1", false, &["a"], &[]),1058
with_mentions(team("t2", true, &["b", "c"], &["c"]), &[("c", 1, 0, 0)]),1059
];1060
assert!(team_hoisted(&teams[1]));1061
assert!(!team_hoisted(&teams[0]));1062
let rows = team_channel_rows(&teams[1], true, true, |_| true);1063
let shown: Vec<&str> = rows1064
.shown1065
.iter()1066
.map(|channel| channel.id.as_str())1067
.collect();1068
assert_eq!(shown, ["c"]);1069
assert_eq!(rows.hidden_count, 0);1070
let empty = HashSet::new();1071
let input = ChannelOrderInput {1072
teams: &teams,1073
pinned_ids: &[],1074
collapsed_teams: &empty,1075
revealed_channel_teams: &empty,1076
hidden_teams_open: false,1077
selected_channel: None,1078
};1079
assert_eq!(visible_channel_ids(&input), ["a", "c"]);1080
let open = ChannelOrderInput {1081
hidden_teams_open: true,1082
..input1083
};1084
assert_eq!(visible_channel_ids(&open), ["a", "c", "b"]);1085
}1086
860
#[test]1087
#[test]861
fn muted_chats_stay_out_of_unread_counts() {1088
fn muted_chats_stay_out_of_unread_counts() {862
let mut quiet = chat("a", "group", true);1089
let mut quiet = chat("a", "group", true);@@ -1036,7 +1263,10 @@ mod tests {1036
let group = chat_item(&chats[1], &context, None);1263
let group = chat_item(&chats[1], &context, None);1037
assert_eq!(group.presence_user, None);1264
assert_eq!(group.presence_user, None);1038
assert!(matches!(group.avatar, AvatarSpec::Pair(..)));1265
assert!(matches!(group.avatar, AvatarSpec::Pair(..)));1039
assert_eq!(avatar_for(&meeting_chat("meeting-1"), None), AvatarSpec::Meeting);1266
assert_eq!(1267
avatar_for(&meeting_chat("meeting-1"), None),1268
AvatarSpec::Meeting1269
);1040
}1270
}1041
1271
1042
#[test]1272
#[test]@@ -1048,7 +1278,9 @@ mod tests {1048
let collapsed = HashSet::new();1278
let collapsed = HashSet::new();1049
let mut notes = chat(teams_core::NOTES_CHAT_ID, "oneOnOne", false);1279
let mut notes = chat(teams_core::NOTES_CHAT_ID, "oneOnOne", false);1050
notes.title = "Me Myself (You)".into();1280
notes.title = "Me Myself (You)".into();1051
notes.members.retain(|member| member.user_id.as_deref() == Some("me"));1281
notes1282
.members1283
.retain(|member| member.user_id.as_deref() == Some("me"));1052
let chats = vec![notes];1284
let chats = vec![notes];1053
let context = input(&chats, &directory, &collapsed);1285
let context = input(&chats, &directory, &collapsed);1054
let item = chat_item(&chats[0], &context, None);1286
let item = chat_item(&chats[0], &context, None);@@ -180,11 +180,16 @@ mod frames {
180
180
COMPOSER_BOX_TAG, COMPOSER_FORMAT_BAR_TAG, COMPOSER_FORMAT_DIVIDER_TAG,
181
181
COMPOSER_FORMAT_TAG, COMPOSER_LEADING_TAG, COMPOSER_SEND_TAG,
182
182
};
183
use crate::views::conversation::{HEADER_DIVIDER, MEMBERS_BUTTON};
183
use crate::views::conversation::{
184
CHANNEL_DETAILS_BUTTON, CHANNEL_DETAILS_PINNED_TAG, CHANNEL_DETAILS_SHARED_TAG,
185
CHANNEL_DETAILS_TAG,
186
};
187
use crate::views::conversation::{HEADER_DIVIDER, MEMBERS_BUTTON, TIMELINE_TAG};
184
188
use crate::views::find_panel::{
185
189
FIND_DIVIDER_TAG, FIND_INPUT_TAG, FIND_PANEL_TAG, FIND_RESULTS_TAG,
186
190
};
187
191
use crate::views::message_row::BUBBLE_TAGS;
192
use crate::views::pin_banner::PIN_BANNER_TAG;
188
193
use crate::views::proposal_card::{PROPOSAL_BUTTONS, PROPOSAL_CARD, PROPOSAL_THUMBNAILS};
189
194
use crate::views::reaction_proposal_pill::REACTION_PILL;
190
195
use crate::views::recap_tab::RECAP_REGION;
@@ -1476,6 +1481,128 @@ mod frames {
1476
1481
}
1477
1482
}
1478
1483
1484
const PINNED_CHAT: &str = "demo-chat-release";
1485
const PINNED_CHANNEL: &str = "demo-channel-1-1";
1486
1487
#[gpui_kit::test]
1488
fn the_pin_banner_top_gap_matches_its_side_gaps(cx: &mut TestAppContext) {
1489
let (handle, state) = mount(cx);
1490
let mut visual = VisualTestContext::from_window(handle, cx);
1491
let mut found = Vec::new();
1492
for (width, height) in SIZES {
1493
visual.simulate_resize(size(px(width), px(height)));
1494
visual.update(|_, cx| {
1495
state.update(cx, |state, cx| {
1496
state.select(Selection::Chat(PINNED_CHAT.to_owned()), cx)
1497
})
1498
});
1499
collect(&mut visual, Some(PIN_BANNER_TAG));
1500
let banner = visual.debug_bounds(PIN_BANNER_TAG).expect("pin banner");
1501
let timeline = visual.debug_bounds(TIMELINE_TAG).expect("timeline");
1502
let divider = visual.debug_bounds(HEADER_DIVIDER).expect("header divider");
1503
let gaps = [
1504
("top", f32::from(banner.top() - timeline.top())),
1505
("left", f32::from(banner.left() - timeline.left())),
1506
("right", f32::from(timeline.right() - banner.right())),
1507
("below divider", f32::from(banner.top() - divider.bottom())),
1508
];
1509
let side = gaps[1].1;
1510
if gaps
1511
.iter()
1512
.any(|(_, gap)| (gap - side).abs() > INSET_TOLERANCE)
1513
{
1514
found.push(format!(
1515
"pin banner@{width}x{height}: gaps {gaps:?} must match"
1516
));
1517
}
1518
}
1519
assert!(found.is_empty(), "{}", found.join("\n"));
1520
}
1521
1522
#[gpui_kit::test]
1523
fn channels_show_no_pin_banner_like_teams(cx: &mut TestAppContext) {
1524
let (handle, state) = mount(cx);
1525
let mut visual = VisualTestContext::from_window(handle, cx);
1526
visual.simulate_resize(size(px(1280.), px(800.)));
1527
visual.update(|_, cx| {
1528
state.update(cx, |state, cx| {
1529
state.select(Selection::Channel(PINNED_CHANNEL.to_owned()), cx)
1530
})
1531
});
1532
collect(&mut visual, Some(TIMELINE_TAG));
1533
assert!(visual.debug_bounds(PIN_BANNER_TAG).is_none());
1534
}
1535
1536
#[gpui_kit::test]
1537
fn the_channel_details_pane_lists_pinned_posts_inside_the_main_island(cx: &mut TestAppContext) {
1538
let (handle, state) = mount(cx);
1539
let mut visual = VisualTestContext::from_window(handle, cx);
1540
visual.simulate_resize(size(px(1280.), px(800.)));
1541
visual.update(|_, cx| {
1542
state.update(cx, |state, cx| {
1543
state.select(Selection::Channel(PINNED_CHANNEL.to_owned()), cx)
1544
})
1545
});
1546
collect(&mut visual, Some(CHANNEL_DETAILS_BUTTON));
1547
let button = visual
1548
.debug_bounds(CHANNEL_DETAILS_BUTTON)
1549
.expect("channel details button");
1550
visual.simulate_click(button.center(), Default::default());
1551
collect(&mut visual, Some(CHANNEL_DETAILS_TAG));
1552
let pane = visual
1553
.debug_bounds(CHANNEL_DETAILS_TAG)
1554
.expect("details pane");
1555
let main = visual.debug_bounds(MAIN).expect("main island");
1556
let divider = visual.debug_bounds(HEADER_DIVIDER).expect("header divider");
1557
assert!(
1558
(f32::from(main.right() - pane.right())).abs() < INSET_TOLERANCE,
1559
"pane {pane:?} must end at the main island edge {main:?}"
1560
);
1561
assert!(
1562
(f32::from(pane.top() - divider.bottom())).abs() < INSET_TOLERANCE,
1563
"pane {pane:?} must start under the header divider {divider:?}"
1564
);
1565
}
1566
1567
#[gpui_kit::test]
1568
fn the_channel_details_sections_follow_teams_order_with_equal_insets(cx: &mut TestAppContext) {
1569
let (handle, state) = mount(cx);
1570
let mut visual = VisualTestContext::from_window(handle, cx);
1571
visual.simulate_resize(size(px(1280.), px(800.)));
1572
visual.update(|_, cx| {
1573
state.update(cx, |state, cx| {
1574
state.select(Selection::Channel(PINNED_CHANNEL.to_owned()), cx)
1575
})
1576
});
1577
collect(&mut visual, Some(CHANNEL_DETAILS_BUTTON));
1578
let button = visual
1579
.debug_bounds(CHANNEL_DETAILS_BUTTON)
1580
.expect("channel details button");
1581
visual.simulate_click(button.center(), Default::default());
1582
collect(&mut visual, Some(CHANNEL_DETAILS_SHARED_TAG));
1583
let pane = visual
1584
.debug_bounds(CHANNEL_DETAILS_TAG)
1585
.expect("details pane");
1586
let pinned = visual
1587
.debug_bounds(CHANNEL_DETAILS_PINNED_TAG)
1588
.expect("pinned section");
1589
let shared = visual
1590
.debug_bounds(CHANNEL_DETAILS_SHARED_TAG)
1591
.expect("shared section");
1592
assert!(
1593
pinned.bottom() <= shared.top(),
1594
"pinned {pinned:?} must come before shared {shared:?}"
1595
);
1596
for (name, section) in [("pinned", pinned), ("shared", shared)] {
1597
let left = f32::from(section.left() - pane.left());
1598
let right = f32::from(pane.right() - section.right());
1599
assert!(
1600
(left - right).abs() < INSET_TOLERANCE && left > 0.,
1601
"{name} section insets left {left} right {right} must match"
1602
);
1603
}
1604
}
1605
1479
1606
fn composer_button_insets(visual: &mut VisualTestContext) -> [f32; 6] {
1480
1607
collect(visual, Some(COMPOSER_SEND_TAG));
1481
1608
let mut bounds_of = |path: &'static str| {
@@ -180,11 +180,16 @@ mod frames {180
COMPOSER_BOX_TAG, COMPOSER_FORMAT_BAR_TAG, COMPOSER_FORMAT_DIVIDER_TAG,180
COMPOSER_BOX_TAG, COMPOSER_FORMAT_BAR_TAG, COMPOSER_FORMAT_DIVIDER_TAG,181
COMPOSER_FORMAT_TAG, COMPOSER_LEADING_TAG, COMPOSER_SEND_TAG,181
COMPOSER_FORMAT_TAG, COMPOSER_LEADING_TAG, COMPOSER_SEND_TAG,182
};182
};183
use crate::views::conversation::{HEADER_DIVIDER, MEMBERS_BUTTON};183
use crate::views::conversation::{184
CHANNEL_DETAILS_BUTTON, CHANNEL_DETAILS_PINNED_TAG, CHANNEL_DETAILS_SHARED_TAG,185
CHANNEL_DETAILS_TAG,186
};187
use crate::views::conversation::{HEADER_DIVIDER, MEMBERS_BUTTON, TIMELINE_TAG};184
use crate::views::find_panel::{188
use crate::views::find_panel::{185
FIND_DIVIDER_TAG, FIND_INPUT_TAG, FIND_PANEL_TAG, FIND_RESULTS_TAG,189
FIND_DIVIDER_TAG, FIND_INPUT_TAG, FIND_PANEL_TAG, FIND_RESULTS_TAG,186
};190
};187
use crate::views::message_row::BUBBLE_TAGS;191
use crate::views::message_row::BUBBLE_TAGS;192
use crate::views::pin_banner::PIN_BANNER_TAG;188
use crate::views::proposal_card::{PROPOSAL_BUTTONS, PROPOSAL_CARD, PROPOSAL_THUMBNAILS};193
use crate::views::proposal_card::{PROPOSAL_BUTTONS, PROPOSAL_CARD, PROPOSAL_THUMBNAILS};189
use crate::views::reaction_proposal_pill::REACTION_PILL;194
use crate::views::reaction_proposal_pill::REACTION_PILL;190
use crate::views::recap_tab::RECAP_REGION;195
use crate::views::recap_tab::RECAP_REGION;@@ -1476,6 +1481,128 @@ mod frames {1476
}1481
}1477
}1482
}1478
1483
1484
const PINNED_CHAT: &str = "demo-chat-release";1485
const PINNED_CHANNEL: &str = "demo-channel-1-1";1486
1487
#[gpui_kit::test]1488
fn the_pin_banner_top_gap_matches_its_side_gaps(cx: &mut TestAppContext) {1489
let (handle, state) = mount(cx);1490
let mut visual = VisualTestContext::from_window(handle, cx);1491
let mut found = Vec::new();1492
for (width, height) in SIZES {1493
visual.simulate_resize(size(px(width), px(height)));1494
visual.update(|_, cx| {1495
state.update(cx, |state, cx| {1496
state.select(Selection::Chat(PINNED_CHAT.to_owned()), cx)1497
})1498
});1499
collect(&mut visual, Some(PIN_BANNER_TAG));1500
let banner = visual.debug_bounds(PIN_BANNER_TAG).expect("pin banner");1501
let timeline = visual.debug_bounds(TIMELINE_TAG).expect("timeline");1502
let divider = visual.debug_bounds(HEADER_DIVIDER).expect("header divider");1503
let gaps = [1504
("top", f32::from(banner.top() - timeline.top())),1505
("left", f32::from(banner.left() - timeline.left())),1506
("right", f32::from(timeline.right() - banner.right())),1507
("below divider", f32::from(banner.top() - divider.bottom())),1508
];1509
let side = gaps[1].1;1510
if gaps1511
.iter()1512
.any(|(_, gap)| (gap - side).abs() > INSET_TOLERANCE)1513
{1514
found.push(format!(1515
"pin banner@{width}x{height}: gaps {gaps:?} must match"1516
));1517
}1518
}1519
assert!(found.is_empty(), "{}", found.join("\n"));1520
}1521
1522
#[gpui_kit::test]1523
fn channels_show_no_pin_banner_like_teams(cx: &mut TestAppContext) {1524
let (handle, state) = mount(cx);1525
let mut visual = VisualTestContext::from_window(handle, cx);1526
visual.simulate_resize(size(px(1280.), px(800.)));1527
visual.update(|_, cx| {1528
state.update(cx, |state, cx| {1529
state.select(Selection::Channel(PINNED_CHANNEL.to_owned()), cx)1530
})1531
});1532
collect(&mut visual, Some(TIMELINE_TAG));1533
assert!(visual.debug_bounds(PIN_BANNER_TAG).is_none());1534
}1535
1536
#[gpui_kit::test]1537
fn the_channel_details_pane_lists_pinned_posts_inside_the_main_island(cx: &mut TestAppContext) {1538
let (handle, state) = mount(cx);1539
let mut visual = VisualTestContext::from_window(handle, cx);1540
visual.simulate_resize(size(px(1280.), px(800.)));1541
visual.update(|_, cx| {1542
state.update(cx, |state, cx| {1543
state.select(Selection::Channel(PINNED_CHANNEL.to_owned()), cx)1544
})1545
});1546
collect(&mut visual, Some(CHANNEL_DETAILS_BUTTON));1547
let button = visual1548
.debug_bounds(CHANNEL_DETAILS_BUTTON)1549
.expect("channel details button");1550
visual.simulate_click(button.center(), Default::default());1551
collect(&mut visual, Some(CHANNEL_DETAILS_TAG));1552
let pane = visual1553
.debug_bounds(CHANNEL_DETAILS_TAG)1554
.expect("details pane");1555
let main = visual.debug_bounds(MAIN).expect("main island");1556
let divider = visual.debug_bounds(HEADER_DIVIDER).expect("header divider");1557
assert!(1558
(f32::from(main.right() - pane.right())).abs() < INSET_TOLERANCE,1559
"pane {pane:?} must end at the main island edge {main:?}"1560
);1561
assert!(1562
(f32::from(pane.top() - divider.bottom())).abs() < INSET_TOLERANCE,1563
"pane {pane:?} must start under the header divider {divider:?}"1564
);1565
}1566
1567
#[gpui_kit::test]1568
fn the_channel_details_sections_follow_teams_order_with_equal_insets(cx: &mut TestAppContext) {1569
let (handle, state) = mount(cx);1570
let mut visual = VisualTestContext::from_window(handle, cx);1571
visual.simulate_resize(size(px(1280.), px(800.)));1572
visual.update(|_, cx| {1573
state.update(cx, |state, cx| {1574
state.select(Selection::Channel(PINNED_CHANNEL.to_owned()), cx)1575
})1576
});1577
collect(&mut visual, Some(CHANNEL_DETAILS_BUTTON));1578
let button = visual1579
.debug_bounds(CHANNEL_DETAILS_BUTTON)1580
.expect("channel details button");1581
visual.simulate_click(button.center(), Default::default());1582
collect(&mut visual, Some(CHANNEL_DETAILS_SHARED_TAG));1583
let pane = visual1584
.debug_bounds(CHANNEL_DETAILS_TAG)1585
.expect("details pane");1586
let pinned = visual1587
.debug_bounds(CHANNEL_DETAILS_PINNED_TAG)1588
.expect("pinned section");1589
let shared = visual1590
.debug_bounds(CHANNEL_DETAILS_SHARED_TAG)1591
.expect("shared section");1592
assert!(1593
pinned.bottom() <= shared.top(),1594
"pinned {pinned:?} must come before shared {shared:?}"1595
);1596
for (name, section) in [("pinned", pinned), ("shared", shared)] {1597
let left = f32::from(section.left() - pane.left());1598
let right = f32::from(pane.right() - section.right());1599
assert!(1600
(left - right).abs() < INSET_TOLERANCE && left > 0.,1601
"{name} section insets left {left} right {right} must match"1602
);1603
}1604
}1605
1479
fn composer_button_insets(visual: &mut VisualTestContext) -> [f32; 6] {1606
fn composer_button_insets(visual: &mut VisualTestContext) -> [f32; 6] {1480
collect(visual, Some(COMPOSER_SEND_TAG));1607
collect(visual, Some(COMPOSER_SEND_TAG));1481
let mut bounds_of = |path: &'static str| {1608
let mut bounds_of = |path: &'static str| {@@ -1397,6 +1397,7 @@ mod tests {
1397
1397
hidden: false,
1398
1398
hidden_channel_ids: Vec::new(),
1399
1399
notifications: Default::default(),
1400
mentions: Default::default(),
1400
1401
}],
1401
1402
}
1402
1403
}
@@ -1397,6 +1397,7 @@ mod tests {1397
hidden: false,1397
hidden: false,1398
hidden_channel_ids: Vec::new(),1398
hidden_channel_ids: Vec::new(),1399
notifications: Default::default(),1399
notifications: Default::default(),1400
mentions: Default::default(),1400
}],1401
}],1401
}1402
}1402
}1403
}@@ -21,6 +21,11 @@ use teams_core::{
21
21
ExecuteAction, FileCard, JumpPlan, LinkPreview, WindowDirection, without_islands,
22
22
};
23
23
24
mod channel_details;
25
pub use channel_details::{
26
CHANNEL_DETAILS_BUTTON, CHANNEL_DETAILS_PINNED_TAG, CHANNEL_DETAILS_SHARED_TAG,
27
CHANNEL_DETAILS_TAG,
28
};
24
29
mod deletes;
25
30
mod detached;
26
31
mod feed;
@@ -43,7 +48,8 @@ use super::channel_tabs::{ChannelPane, HEADER_TITLE_MAX_WIDTH};
43
48
use super::chat_members::members_popover;
44
49
use super::composer::{Composer, ComposerEvent, EditPreview, Outgoing, ReplyPreview};
45
50
use super::find_panel::{FIND_PANEL_WIDTH, FindPanel, FindPanelEvent};
46
use super::message_actions::{Action, DelegateEntry, MessageMenu, QUICK_REACTION_COUNT};
51
use super::group_name::group_name_button;
52
use super::message_actions::{Action, DelegateEntry, MessageMenu};
47
53
use super::message_row::{AVATAR_GAP, AVATAR_SIZE, render_message_row, render_skeleton_row};
48
54
use super::new_chat::{NewChatDraft, NewChatEvent, Pick, composer_placeholder};
49
55
use super::pin_banner::{pin_banner_inset, pin_banner_overlay};
@@ -93,6 +99,7 @@ use shared::SharedState;
93
99
94
100
pub const MEMBERS_BUTTON: &str = "shell/islands/main/members-button";
95
101
pub const HEADER_DIVIDER: &str = "shell/islands/main/divider-header";
102
pub const TIMELINE_TAG: &str = "shell/islands/main/timeline";
96
103
const HEADER_HEIGHT: f32 = 60.;
97
104
const HEADER_PADDING: f32 = 20.;
98
105
const HEADER_GAP: f32 = 12.;
@@ -215,6 +222,8 @@ pub struct ConversationView {
215
222
reaction_details: Option<ReactionDetails>,
216
223
highlighted_message: Option<String>,
217
224
pin_index: usize,
225
channel_details_open: bool,
226
pinned_posts_expanded: bool,
218
227
pin_previews: HashMap<String, pins::PinPreview>,
219
228
pin_fetches: HashSet<String>,
220
229
notice: Option<String>,
@@ -546,6 +555,8 @@ impl ConversationView {
546
555
reaction_details: None,
547
556
highlighted_message: None,
548
557
pin_index: 0,
558
channel_details_open: false,
559
pinned_posts_expanded: false,
549
560
pin_previews: HashMap::new(),
550
561
pin_fetches: HashSet::new(),
551
562
notice: None,
@@ -638,7 +649,7 @@ impl ConversationView {
638
649
.as_ref()
639
650
.is_some_and(|current| current.selection.conversation_id() == conversation_id);
640
651
if is_current {
641
if self.shared_active() || self.recap_active() {
652
if self.shared_active() || self.recap_active() || self.channel_details_open {
642
653
self.refresh_shared_items(cx);
643
654
}
644
655
self.rebuild(false, cx);
@@ -898,9 +909,10 @@ impl ConversationView {
898
909
self.start_fetch(cx);
899
910
self.mark_read(ReadTrigger::Open, cx);
900
911
self.refresh_pin_previews(cx);
901
if let Some(chat_id) = self.chat_id() {
912
self.pinned_posts_expanded = false;
913
if let Some(conversation_id) = self.pin_conversation_id() {
902
914
self.app
903
.update(cx, |state, cx| state.refresh_pins(&chat_id, cx));
915
.update(cx, |state, cx| state.refresh_pins(&conversation_id, cx));
904
916
}
905
917
let target = self
906
918
.current
@@ -3028,10 +3040,18 @@ impl ConversationView {
3028
3040
let saved = self
3029
3041
.conversation_id()
3030
3042
.is_some_and(|conversation_id| state.is_saved(&conversation_id, key));
3031
let pinned = chat_id
3032
.as_deref()
3033
.is_some_and(|chat_id| state.is_pinned(chat_id, key));
3043
let quick = state.quick_reactions();
3034
3044
let in_chat = chat_id.is_some();
3045
let pin_conversation_id = self.pin_conversation_id();
3046
let pinned = pin_conversation_id
3047
.as_deref()
3048
.is_some_and(|conversation_id| state.is_pinned(conversation_id, key));
3049
let pinnable = in_chat
3050
|| pin_conversation_id.as_deref().is_some_and(|channel_id| {
3051
state
3052
.message_record(channel_id, key)
3053
.is_some_and(|record| record.reply_to_id.is_none())
3054
});
3035
3055
let (delegate, manage_agents) = self.delegate_entries(key, cx);
3036
3056
MessageMenu {
3037
3057
key: key.to_owned(),
@@ -3046,7 +3066,8 @@ impl ConversationView {
3046
3066
translate_label,
3047
3067
save: Some(action(|this, key, _, cx| this.toggle_saved(key, cx))),
3048
3068
saved,
3049
toggle_pinned: in_chat.then(|| action(|this, key, _, cx| this.toggle_pinned(key, cx))),
3069
toggle_pinned: pinnable
3070
.then(|| action(|this, key, window, cx| this.toggle_pinned(key, window, cx))),
3050
3071
pinned,
3051
3072
edit: own.then(|| action(|this, key, window, cx| this.begin_edit(key, window, cx))),
3052
3073
delete: own.then(|| action(|this, key, _, cx| this.delete(key, cx))),
@@ -3058,7 +3079,7 @@ impl ConversationView {
3058
3079
pin,
3059
3080
hover,
3060
3081
picker: self.picker.clone(),
3061
quick: self.recent.read(cx).most_used(QUICK_REACTION_COUNT),
3082
quick,
3062
3083
mine,
3063
3084
done: action(|this, key, _, cx| this.suppress_toolbar(key, cx)),
3064
3085
}
@@ -3236,6 +3257,7 @@ impl ConversationView {
3236
3257
else {
3237
3258
return;
3238
3259
};
3260
self.channel_details_open = false;
3239
3261
if let Some(panel) = &self.find_panel {
3240
3262
panel.update(cx, |panel, cx| panel.focus(window, cx));
3241
3263
return;
@@ -3297,6 +3319,7 @@ impl ConversationView {
3297
3319
let mut lead: Option<AnyElement> = None;
3298
3320
let mut subline = String::new();
3299
3321
let mut stack: Option<AnyElement> = None;
3322
let mut rename: Option<AnyElement> = None;
3300
3323
match ¤t.selection {
3301
3324
Selection::Chat(chat_id) => {
3302
3325
if let Some(chat) = app.sidebar.chats.iter().find(|chat| &chat.id == chat_id) {
@@ -3332,6 +3355,15 @@ impl ConversationView {
3332
3355
stack = Some(add_people_button(&self.app, chat_id));
3333
3356
}
3334
3357
} else {
3358
if chat.kind == GROUP_KIND
3359
&& me.is_some_and(|me| {
3360
chat.members
3361
.iter()
3362
.any(|member| member.user_id.as_deref() == Some(&me.user_id))
3363
})
3364
{
3365
rename = Some(group_name_button(&self.app, chat_id, &chat.title));
3366
}
3335
3367
let pair = AvatarSpec::Pair(face(faces[0].clone()), face(faces[1].clone()));
3336
3368
lead = Some(spec_avatar(directory, &pair, 36., theme::surface()));
3337
3369
subline = format!("{} participants", chat.members.len());
@@ -3434,12 +3466,19 @@ impl ConversationView {
3434
3466
.overflow_hidden()
3435
3467
.gap(px(1.))
3436
3468
.child(
3437
div()
3438
.truncate()
3439
.text_size(px(15.))
3440
.font_weight(FontWeight::SEMIBOLD)
3441
.text_color(theme::text())
3442
.child(current.title.clone()),
3469
h_flex()
3470
.min_w_0()
3471
.gap(px(2.))
3472
.items_center()
3473
.child(
3474
div()
3475
.truncate()
3476
.text_size(px(15.))
3477
.font_weight(FontWeight::SEMIBOLD)
3478
.text_color(theme::text())
3479
.child(current.title.clone()),
3480
)
3481
.children(rename),
3443
3482
)
3444
3483
.when(!subline.is_empty(), |column| {
3445
3484
column.child(
@@ -3453,9 +3492,12 @@ impl ConversationView {
3453
3492
.children(inline_tabs)
3454
3493
.children(stack)
3455
3494
.children(call_controls)
3495
.children(self.channel_details_button(cx))
3456
3496
}
3457
3497
}
3458
3498
3499
const GROUP_KIND: &str = "group";
3500
3459
3501
impl Render for ConversationView {
3460
3502
fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
3461
3503
let background = theme::surface();
@@ -3687,9 +3729,10 @@ impl Render for ConversationView {
3687
3729
} else {
3688
3730
scroller.into_any_element()
3689
3731
};
3732
let channel_details = self.render_channel_details(cx);
3690
3733
let find_panel = self.find_panel.clone().filter(|_| !drafting);
3691
3734
let find_overlays = self.header_width(window) < FIND_PANEL_WIDTH + FIND_MIN_TIMELINE_WIDTH;
3692
let body_column = v_flex()
3735
let content = v_flex()
3693
3736
.relative()
3694
3737
.flex_1()
3695
3738
.min_w_0()
@@ -3697,6 +3740,7 @@ impl Render for ConversationView {
3697
3740
.children(new_post)
3698
3741
.child(
3699
3742
div()
3743
.debug_selector(|| TIMELINE_TAG.into())
3700
3744
.relative()
3701
3745
.flex_1()
3702
3746
.min_h_0()
@@ -3714,13 +3758,14 @@ impl Render for ConversationView {
3714
3758
})
3715
3759
.child(self.render_drop_overlay(cx));
3716
3760
root.child(
3717
div()
3761
h_flex()
3718
3762
.relative()
3719
.flex()
3720
.flex_row()
3721
3763
.flex_1()
3722
3764
.min_h_0()
3723
.child(body_column)
3765
.w_full()
3766
.items_stretch()
3767
.child(content)
3768
.children(channel_details)
3724
3769
.children(find_panel.map(|panel| {
3725
3770
div()
3726
3771
.h_full()
@@ -21,6 +21,11 @@ use teams_core::{21
ExecuteAction, FileCard, JumpPlan, LinkPreview, WindowDirection, without_islands,21
ExecuteAction, FileCard, JumpPlan, LinkPreview, WindowDirection, without_islands,22
};22
};23
23
24
mod channel_details;25
pub use channel_details::{26
CHANNEL_DETAILS_BUTTON, CHANNEL_DETAILS_PINNED_TAG, CHANNEL_DETAILS_SHARED_TAG,27
CHANNEL_DETAILS_TAG,28
};24
mod deletes;29
mod deletes;25
mod detached;30
mod detached;26
mod feed;31
mod feed;@@ -43,7 +48,8 @@ use super::channel_tabs::{ChannelPane, HEADER_TITLE_MAX_WIDTH};43
use super::chat_members::members_popover;48
use super::chat_members::members_popover;44
use super::composer::{Composer, ComposerEvent, EditPreview, Outgoing, ReplyPreview};49
use super::composer::{Composer, ComposerEvent, EditPreview, Outgoing, ReplyPreview};45
use super::find_panel::{FIND_PANEL_WIDTH, FindPanel, FindPanelEvent};50
use super::find_panel::{FIND_PANEL_WIDTH, FindPanel, FindPanelEvent};46
use super::message_actions::{Action, DelegateEntry, MessageMenu, QUICK_REACTION_COUNT};51
use super::group_name::group_name_button;52
use super::message_actions::{Action, DelegateEntry, MessageMenu};47
use super::message_row::{AVATAR_GAP, AVATAR_SIZE, render_message_row, render_skeleton_row};53
use super::message_row::{AVATAR_GAP, AVATAR_SIZE, render_message_row, render_skeleton_row};48
use super::new_chat::{NewChatDraft, NewChatEvent, Pick, composer_placeholder};54
use super::new_chat::{NewChatDraft, NewChatEvent, Pick, composer_placeholder};49
use super::pin_banner::{pin_banner_inset, pin_banner_overlay};55
use super::pin_banner::{pin_banner_inset, pin_banner_overlay};@@ -93,6 +99,7 @@ use shared::SharedState;93
99
94
pub const MEMBERS_BUTTON: &str = "shell/islands/main/members-button";100
pub const MEMBERS_BUTTON: &str = "shell/islands/main/members-button";95
pub const HEADER_DIVIDER: &str = "shell/islands/main/divider-header";101
pub const HEADER_DIVIDER: &str = "shell/islands/main/divider-header";102
pub const TIMELINE_TAG: &str = "shell/islands/main/timeline";96
const HEADER_HEIGHT: f32 = 60.;103
const HEADER_HEIGHT: f32 = 60.;97
const HEADER_PADDING: f32 = 20.;104
const HEADER_PADDING: f32 = 20.;98
const HEADER_GAP: f32 = 12.;105
const HEADER_GAP: f32 = 12.;@@ -215,6 +222,8 @@ pub struct ConversationView {215
reaction_details: Option<ReactionDetails>,222
reaction_details: Option<ReactionDetails>,216
highlighted_message: Option<String>,223
highlighted_message: Option<String>,217
pin_index: usize,224
pin_index: usize,225
channel_details_open: bool,226
pinned_posts_expanded: bool,218
pin_previews: HashMap<String, pins::PinPreview>,227
pin_previews: HashMap<String, pins::PinPreview>,219
pin_fetches: HashSet<String>,228
pin_fetches: HashSet<String>,220
notice: Option<String>,229
notice: Option<String>,@@ -546,6 +555,8 @@ impl ConversationView {546
reaction_details: None,555
reaction_details: None,547
highlighted_message: None,556
highlighted_message: None,548
pin_index: 0,557
pin_index: 0,558
channel_details_open: false,559
pinned_posts_expanded: false,549
pin_previews: HashMap::new(),560
pin_previews: HashMap::new(),550
pin_fetches: HashSet::new(),561
pin_fetches: HashSet::new(),551
notice: None,562
notice: None,@@ -638,7 +649,7 @@ impl ConversationView {638
.as_ref()649
.as_ref()639
.is_some_and(|current| current.selection.conversation_id() == conversation_id);650
.is_some_and(|current| current.selection.conversation_id() == conversation_id);640
if is_current {651
if is_current {641
if self.shared_active() || self.recap_active() {652
if self.shared_active() || self.recap_active() || self.channel_details_open {642
self.refresh_shared_items(cx);653
self.refresh_shared_items(cx);643
}654
}644
self.rebuild(false, cx);655
self.rebuild(false, cx);@@ -898,9 +909,10 @@ impl ConversationView {898
self.start_fetch(cx);909
self.start_fetch(cx);899
self.mark_read(ReadTrigger::Open, cx);910
self.mark_read(ReadTrigger::Open, cx);900
self.refresh_pin_previews(cx);911
self.refresh_pin_previews(cx);901
if let Some(chat_id) = self.chat_id() {912
self.pinned_posts_expanded = false;913
if let Some(conversation_id) = self.pin_conversation_id() {902
self.app914
self.app903
.update(cx, |state, cx| state.refresh_pins(&chat_id, cx));915
.update(cx, |state, cx| state.refresh_pins(&conversation_id, cx));904
}916
}905
let target = self917
let target = self906
.current918
.current@@ -3028,10 +3040,18 @@ impl ConversationView {3028
let saved = self3040
let saved = self3029
.conversation_id()3041
.conversation_id()3030
.is_some_and(|conversation_id| state.is_saved(&conversation_id, key));3042
.is_some_and(|conversation_id| state.is_saved(&conversation_id, key));3031
let pinned = chat_id3043
let quick = state.quick_reactions();3032
.as_deref()3033
.is_some_and(|chat_id| state.is_pinned(chat_id, key));3034
let in_chat = chat_id.is_some();3044
let in_chat = chat_id.is_some();3045
let pin_conversation_id = self.pin_conversation_id();3046
let pinned = pin_conversation_id3047
.as_deref()3048
.is_some_and(|conversation_id| state.is_pinned(conversation_id, key));3049
let pinnable = in_chat3050
|| pin_conversation_id.as_deref().is_some_and(|channel_id| {3051
state3052
.message_record(channel_id, key)3053
.is_some_and(|record| record.reply_to_id.is_none())3054
});3035
let (delegate, manage_agents) = self.delegate_entries(key, cx);3055
let (delegate, manage_agents) = self.delegate_entries(key, cx);3036
MessageMenu {3056
MessageMenu {3037
key: key.to_owned(),3057
key: key.to_owned(),@@ -3046,7 +3066,8 @@ impl ConversationView {3046
translate_label,3066
translate_label,3047
save: Some(action(|this, key, _, cx| this.toggle_saved(key, cx))),3067
save: Some(action(|this, key, _, cx| this.toggle_saved(key, cx))),3048
saved,3068
saved,3049
toggle_pinned: in_chat.then(|| action(|this, key, _, cx| this.toggle_pinned(key, cx))),3069
toggle_pinned: pinnable3070
.then(|| action(|this, key, window, cx| this.toggle_pinned(key, window, cx))),3050
pinned,3071
pinned,3051
edit: own.then(|| action(|this, key, window, cx| this.begin_edit(key, window, cx))),3072
edit: own.then(|| action(|this, key, window, cx| this.begin_edit(key, window, cx))),3052
delete: own.then(|| action(|this, key, _, cx| this.delete(key, cx))),3073
delete: own.then(|| action(|this, key, _, cx| this.delete(key, cx))),@@ -3058,7 +3079,7 @@ impl ConversationView {3058
pin,3079
pin,3059
hover,3080
hover,3060
picker: self.picker.clone(),3081
picker: self.picker.clone(),3061
quick: self.recent.read(cx).most_used(QUICK_REACTION_COUNT),3082
quick,3062
mine,3083
mine,3063
done: action(|this, key, _, cx| this.suppress_toolbar(key, cx)),3084
done: action(|this, key, _, cx| this.suppress_toolbar(key, cx)),3064
}3085
}@@ -3236,6 +3257,7 @@ impl ConversationView {3236
else {3257
else {3237
return;3258
return;3238
};3259
};3260
self.channel_details_open = false;3239
if let Some(panel) = &self.find_panel {3261
if let Some(panel) = &self.find_panel {3240
panel.update(cx, |panel, cx| panel.focus(window, cx));3262
panel.update(cx, |panel, cx| panel.focus(window, cx));3241
return;3263
return;@@ -3297,6 +3319,7 @@ impl ConversationView {3297
let mut lead: Option<AnyElement> = None;3319
let mut lead: Option<AnyElement> = None;3298
let mut subline = String::new();3320
let mut subline = String::new();3299
let mut stack: Option<AnyElement> = None;3321
let mut stack: Option<AnyElement> = None;3322
let mut rename: Option<AnyElement> = None;3300
match ¤t.selection {3323
match ¤t.selection {3301
Selection::Chat(chat_id) => {3324
Selection::Chat(chat_id) => {3302
if let Some(chat) = app.sidebar.chats.iter().find(|chat| &chat.id == chat_id) {3325
if let Some(chat) = app.sidebar.chats.iter().find(|chat| &chat.id == chat_id) {@@ -3332,6 +3355,15 @@ impl ConversationView {3332
stack = Some(add_people_button(&self.app, chat_id));3355
stack = Some(add_people_button(&self.app, chat_id));3333
}3356
}3334
} else {3357
} else {3358
if chat.kind == GROUP_KIND3359
&& me.is_some_and(|me| {3360
chat.members3361
.iter()3362
.any(|member| member.user_id.as_deref() == Some(&me.user_id))3363
})3364
{3365
rename = Some(group_name_button(&self.app, chat_id, &chat.title));3366
}3335
let pair = AvatarSpec::Pair(face(faces[0].clone()), face(faces[1].clone()));3367
let pair = AvatarSpec::Pair(face(faces[0].clone()), face(faces[1].clone()));3336
lead = Some(spec_avatar(directory, &pair, 36., theme::surface()));3368
lead = Some(spec_avatar(directory, &pair, 36., theme::surface()));3337
subline = format!("{} participants", chat.members.len());3369
subline = format!("{} participants", chat.members.len());@@ -3434,12 +3466,19 @@ impl ConversationView {3434
.overflow_hidden()3466
.overflow_hidden()3435
.gap(px(1.))3467
.gap(px(1.))3436
.child(3468
.child(3437
div()3469
h_flex()3438
.truncate()3470
.min_w_0()3439
.text_size(px(15.))3471
.gap(px(2.))3440
.font_weight(FontWeight::SEMIBOLD)3472
.items_center()3441
.text_color(theme::text())3473
.child(3442
.child(current.title.clone()),3474
div()3475
.truncate()3476
.text_size(px(15.))3477
.font_weight(FontWeight::SEMIBOLD)3478
.text_color(theme::text())3479
.child(current.title.clone()),3480
)3481
.children(rename),3443
)3482
)3444
.when(!subline.is_empty(), |column| {3483
.when(!subline.is_empty(), |column| {3445
column.child(3484
column.child(@@ -3453,9 +3492,12 @@ impl ConversationView {3453
.children(inline_tabs)3492
.children(inline_tabs)3454
.children(stack)3493
.children(stack)3455
.children(call_controls)3494
.children(call_controls)3495
.children(self.channel_details_button(cx))3456
}3496
}3457
}3497
}3458
3498
3499
const GROUP_KIND: &str = "group";3500
3459
impl Render for ConversationView {3501
impl Render for ConversationView {3460
fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {3502
fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {3461
let background = theme::surface();3503
let background = theme::surface();@@ -3687,9 +3729,10 @@ impl Render for ConversationView {3687
} else {3729
} else {3688
scroller.into_any_element()3730
scroller.into_any_element()3689
};3731
};3732
let channel_details = self.render_channel_details(cx);3690
let find_panel = self.find_panel.clone().filter(|_| !drafting);3733
let find_panel = self.find_panel.clone().filter(|_| !drafting);3691
let find_overlays = self.header_width(window) < FIND_PANEL_WIDTH + FIND_MIN_TIMELINE_WIDTH;3734
let find_overlays = self.header_width(window) < FIND_PANEL_WIDTH + FIND_MIN_TIMELINE_WIDTH;3692
let body_column = v_flex()3735
let content = v_flex()3693
.relative()3736
.relative()3694
.flex_1()3737
.flex_1()3695
.min_w_0()3738
.min_w_0()@@ -3697,6 +3740,7 @@ impl Render for ConversationView {3697
.children(new_post)3740
.children(new_post)3698
.child(3741
.child(3699
div()3742
div()3743
.debug_selector(|| TIMELINE_TAG.into())3700
.relative()3744
.relative()3701
.flex_1()3745
.flex_1()3702
.min_h_0()3746
.min_h_0()@@ -3714,13 +3758,14 @@ impl Render for ConversationView {3714
})3758
})3715
.child(self.render_drop_overlay(cx));3759
.child(self.render_drop_overlay(cx));3716
root.child(3760
root.child(3717
div()3761
h_flex()3718
.relative()3762
.relative()3719
.flex()3720
.flex_row()3721
.flex_1()3763
.flex_1()3722
.min_h_0()3764
.min_h_0()3723
.child(body_column)3765
.w_full()3766
.items_stretch()3767
.child(content)3768
.children(channel_details)3724
.children(find_panel.map(|panel| {3769
.children(find_panel.map(|panel| {3725
div()3770
div()3726
.h_full()3771
.h_full()@@ -0,0 +1,529 @@
1
use chrono::{Local, Offset, Utc};
2
use gpui_kit::assets::IconName;
3
use gpui_kit::component::button::{Button, ButtonVariants as _};
4
use gpui_kit::component::{h_flex, v_flex};
5
use gpui_kit::prelude::FluentBuilder as _;
6
use gpui_kit::*;
7
use store::MessageRecord;
8
use teams_core::FileKind;
9
10
use super::{ChannelPane, ConversationView};
11
use crate::app_state::Selection;
12
use crate::channel_files::{SharedContent, SharedItem};
13
use crate::format;
14
use crate::rows::reply_excerpt;
15
use crate::theme;
16
use crate::views::attachments::file_badge;
17
use crate::views::avatar::person_avatar;
18
19
pub const CHANNEL_DETAILS_TAG: &str = "shell/islands/main/channel-details";
20
pub const CHANNEL_DETAILS_BUTTON: &str = "shell/islands/main/channel-details-button";
21
pub const CHANNEL_DETAILS_PINNED_TAG: &str = "shell/islands/main/channel-details/pinned";
22
pub const CHANNEL_DETAILS_SHARED_TAG: &str = "shell/islands/main/channel-details/shared";
23
const OPEN_LABEL: &str = "Open channel details";
24
const CLOSE_LABEL: &str = "Close channel details";
25
const PINNED_TITLE: &str = "Pinned";
26
const SHARED_TITLE: &str = "Shared";
27
const SEE_ALL_SHARED_ARIA: &str = "See all shared files";
28
const SEE_ALL_LABEL: &str = "See all";
29
const SEE_ALL_ARIA: &str = "See all pinned posts";
30
const BACK_LABEL: &str = "Back";
31
const FALLBACK_PREVIEW: &str = "Pinned post";
32
const PANE_WIDTH: f32 = 320.;
33
const PANE_PADDING: f32 = 16.;
34
const HEADER_HEIGHT: f32 = 48.;
35
const BUTTON_SIZE: f32 = 32.;
36
const ITEM_AVATAR: f32 = 24.;
37
const COLLAPSED_PIN_COUNT: usize = 3;
38
const SHARED_FILE_COUNT: usize = 3;
39
40
pub(super) struct PinnedPostItem {
41
pub message_id: String,
42
pub author_id: Option<String>,
43
pub title: String,
44
pub byline: String,
45
}
46
47
/// Teams' info pane item: post subject or text, then "author, date".
48
pub(super) fn pinned_post_item(message_id: &str, record: Option<&MessageRecord>) -> PinnedPostItem {
49
let Some(record) = record else {
50
return PinnedPostItem {
51
message_id: message_id.to_owned(),
52
author_id: None,
53
title: FALLBACK_PREVIEW.to_owned(),
54
byline: String::new(),
55
};
56
};
57
let offset = Local::now().offset().fix();
58
let today = Utc::now().with_timezone(&offset).date_naive();
59
let date = format::list_time_label(record.created_at, today, offset);
60
let author = record.sender_name.clone().unwrap_or_default();
61
let byline = match (author.is_empty(), date.is_empty()) {
62
(false, false) => format!("{author}, {date}"),
63
(false, true) => author,
64
_ => date,
65
};
66
PinnedPostItem {
67
message_id: message_id.to_owned(),
68
author_id: record.sender_id.clone(),
69
title: record
70
.subject
71
.clone()
72
.filter(|subject| !subject.trim().is_empty())
73
.unwrap_or_else(|| reply_excerpt(record)),
74
byline,
75
}
76
}
77
78
pub(super) struct SharedFileRow {
79
pub message_id: String,
80
pub name: String,
81
pub kind: FileKind,
82
pub byline: String,
83
}
84
85
pub(super) fn shared_file_rows(items: &[SharedItem]) -> (Vec<SharedFileRow>, bool) {
86
let offset = Local::now().offset().fix();
87
let today = Utc::now().with_timezone(&offset).date_naive();
88
let mut files = items.iter().filter_map(|item| match &item.content {
89
SharedContent::File(card) => Some((item, card)),
90
SharedContent::Link(_) => None,
91
});
92
let rows = files
93
.by_ref()
94
.take(SHARED_FILE_COUNT)
95
.map(|(item, card)| {
96
let date = format::list_time_label(item.created_at, today, offset);
97
SharedFileRow {
98
message_id: item.message_id.clone(),
99
name: card.name.clone(),
100
kind: card.kind,
101
byline: [item.author.as_str(), date.as_str()]
102
.into_iter()
103
.filter(|part| !part.is_empty())
104
.collect::<Vec<_>>()
105
.join(", "),
106
}
107
})
108
.collect();
109
(rows, files.next().is_some())
110
}
111
112
pub(super) fn shown_pin_count(total: usize, expanded: bool) -> usize {
113
if expanded {
114
total
115
} else {
116
total.min(COLLAPSED_PIN_COUNT)
117
}
118
}
119
120
impl ConversationView {
121
fn details_channel_id(&self) -> Option<String> {
122
match &self.current.as_ref()?.selection {
123
Selection::Channel(channel_id) => Some(channel_id.clone()),
124
Selection::Chat(_) => None,
125
}
126
}
127
128
pub(super) fn channel_details_button(&self, cx: &mut Context<Self>) -> Option<AnyElement> {
129
self.details_channel_id()?;
130
let open = self.channel_details_open;
131
Some(
132
Button::new("channel-details-toggle")
133
.debug_selector(|| CHANNEL_DETAILS_BUTTON.into())
134
.icon(if open {
135
IconName::PanelRightClose
136
} else {
137
IconName::PanelRight
138
})
139
.ghost()
140
.size(px(BUTTON_SIZE))
141
.rounded(px(8.))
142
.tooltip(if open { CLOSE_LABEL } else { OPEN_LABEL })
143
.on_click(cx.listener(|this, _, _, cx| {
144
this.channel_details_open = !this.channel_details_open;
145
this.pinned_posts_expanded = false;
146
if this.channel_details_open {
147
this.find_panel = None;
148
this.find_subscription = None;
149
this.refresh_shared_items(cx);
150
}
151
cx.notify();
152
}))
153
.into_any_element(),
154
)
155
}
156
157
pub(super) fn render_channel_details(&self, cx: &mut Context<Self>) -> Option<AnyElement> {
158
if !self.channel_details_open {
159
return None;
160
}
161
let channel_id = self.details_channel_id()?;
162
let state = self.app.read(cx);
163
let ids: Vec<String> = state
164
.pinned_messages(&channel_id)
165
.iter()
166
.map(|pin| pin.message_id.clone())
167
.collect();
168
let records = state
169
.store
170
.messages_by_id(&channel_id, &ids)
171
.unwrap_or_default();
172
let items: Vec<PinnedPostItem> = ids
173
.iter()
174
.map(|id| pinned_post_item(id, records.get(id)))
175
.collect();
176
let expanded = self.pinned_posts_expanded;
177
let shown = shown_pin_count(items.len(), expanded);
178
let has_more = items.len() > shown;
179
let title = self
180
.current
181
.as_ref()
182
.map(|current| current.title.clone())
183
.unwrap_or_default();
184
let directory = &state.directory;
185
let mut body = v_flex()
186
.w_full()
187
.px(px(PANE_PADDING))
188
.pb(px(PANE_PADDING))
189
.gap(px(4.));
190
if !items.is_empty() {
191
let mut section = v_flex()
192
.w_full()
193
.gap(px(4.))
194
.debug_selector(|| CHANNEL_DETAILS_PINNED_TAG.into());
195
if !expanded {
196
section = section.child(section_title(PINNED_TITLE));
197
}
198
for item in items.iter().take(shown) {
199
section = section.child(self.pinned_post_row(&channel_id, item, directory, cx));
200
}
201
if has_more {
202
section = section.child(
203
Button::new("channel-details-see-all-pins")
204
.ghost()
205
.label(SEE_ALL_LABEL)
206
.tooltip(SEE_ALL_ARIA)
207
.on_click(cx.listener(|this, _, _, cx| {
208
this.pinned_posts_expanded = true;
209
cx.notify();
210
})),
211
);
212
}
213
body = body.child(section);
214
}
215
let (shared_rows, more_shared) = shared_file_rows(&self.shared.items);
216
if !expanded && !shared_rows.is_empty() {
217
let mut section = v_flex()
218
.w_full()
219
.gap(px(4.))
220
.debug_selector(|| CHANNEL_DETAILS_SHARED_TAG.into())
221
.child(section_title(SHARED_TITLE));
222
for row in &shared_rows {
223
section = section.child(self.shared_file_row(&channel_id, row, cx));
224
}
225
if more_shared {
226
section = section.child(
227
Button::new("channel-details-see-all-shared")
228
.ghost()
229
.label(SEE_ALL_LABEL)
230
.tooltip(SEE_ALL_SHARED_ARIA)
231
.on_click(cx.listener(|this, _, _, cx| {
232
this.select_pane(ChannelPane::Shared, cx);
233
})),
234
);
235
}
236
body = body.child(section);
237
}
238
let header = if expanded {
239
h_flex()
240
.gap(px(8.))
241
.child(
242
Button::new("channel-details-back")
243
.icon(IconName::ChevronLeft)
244
.ghost()
245
.size(px(BUTTON_SIZE))
246
.rounded(px(8.))
247
.tooltip(BACK_LABEL)
248
.on_click(cx.listener(|this, _, _, cx| {
249
this.pinned_posts_expanded = false;
250
cx.notify();
251
})),
252
)
253
.child(header_title(PINNED_TITLE.to_owned()))
254
} else {
255
h_flex().child(header_title(title))
256
};
257
Some(
258
h_flex()
259
.h_full()
260
.flex_none()
261
.child(div().w(px(1.)).h_full().flex_none().bg(theme::border()))
262
.child(
263
v_flex()
264
.debug_selector(|| CHANNEL_DETAILS_TAG.into())
265
.w(px(PANE_WIDTH))
266
.h_full()
267
.bg(theme::surface())
268
.child(
269
h_flex()
270
.h(px(HEADER_HEIGHT))
271
.flex_none()
272
.px(px(PANE_PADDING))
273
.items_center()
274
.justify_between()
275
.child(header.flex_1().min_w_0().items_center())
276
.child(
277
Button::new("channel-details-close")
278
.icon(IconName::X)
279
.ghost()
280
.size(px(BUTTON_SIZE))
281
.rounded(px(8.))
282
.tooltip(CLOSE_LABEL)
283
.on_click(cx.listener(|this, _, _, cx| {
284
this.channel_details_open = false;
285
this.pinned_posts_expanded = false;
286
cx.notify();
287
})),
288
),
289
)
290
.child(
291
div()
292
.id("channel-details-body")
293
.flex_1()
294
.min_h_0()
295
.overflow_y_scroll()
296
.child(body),
297
),
298
)
299
.into_any_element(),
300
)
301
}
302
303
fn pinned_post_row(
304
&self,
305
channel_id: &str,
306
item: &PinnedPostItem,
307
directory: &crate::data::Directory,
308
cx: &Context<Self>,
309
) -> AnyElement {
310
let (channel_id, message_id) = (channel_id.to_owned(), item.message_id.clone());
311
let author_name = item.byline.split(',').next().unwrap_or_default().to_owned();
312
h_flex()
313
.id(SharedString::from(format!(
314
"pinned-post-{}",
315
item.message_id
316
)))
317
.w_full()
318
.p(px(8.))
319
.gap(px(10.))
320
.items_start()
321
.rounded(px(8.))
322
.cursor_pointer()
323
.hover(|row| row.bg(theme::row_hover()))
324
.child(person_avatar(
325
directory,
326
item.author_id.as_deref(),
327
&author_name,
328
ITEM_AVATAR,
329
))
330
.child(
331
v_flex()
332
.flex_1()
333
.min_w_0()
334
.gap(px(2.))
335
.child(
336
div()
337
.truncate()
338
.text_size(px(13.))
339
.text_color(theme::text())
340
.child(item.title.clone()),
341
)
342
.when(!item.byline.is_empty(), |column| {
343
column.child(
344
div()
345
.truncate()
346
.text_size(px(12.))
347
.text_color(theme::text_muted())
348
.child(item.byline.clone()),
349
)
350
}),
351
)
352
.on_click(cx.listener(move |this, _, _, cx| {
353
this.jump_to_message(&channel_id, &message_id, cx);
354
}))
355
.into_any_element()
356
}
357
}
358
359
impl ConversationView {
360
fn shared_file_row(
361
&self,
362
channel_id: &str,
363
row: &SharedFileRow,
364
cx: &Context<Self>,
365
) -> AnyElement {
366
let (channel_id, message_id) = (channel_id.to_owned(), row.message_id.clone());
367
h_flex()
368
.id(SharedString::from(format!(
369
"shared-file-{}-{}",
370
row.message_id, row.name
371
)))
372
.w_full()
373
.p(px(8.))
374
.gap(px(10.))
375
.items_start()
376
.rounded(px(8.))
377
.cursor_pointer()
378
.hover(|item| item.bg(theme::row_hover()))
379
.child(file_badge(row.kind, ITEM_AVATAR))
380
.child(
381
v_flex()
382
.flex_1()
383
.min_w_0()
384
.gap(px(2.))
385
.child(
386
div()
387
.truncate()
388
.text_size(px(13.))
389
.text_color(theme::text())
390
.child(row.name.clone()),
391
)
392
.when(!row.byline.is_empty(), |column| {
393
column.child(
394
div()
395
.truncate()
396
.text_size(px(12.))
397
.text_color(theme::text_muted())
398
.child(row.byline.clone()),
399
)
400
}),
401
)
402
.on_click(cx.listener(move |this, _, _, cx| {
403
this.jump_to_message(&channel_id, &message_id, cx);
404
}))
405
.into_any_element()
406
}
407
}
408
409
fn section_title(text: &'static str) -> Div {
410
div()
411
.py(px(8.))
412
.text_size(px(14.))
413
.font_weight(FontWeight::SEMIBOLD)
414
.text_color(theme::text())
415
.child(text)
416
}
417
418
fn header_title(text: String) -> Div {
419
div()
420
.flex_1()
421
.min_w_0()
422
.truncate()
423
.text_size(px(15.))
424
.font_weight(FontWeight::SEMIBOLD)
425
.text_color(theme::text())
426
.child(text)
427
}
428
429
#[cfg(test)]
430
mod tests {
431
use chrono::{TimeZone, Utc};
432
use store::MessageRecord;
433
434
use teams_core::{FileCard, FileKind};
435
436
use super::{FALLBACK_PREVIEW, pinned_post_item, shared_file_rows, shown_pin_count};
437
use crate::channel_files::{SharedContent, SharedItem};
438
439
fn record(subject: Option<&str>) -> MessageRecord {
440
MessageRecord {
441
conversation_id: "19:channel".into(),
442
message_id: "1".into(),
443
sender_id: Some("user-ada".into()),
444
sender_name: Some("Ada Lovelace".into()),
445
created_at: Utc.with_ymd_and_hms(2024, 3, 4, 9, 30, 0).unwrap(),
446
body_html: "<p>Release notes are up</p>".into(),
447
subject: subject.map(str::to_owned),
448
attachments_json: "[]".into(),
449
reactions_json: "[]".into(),
450
mentions_json: "[]".into(),
451
links_json: "[]".into(),
452
..MessageRecord::default()
453
}
454
}
455
456
#[test]
457
fn the_item_prefers_the_subject_and_names_author_and_date() {
458
let item = pinned_post_item("1", Some(&record(Some("Release 4.2"))));
459
assert_eq!(item.title, "Release 4.2");
460
assert!(item.byline.starts_with("Ada Lovelace, "), "{}", item.byline);
461
assert_eq!(item.author_id.as_deref(), Some("user-ada"));
462
let plain = pinned_post_item("1", Some(&record(None)));
463
assert_eq!(plain.title, "Release notes are up");
464
}
465
466
#[test]
467
fn an_uncached_post_keeps_its_place_with_a_fallback() {
468
let item = pinned_post_item("9", None);
469
assert_eq!(item.message_id, "9");
470
assert_eq!(item.title, FALLBACK_PREVIEW);
471
assert!(item.byline.is_empty());
472
}
473
474
#[test]
475
fn three_pins_show_until_see_all() {
476
assert_eq!(shown_pin_count(5, false), 3);
477
assert_eq!(shown_pin_count(2, false), 2);
478
assert_eq!(shown_pin_count(5, true), 5);
479
}
480
481
fn shared(content: SharedContent, message_id: &str) -> SharedItem {
482
SharedItem {
483
content,
484
author: "Ada Lovelace".into(),
485
post_label: String::new(),
486
message_id: message_id.into(),
487
created_at: Utc.with_ymd_and_hms(2024, 3, 4, 9, 30, 0).unwrap(),
488
}
489
}
490
491
fn file(name: &str) -> SharedContent {
492
SharedContent::File(FileCard {
493
name: name.into(),
494
kind: FileKind::from_name(name),
495
content_type: None,
496
size: None,
497
open_url: format!("https://example.invalid/{name}"),
498
})
499
}
500
501
#[test]
502
fn shared_section_lists_the_newest_files_and_skips_links() {
503
let items = vec![
504
shared(SharedContent::Link("https://example.invalid".into()), "1"),
505
shared(file("plan.docx"), "2"),
506
shared(file("budget.xlsx"), "3"),
507
];
508
let (rows, more) = shared_file_rows(&items);
509
let names: Vec<&str> = rows.iter().map(|row| row.name.as_str()).collect();
510
assert_eq!(names, ["plan.docx", "budget.xlsx"]);
511
assert!(!more);
512
assert_eq!(rows[0].message_id, "2");
513
assert!(
514
rows[0].byline.starts_with("Ada Lovelace, "),
515
"{}",
516
rows[0].byline
517
);
518
}
519
520
#[test]
521
fn shared_section_offers_see_all_after_three_files() {
522
let items: Vec<SharedItem> = (0..4)
523
.map(|index| shared(file(&format!("file-{index}.pdf")), &index.to_string()))
524
.collect();
525
let (rows, more) = shared_file_rows(&items);
526
assert_eq!(rows.len(), 3);
527
assert!(more);
528
}
529
}
@@ -0,0 +1,529 @@1
use chrono::{Local, Offset, Utc};2
use gpui_kit::assets::IconName;3
use gpui_kit::component::button::{Button, ButtonVariants as _};4
use gpui_kit::component::{h_flex, v_flex};5
use gpui_kit::prelude::FluentBuilder as _;6
use gpui_kit::*;7
use store::MessageRecord;8
use teams_core::FileKind;9
10
use super::{ChannelPane, ConversationView};11
use crate::app_state::Selection;12
use crate::channel_files::{SharedContent, SharedItem};13
use crate::format;14
use crate::rows::reply_excerpt;15
use crate::theme;16
use crate::views::attachments::file_badge;17
use crate::views::avatar::person_avatar;18
19
pub const CHANNEL_DETAILS_TAG: &str = "shell/islands/main/channel-details";20
pub const CHANNEL_DETAILS_BUTTON: &str = "shell/islands/main/channel-details-button";21
pub const CHANNEL_DETAILS_PINNED_TAG: &str = "shell/islands/main/channel-details/pinned";22
pub const CHANNEL_DETAILS_SHARED_TAG: &str = "shell/islands/main/channel-details/shared";23
const OPEN_LABEL: &str = "Open channel details";24
const CLOSE_LABEL: &str = "Close channel details";25
const PINNED_TITLE: &str = "Pinned";26
const SHARED_TITLE: &str = "Shared";27
const SEE_ALL_SHARED_ARIA: &str = "See all shared files";28
const SEE_ALL_LABEL: &str = "See all";29
const SEE_ALL_ARIA: &str = "See all pinned posts";30
const BACK_LABEL: &str = "Back";31
const FALLBACK_PREVIEW: &str = "Pinned post";32
const PANE_WIDTH: f32 = 320.;33
const PANE_PADDING: f32 = 16.;34
const HEADER_HEIGHT: f32 = 48.;35
const BUTTON_SIZE: f32 = 32.;36
const ITEM_AVATAR: f32 = 24.;37
const COLLAPSED_PIN_COUNT: usize = 3;38
const SHARED_FILE_COUNT: usize = 3;39
40
pub(super) struct PinnedPostItem {41
pub message_id: String,42
pub author_id: Option<String>,43
pub title: String,44
pub byline: String,45
}46
47
/// Teams' info pane item: post subject or text, then "author, date".48
pub(super) fn pinned_post_item(message_id: &str, record: Option<&MessageRecord>) -> PinnedPostItem {49
let Some(record) = record else {50
return PinnedPostItem {51
message_id: message_id.to_owned(),52
author_id: None,53
title: FALLBACK_PREVIEW.to_owned(),54
byline: String::new(),55
};56
};57
let offset = Local::now().offset().fix();58
let today = Utc::now().with_timezone(&offset).date_naive();59
let date = format::list_time_label(record.created_at, today, offset);60
let author = record.sender_name.clone().unwrap_or_default();61
let byline = match (author.is_empty(), date.is_empty()) {62
(false, false) => format!("{author}, {date}"),63
(false, true) => author,64
_ => date,65
};66
PinnedPostItem {67
message_id: message_id.to_owned(),68
author_id: record.sender_id.clone(),69
title: record70
.subject71
.clone()72
.filter(|subject| !subject.trim().is_empty())73
.unwrap_or_else(|| reply_excerpt(record)),74
byline,75
}76
}77
78
pub(super) struct SharedFileRow {79
pub message_id: String,80
pub name: String,81
pub kind: FileKind,82
pub byline: String,83
}84
85
pub(super) fn shared_file_rows(items: &[SharedItem]) -> (Vec<SharedFileRow>, bool) {86
let offset = Local::now().offset().fix();87
let today = Utc::now().with_timezone(&offset).date_naive();88
let mut files = items.iter().filter_map(|item| match &item.content {89
SharedContent::File(card) => Some((item, card)),90
SharedContent::Link(_) => None,91
});92
let rows = files93
.by_ref()94
.take(SHARED_FILE_COUNT)95
.map(|(item, card)| {96
let date = format::list_time_label(item.created_at, today, offset);97
SharedFileRow {98
message_id: item.message_id.clone(),99
name: card.name.clone(),100
kind: card.kind,101
byline: [item.author.as_str(), date.as_str()]102
.into_iter()103
.filter(|part| !part.is_empty())104
.collect::<Vec<_>>()105
.join(", "),106
}107
})108
.collect();109
(rows, files.next().is_some())110
}111
112
pub(super) fn shown_pin_count(total: usize, expanded: bool) -> usize {113
if expanded {114
total115
} else {116
total.min(COLLAPSED_PIN_COUNT)117
}118
}119
120
impl ConversationView {121
fn details_channel_id(&self) -> Option<String> {122
match &self.current.as_ref()?.selection {123
Selection::Channel(channel_id) => Some(channel_id.clone()),124
Selection::Chat(_) => None,125
}126
}127
128
pub(super) fn channel_details_button(&self, cx: &mut Context<Self>) -> Option<AnyElement> {129
self.details_channel_id()?;130
let open = self.channel_details_open;131
Some(132
Button::new("channel-details-toggle")133
.debug_selector(|| CHANNEL_DETAILS_BUTTON.into())134
.icon(if open {135
IconName::PanelRightClose136
} else {137
IconName::PanelRight138
})139
.ghost()140
.size(px(BUTTON_SIZE))141
.rounded(px(8.))142
.tooltip(if open { CLOSE_LABEL } else { OPEN_LABEL })143
.on_click(cx.listener(|this, _, _, cx| {144
this.channel_details_open = !this.channel_details_open;145
this.pinned_posts_expanded = false;146
if this.channel_details_open {147
this.find_panel = None;148
this.find_subscription = None;149
this.refresh_shared_items(cx);150
}151
cx.notify();152
}))153
.into_any_element(),154
)155
}156
157
pub(super) fn render_channel_details(&self, cx: &mut Context<Self>) -> Option<AnyElement> {158
if !self.channel_details_open {159
return None;160
}161
let channel_id = self.details_channel_id()?;162
let state = self.app.read(cx);163
let ids: Vec<String> = state164
.pinned_messages(&channel_id)165
.iter()166
.map(|pin| pin.message_id.clone())167
.collect();168
let records = state169
.store170
.messages_by_id(&channel_id, &ids)171
.unwrap_or_default();172
let items: Vec<PinnedPostItem> = ids173
.iter()174
.map(|id| pinned_post_item(id, records.get(id)))175
.collect();176
let expanded = self.pinned_posts_expanded;177
let shown = shown_pin_count(items.len(), expanded);178
let has_more = items.len() > shown;179
let title = self180
.current181
.as_ref()182
.map(|current| current.title.clone())183
.unwrap_or_default();184
let directory = &state.directory;185
let mut body = v_flex()186
.w_full()187
.px(px(PANE_PADDING))188
.pb(px(PANE_PADDING))189
.gap(px(4.));190
if !items.is_empty() {191
let mut section = v_flex()192
.w_full()193
.gap(px(4.))194
.debug_selector(|| CHANNEL_DETAILS_PINNED_TAG.into());195
if !expanded {196
section = section.child(section_title(PINNED_TITLE));197
}198
for item in items.iter().take(shown) {199
section = section.child(self.pinned_post_row(&channel_id, item, directory, cx));200
}201
if has_more {202
section = section.child(203
Button::new("channel-details-see-all-pins")204
.ghost()205
.label(SEE_ALL_LABEL)206
.tooltip(SEE_ALL_ARIA)207
.on_click(cx.listener(|this, _, _, cx| {208
this.pinned_posts_expanded = true;209
cx.notify();210
})),211
);212
}213
body = body.child(section);214
}215
let (shared_rows, more_shared) = shared_file_rows(&self.shared.items);216
if !expanded && !shared_rows.is_empty() {217
let mut section = v_flex()218
.w_full()219
.gap(px(4.))220
.debug_selector(|| CHANNEL_DETAILS_SHARED_TAG.into())221
.child(section_title(SHARED_TITLE));222
for row in &shared_rows {223
section = section.child(self.shared_file_row(&channel_id, row, cx));224
}225
if more_shared {226
section = section.child(227
Button::new("channel-details-see-all-shared")228
.ghost()229
.label(SEE_ALL_LABEL)230
.tooltip(SEE_ALL_SHARED_ARIA)231
.on_click(cx.listener(|this, _, _, cx| {232
this.select_pane(ChannelPane::Shared, cx);233
})),234
);235
}236
body = body.child(section);237
}238
let header = if expanded {239
h_flex()240
.gap(px(8.))241
.child(242
Button::new("channel-details-back")243
.icon(IconName::ChevronLeft)244
.ghost()245
.size(px(BUTTON_SIZE))246
.rounded(px(8.))247
.tooltip(BACK_LABEL)248
.on_click(cx.listener(|this, _, _, cx| {249
this.pinned_posts_expanded = false;250
cx.notify();251
})),252
)253
.child(header_title(PINNED_TITLE.to_owned()))254
} else {255
h_flex().child(header_title(title))256
};257
Some(258
h_flex()259
.h_full()260
.flex_none()261
.child(div().w(px(1.)).h_full().flex_none().bg(theme::border()))262
.child(263
v_flex()264
.debug_selector(|| CHANNEL_DETAILS_TAG.into())265
.w(px(PANE_WIDTH))266
.h_full()267
.bg(theme::surface())268
.child(269
h_flex()270
.h(px(HEADER_HEIGHT))271
.flex_none()272
.px(px(PANE_PADDING))273
.items_center()274
.justify_between()275
.child(header.flex_1().min_w_0().items_center())276
.child(277
Button::new("channel-details-close")278
.icon(IconName::X)279
.ghost()280
.size(px(BUTTON_SIZE))281
.rounded(px(8.))282
.tooltip(CLOSE_LABEL)283
.on_click(cx.listener(|this, _, _, cx| {284
this.channel_details_open = false;285
this.pinned_posts_expanded = false;286
cx.notify();287
})),288
),289
)290
.child(291
div()292
.id("channel-details-body")293
.flex_1()294
.min_h_0()295
.overflow_y_scroll()296
.child(body),297
),298
)299
.into_any_element(),300
)301
}302
303
fn pinned_post_row(304
&self,305
channel_id: &str,306
item: &PinnedPostItem,307
directory: &crate::data::Directory,308
cx: &Context<Self>,309
) -> AnyElement {310
let (channel_id, message_id) = (channel_id.to_owned(), item.message_id.clone());311
let author_name = item.byline.split(',').next().unwrap_or_default().to_owned();312
h_flex()313
.id(SharedString::from(format!(314
"pinned-post-{}",315
item.message_id316
)))317
.w_full()318
.p(px(8.))319
.gap(px(10.))320
.items_start()321
.rounded(px(8.))322
.cursor_pointer()323
.hover(|row| row.bg(theme::row_hover()))324
.child(person_avatar(325
directory,326
item.author_id.as_deref(),327
&author_name,328
ITEM_AVATAR,329
))330
.child(331
v_flex()332
.flex_1()333
.min_w_0()334
.gap(px(2.))335
.child(336
div()337
.truncate()338
.text_size(px(13.))339
.text_color(theme::text())340
.child(item.title.clone()),341
)342
.when(!item.byline.is_empty(), |column| {343
column.child(344
div()345
.truncate()346
.text_size(px(12.))347
.text_color(theme::text_muted())348
.child(item.byline.clone()),349
)350
}),351
)352
.on_click(cx.listener(move |this, _, _, cx| {353
this.jump_to_message(&channel_id, &message_id, cx);354
}))355
.into_any_element()356
}357
}358
359
impl ConversationView {360
fn shared_file_row(361
&self,362
channel_id: &str,363
row: &SharedFileRow,364
cx: &Context<Self>,365
) -> AnyElement {366
let (channel_id, message_id) = (channel_id.to_owned(), row.message_id.clone());367
h_flex()368
.id(SharedString::from(format!(369
"shared-file-{}-{}",370
row.message_id, row.name371
)))372
.w_full()373
.p(px(8.))374
.gap(px(10.))375
.items_start()376
.rounded(px(8.))377
.cursor_pointer()378
.hover(|item| item.bg(theme::row_hover()))379
.child(file_badge(row.kind, ITEM_AVATAR))380
.child(381
v_flex()382
.flex_1()383
.min_w_0()384
.gap(px(2.))385
.child(386
div()387
.truncate()388
.text_size(px(13.))389
.text_color(theme::text())390
.child(row.name.clone()),391
)392
.when(!row.byline.is_empty(), |column| {393
column.child(394
div()395
.truncate()396
.text_size(px(12.))397
.text_color(theme::text_muted())398
.child(row.byline.clone()),399
)400
}),401
)402
.on_click(cx.listener(move |this, _, _, cx| {403
this.jump_to_message(&channel_id, &message_id, cx);404
}))405
.into_any_element()406
}407
}408
409
fn section_title(text: &'static str) -> Div {410
div()411
.py(px(8.))412
.text_size(px(14.))413
.font_weight(FontWeight::SEMIBOLD)414
.text_color(theme::text())415
.child(text)416
}417
418
fn header_title(text: String) -> Div {419
div()420
.flex_1()421
.min_w_0()422
.truncate()423
.text_size(px(15.))424
.font_weight(FontWeight::SEMIBOLD)425
.text_color(theme::text())426
.child(text)427
}428
429
#[cfg(test)]430
mod tests {431
use chrono::{TimeZone, Utc};432
use store::MessageRecord;433
434
use teams_core::{FileCard, FileKind};435
436
use super::{FALLBACK_PREVIEW, pinned_post_item, shared_file_rows, shown_pin_count};437
use crate::channel_files::{SharedContent, SharedItem};438
439
fn record(subject: Option<&str>) -> MessageRecord {440
MessageRecord {441
conversation_id: "19:channel".into(),442
message_id: "1".into(),443
sender_id: Some("user-ada".into()),444
sender_name: Some("Ada Lovelace".into()),445
created_at: Utc.with_ymd_and_hms(2024, 3, 4, 9, 30, 0).unwrap(),446
body_html: "<p>Release notes are up</p>".into(),447
subject: subject.map(str::to_owned),448
attachments_json: "[]".into(),449
reactions_json: "[]".into(),450
mentions_json: "[]".into(),451
links_json: "[]".into(),452
..MessageRecord::default()453
}454
}455
456
#[test]457
fn the_item_prefers_the_subject_and_names_author_and_date() {458
let item = pinned_post_item("1", Some(&record(Some("Release 4.2"))));459
assert_eq!(item.title, "Release 4.2");460
assert!(item.byline.starts_with("Ada Lovelace, "), "{}", item.byline);461
assert_eq!(item.author_id.as_deref(), Some("user-ada"));462
let plain = pinned_post_item("1", Some(&record(None)));463
assert_eq!(plain.title, "Release notes are up");464
}465
466
#[test]467
fn an_uncached_post_keeps_its_place_with_a_fallback() {468
let item = pinned_post_item("9", None);469
assert_eq!(item.message_id, "9");470
assert_eq!(item.title, FALLBACK_PREVIEW);471
assert!(item.byline.is_empty());472
}473
474
#[test]475
fn three_pins_show_until_see_all() {476
assert_eq!(shown_pin_count(5, false), 3);477
assert_eq!(shown_pin_count(2, false), 2);478
assert_eq!(shown_pin_count(5, true), 5);479
}480
481
fn shared(content: SharedContent, message_id: &str) -> SharedItem {482
SharedItem {483
content,484
author: "Ada Lovelace".into(),485
post_label: String::new(),486
message_id: message_id.into(),487
created_at: Utc.with_ymd_and_hms(2024, 3, 4, 9, 30, 0).unwrap(),488
}489
}490
491
fn file(name: &str) -> SharedContent {492
SharedContent::File(FileCard {493
name: name.into(),494
kind: FileKind::from_name(name),495
content_type: None,496
size: None,497
open_url: format!("https://example.invalid/{name}"),498
})499
}500
501
#[test]502
fn shared_section_lists_the_newest_files_and_skips_links() {503
let items = vec![504
shared(SharedContent::Link("https://example.invalid".into()), "1"),505
shared(file("plan.docx"), "2"),506
shared(file("budget.xlsx"), "3"),507
];508
let (rows, more) = shared_file_rows(&items);509
let names: Vec<&str> = rows.iter().map(|row| row.name.as_str()).collect();510
assert_eq!(names, ["plan.docx", "budget.xlsx"]);511
assert!(!more);512
assert_eq!(rows[0].message_id, "2");513
assert!(514
rows[0].byline.starts_with("Ada Lovelace, "),515
"{}",516
rows[0].byline517
);518
}519
520
#[test]521
fn shared_section_offers_see_all_after_three_files() {522
let items: Vec<SharedItem> = (0..4)523
.map(|index| shared(file(&format!("file-{index}.pdf")), &index.to_string()))524
.collect();525
let (rows, more) = shared_file_rows(&items);526
assert_eq!(rows.len(), 3);527
assert!(more);528
}529
}@@ -5,7 +5,12 @@ use gpui_kit::*;
5
5
use store::MessageRecord;
6
6
7
7
use super::ConversationView;
8
use crate::app_state::Selection;
8
use gpui_kit::component::WindowExt as _;
9
use gpui_kit::component::button::{Button, ButtonVariants as _};
10
use gpui_kit::component::dialog::DialogFooter;
11
12
use crate::app_state::{AppState, Selection};
13
use crate::channel_menu::post_pin_dialog;
9
14
use crate::rows::reply_excerpt;
10
15
use crate::runtime;
11
16
use crate::views::message_actions::Action;
@@ -25,6 +30,40 @@ impl PinPreview {
25
30
}
26
31
}
27
32
33
fn confirm_post_pin(
34
state: &Entity<AppState>,
35
channel_id: &str,
36
message_id: &str,
37
pin: bool,
38
window: &mut Window,
39
cx: &mut App,
40
) {
41
let dialog = post_pin_dialog(pin);
42
let (state, channel_id, message_id) =
43
(state.clone(), channel_id.to_owned(), message_id.to_owned());
44
window.open_alert_dialog(cx, move |alert, _, _| {
45
let (state, channel_id, message_id) =
46
(state.clone(), channel_id.clone(), message_id.clone());
47
let cancel = Button::new("post-pin-cancel")
48
.label("Cancel")
49
.on_click(|_, window, cx| window.close_dialog(cx));
50
let confirm = Button::new("post-pin-confirm")
51
.label(dialog.confirm)
52
.primary()
53
.on_click(move |_, window, cx| {
54
state.update(cx, |state, cx| {
55
state.set_pinned(&channel_id, &message_id, pin, cx)
56
});
57
window.close_dialog(cx);
58
});
59
alert
60
.title(dialog.title)
61
.description(dialog.body)
62
.footer(DialogFooter::new().child(cancel).child(confirm))
63
.on_ok(|_, _, _| false)
64
});
65
}
66
28
67
impl ConversationView {
29
68
pub(super) fn chat_id(&self) -> Option<String> {
30
69
match self.current.as_ref()?.selection {
@@ -33,36 +72,42 @@ impl ConversationView {
33
72
}
34
73
}
35
74
75
pub(super) fn pin_conversation_id(&self) -> Option<String> {
76
self.current
77
.as_ref()
78
.map(|current| current.selection.conversation_id().to_owned())
79
}
80
36
81
pub(super) fn refresh_pin_previews(&mut self, cx: &mut Context<Self>) {
37
82
self.pin_previews.clear();
38
83
self.pin_fetches.clear();
39
84
self.pin_index = 0;
40
let Some(chat_id) = self.chat_id() else {
85
let Some(conversation_id) = self.pin_conversation_id() else {
41
86
return;
42
87
};
43
self.update_pin_previews(&chat_id, cx);
88
self.update_pin_previews(&conversation_id, cx);
44
89
cx.notify();
45
90
}
46
91
47
pub(super) fn on_pins_changed(&mut self, chat_id: &str, cx: &mut Context<Self>) {
48
if self.chat_id().as_deref() != Some(chat_id) {
92
pub(super) fn on_pins_changed(&mut self, conversation_id: &str, cx: &mut Context<Self>) {
93
if self.pin_conversation_id().as_deref() != Some(conversation_id) {
49
94
return;
50
95
}
51
96
self.pin_index = 0;
52
self.update_pin_previews(chat_id, cx);
97
self.update_pin_previews(conversation_id, cx);
53
98
cx.notify();
54
99
}
55
100
56
fn update_pin_previews(&mut self, chat_id: &str, cx: &mut Context<Self>) {
101
fn update_pin_previews(&mut self, conversation_id: &str, cx: &mut Context<Self>) {
57
102
let state = self.app.read(cx);
58
103
let ids: Vec<String> = state
59
.pinned_messages(chat_id)
104
.pinned_messages(conversation_id)
60
105
.iter()
61
106
.map(|pin| pin.message_id.clone())
62
107
.collect();
63
108
let records = state
64
109
.store
65
.messages_by_id(chat_id, &ids)
110
.messages_by_id(conversation_id, &ids)
66
111
.unwrap_or_default();
67
112
let mut previews: HashMap<String, PinPreview> = records
68
113
.into_iter()
@@ -82,24 +127,29 @@ impl ConversationView {
82
127
}
83
128
for id in ids {
84
129
if !self.pin_previews.contains_key(&id) {
85
self.fetch_pin_preview(chat_id, id, cx);
130
self.fetch_pin_preview(conversation_id, id, cx);
86
131
}
87
132
}
88
133
}
89
134
90
fn fetch_pin_preview(&mut self, chat_id: &str, message_id: String, cx: &mut Context<Self>) {
135
fn fetch_pin_preview(
136
&mut self,
137
conversation_id: &str,
138
message_id: String,
139
cx: &mut Context<Self>,
140
) {
91
141
let Some(engine) = self.app.read(cx).engine.clone() else {
92
142
return;
93
143
};
94
if !self.pin_fetches.insert(message_id.clone()) {
144
if self.chat_id().is_none() || !self.pin_fetches.insert(message_id.clone()) {
95
145
return;
96
146
}
97
let chat_id = chat_id.to_owned();
98
let task_chat_id = chat_id.clone();
147
let conversation_id = conversation_id.to_owned();
148
let task_conversation_id = conversation_id.clone();
99
149
let task_message_id = message_id.clone();
100
150
let receiver = runtime::spawn(async move {
101
151
engine
102
.fetch_chat_message(&task_chat_id, &task_message_id)
152
.fetch_chat_message(&task_conversation_id, &task_message_id)
103
153
.await
104
154
});
105
155
cx.spawn(async move |this, cx| {
@@ -107,8 +157,9 @@ impl ConversationView {
107
157
return;
108
158
};
109
159
this.update(cx, |this, cx| {
110
if this.chat_id().as_deref() == Some(chat_id.as_str()) {
111
this.pin_previews.insert(message_id, PinPreview::of(&record));
160
if this.conversation_id().as_deref() == Some(conversation_id.as_str()) {
161
this.pin_previews
162
.insert(message_id, PinPreview::of(&record));
112
163
cx.notify();
113
164
}
114
165
})
@@ -128,8 +179,8 @@ impl ConversationView {
128
179
}
129
180
130
181
pub(super) fn render_pin_banner(&self, cx: &mut Context<Self>) -> Option<AnyElement> {
131
let chat_id = self.chat_id()?;
132
let pins = self.app.read(cx).pinned_messages(&chat_id);
182
let conversation_id = self.chat_id()?;
183
let pins = self.app.read(cx).pinned_messages(&conversation_id);
133
184
let pin = pins.get(self.pin_index)?;
134
185
let preview = self.pin_previews.get(&pin.message_id);
135
186
let data = PinBannerData {
@@ -149,36 +200,40 @@ impl ConversationView {
149
200
}
150
201
151
202
fn shown_pin_id(&self, cx: &App) -> Option<String> {
152
let chat_id = self.chat_id()?;
203
let conversation_id = self.pin_conversation_id()?;
153
204
self.app
154
205
.read(cx)
155
.pinned_messages(&chat_id)
206
.pinned_messages(&conversation_id)
156
207
.get(self.pin_index)
157
208
.map(|pin| pin.message_id.clone())
158
209
}
159
210
160
211
fn open_shown_pin(&mut self, cx: &mut Context<Self>) {
161
let (Some(chat_id), Some(message_id)) = (self.chat_id(), self.shown_pin_id(cx)) else {
212
let (Some(conversation_id), Some(message_id)) =
213
(self.pin_conversation_id(), self.shown_pin_id(cx))
214
else {
162
215
return;
163
216
};
164
self.jump_to_message(&chat_id, &message_id, cx);
217
self.jump_to_message(&conversation_id, &message_id, cx);
165
218
}
166
219
167
220
fn step_pin(&mut self, delta: isize, cx: &mut Context<Self>) {
168
let Some(chat_id) = self.chat_id() else {
221
let Some(conversation_id) = self.pin_conversation_id() else {
169
222
return;
170
223
};
171
let total = self.app.read(cx).pinned_messages(&chat_id).len();
224
let total = self.app.read(cx).pinned_messages(&conversation_id).len();
172
225
self.pin_index = cycle_pin(self.pin_index, total, delta);
173
226
cx.notify();
174
227
}
175
228
176
229
fn unpin_shown_pin(&mut self, cx: &mut Context<Self>) {
177
let (Some(chat_id), Some(message_id)) = (self.chat_id(), self.shown_pin_id(cx)) else {
230
let (Some(conversation_id), Some(message_id)) =
231
(self.pin_conversation_id(), self.shown_pin_id(cx))
232
else {
178
233
return;
179
234
};
180
235
self.app.update(cx, |state, cx| {
181
state.set_pinned(&chat_id, &message_id, false, cx)
236
state.set_pinned(&conversation_id, &message_id, false, cx)
182
237
});
183
238
}
184
239
@@ -206,12 +261,23 @@ impl ConversationView {
206
261
}
207
262
}
208
263
209
pub(super) fn toggle_pinned(&mut self, message_id: &str, cx: &mut Context<Self>) {
210
if let Some(chat_id) = self.chat_id() {
264
pub(super) fn toggle_pinned(
265
&mut self,
266
message_id: &str,
267
window: &mut Window,
268
cx: &mut Context<Self>,
269
) {
270
let Some(conversation_id) = self.pin_conversation_id() else {
271
return;
272
};
273
if self.chat_id().is_some() {
211
274
self.app.update(cx, |state, cx| {
212
state.toggle_pinned(&chat_id, message_id, cx)
275
state.toggle_pinned(&conversation_id, message_id, cx)
213
276
});
277
return;
214
278
}
279
let pin = !self.app.read(cx).is_pinned(&conversation_id, message_id);
280
confirm_post_pin(&self.app, &conversation_id, message_id, pin, window, cx);
215
281
}
216
282
217
283
pub(super) fn mark_unread_from(&mut self, message_id: &str, cx: &mut Context<Self>) {
@@ -5,7 +5,12 @@ use gpui_kit::*;5
use store::MessageRecord;5
use store::MessageRecord;6
6
7
use super::ConversationView;7
use super::ConversationView;8
use crate::app_state::Selection;8
use gpui_kit::component::WindowExt as _;9
use gpui_kit::component::button::{Button, ButtonVariants as _};10
use gpui_kit::component::dialog::DialogFooter;11
12
use crate::app_state::{AppState, Selection};13
use crate::channel_menu::post_pin_dialog;9
use crate::rows::reply_excerpt;14
use crate::rows::reply_excerpt;10
use crate::runtime;15
use crate::runtime;11
use crate::views::message_actions::Action;16
use crate::views::message_actions::Action;@@ -25,6 +30,40 @@ impl PinPreview {25
}30
}26
}31
}27
32
33
fn confirm_post_pin(34
state: &Entity<AppState>,35
channel_id: &str,36
message_id: &str,37
pin: bool,38
window: &mut Window,39
cx: &mut App,40
) {41
let dialog = post_pin_dialog(pin);42
let (state, channel_id, message_id) =43
(state.clone(), channel_id.to_owned(), message_id.to_owned());44
window.open_alert_dialog(cx, move |alert, _, _| {45
let (state, channel_id, message_id) =46
(state.clone(), channel_id.clone(), message_id.clone());47
let cancel = Button::new("post-pin-cancel")48
.label("Cancel")49
.on_click(|_, window, cx| window.close_dialog(cx));50
let confirm = Button::new("post-pin-confirm")51
.label(dialog.confirm)52
.primary()53
.on_click(move |_, window, cx| {54
state.update(cx, |state, cx| {55
state.set_pinned(&channel_id, &message_id, pin, cx)56
});57
window.close_dialog(cx);58
});59
alert60
.title(dialog.title)61
.description(dialog.body)62
.footer(DialogFooter::new().child(cancel).child(confirm))63
.on_ok(|_, _, _| false)64
});65
}66
28
impl ConversationView {67
impl ConversationView {29
pub(super) fn chat_id(&self) -> Option<String> {68
pub(super) fn chat_id(&self) -> Option<String> {30
match self.current.as_ref()?.selection {69
match self.current.as_ref()?.selection {@@ -33,36 +72,42 @@ impl ConversationView {33
}72
}34
}73
}35
74
75
pub(super) fn pin_conversation_id(&self) -> Option<String> {76
self.current77
.as_ref()78
.map(|current| current.selection.conversation_id().to_owned())79
}80
36
pub(super) fn refresh_pin_previews(&mut self, cx: &mut Context<Self>) {81
pub(super) fn refresh_pin_previews(&mut self, cx: &mut Context<Self>) {37
self.pin_previews.clear();82
self.pin_previews.clear();38
self.pin_fetches.clear();83
self.pin_fetches.clear();39
self.pin_index = 0;84
self.pin_index = 0;40
let Some(chat_id) = self.chat_id() else {85
let Some(conversation_id) = self.pin_conversation_id() else {41
return;86
return;42
};87
};43
self.update_pin_previews(&chat_id, cx);88
self.update_pin_previews(&conversation_id, cx);44
cx.notify();89
cx.notify();45
}90
}46
91
47
pub(super) fn on_pins_changed(&mut self, chat_id: &str, cx: &mut Context<Self>) {92
pub(super) fn on_pins_changed(&mut self, conversation_id: &str, cx: &mut Context<Self>) {48
if self.chat_id().as_deref() != Some(chat_id) {93
if self.pin_conversation_id().as_deref() != Some(conversation_id) {49
return;94
return;50
}95
}51
self.pin_index = 0;96
self.pin_index = 0;52
self.update_pin_previews(chat_id, cx);97
self.update_pin_previews(conversation_id, cx);53
cx.notify();98
cx.notify();54
}99
}55
100
56
fn update_pin_previews(&mut self, chat_id: &str, cx: &mut Context<Self>) {101
fn update_pin_previews(&mut self, conversation_id: &str, cx: &mut Context<Self>) {57
let state = self.app.read(cx);102
let state = self.app.read(cx);58
let ids: Vec<String> = state103
let ids: Vec<String> = state59
.pinned_messages(chat_id)104
.pinned_messages(conversation_id)60
.iter()105
.iter()61
.map(|pin| pin.message_id.clone())106
.map(|pin| pin.message_id.clone())62
.collect();107
.collect();63
let records = state108
let records = state64
.store109
.store65
.messages_by_id(chat_id, &ids)110
.messages_by_id(conversation_id, &ids)66
.unwrap_or_default();111
.unwrap_or_default();67
let mut previews: HashMap<String, PinPreview> = records112
let mut previews: HashMap<String, PinPreview> = records68
.into_iter()113
.into_iter()@@ -82,24 +127,29 @@ impl ConversationView {82
}127
}83
for id in ids {128
for id in ids {84
if !self.pin_previews.contains_key(&id) {129
if !self.pin_previews.contains_key(&id) {85
self.fetch_pin_preview(chat_id, id, cx);130
self.fetch_pin_preview(conversation_id, id, cx);86
}131
}87
}132
}88
}133
}89
134
90
fn fetch_pin_preview(&mut self, chat_id: &str, message_id: String, cx: &mut Context<Self>) {135
fn fetch_pin_preview(136
&mut self,137
conversation_id: &str,138
message_id: String,139
cx: &mut Context<Self>,140
) {91
let Some(engine) = self.app.read(cx).engine.clone() else {141
let Some(engine) = self.app.read(cx).engine.clone() else {92
return;142
return;93
};143
};94
if !self.pin_fetches.insert(message_id.clone()) {144
if self.chat_id().is_none() || !self.pin_fetches.insert(message_id.clone()) {95
return;145
return;96
}146
}97
let chat_id = chat_id.to_owned();147
let conversation_id = conversation_id.to_owned();98
let task_chat_id = chat_id.clone();148
let task_conversation_id = conversation_id.clone();99
let task_message_id = message_id.clone();149
let task_message_id = message_id.clone();100
let receiver = runtime::spawn(async move {150
let receiver = runtime::spawn(async move {101
engine151
engine102
.fetch_chat_message(&task_chat_id, &task_message_id)152
.fetch_chat_message(&task_conversation_id, &task_message_id)103
.await153
.await104
});154
});105
cx.spawn(async move |this, cx| {155
cx.spawn(async move |this, cx| {@@ -107,8 +157,9 @@ impl ConversationView {107
return;157
return;108
};158
};109
this.update(cx, |this, cx| {159
this.update(cx, |this, cx| {110
if this.chat_id().as_deref() == Some(chat_id.as_str()) {160
if this.conversation_id().as_deref() == Some(conversation_id.as_str()) {111
this.pin_previews.insert(message_id, PinPreview::of(&record));161
this.pin_previews162
.insert(message_id, PinPreview::of(&record));112
cx.notify();163
cx.notify();113
}164
}114
})165
})@@ -128,8 +179,8 @@ impl ConversationView {128
}179
}129
180
130
pub(super) fn render_pin_banner(&self, cx: &mut Context<Self>) -> Option<AnyElement> {181
pub(super) fn render_pin_banner(&self, cx: &mut Context<Self>) -> Option<AnyElement> {131
let chat_id = self.chat_id()?;182
let conversation_id = self.chat_id()?;132
let pins = self.app.read(cx).pinned_messages(&chat_id);183
let pins = self.app.read(cx).pinned_messages(&conversation_id);133
let pin = pins.get(self.pin_index)?;184
let pin = pins.get(self.pin_index)?;134
let preview = self.pin_previews.get(&pin.message_id);185
let preview = self.pin_previews.get(&pin.message_id);135
let data = PinBannerData {186
let data = PinBannerData {@@ -149,36 +200,40 @@ impl ConversationView {149
}200
}150
201
151
fn shown_pin_id(&self, cx: &App) -> Option<String> {202
fn shown_pin_id(&self, cx: &App) -> Option<String> {152
let chat_id = self.chat_id()?;203
let conversation_id = self.pin_conversation_id()?;153
self.app204
self.app154
.read(cx)205
.read(cx)155
.pinned_messages(&chat_id)206
.pinned_messages(&conversation_id)156
.get(self.pin_index)207
.get(self.pin_index)157
.map(|pin| pin.message_id.clone())208
.map(|pin| pin.message_id.clone())158
}209
}159
210
160
fn open_shown_pin(&mut self, cx: &mut Context<Self>) {211
fn open_shown_pin(&mut self, cx: &mut Context<Self>) {161
let (Some(chat_id), Some(message_id)) = (self.chat_id(), self.shown_pin_id(cx)) else {212
let (Some(conversation_id), Some(message_id)) =213
(self.pin_conversation_id(), self.shown_pin_id(cx))214
else {162
return;215
return;163
};216
};164
self.jump_to_message(&chat_id, &message_id, cx);217
self.jump_to_message(&conversation_id, &message_id, cx);165
}218
}166
219
167
fn step_pin(&mut self, delta: isize, cx: &mut Context<Self>) {220
fn step_pin(&mut self, delta: isize, cx: &mut Context<Self>) {168
let Some(chat_id) = self.chat_id() else {221
let Some(conversation_id) = self.pin_conversation_id() else {169
return;222
return;170
};223
};171
let total = self.app.read(cx).pinned_messages(&chat_id).len();224
let total = self.app.read(cx).pinned_messages(&conversation_id).len();172
self.pin_index = cycle_pin(self.pin_index, total, delta);225
self.pin_index = cycle_pin(self.pin_index, total, delta);173
cx.notify();226
cx.notify();174
}227
}175
228
176
fn unpin_shown_pin(&mut self, cx: &mut Context<Self>) {229
fn unpin_shown_pin(&mut self, cx: &mut Context<Self>) {177
let (Some(chat_id), Some(message_id)) = (self.chat_id(), self.shown_pin_id(cx)) else {230
let (Some(conversation_id), Some(message_id)) =231
(self.pin_conversation_id(), self.shown_pin_id(cx))232
else {178
return;233
return;179
};234
};180
self.app.update(cx, |state, cx| {235
self.app.update(cx, |state, cx| {181
state.set_pinned(&chat_id, &message_id, false, cx)236
state.set_pinned(&conversation_id, &message_id, false, cx)182
});237
});183
}238
}184
239
@@ -206,12 +261,23 @@ impl ConversationView {206
}261
}207
}262
}208
263
209
pub(super) fn toggle_pinned(&mut self, message_id: &str, cx: &mut Context<Self>) {264
pub(super) fn toggle_pinned(210
if let Some(chat_id) = self.chat_id() {265
&mut self,266
message_id: &str,267
window: &mut Window,268
cx: &mut Context<Self>,269
) {270
let Some(conversation_id) = self.pin_conversation_id() else {271
return;272
};273
if self.chat_id().is_some() {211
self.app.update(cx, |state, cx| {274
self.app.update(cx, |state, cx| {212
state.toggle_pinned(&chat_id, message_id, cx)275
state.toggle_pinned(&conversation_id, message_id, cx)213
});276
});277
return;214
}278
}279
let pin = !self.app.read(cx).is_pinned(&conversation_id, message_id);280
confirm_post_pin(&self.app, &conversation_id, message_id, pin, window, cx);215
}281
}216
282
217
pub(super) fn mark_unread_from(&mut self, message_id: &str, cx: &mut Context<Self>) {283
pub(super) fn mark_unread_from(&mut self, message_id: &str, cx: &mut Context<Self>) {@@ -15,12 +15,12 @@ use crate::agent_api::agent_label;
15
15
use crate::agents::AgentRun;
16
16
use crate::app_state::AppState;
17
17
use crate::rows::{Delivery, MessageRow, PostRow, RecordingCard};
18
use crate::views::call_notice::RecapActions;
19
18
use crate::scheduled_rows::SCHEDULED_KEY_PREFIX;
20
19
use crate::translation::TranslationLine;
21
20
use crate::views::adaptive_card::{ensure_cards_inputs, request_card_refreshes};
22
21
use crate::views::attachments::ImageActions;
23
22
use crate::views::call_card::CallActions;
23
use crate::views::call_notice::RecapActions;
24
24
use crate::views::composer::Composer;
25
25
use crate::views::message_row::{DeliveryActions, RowActions, SharedRowAction};
26
26
use crate::views::post_card::{PostAction, PostActions};
@@ -103,12 +103,16 @@ impl RenderEnv {
103
103
emoji: proposal.emoji,
104
104
accept: Rc::new(move |cx| {
105
105
accept_view
106
.update(cx, |this, cx| this.accept_reaction(&accept_key, &accept_id, &emoji, cx))
106
.update(cx, |this, cx| {
107
this.accept_reaction(&accept_key, &accept_id, &emoji, cx)
108
})
107
109
.ok();
108
110
}),
109
111
discard: Rc::new(move |cx| {
110
112
discard_view
111
.update(cx, |this, cx| this.discard_reaction(&discard_key, &discard_id, cx))
113
.update(cx, |this, cx| {
114
this.discard_reaction(&discard_key, &discard_id, cx)
115
})
112
116
.ok();
113
117
}),
114
118
})
@@ -300,6 +304,10 @@ impl RenderEnv {
300
304
.app
301
305
.read(cx)
302
306
.is_saved(&message.conversation_id, &message.key),
307
pinned: self
308
.app
309
.read(cx)
310
.is_pinned(&message.conversation_id, &message.key),
303
311
translation,
304
312
timeline: self.timeline.clone(),
305
313
agent_run: actionable_run,
@@ -365,9 +373,11 @@ impl RenderEnv {
365
373
})
366
374
};
367
375
let recording = call.recap.as_ref().map(|recap| &recap.recording);
368
let share = recording.and_then(|recording| recording.url.clone()).map(|url| {
369
boxed(move |cx| cx.write_to_clipboard(ClipboardItem::new_string(url.clone())))
370
});
376
let share = recording
377
.and_then(|recording| recording.url.clone())
378
.map(|url| {
379
boxed(move |cx| cx.write_to_clipboard(ClipboardItem::new_string(url.clone())))
380
});
371
381
CallActions {
372
382
call_back,
373
383
join,
@@ -15,12 +15,12 @@ use crate::agent_api::agent_label;15
use crate::agents::AgentRun;15
use crate::agents::AgentRun;16
use crate::app_state::AppState;16
use crate::app_state::AppState;17
use crate::rows::{Delivery, MessageRow, PostRow, RecordingCard};17
use crate::rows::{Delivery, MessageRow, PostRow, RecordingCard};18
use crate::views::call_notice::RecapActions;19
use crate::scheduled_rows::SCHEDULED_KEY_PREFIX;18
use crate::scheduled_rows::SCHEDULED_KEY_PREFIX;20
use crate::translation::TranslationLine;19
use crate::translation::TranslationLine;21
use crate::views::adaptive_card::{ensure_cards_inputs, request_card_refreshes};20
use crate::views::adaptive_card::{ensure_cards_inputs, request_card_refreshes};22
use crate::views::attachments::ImageActions;21
use crate::views::attachments::ImageActions;23
use crate::views::call_card::CallActions;22
use crate::views::call_card::CallActions;23
use crate::views::call_notice::RecapActions;24
use crate::views::composer::Composer;24
use crate::views::composer::Composer;25
use crate::views::message_row::{DeliveryActions, RowActions, SharedRowAction};25
use crate::views::message_row::{DeliveryActions, RowActions, SharedRowAction};26
use crate::views::post_card::{PostAction, PostActions};26
use crate::views::post_card::{PostAction, PostActions};@@ -103,12 +103,16 @@ impl RenderEnv {103
emoji: proposal.emoji,103
emoji: proposal.emoji,104
accept: Rc::new(move |cx| {104
accept: Rc::new(move |cx| {105
accept_view105
accept_view106
.update(cx, |this, cx| this.accept_reaction(&accept_key, &accept_id, &emoji, cx))106
.update(cx, |this, cx| {107
this.accept_reaction(&accept_key, &accept_id, &emoji, cx)108
})107
.ok();109
.ok();108
}),110
}),109
discard: Rc::new(move |cx| {111
discard: Rc::new(move |cx| {110
discard_view112
discard_view111
.update(cx, |this, cx| this.discard_reaction(&discard_key, &discard_id, cx))113
.update(cx, |this, cx| {114
this.discard_reaction(&discard_key, &discard_id, cx)115
})112
.ok();116
.ok();113
}),117
}),114
})118
})@@ -300,6 +304,10 @@ impl RenderEnv {300
.app304
.app301
.read(cx)305
.read(cx)302
.is_saved(&message.conversation_id, &message.key),306
.is_saved(&message.conversation_id, &message.key),307
pinned: self308
.app309
.read(cx)310
.is_pinned(&message.conversation_id, &message.key),303
translation,311
translation,304
timeline: self.timeline.clone(),312
timeline: self.timeline.clone(),305
agent_run: actionable_run,313
agent_run: actionable_run,@@ -365,9 +373,11 @@ impl RenderEnv {365
})373
})366
};374
};367
let recording = call.recap.as_ref().map(|recap| &recap.recording);375
let recording = call.recap.as_ref().map(|recap| &recap.recording);368
let share = recording.and_then(|recording| recording.url.clone()).map(|url| {376
let share = recording369
boxed(move |cx| cx.write_to_clipboard(ClipboardItem::new_string(url.clone())))377
.and_then(|recording| recording.url.clone())370
});378
.map(|url| {379
boxed(move |cx| cx.write_to_clipboard(ClipboardItem::new_string(url.clone())))380
});371
CallActions {381
CallActions {372
call_back,382
call_back,373
join,383
join,@@ -0,0 +1,263 @@
1
use std::collections::HashSet;
2
use std::rc::Rc;
3
4
use gpui_kit::assets::IconName;
5
use gpui_kit::component::button::{Button, ButtonVariants as _};
6
use gpui_kit::component::dialog::{Dialog, DialogFooter};
7
use gpui_kit::component::popover::Popover;
8
use gpui_kit::component::tooltip::Tooltip;
9
use gpui_kit::component::{Disableable as _, WindowExt as _, h_flex, v_flex};
10
use gpui_kit::prelude::FluentBuilder as _;
11
use gpui_kit::*;
12
13
use super::reaction_picker::ReactionPicker;
14
use super::widgets::{Corner, corner_badge, icon};
15
use crate::app_state::AppState;
16
use crate::default_reactions::{
17
filled, place_in_slot, quick_reaction_glyphs, reaction_id_for_glyph, slots_for,
18
};
19
use crate::emoji;
20
use crate::emoticons::{SKIN_TONE_COUNT, with_tone};
21
use crate::theme;
22
23
pub const CUSTOMIZE_TOOLTIP: &str = "Customise default reactions";
24
const TITLE: &str = "Customise your reactions and appearance in Teams";
25
const DESCRIPTION: &str = "Click on a reaction below, then choose an emoji to replace it with.";
26
const SKIN_TONE_TEXT: &str =
27
"Choose a skin tone. After selection, reactions and emoji will appear with this skin tone.";
28
const CHOOSE_EMOJI: &str = "Choose an emoji";
29
const REMOVE_REACTION: &str = "Remove reaction";
30
const TONE_SAMPLE: &str = "\u{1F44D}";
31
const DIALOG_WIDTH: f32 = 440.;
32
const SLOT_SIZE: f32 = 48.;
33
const SLOT_GLYPH_SIZE: f32 = 26.;
34
const TONE_SIZE: f32 = 36.;
35
const TONE_GLYPH_SIZE: f32 = 20.;
36
const REMOVE_SIZE: f32 = 18.;
37
const REMOVE_OVERHANG: f32 = 5.;
38
const SECTION_GAP: f32 = 16.;
39
const TEXT_SIZE: f32 = 13.;
40
41
struct CustomizeForm {
42
state: Entity<AppState>,
43
picker: Entity<ReactionPicker>,
44
saved_ids: Vec<String>,
45
saved_tone: u8,
46
slots: Vec<Option<String>>,
47
skin_tone: u8,
48
}
49
50
impl CustomizeForm {
51
fn new(state: Entity<AppState>, window: &mut Window, cx: &mut Context<Self>) -> Self {
52
let (saved_ids, saved_tone, store) = {
53
let app = state.read(cx);
54
(
55
app.default_reactions(),
56
teams_core::skin_tone(&app.store),
57
app.store.clone(),
58
)
59
};
60
let recent = cx.new(|_| emoji::Recent::load(&store));
61
let picker_state = state.clone();
62
let picker =
63
cx.new(|cx| ReactionPicker::new(picker_state, recent, window, cx).for_customizing());
64
CustomizeForm {
65
state,
66
picker,
67
slots: slots_for(&saved_ids),
68
saved_ids,
69
saved_tone,
70
skin_tone: saved_tone,
71
}
72
}
73
74
fn unchanged(&self) -> bool {
75
filled(&self.slots) == self.saved_ids && self.skin_tone == self.saved_tone
76
}
77
78
fn place(&mut self, index: usize, glyph: &str, cx: &mut Context<Self>) {
79
if let Some(reaction_id) = reaction_id_for_glyph(glyph) {
80
place_in_slot(&mut self.slots, index, reaction_id);
81
cx.notify();
82
}
83
}
84
85
fn remove(&mut self, index: usize, cx: &mut Context<Self>) {
86
if let Some(slot) = self.slots.get_mut(index) {
87
*slot = None;
88
cx.notify();
89
}
90
}
91
92
fn save(&mut self, window: &mut Window, cx: &mut Context<Self>) {
93
let reaction_ids = filled(&self.slots);
94
let (tone_changed, tone) = (self.skin_tone != self.saved_tone, self.skin_tone);
95
self.state.update(cx, |state, cx| {
96
if tone_changed {
97
state.set_skin_tone(tone, cx);
98
}
99
state.set_default_reactions(reaction_ids, cx);
100
});
101
window.close_dialog(cx);
102
}
103
104
fn slot_glyph(&self, reaction_id: &str) -> Option<String> {
105
quick_reaction_glyphs(&[reaction_id.to_owned()], self.skin_tone)
106
.into_iter()
107
.next()
108
}
109
110
fn slot(&self, index: usize, cx: &mut Context<Self>) -> AnyElement {
111
let glyph = self
112
.slots
113
.get(index)
114
.cloned()
115
.flatten()
116
.and_then(|reaction_id| self.slot_glyph(&reaction_id));
117
let label = if glyph.is_some() {
118
REMOVE_REACTION
119
} else {
120
CHOOSE_EMOJI
121
};
122
let trigger = Button::new(("customize-reaction-slot", index))
123
.size(px(SLOT_SIZE))
124
.rounded(px(10.))
125
.tooltip(label)
126
.map(|button| match &glyph {
127
Some(glyph) => {
128
button.child(div().text_size(px(SLOT_GLYPH_SIZE)).child(glyph.clone()))
129
}
130
None => button.child(icon(IconName::Plus, 18., theme::text_muted())),
131
});
132
let (picker, view) = (self.picker.clone(), cx.entity().downgrade());
133
let selected: HashSet<String> = glyph.iter().cloned().collect();
134
let popover = Popover::new(("customize-reaction-picker", index))
135
.anchor(Anchor::TopLeft)
136
.trigger(trigger)
137
.on_open_change({
138
let picker = self.picker.clone();
139
move |open, window, cx| {
140
if *open {
141
picker.update(cx, |picker, cx| picker.reset(window, cx));
142
}
143
}
144
})
145
.content(move |_, _, cx| {
146
let popover = cx.entity().downgrade();
147
let view = view.clone();
148
picker.update(cx, |picker, _| {
149
picker.set_target(
150
Rc::new(move |glyph, _, cx| {
151
view.update(cx, |form, cx| form.place(index, glyph, cx))
152
.ok();
153
}),
154
Rc::new(|_, _| {}),
155
popover,
156
selected.clone(),
157
)
158
});
159
picker.clone()
160
});
161
let remove = glyph.is_some().then(|| {
162
corner_badge(Corner::TopRight, REMOVE_OVERHANG).child(
163
div()
164
.id(("customize-reaction-remove", index))
165
.size(px(REMOVE_SIZE))
166
.flex()
167
.items_center()
168
.justify_center()
169
.rounded_full()
170
.cursor_pointer()
171
.bg(theme::popup_hover())
172
.hover(|button| button.bg(theme::row_hover()))
173
.child(icon(IconName::X, 10., theme::text_soft()))
174
.tooltip(|window, cx| Tooltip::new(REMOVE_REACTION).build(window, cx))
175
.on_click(cx.listener(move |form, _, _, cx| {
176
cx.stop_propagation();
177
form.remove(index, cx);
178
})),
179
)
180
});
181
div()
182
.relative()
183
.child(popover)
184
.children(remove)
185
.into_any_element()
186
}
187
188
fn tone_choice(&self, tone: u8, cx: &mut Context<Self>) -> AnyElement {
189
let selected = tone == self.skin_tone;
190
div()
191
.id(("customize-skin-tone", usize::from(tone)))
192
.size(px(TONE_SIZE))
193
.flex()
194
.items_center()
195
.justify_center()
196
.rounded_full()
197
.cursor_pointer()
198
.text_size(px(TONE_GLYPH_SIZE))
199
.when(selected, |choice| choice.bg(theme::reaction_on_own()))
200
.when(!selected, |choice| {
201
choice.hover(|choice| choice.bg(theme::popup_hover()))
202
})
203
.child(with_tone(TONE_SAMPLE, tone))
204
.on_click(cx.listener(move |form, _, _, cx| {
205
form.skin_tone = tone;
206
cx.notify();
207
}))
208
.into_any_element()
209
}
210
}
211
212
impl Render for CustomizeForm {
213
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
214
let slots: Vec<AnyElement> = (0..self.slots.len())
215
.map(|index| self.slot(index, cx))
216
.collect();
217
let tones: Vec<AnyElement> = (0..=SKIN_TONE_COUNT)
218
.map(|tone| self.tone_choice(tone, cx))
219
.collect();
220
v_flex()
221
.gap(px(SECTION_GAP))
222
.text_size(px(TEXT_SIZE))
223
.text_color(theme::text())
224
.child(div().text_color(theme::text_soft()).child(DESCRIPTION))
225
.child(
226
h_flex()
227
.justify_center()
228
.gap(px(10.))
229
.py(px(4.))
230
.children(slots),
231
)
232
.child(div().text_color(theme::text_soft()).child(SKIN_TONE_TEXT))
233
.child(h_flex().gap(px(6.)).children(tones))
234
}
235
}
236
237
pub fn open_customize_reactions(state: Entity<AppState>, window: &mut Window, cx: &mut App) {
238
let form = cx.new(|cx| CustomizeForm::new(state, window, cx));
239
window.open_dialog(cx, move |dialog: Dialog, _, cx| {
240
let submit_form = form.clone();
241
let unchanged = form.read(cx).unchanged();
242
let footer = DialogFooter::new()
243
.child(
244
Button::new("customize-reactions-cancel")
245
.label("Cancel")
246
.on_click(|_, window, cx| window.close_dialog(cx)),
247
)
248
.child(
249
Button::new("customize-reactions-save")
250
.primary()
251
.label("Save")
252
.disabled(unchanged)
253
.on_click(move |_, window, cx| {
254
submit_form.update(cx, |form, cx| form.save(window, cx));
255
}),
256
);
257
dialog
258
.title(TITLE)
259
.w(px(DIALOG_WIDTH))
260
.child(form.clone())
261
.footer(footer)
262
});
263
}
@@ -0,0 +1,263 @@1
use std::collections::HashSet;2
use std::rc::Rc;3
4
use gpui_kit::assets::IconName;5
use gpui_kit::component::button::{Button, ButtonVariants as _};6
use gpui_kit::component::dialog::{Dialog, DialogFooter};7
use gpui_kit::component::popover::Popover;8
use gpui_kit::component::tooltip::Tooltip;9
use gpui_kit::component::{Disableable as _, WindowExt as _, h_flex, v_flex};10
use gpui_kit::prelude::FluentBuilder as _;11
use gpui_kit::*;12
13
use super::reaction_picker::ReactionPicker;14
use super::widgets::{Corner, corner_badge, icon};15
use crate::app_state::AppState;16
use crate::default_reactions::{17
filled, place_in_slot, quick_reaction_glyphs, reaction_id_for_glyph, slots_for,18
};19
use crate::emoji;20
use crate::emoticons::{SKIN_TONE_COUNT, with_tone};21
use crate::theme;22
23
pub const CUSTOMIZE_TOOLTIP: &str = "Customise default reactions";24
const TITLE: &str = "Customise your reactions and appearance in Teams";25
const DESCRIPTION: &str = "Click on a reaction below, then choose an emoji to replace it with.";26
const SKIN_TONE_TEXT: &str =27
"Choose a skin tone. After selection, reactions and emoji will appear with this skin tone.";28
const CHOOSE_EMOJI: &str = "Choose an emoji";29
const REMOVE_REACTION: &str = "Remove reaction";30
const TONE_SAMPLE: &str = "\u{1F44D}";31
const DIALOG_WIDTH: f32 = 440.;32
const SLOT_SIZE: f32 = 48.;33
const SLOT_GLYPH_SIZE: f32 = 26.;34
const TONE_SIZE: f32 = 36.;35
const TONE_GLYPH_SIZE: f32 = 20.;36
const REMOVE_SIZE: f32 = 18.;37
const REMOVE_OVERHANG: f32 = 5.;38
const SECTION_GAP: f32 = 16.;39
const TEXT_SIZE: f32 = 13.;40
41
struct CustomizeForm {42
state: Entity<AppState>,43
picker: Entity<ReactionPicker>,44
saved_ids: Vec<String>,45
saved_tone: u8,46
slots: Vec<Option<String>>,47
skin_tone: u8,48
}49
50
impl CustomizeForm {51
fn new(state: Entity<AppState>, window: &mut Window, cx: &mut Context<Self>) -> Self {52
let (saved_ids, saved_tone, store) = {53
let app = state.read(cx);54
(55
app.default_reactions(),56
teams_core::skin_tone(&app.store),57
app.store.clone(),58
)59
};60
let recent = cx.new(|_| emoji::Recent::load(&store));61
let picker_state = state.clone();62
let picker =63
cx.new(|cx| ReactionPicker::new(picker_state, recent, window, cx).for_customizing());64
CustomizeForm {65
state,66
picker,67
slots: slots_for(&saved_ids),68
saved_ids,69
saved_tone,70
skin_tone: saved_tone,71
}72
}73
74
fn unchanged(&self) -> bool {75
filled(&self.slots) == self.saved_ids && self.skin_tone == self.saved_tone76
}77
78
fn place(&mut self, index: usize, glyph: &str, cx: &mut Context<Self>) {79
if let Some(reaction_id) = reaction_id_for_glyph(glyph) {80
place_in_slot(&mut self.slots, index, reaction_id);81
cx.notify();82
}83
}84
85
fn remove(&mut self, index: usize, cx: &mut Context<Self>) {86
if let Some(slot) = self.slots.get_mut(index) {87
*slot = None;88
cx.notify();89
}90
}91
92
fn save(&mut self, window: &mut Window, cx: &mut Context<Self>) {93
let reaction_ids = filled(&self.slots);94
let (tone_changed, tone) = (self.skin_tone != self.saved_tone, self.skin_tone);95
self.state.update(cx, |state, cx| {96
if tone_changed {97
state.set_skin_tone(tone, cx);98
}99
state.set_default_reactions(reaction_ids, cx);100
});101
window.close_dialog(cx);102
}103
104
fn slot_glyph(&self, reaction_id: &str) -> Option<String> {105
quick_reaction_glyphs(&[reaction_id.to_owned()], self.skin_tone)106
.into_iter()107
.next()108
}109
110
fn slot(&self, index: usize, cx: &mut Context<Self>) -> AnyElement {111
let glyph = self112
.slots113
.get(index)114
.cloned()115
.flatten()116
.and_then(|reaction_id| self.slot_glyph(&reaction_id));117
let label = if glyph.is_some() {118
REMOVE_REACTION119
} else {120
CHOOSE_EMOJI121
};122
let trigger = Button::new(("customize-reaction-slot", index))123
.size(px(SLOT_SIZE))124
.rounded(px(10.))125
.tooltip(label)126
.map(|button| match &glyph {127
Some(glyph) => {128
button.child(div().text_size(px(SLOT_GLYPH_SIZE)).child(glyph.clone()))129
}130
None => button.child(icon(IconName::Plus, 18., theme::text_muted())),131
});132
let (picker, view) = (self.picker.clone(), cx.entity().downgrade());133
let selected: HashSet<String> = glyph.iter().cloned().collect();134
let popover = Popover::new(("customize-reaction-picker", index))135
.anchor(Anchor::TopLeft)136
.trigger(trigger)137
.on_open_change({138
let picker = self.picker.clone();139
move |open, window, cx| {140
if *open {141
picker.update(cx, |picker, cx| picker.reset(window, cx));142
}143
}144
})145
.content(move |_, _, cx| {146
let popover = cx.entity().downgrade();147
let view = view.clone();148
picker.update(cx, |picker, _| {149
picker.set_target(150
Rc::new(move |glyph, _, cx| {151
view.update(cx, |form, cx| form.place(index, glyph, cx))152
.ok();153
}),154
Rc::new(|_, _| {}),155
popover,156
selected.clone(),157
)158
});159
picker.clone()160
});161
let remove = glyph.is_some().then(|| {162
corner_badge(Corner::TopRight, REMOVE_OVERHANG).child(163
div()164
.id(("customize-reaction-remove", index))165
.size(px(REMOVE_SIZE))166
.flex()167
.items_center()168
.justify_center()169
.rounded_full()170
.cursor_pointer()171
.bg(theme::popup_hover())172
.hover(|button| button.bg(theme::row_hover()))173
.child(icon(IconName::X, 10., theme::text_soft()))174
.tooltip(|window, cx| Tooltip::new(REMOVE_REACTION).build(window, cx))175
.on_click(cx.listener(move |form, _, _, cx| {176
cx.stop_propagation();177
form.remove(index, cx);178
})),179
)180
});181
div()182
.relative()183
.child(popover)184
.children(remove)185
.into_any_element()186
}187
188
fn tone_choice(&self, tone: u8, cx: &mut Context<Self>) -> AnyElement {189
let selected = tone == self.skin_tone;190
div()191
.id(("customize-skin-tone", usize::from(tone)))192
.size(px(TONE_SIZE))193
.flex()194
.items_center()195
.justify_center()196
.rounded_full()197
.cursor_pointer()198
.text_size(px(TONE_GLYPH_SIZE))199
.when(selected, |choice| choice.bg(theme::reaction_on_own()))200
.when(!selected, |choice| {201
choice.hover(|choice| choice.bg(theme::popup_hover()))202
})203
.child(with_tone(TONE_SAMPLE, tone))204
.on_click(cx.listener(move |form, _, _, cx| {205
form.skin_tone = tone;206
cx.notify();207
}))208
.into_any_element()209
}210
}211
212
impl Render for CustomizeForm {213
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {214
let slots: Vec<AnyElement> = (0..self.slots.len())215
.map(|index| self.slot(index, cx))216
.collect();217
let tones: Vec<AnyElement> = (0..=SKIN_TONE_COUNT)218
.map(|tone| self.tone_choice(tone, cx))219
.collect();220
v_flex()221
.gap(px(SECTION_GAP))222
.text_size(px(TEXT_SIZE))223
.text_color(theme::text())224
.child(div().text_color(theme::text_soft()).child(DESCRIPTION))225
.child(226
h_flex()227
.justify_center()228
.gap(px(10.))229
.py(px(4.))230
.children(slots),231
)232
.child(div().text_color(theme::text_soft()).child(SKIN_TONE_TEXT))233
.child(h_flex().gap(px(6.)).children(tones))234
}235
}236
237
pub fn open_customize_reactions(state: Entity<AppState>, window: &mut Window, cx: &mut App) {238
let form = cx.new(|cx| CustomizeForm::new(state, window, cx));239
window.open_dialog(cx, move |dialog: Dialog, _, cx| {240
let submit_form = form.clone();241
let unchanged = form.read(cx).unchanged();242
let footer = DialogFooter::new()243
.child(244
Button::new("customize-reactions-cancel")245
.label("Cancel")246
.on_click(|_, window, cx| window.close_dialog(cx)),247
)248
.child(249
Button::new("customize-reactions-save")250
.primary()251
.label("Save")252
.disabled(unchanged)253
.on_click(move |_, window, cx| {254
submit_form.update(cx, |form, cx| form.save(window, cx));255
}),256
);257
dialog258
.title(TITLE)259
.w(px(DIALOG_WIDTH))260
.child(form.clone())261
.footer(footer)262
});263
}@@ -0,0 +1,196 @@
1
use std::cell::RefCell;
2
use std::rc::Rc;
3
4
use chatsvc::{INVALID_TOPIC_CHARACTER, MAX_TOPIC_LENGTH, TopicProblem, topic_problem};
5
use gpui_kit::assets::IconName;
6
use gpui_kit::base::PopoverState;
7
use gpui_kit::component::button::{Button, ButtonVariants as _};
8
use gpui_kit::component::input::{Input, InputEvent, InputState};
9
use gpui_kit::component::popover::Popover;
10
use gpui_kit::component::{Disableable as _, h_flex, v_flex};
11
use gpui_kit::prelude::FluentBuilder as _;
12
use gpui_kit::*;
13
14
use super::widgets::icon;
15
use crate::app_state::AppState;
16
use crate::theme;
17
18
const BUTTON_TOOLTIP: &str = "Name group chat";
19
const FIELD_LABEL: &str = "Group name";
20
const PLACEHOLDER: &str = "Type a group name";
21
const FORM_WIDTH: f32 = 300.;
22
const FORM_PADDING: f32 = 12.;
23
const FORM_GAP: f32 = 8.;
24
const LABEL_SIZE: f32 = 12.;
25
const ICON_SIZE: f32 = 16.;
26
27
pub fn problem_text(problem: TopicProblem) -> String {
28
match problem {
29
TopicProblem::TooLong => {
30
format!("Your group name can't be longer than {MAX_TOPIC_LENGTH} characters.")
31
}
32
TopicProblem::InvalidCharacter => {
33
format!("'{INVALID_TOPIC_CHARACTER}' is not a valid character in group names.")
34
}
35
}
36
}
37
38
struct GroupNameForm {
39
app: Entity<AppState>,
40
chat_id: String,
41
input: Entity<InputState>,
42
popover: WeakEntity<PopoverState>,
43
_subscription: Subscription,
44
}
45
46
impl GroupNameForm {
47
fn new(
48
app: Entity<AppState>,
49
chat_id: String,
50
title: String,
51
popover: WeakEntity<PopoverState>,
52
window: &mut Window,
53
cx: &mut Context<Self>,
54
) -> Self {
55
let input = cx.new(|cx| {
56
let mut state = InputState::new(window, cx).placeholder(PLACEHOLDER);
57
state.set_value(title, window, cx);
58
state
59
});
60
input.update(cx, |state, cx| state.focus(window, cx));
61
let subscription = cx.subscribe_in(&input, window, Self::on_input_event);
62
GroupNameForm {
63
app,
64
chat_id,
65
input,
66
popover,
67
_subscription: subscription,
68
}
69
}
70
71
fn on_input_event(
72
&mut self,
73
_: &Entity<InputState>,
74
event: &InputEvent,
75
window: &mut Window,
76
cx: &mut Context<Self>,
77
) {
78
match event {
79
InputEvent::Change => cx.notify(),
80
InputEvent::PressEnter { .. } => self.save(window, cx),
81
_ => {}
82
}
83
}
84
85
fn problem(&self, cx: &App) -> Option<TopicProblem> {
86
topic_problem(self.input.read(cx).value().trim())
87
}
88
89
fn close(&self, window: &mut Window, cx: &mut App) {
90
self.popover
91
.update(cx, |state, cx| state.dismiss(window, cx))
92
.ok();
93
}
94
95
fn save(&mut self, window: &mut Window, cx: &mut Context<Self>) {
96
if self.problem(cx).is_some() {
97
return;
98
}
99
let topic = self.input.read(cx).value().trim().to_owned();
100
let chat_id = self.chat_id.clone();
101
self.app
102
.update(cx, |state, cx| state.rename_chat(&chat_id, &topic, cx));
103
self.close(window, cx);
104
}
105
}
106
107
impl Render for GroupNameForm {
108
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
109
let problem = self.problem(cx);
110
v_flex()
111
.w(px(FORM_WIDTH))
112
.p(px(FORM_PADDING))
113
.gap(px(FORM_GAP))
114
.child(
115
div()
116
.text_size(px(LABEL_SIZE))
117
.text_color(theme::text_soft())
118
.child(FIELD_LABEL),
119
)
120
.child(Input::new(&self.input))
121
.when_some(problem, |form, problem| {
122
form.child(
123
div()
124
.text_size(px(LABEL_SIZE))
125
.text_color(theme::red_soft())
126
.child(problem_text(problem)),
127
)
128
})
129
.child(
130
h_flex()
131
.justify_end()
132
.gap(px(FORM_GAP))
133
.child(
134
Button::new("group-name-cancel")
135
.label("Cancel")
136
.on_click(cx.listener(|form, _, window, cx| form.close(window, cx))),
137
)
138
.child(
139
Button::new("group-name-save")
140
.primary()
141
.label("Save")
142
.disabled(problem.is_some())
143
.on_click(cx.listener(|form, _, window, cx| form.save(window, cx))),
144
),
145
)
146
}
147
}
148
149
pub fn group_name_button(app: &Entity<AppState>, chat_id: &str, title: &str) -> AnyElement {
150
let (app, chat_id, title) = (app.clone(), chat_id.to_owned(), title.to_owned());
151
let form: Rc<RefCell<Option<Entity<GroupNameForm>>>> = Rc::default();
152
let reset = form.clone();
153
Popover::new("group-name")
154
.anchor(Anchor::TopLeft)
155
.p(px(0.))
156
.trigger(
157
Button::new("group-name-button")
158
.ghost()
159
.compact()
160
.tooltip(BUTTON_TOOLTIP)
161
.child(icon(IconName::Pencil, ICON_SIZE, theme::text_soft())),
162
)
163
.on_open_change(move |open, _, _| {
164
if !*open {
165
reset.borrow_mut().take();
166
}
167
})
168
.content(move |_, window, cx| {
169
if let Some(existing) = form.borrow().clone() {
170
return existing;
171
}
172
let popover = cx.entity().downgrade();
173
let (app, chat_id, title) = (app.clone(), chat_id.clone(), title.clone());
174
let created = cx.new(|cx| GroupNameForm::new(app, chat_id, title, popover, window, cx));
175
*form.borrow_mut() = Some(created.clone());
176
created
177
})
178
.into_any_element()
179
}
180
181
#[cfg(test)]
182
mod tests {
183
use super::{TopicProblem, problem_text};
184
185
#[test]
186
fn problems_use_the_teams_wording() {
187
assert_eq!(
188
problem_text(TopicProblem::TooLong),
189
"Your group name can't be longer than 250 characters."
190
);
191
assert_eq!(
192
problem_text(TopicProblem::InvalidCharacter),
193
"':' is not a valid character in group names."
194
);
195
}
196
}
@@ -0,0 +1,196 @@1
use std::cell::RefCell;2
use std::rc::Rc;3
4
use chatsvc::{INVALID_TOPIC_CHARACTER, MAX_TOPIC_LENGTH, TopicProblem, topic_problem};5
use gpui_kit::assets::IconName;6
use gpui_kit::base::PopoverState;7
use gpui_kit::component::button::{Button, ButtonVariants as _};8
use gpui_kit::component::input::{Input, InputEvent, InputState};9
use gpui_kit::component::popover::Popover;10
use gpui_kit::component::{Disableable as _, h_flex, v_flex};11
use gpui_kit::prelude::FluentBuilder as _;12
use gpui_kit::*;13
14
use super::widgets::icon;15
use crate::app_state::AppState;16
use crate::theme;17
18
const BUTTON_TOOLTIP: &str = "Name group chat";19
const FIELD_LABEL: &str = "Group name";20
const PLACEHOLDER: &str = "Type a group name";21
const FORM_WIDTH: f32 = 300.;22
const FORM_PADDING: f32 = 12.;23
const FORM_GAP: f32 = 8.;24
const LABEL_SIZE: f32 = 12.;25
const ICON_SIZE: f32 = 16.;26
27
pub fn problem_text(problem: TopicProblem) -> String {28
match problem {29
TopicProblem::TooLong => {30
format!("Your group name can't be longer than {MAX_TOPIC_LENGTH} characters.")31
}32
TopicProblem::InvalidCharacter => {33
format!("'{INVALID_TOPIC_CHARACTER}' is not a valid character in group names.")34
}35
}36
}37
38
struct GroupNameForm {39
app: Entity<AppState>,40
chat_id: String,41
input: Entity<InputState>,42
popover: WeakEntity<PopoverState>,43
_subscription: Subscription,44
}45
46
impl GroupNameForm {47
fn new(48
app: Entity<AppState>,49
chat_id: String,50
title: String,51
popover: WeakEntity<PopoverState>,52
window: &mut Window,53
cx: &mut Context<Self>,54
) -> Self {55
let input = cx.new(|cx| {56
let mut state = InputState::new(window, cx).placeholder(PLACEHOLDER);57
state.set_value(title, window, cx);58
state59
});60
input.update(cx, |state, cx| state.focus(window, cx));61
let subscription = cx.subscribe_in(&input, window, Self::on_input_event);62
GroupNameForm {63
app,64
chat_id,65
input,66
popover,67
_subscription: subscription,68
}69
}70
71
fn on_input_event(72
&mut self,73
_: &Entity<InputState>,74
event: &InputEvent,75
window: &mut Window,76
cx: &mut Context<Self>,77
) {78
match event {79
InputEvent::Change => cx.notify(),80
InputEvent::PressEnter { .. } => self.save(window, cx),81
_ => {}82
}83
}84
85
fn problem(&self, cx: &App) -> Option<TopicProblem> {86
topic_problem(self.input.read(cx).value().trim())87
}88
89
fn close(&self, window: &mut Window, cx: &mut App) {90
self.popover91
.update(cx, |state, cx| state.dismiss(window, cx))92
.ok();93
}94
95
fn save(&mut self, window: &mut Window, cx: &mut Context<Self>) {96
if self.problem(cx).is_some() {97
return;98
}99
let topic = self.input.read(cx).value().trim().to_owned();100
let chat_id = self.chat_id.clone();101
self.app102
.update(cx, |state, cx| state.rename_chat(&chat_id, &topic, cx));103
self.close(window, cx);104
}105
}106
107
impl Render for GroupNameForm {108
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {109
let problem = self.problem(cx);110
v_flex()111
.w(px(FORM_WIDTH))112
.p(px(FORM_PADDING))113
.gap(px(FORM_GAP))114
.child(115
div()116
.text_size(px(LABEL_SIZE))117
.text_color(theme::text_soft())118
.child(FIELD_LABEL),119
)120
.child(Input::new(&self.input))121
.when_some(problem, |form, problem| {122
form.child(123
div()124
.text_size(px(LABEL_SIZE))125
.text_color(theme::red_soft())126
.child(problem_text(problem)),127
)128
})129
.child(130
h_flex()131
.justify_end()132
.gap(px(FORM_GAP))133
.child(134
Button::new("group-name-cancel")135
.label("Cancel")136
.on_click(cx.listener(|form, _, window, cx| form.close(window, cx))),137
)138
.child(139
Button::new("group-name-save")140
.primary()141
.label("Save")142
.disabled(problem.is_some())143
.on_click(cx.listener(|form, _, window, cx| form.save(window, cx))),144
),145
)146
}147
}148
149
pub fn group_name_button(app: &Entity<AppState>, chat_id: &str, title: &str) -> AnyElement {150
let (app, chat_id, title) = (app.clone(), chat_id.to_owned(), title.to_owned());151
let form: Rc<RefCell<Option<Entity<GroupNameForm>>>> = Rc::default();152
let reset = form.clone();153
Popover::new("group-name")154
.anchor(Anchor::TopLeft)155
.p(px(0.))156
.trigger(157
Button::new("group-name-button")158
.ghost()159
.compact()160
.tooltip(BUTTON_TOOLTIP)161
.child(icon(IconName::Pencil, ICON_SIZE, theme::text_soft())),162
)163
.on_open_change(move |open, _, _| {164
if !*open {165
reset.borrow_mut().take();166
}167
})168
.content(move |_, window, cx| {169
if let Some(existing) = form.borrow().clone() {170
return existing;171
}172
let popover = cx.entity().downgrade();173
let (app, chat_id, title) = (app.clone(), chat_id.clone(), title.clone());174
let created = cx.new(|cx| GroupNameForm::new(app, chat_id, title, popover, window, cx));175
*form.borrow_mut() = Some(created.clone());176
created177
})178
.into_any_element()179
}180
181
#[cfg(test)]182
mod tests {183
use super::{TopicProblem, problem_text};184
185
#[test]186
fn problems_use_the_teams_wording() {187
assert_eq!(188
problem_text(TopicProblem::TooLong),189
"Your group name can't be longer than 250 characters."190
);191
assert_eq!(192
problem_text(TopicProblem::InvalidCharacter),193
"':' is not a valid character in group names."194
);195
}196
}@@ -23,7 +23,6 @@ const BAR_PADDING: f32 = 3.;
23
23
const BAR_ICON: f32 = 16.;
24
24
const DELEGATE_ITEM_WIDTH: f32 = 188.;
25
25
const DELEGATE_AGENT_SIZE: f32 = 11.;
26
pub const QUICK_REACTION_COUNT: usize = 4;
27
26
28
27
pub type Action = Rc<dyn Fn(&mut Window, &mut App)>;
29
28
pub type OpenChange = Rc<dyn Fn(bool, &mut Window, &mut App)>;
@@ -23,7 +23,6 @@ const BAR_PADDING: f32 = 3.;23
const BAR_ICON: f32 = 16.;23
const BAR_ICON: f32 = 16.;24
const DELEGATE_ITEM_WIDTH: f32 = 188.;24
const DELEGATE_ITEM_WIDTH: f32 = 188.;25
const DELEGATE_AGENT_SIZE: f32 = 11.;25
const DELEGATE_AGENT_SIZE: f32 = 11.;26
pub const QUICK_REACTION_COUNT: usize = 4;27
26
28
pub type Action = Rc<dyn Fn(&mut Window, &mut App)>;27
pub type Action = Rc<dyn Fn(&mut Window, &mut App)>;29
pub type OpenChange = Rc<dyn Fn(bool, &mut Window, &mut App)>;28
pub type OpenChange = Rc<dyn Fn(bool, &mut Window, &mut App)>;@@ -82,6 +82,7 @@ pub struct RowActions {
82
82
pub open_image: Option<ImageActions>,
83
83
pub highlighted: bool,
84
84
pub saved: bool,
85
pub pinned: bool,
85
86
pub translation: Option<TranslationActions>,
86
87
pub timeline: TimelineBounds,
87
88
pub agent_run: Option<AgentRun>,
@@ -638,15 +639,12 @@ fn own_row(
638
639
let reaction_proposal = extras.reaction_proposal.take();
639
640
let mut column = v_flex().w_full().items_end().gap(px(2.));
640
641
column = column.child(
641
h_flex()
642
.w_full()
643
.justify_end()
644
.child(
645
div()
646
.min_w_0()
647
.max_w(bubble_max_width(&extras.timeline, 0.))
648
.child(bubble(row, index, true, directory, extras, cx)),
649
),
642
h_flex().w_full().justify_end().child(
643
div()
644
.min_w_0()
645
.max_w(bubble_max_width(&extras.timeline, 0.))
646
.child(bubble(row, index, true, directory, extras, cx)),
647
),
650
648
);
651
649
column = column.children(agent_chip(agent_run));
652
650
column = column.children(reaction_proposal.map(|pill| reaction_pill(pill, &row.key)));
@@ -684,6 +682,7 @@ pub fn render_message_row(
684
682
timeline,
685
683
agent_run,
686
684
call: _,
685
pinned: _,
687
686
reaction_proposal,
688
687
undo_delete,
689
688
} = actions;
@@ -82,6 +82,7 @@ pub struct RowActions {82
pub open_image: Option<ImageActions>,82
pub open_image: Option<ImageActions>,83
pub highlighted: bool,83
pub highlighted: bool,84
pub saved: bool,84
pub saved: bool,85
pub pinned: bool,85
pub translation: Option<TranslationActions>,86
pub translation: Option<TranslationActions>,86
pub timeline: TimelineBounds,87
pub timeline: TimelineBounds,87
pub agent_run: Option<AgentRun>,88
pub agent_run: Option<AgentRun>,@@ -638,15 +639,12 @@ fn own_row(638
let reaction_proposal = extras.reaction_proposal.take();639
let reaction_proposal = extras.reaction_proposal.take();639
let mut column = v_flex().w_full().items_end().gap(px(2.));640
let mut column = v_flex().w_full().items_end().gap(px(2.));640
column = column.child(641
column = column.child(641
h_flex()642
h_flex().w_full().justify_end().child(642
.w_full()643
div()643
.justify_end()644
.min_w_0()644
.child(645
.max_w(bubble_max_width(&extras.timeline, 0.))645
div()646
.child(bubble(row, index, true, directory, extras, cx)),646
.min_w_0()647
),647
.max_w(bubble_max_width(&extras.timeline, 0.))648
.child(bubble(row, index, true, directory, extras, cx)),649
),650
);648
);651
column = column.children(agent_chip(agent_run));649
column = column.children(agent_chip(agent_run));652
column = column.children(reaction_proposal.map(|pill| reaction_pill(pill, &row.key)));650
column = column.children(reaction_proposal.map(|pill| reaction_pill(pill, &row.key)));@@ -684,6 +682,7 @@ pub fn render_message_row(684
timeline,682
timeline,685
agent_run,683
agent_run,686
call: _,684
call: _,685
pinned: _,687
reaction_proposal,686
reaction_proposal,688
undo_delete,687
undo_delete,689
} = actions;688
} = actions;@@ -38,12 +38,14 @@ pub mod chat_members;
38
38
pub mod composer;
39
39
pub mod connection_banner;
40
40
pub mod conversation;
41
pub mod customize_reactions;
41
42
pub mod dialog_overlay;
42
43
pub mod emoji_popup;
43
44
pub mod format_toolbar;
44
45
pub mod forward_dialog;
45
46
pub mod find_panel;
46
47
pub mod fun_picker;
48
pub mod group_name;
47
49
pub mod image_menu;
48
50
pub mod image_viewer;
49
51
pub mod join_dialog;
@@ -38,12 +38,14 @@ pub mod chat_members;38
pub mod composer;38
pub mod composer;39
pub mod connection_banner;39
pub mod connection_banner;40
pub mod conversation;40
pub mod conversation;41
pub mod customize_reactions;41
pub mod dialog_overlay;42
pub mod dialog_overlay;42
pub mod emoji_popup;43
pub mod emoji_popup;43
pub mod format_toolbar;44
pub mod format_toolbar;44
pub mod forward_dialog;45
pub mod forward_dialog;45
pub mod find_panel;46
pub mod find_panel;46
pub mod fun_picker;47
pub mod fun_picker;48
pub mod group_name;47
pub mod image_menu;49
pub mod image_menu;48
pub mod image_viewer;50
pub mod image_viewer;49
pub mod join_dialog;51
pub mod join_dialog;@@ -12,7 +12,7 @@ use gpui_kit::component::{WindowExt as _, h_flex, v_flex};
12
12
use gpui_kit::prelude::FluentBuilder as _;
13
13
use gpui_kit::*;
14
14
15
use super::new_chat::NewChatDraft;
15
use super::new_chat::{NewChatDraft, Pick};
16
16
use super::widgets::icon;
17
17
use crate::app_state::AppState;
18
18
use crate::call::{FormValues, Invitee, default_window, draft_from_form};
@@ -233,7 +233,20 @@ impl Render for MeetingForm {
233
233
}
234
234
235
235
pub fn open_new_meeting(state: Entity<AppState>, window: &mut Window, cx: &mut App) {
236
open_new_meeting_with(state, Vec::new(), window, cx);
237
}
238
239
pub fn open_new_meeting_with(
240
state: Entity<AppState>,
241
people: Vec<Pick>,
242
window: &mut Window,
243
cx: &mut App,
244
) {
236
245
let form = cx.new(|cx| MeetingForm::new(state, window, cx));
246
if !people.is_empty() {
247
let draft = form.read(cx).people.clone();
248
draft.update(cx, |draft, cx| draft.set_chips(people, cx));
249
}
237
250
let first_field = form.read(cx).title.clone();
238
251
window.open_dialog(cx, move |dialog: Dialog, _, cx| {
239
252
let submit_form = form.clone();
@@ -12,7 +12,7 @@ use gpui_kit::component::{WindowExt as _, h_flex, v_flex};12
use gpui_kit::prelude::FluentBuilder as _;12
use gpui_kit::prelude::FluentBuilder as _;13
use gpui_kit::*;13
use gpui_kit::*;14
14
15
use super::new_chat::NewChatDraft;15
use super::new_chat::{NewChatDraft, Pick};16
use super::widgets::icon;16
use super::widgets::icon;17
use crate::app_state::AppState;17
use crate::app_state::AppState;18
use crate::call::{FormValues, Invitee, default_window, draft_from_form};18
use crate::call::{FormValues, Invitee, default_window, draft_from_form};@@ -233,7 +233,20 @@ impl Render for MeetingForm {233
}233
}234
234
235
pub fn open_new_meeting(state: Entity<AppState>, window: &mut Window, cx: &mut App) {235
pub fn open_new_meeting(state: Entity<AppState>, window: &mut Window, cx: &mut App) {236
open_new_meeting_with(state, Vec::new(), window, cx);237
}238
239
pub fn open_new_meeting_with(240
state: Entity<AppState>,241
people: Vec<Pick>,242
window: &mut Window,243
cx: &mut App,244
) {236
let form = cx.new(|cx| MeetingForm::new(state, window, cx));245
let form = cx.new(|cx| MeetingForm::new(state, window, cx));246
if !people.is_empty() {247
let draft = form.read(cx).people.clone();248
draft.update(cx, |draft, cx| draft.set_chips(people, cx));249
}237
let first_field = form.read(cx).title.clone();250
let first_field = form.read(cx).title.clone();238
window.open_dialog(cx, move |dialog: Dialog, _, cx| {251
window.open_dialog(cx, move |dialog: Dialog, _, cx| {239
let submit_form = form.clone();252
let submit_form = form.clone();@@ -3,12 +3,15 @@ use gpui_kit::component::{h_flex, tooltip::Tooltip};
3
3
use gpui_kit::prelude::FluentBuilder as _;
4
4
use gpui_kit::*;
5
5
6
use app_ui_kit::layout::ROW_PADDING;
7
6
8
use super::message_actions::Action;
7
9
use super::widgets::icon;
8
10
use crate::theme;
9
11
10
12
const BANNER_HEIGHT: f32 = 40.;
11
const BANNER_MARGIN: f32 = 20.;
13
const BANNER_INSET: f32 = ROW_PADDING;
14
pub const PIN_BANNER_TAG: &str = "shell/islands/main/pin-banner";
12
15
const BANNER_GAP: f32 = 8.;
13
16
const BANNER_PADDING: f32 = 12.;
14
17
const BUTTON_SIZE: f32 = 28.;
@@ -29,15 +32,19 @@ pub struct PinBannerActions {
29
32
}
30
33
31
34
pub fn pin_banner_inset(shown: bool) -> Pixels {
32
px(if shown { BANNER_HEIGHT + BANNER_GAP } else { 0. })
35
px(if shown {
36
BANNER_INSET + BANNER_HEIGHT + BANNER_GAP
37
} else {
38
0.
39
})
33
40
}
34
41
35
42
pub fn pin_banner_overlay(banner: AnyElement) -> AnyElement {
36
43
div()
37
44
.absolute()
38
.top_0()
39
.left(px(BANNER_MARGIN))
40
.right(px(BANNER_MARGIN))
45
.top(px(BANNER_INSET))
46
.left(px(BANNER_INSET))
47
.right(px(BANNER_INSET))
41
48
.child(banner)
42
49
.into_any_element()
43
50
}
@@ -86,6 +93,7 @@ pub fn render_pin_banner(data: PinBannerData, actions: PinBannerActions) -> AnyE
86
93
} = actions;
87
94
h_flex()
88
95
.id("pin-banner")
96
.debug_selector(|| PIN_BANNER_TAG.into())
89
97
.group("pin-banner")
90
98
.occlude()
91
99
.w_full()
@@ -3,12 +3,15 @@ use gpui_kit::component::{h_flex, tooltip::Tooltip};3
use gpui_kit::prelude::FluentBuilder as _;3
use gpui_kit::prelude::FluentBuilder as _;4
use gpui_kit::*;4
use gpui_kit::*;5
5
6
use app_ui_kit::layout::ROW_PADDING;7
6
use super::message_actions::Action;8
use super::message_actions::Action;7
use super::widgets::icon;9
use super::widgets::icon;8
use crate::theme;10
use crate::theme;9
11
10
const BANNER_HEIGHT: f32 = 40.;12
const BANNER_HEIGHT: f32 = 40.;11
const BANNER_MARGIN: f32 = 20.;13
const BANNER_INSET: f32 = ROW_PADDING;14
pub const PIN_BANNER_TAG: &str = "shell/islands/main/pin-banner";12
const BANNER_GAP: f32 = 8.;15
const BANNER_GAP: f32 = 8.;13
const BANNER_PADDING: f32 = 12.;16
const BANNER_PADDING: f32 = 12.;14
const BUTTON_SIZE: f32 = 28.;17
const BUTTON_SIZE: f32 = 28.;@@ -29,15 +32,19 @@ pub struct PinBannerActions {29
}32
}30
33
31
pub fn pin_banner_inset(shown: bool) -> Pixels {34
pub fn pin_banner_inset(shown: bool) -> Pixels {32
px(if shown { BANNER_HEIGHT + BANNER_GAP } else { 0. })35
px(if shown {36
BANNER_INSET + BANNER_HEIGHT + BANNER_GAP37
} else {38
0.39
})33
}40
}34
41
35
pub fn pin_banner_overlay(banner: AnyElement) -> AnyElement {42
pub fn pin_banner_overlay(banner: AnyElement) -> AnyElement {36
div()43
div()37
.absolute()44
.absolute()38
.top_0()45
.top(px(BANNER_INSET))39
.left(px(BANNER_MARGIN))46
.left(px(BANNER_INSET))40
.right(px(BANNER_MARGIN))47
.right(px(BANNER_INSET))41
.child(banner)48
.child(banner)42
.into_any_element()49
.into_any_element()43
}50
}@@ -86,6 +93,7 @@ pub fn render_pin_banner(data: PinBannerData, actions: PinBannerActions) -> AnyE86
} = actions;93
} = actions;87
h_flex()94
h_flex()88
.id("pin-banner")95
.id("pin-banner")96
.debug_selector(|| PIN_BANNER_TAG.into())89
.group("pin-banner")97
.group("pin-banner")90
.occlude()98
.occlude()91
.w_full()99
.w_full()@@ -31,6 +31,7 @@ const AVATAR_GAP: f32 = 10.;
31
31
const CARD_PADDING: f32 = 12.;
32
32
const CARD_RADIUS: f32 = 10.;
33
33
const CARD_GAP: f32 = 12.;
34
const PINNED_LABEL: &str = "Pinned";
34
35
const SLOTS_PER_POST: usize = 64;
35
36
const TOOLBAR_RIGHT_INSET: f32 = 8.;
36
37
const SUBJECT_SIZE: f32 = 14.;
@@ -63,6 +64,16 @@ fn edited_marker() -> Div {
63
64
.child("Edited")
64
65
}
65
66
67
fn pinned_marker() -> Div {
68
h_flex()
69
.gap(px(3.))
70
.items_center()
71
.text_size(px(11.))
72
.text_color(theme::text_muted())
73
.child(icon(IconName::Pin, 11., theme::text_muted()))
74
.child(PINNED_LABEL)
75
}
76
66
77
fn message_content(
67
78
row: &MessageRow,
68
79
index: usize,
@@ -145,6 +156,7 @@ fn message_header(
145
156
author: String,
146
157
profile_user: Option<&str>,
147
158
saved: bool,
159
pinned: bool,
148
160
) -> Div {
149
161
h_flex()
150
162
.gap(px(6.))
@@ -166,6 +178,7 @@ fn message_header(
166
178
.child(row.time.clone()),
167
179
)
168
180
.when(row.edited, |line| line.child(edited_marker()))
181
.when(pinned, |line| line.child(pinned_marker()))
169
182
.when(saved, |line| {
170
183
line.child(icon(IconName::Bookmark, 12., theme::accent_text()))
171
184
})
@@ -218,6 +231,7 @@ fn message_block(
218
231
None => message_content(row, index, directory, &actions, cx),
219
232
};
220
233
let saved = actions.saved;
234
let pinned = actions.pinned && role == Role::Root;
221
235
let RowActions {
222
236
delivery,
223
237
reply,
@@ -237,7 +251,14 @@ fn message_block(
237
251
.flex_1()
238
252
.min_w_0()
239
253
.gap(px(6.))
240
.child(message_header(row, index, author, profile_user, saved))
254
.child(message_header(
255
row,
256
index,
257
author,
258
profile_user,
259
saved,
260
pinned,
261
))
241
262
.when_some(
242
263
row.subject.clone().filter(|_| role == Role::Root),
243
264
|column, subject| {
@@ -31,6 +31,7 @@ const AVATAR_GAP: f32 = 10.;31
const CARD_PADDING: f32 = 12.;31
const CARD_PADDING: f32 = 12.;32
const CARD_RADIUS: f32 = 10.;32
const CARD_RADIUS: f32 = 10.;33
const CARD_GAP: f32 = 12.;33
const CARD_GAP: f32 = 12.;34
const PINNED_LABEL: &str = "Pinned";34
const SLOTS_PER_POST: usize = 64;35
const SLOTS_PER_POST: usize = 64;35
const TOOLBAR_RIGHT_INSET: f32 = 8.;36
const TOOLBAR_RIGHT_INSET: f32 = 8.;36
const SUBJECT_SIZE: f32 = 14.;37
const SUBJECT_SIZE: f32 = 14.;@@ -63,6 +64,16 @@ fn edited_marker() -> Div {63
.child("Edited")64
.child("Edited")64
}65
}65
66
67
fn pinned_marker() -> Div {68
h_flex()69
.gap(px(3.))70
.items_center()71
.text_size(px(11.))72
.text_color(theme::text_muted())73
.child(icon(IconName::Pin, 11., theme::text_muted()))74
.child(PINNED_LABEL)75
}76
66
fn message_content(77
fn message_content(67
row: &MessageRow,78
row: &MessageRow,68
index: usize,79
index: usize,@@ -145,6 +156,7 @@ fn message_header(145
author: String,156
author: String,146
profile_user: Option<&str>,157
profile_user: Option<&str>,147
saved: bool,158
saved: bool,159
pinned: bool,148
) -> Div {160
) -> Div {149
h_flex()161
h_flex()150
.gap(px(6.))162
.gap(px(6.))@@ -166,6 +178,7 @@ fn message_header(166
.child(row.time.clone()),178
.child(row.time.clone()),167
)179
)168
.when(row.edited, |line| line.child(edited_marker()))180
.when(row.edited, |line| line.child(edited_marker()))181
.when(pinned, |line| line.child(pinned_marker()))169
.when(saved, |line| {182
.when(saved, |line| {170
line.child(icon(IconName::Bookmark, 12., theme::accent_text()))183
line.child(icon(IconName::Bookmark, 12., theme::accent_text()))171
})184
})@@ -218,6 +231,7 @@ fn message_block(218
None => message_content(row, index, directory, &actions, cx),231
None => message_content(row, index, directory, &actions, cx),219
};232
};220
let saved = actions.saved;233
let saved = actions.saved;234
let pinned = actions.pinned && role == Role::Root;221
let RowActions {235
let RowActions {222
delivery,236
delivery,223
reply,237
reply,@@ -237,7 +251,14 @@ fn message_block(237
.flex_1()251
.flex_1()238
.min_w_0()252
.min_w_0()239
.gap(px(6.))253
.gap(px(6.))240
.child(message_header(row, index, author, profile_user, saved))254
.child(message_header(255
row,256
index,257
author,258
profile_user,259
saved,260
pinned,261
))241
.when_some(262
.when_some(242
row.subject.clone().filter(|_| role == Role::Root),263
row.subject.clone().filter(|_| role == Role::Root),243
|column, subject| {264
|column, subject| {@@ -9,6 +9,8 @@ use gpui_kit::*;
9
9
use teams_core::{OrgPerson, PROFILE_LINK_PREFIX, PersonProfile, WorkLocationKind};
10
10
11
11
use super::avatar::{person_avatar, with_presence};
12
use super::new_chat::Pick;
13
use super::new_meeting_dialog::open_new_meeting_with;
12
14
use super::widgets::icon;
13
15
use crate::app_state::{AppHandle, AppState};
14
16
use crate::data::{Presence, PresenceKind, presence_kind_of};
@@ -31,6 +33,9 @@ const STATUS_LINES: usize = 3;
31
33
const REPORTS_MAX_HEIGHT: f32 = 168.;
32
34
const ACTION_HEIGHT: f32 = 30.;
33
35
const SKELETON_HEIGHT: f32 = 10.;
36
const SCHEDULE_MEETING: &str = "Schedule meeting";
37
const EMAIL: &str = "Email";
38
const COPY_EMAIL: &str = "Copy email";
34
39
35
40
pub enum ProfileCardEvent {
36
41
Close,
@@ -255,25 +260,76 @@ impl ProfileCard {
255
260
.me
256
261
.as_ref()
257
262
.is_some_and(|me| me.user_id == self.user_id);
263
let profile = self
264
.app
265
.read(cx)
266
.profiles
267
.get(&self.user_id)
268
.and_then(|entry| entry.profile.clone());
269
let name = self.display_name(profile.as_deref(), cx);
258
270
let user_id = self.user_id.clone();
259
271
let (mail_email, copy_email) = (email.clone(), email.clone());
272
let invitee = Pick {
273
user_id: user_id.clone(),
274
name: name.clone(),
275
mail: email,
276
};
277
let chat_id = user_id.clone();
278
let (video_id, audio_id) = (user_id.clone(), user_id.clone());
260
279
h_flex()
261
280
.gap(px(8.))
262
281
.when(!is_me, |row| {
263
282
row.child(
264
283
action_button("profile-chat", "Chat", IconName::MessageSquare, true).on_click(
265
284
cx.listener(move |this, _, _, cx| {
266
let user_id = user_id.clone();
285
let user_id = chat_id.clone();
267
286
this.app
268
287
.update(cx, |state, cx| state.open_chat_with(&user_id, cx));
269
288
cx.emit(ProfileCardEvent::Close);
270
289
}),
271
290
),
272
291
)
292
.child(
293
icon_action(
294
"profile-video-call",
295
IconName::Video,
296
video_call_tooltip(&name),
297
)
298
.on_click(cx.listener(move |this, _, _, cx| {
299
let user_id = video_id.clone();
300
this.app
301
.update(cx, |state, cx| state.call_person(&user_id, true, cx));
302
cx.emit(ProfileCardEvent::Close);
303
})),
304
)
305
.child(
306
icon_action(
307
"profile-audio-call",
308
IconName::Phone,
309
audio_call_tooltip(&name),
310
)
311
.on_click(cx.listener(move |this, _, _, cx| {
312
let user_id = audio_id.clone();
313
this.app
314
.update(cx, |state, cx| state.call_person(&user_id, false, cx));
315
cx.emit(ProfileCardEvent::Close);
316
})),
317
)
318
.child(
319
icon_action(
320
"profile-schedule-meeting",
321
IconName::Calendar,
322
SCHEDULE_MEETING.to_owned(),
323
)
324
.on_click(cx.listener(move |this, _, window, cx| {
325
open_new_meeting_with(this.app.clone(), vec![invitee.clone()], window, cx);
326
cx.emit(ProfileCardEvent::Close);
327
})),
328
)
273
329
})
274
330
.when_some(mail_email, |row, address| {
275
331
row.child(
276
action_button("profile-email", "Email", IconName::Mail, false).on_click(
332
icon_action("profile-email", IconName::Mail, EMAIL.to_owned()).on_click(
277
333
cx.listener(move |_, _, _, cx| {
278
334
cx.open_url(&mailto_url(&address));
279
335
cx.emit(ProfileCardEvent::Close);
@@ -283,7 +339,7 @@ impl ProfileCard {
283
339
})
284
340
.when_some(copy_email, |row, address| {
285
341
row.child(
286
action_button("profile-copy-email", "Copy email", IconName::Copy, false)
342
icon_action("profile-copy-email", IconName::Copy, COPY_EMAIL.to_owned())
287
343
.on_click(cx.listener(move |this, _, _, cx| {
288
344
this.app
289
345
.update(cx, |state, cx| state.copy_profile_email(&address, cx));
@@ -557,6 +613,30 @@ fn contact_row(row: ContactRow) -> Div {
557
613
)
558
614
}
559
615
616
pub fn video_call_tooltip(name: &str) -> String {
617
format!("Start a video call with {name}")
618
}
619
620
pub fn audio_call_tooltip(name: &str) -> String {
621
format!("Start an audio call with {name}")
622
}
623
624
fn icon_action(id: &'static str, glyph: IconName, tooltip: String) -> Stateful<Div> {
625
div()
626
.id(id)
627
.size(px(ACTION_HEIGHT))
628
.flex()
629
.flex_none()
630
.items_center()
631
.justify_center()
632
.rounded(px(6.))
633
.cursor_pointer()
634
.bg(theme::popup_hover())
635
.hover(|button| button.opacity(0.9))
636
.child(icon(glyph, 14., theme::text_soft()))
637
.tooltip(move |window, cx| Tooltip::new(tooltip.clone()).build(window, cx))
638
}
639
560
640
fn action_button(
561
641
id: &'static str,
562
642
label: &'static str,
@@ -664,3 +744,14 @@ impl Render for ProfileCard {
664
744
)
665
745
}
666
746
}
747
748
#[cfg(test)]
749
mod tests {
750
use super::{audio_call_tooltip, video_call_tooltip};
751
752
#[test]
753
fn call_tooltips_use_the_teams_wording() {
754
assert_eq!(video_call_tooltip("Ann"), "Start a video call with Ann");
755
assert_eq!(audio_call_tooltip("Ann"), "Start an audio call with Ann");
756
}
757
}
@@ -9,6 +9,8 @@ use gpui_kit::*;9
use teams_core::{OrgPerson, PROFILE_LINK_PREFIX, PersonProfile, WorkLocationKind};9
use teams_core::{OrgPerson, PROFILE_LINK_PREFIX, PersonProfile, WorkLocationKind};10
10
11
use super::avatar::{person_avatar, with_presence};11
use super::avatar::{person_avatar, with_presence};12
use super::new_chat::Pick;13
use super::new_meeting_dialog::open_new_meeting_with;12
use super::widgets::icon;14
use super::widgets::icon;13
use crate::app_state::{AppHandle, AppState};15
use crate::app_state::{AppHandle, AppState};14
use crate::data::{Presence, PresenceKind, presence_kind_of};16
use crate::data::{Presence, PresenceKind, presence_kind_of};@@ -31,6 +33,9 @@ const STATUS_LINES: usize = 3;31
const REPORTS_MAX_HEIGHT: f32 = 168.;33
const REPORTS_MAX_HEIGHT: f32 = 168.;32
const ACTION_HEIGHT: f32 = 30.;34
const ACTION_HEIGHT: f32 = 30.;33
const SKELETON_HEIGHT: f32 = 10.;35
const SKELETON_HEIGHT: f32 = 10.;36
const SCHEDULE_MEETING: &str = "Schedule meeting";37
const EMAIL: &str = "Email";38
const COPY_EMAIL: &str = "Copy email";34
39
35
pub enum ProfileCardEvent {40
pub enum ProfileCardEvent {36
Close,41
Close,@@ -255,25 +260,76 @@ impl ProfileCard {255
.me260
.me256
.as_ref()261
.as_ref()257
.is_some_and(|me| me.user_id == self.user_id);262
.is_some_and(|me| me.user_id == self.user_id);263
let profile = self264
.app265
.read(cx)266
.profiles267
.get(&self.user_id)268
.and_then(|entry| entry.profile.clone());269
let name = self.display_name(profile.as_deref(), cx);258
let user_id = self.user_id.clone();270
let user_id = self.user_id.clone();259
let (mail_email, copy_email) = (email.clone(), email.clone());271
let (mail_email, copy_email) = (email.clone(), email.clone());272
let invitee = Pick {273
user_id: user_id.clone(),274
name: name.clone(),275
mail: email,276
};277
let chat_id = user_id.clone();278
let (video_id, audio_id) = (user_id.clone(), user_id.clone());260
h_flex()279
h_flex()261
.gap(px(8.))280
.gap(px(8.))262
.when(!is_me, |row| {281
.when(!is_me, |row| {263
row.child(282
row.child(264
action_button("profile-chat", "Chat", IconName::MessageSquare, true).on_click(283
action_button("profile-chat", "Chat", IconName::MessageSquare, true).on_click(265
cx.listener(move |this, _, _, cx| {284
cx.listener(move |this, _, _, cx| {266
let user_id = user_id.clone();285
let user_id = chat_id.clone();267
this.app286
this.app268
.update(cx, |state, cx| state.open_chat_with(&user_id, cx));287
.update(cx, |state, cx| state.open_chat_with(&user_id, cx));269
cx.emit(ProfileCardEvent::Close);288
cx.emit(ProfileCardEvent::Close);270
}),289
}),271
),290
),272
)291
)292
.child(293
icon_action(294
"profile-video-call",295
IconName::Video,296
video_call_tooltip(&name),297
)298
.on_click(cx.listener(move |this, _, _, cx| {299
let user_id = video_id.clone();300
this.app301
.update(cx, |state, cx| state.call_person(&user_id, true, cx));302
cx.emit(ProfileCardEvent::Close);303
})),304
)305
.child(306
icon_action(307
"profile-audio-call",308
IconName::Phone,309
audio_call_tooltip(&name),310
)311
.on_click(cx.listener(move |this, _, _, cx| {312
let user_id = audio_id.clone();313
this.app314
.update(cx, |state, cx| state.call_person(&user_id, false, cx));315
cx.emit(ProfileCardEvent::Close);316
})),317
)318
.child(319
icon_action(320
"profile-schedule-meeting",321
IconName::Calendar,322
SCHEDULE_MEETING.to_owned(),323
)324
.on_click(cx.listener(move |this, _, window, cx| {325
open_new_meeting_with(this.app.clone(), vec![invitee.clone()], window, cx);326
cx.emit(ProfileCardEvent::Close);327
})),328
)273
})329
})274
.when_some(mail_email, |row, address| {330
.when_some(mail_email, |row, address| {275
row.child(331
row.child(276
action_button("profile-email", "Email", IconName::Mail, false).on_click(332
icon_action("profile-email", IconName::Mail, EMAIL.to_owned()).on_click(277
cx.listener(move |_, _, _, cx| {333
cx.listener(move |_, _, _, cx| {278
cx.open_url(&mailto_url(&address));334
cx.open_url(&mailto_url(&address));279
cx.emit(ProfileCardEvent::Close);335
cx.emit(ProfileCardEvent::Close);@@ -283,7 +339,7 @@ impl ProfileCard {283
})339
})284
.when_some(copy_email, |row, address| {340
.when_some(copy_email, |row, address| {285
row.child(341
row.child(286
action_button("profile-copy-email", "Copy email", IconName::Copy, false)342
icon_action("profile-copy-email", IconName::Copy, COPY_EMAIL.to_owned())287
.on_click(cx.listener(move |this, _, _, cx| {343
.on_click(cx.listener(move |this, _, _, cx| {288
this.app344
this.app289
.update(cx, |state, cx| state.copy_profile_email(&address, cx));345
.update(cx, |state, cx| state.copy_profile_email(&address, cx));@@ -557,6 +613,30 @@ fn contact_row(row: ContactRow) -> Div {557
)613
)558
}614
}559
615
616
pub fn video_call_tooltip(name: &str) -> String {617
format!("Start a video call with {name}")618
}619
620
pub fn audio_call_tooltip(name: &str) -> String {621
format!("Start an audio call with {name}")622
}623
624
fn icon_action(id: &'static str, glyph: IconName, tooltip: String) -> Stateful<Div> {625
div()626
.id(id)627
.size(px(ACTION_HEIGHT))628
.flex()629
.flex_none()630
.items_center()631
.justify_center()632
.rounded(px(6.))633
.cursor_pointer()634
.bg(theme::popup_hover())635
.hover(|button| button.opacity(0.9))636
.child(icon(glyph, 14., theme::text_soft()))637
.tooltip(move |window, cx| Tooltip::new(tooltip.clone()).build(window, cx))638
}639
560
fn action_button(640
fn action_button(561
id: &'static str,641
id: &'static str,562
label: &'static str,642
label: &'static str,@@ -664,3 +744,14 @@ impl Render for ProfileCard {664
)744
)665
}745
}666
}746
}747
748
#[cfg(test)]749
mod tests {750
use super::{audio_call_tooltip, video_call_tooltip};751
752
#[test]753
fn call_tooltips_use_the_teams_wording() {754
assert_eq!(video_call_tooltip("Ann"), "Start a video call with Ann");755
assert_eq!(audio_call_tooltip("Ann"), "Start an audio call with Ann");756
}757
}@@ -10,7 +10,12 @@ use gpui_kit::component::{
10
10
use gpui_kit::prelude::FluentBuilder as _;
11
11
use gpui_kit::*;
12
12
13
use gpui_kit::assets::IconName;
14
use gpui_kit::component::tooltip::Tooltip;
15
16
use super::customize_reactions::{CUSTOMIZE_TOOLTIP, open_customize_reactions};
13
17
use super::skin_tone_choices::{tone_badge, tone_choices};
18
use super::widgets::icon;
14
19
use crate::app_state::AppState;
15
20
use crate::emoji;
16
21
use crate::emoticons;
@@ -67,6 +72,7 @@ pub struct ReactionPicker {
67
72
target: Option<PickTarget>,
68
73
skin_tone: u8,
69
74
tone_menu: Option<(String, Point<Pixels>)>,
75
customizing: bool,
70
76
_subscription: Subscription,
71
77
}
72
78
@@ -88,10 +94,16 @@ impl ReactionPicker {
88
94
target: None,
89
95
skin_tone: 0,
90
96
tone_menu: None,
97
customizing: false,
91
98
_subscription: subscription,
92
99
}
93
100
}
94
101
102
pub fn for_customizing(mut self) -> Self {
103
self.customizing = true;
104
self
105
}
106
95
107
pub fn set_target(
96
108
&mut self,
97
109
on_pick: PickHandler,
@@ -195,10 +207,43 @@ impl ReactionPicker {
195
207
196
208
fn pick_tone(&mut self, glyph: &str, tone: u8, window: &mut Window, cx: &mut Context<Self>) {
197
209
self.skin_tone = tone;
198
self.app.update(cx, |state, cx| state.set_skin_tone(tone, cx));
210
if !self.customizing {
211
self.app
212
.update(cx, |state, cx| state.set_skin_tone(tone, cx));
213
}
199
214
self.pick(&emoticons::with_tone(glyph, tone), false, window, cx);
200
215
}
201
216
217
fn open_customize(&mut self, window: &mut Window, cx: &mut Context<Self>) {
218
if let Some(target) = self.target.take() {
219
target
220
.popover
221
.update(cx, |state, cx| state.dismiss(window, cx))
222
.ok();
223
(target.on_done)(window, cx);
224
}
225
open_customize_reactions(self.app.clone(), window, cx);
226
}
227
228
fn customize_button(&self, cx: &mut Context<Self>) -> Option<AnyElement> {
229
(!self.customizing).then(|| {
230
div()
231
.id("customize-reactions-trigger")
232
.size(px(CELL_SIZE))
233
.flex_none()
234
.flex()
235
.items_center()
236
.justify_center()
237
.rounded(px(8.))
238
.cursor_pointer()
239
.hover(|button| button.bg(theme::popup_hover()))
240
.child(icon(IconName::Settings, 16., theme::text_soft()))
241
.tooltip(|window, cx| Tooltip::new(CUSTOMIZE_TOOLTIP).build(window, cx))
242
.on_click(cx.listener(|this, _, window, cx| this.open_customize(window, cx)))
243
.into_any_element()
244
})
245
}
246
202
247
fn tone_menu(&self, cx: &mut Context<Self>) -> Option<AnyElement> {
203
248
let (base, position) = self.tone_menu.clone()?;
204
249
let (pick_view, dismiss_view) = (cx.entity().downgrade(), cx.entity().downgrade());
@@ -303,14 +348,21 @@ impl Render for ReactionPicker {
303
348
.p(px(8.))
304
349
.child(h_flex().gap(px(2.)).children(quick))
305
350
.child(
306
div()
307
.h(px(32.))
308
.px(px(8.))
309
.flex()
351
h_flex()
352
.gap(px(4.))
310
353
.items_center()
311
.rounded(px(8.))
312
.bg(theme::popup_hover())
313
.child(Input::new(&self.input).appearance(false).bordered(false)),
354
.child(
355
div()
356
.flex_1()
357
.h(px(32.))
358
.px(px(8.))
359
.flex()
360
.items_center()
361
.rounded(px(8.))
362
.bg(theme::popup_hover())
363
.child(Input::new(&self.input).appearance(false).bordered(false)),
364
)
365
.children(self.customize_button(cx)),
314
366
)
315
367
.child(
316
368
div()
@@ -10,7 +10,12 @@ use gpui_kit::component::{10
use gpui_kit::prelude::FluentBuilder as _;10
use gpui_kit::prelude::FluentBuilder as _;11
use gpui_kit::*;11
use gpui_kit::*;12
12
13
use gpui_kit::assets::IconName;14
use gpui_kit::component::tooltip::Tooltip;15
16
use super::customize_reactions::{CUSTOMIZE_TOOLTIP, open_customize_reactions};13
use super::skin_tone_choices::{tone_badge, tone_choices};17
use super::skin_tone_choices::{tone_badge, tone_choices};18
use super::widgets::icon;14
use crate::app_state::AppState;19
use crate::app_state::AppState;15
use crate::emoji;20
use crate::emoji;16
use crate::emoticons;21
use crate::emoticons;@@ -67,6 +72,7 @@ pub struct ReactionPicker {67
target: Option<PickTarget>,72
target: Option<PickTarget>,68
skin_tone: u8,73
skin_tone: u8,69
tone_menu: Option<(String, Point<Pixels>)>,74
tone_menu: Option<(String, Point<Pixels>)>,75
customizing: bool,70
_subscription: Subscription,76
_subscription: Subscription,71
}77
}72
78
@@ -88,10 +94,16 @@ impl ReactionPicker {88
target: None,94
target: None,89
skin_tone: 0,95
skin_tone: 0,90
tone_menu: None,96
tone_menu: None,97
customizing: false,91
_subscription: subscription,98
_subscription: subscription,92
}99
}93
}100
}94
101
102
pub fn for_customizing(mut self) -> Self {103
self.customizing = true;104
self105
}106
95
pub fn set_target(107
pub fn set_target(96
&mut self,108
&mut self,97
on_pick: PickHandler,109
on_pick: PickHandler,@@ -195,10 +207,43 @@ impl ReactionPicker {195
207
196
fn pick_tone(&mut self, glyph: &str, tone: u8, window: &mut Window, cx: &mut Context<Self>) {208
fn pick_tone(&mut self, glyph: &str, tone: u8, window: &mut Window, cx: &mut Context<Self>) {197
self.skin_tone = tone;209
self.skin_tone = tone;198
self.app.update(cx, |state, cx| state.set_skin_tone(tone, cx));210
if !self.customizing {211
self.app212
.update(cx, |state, cx| state.set_skin_tone(tone, cx));213
}199
self.pick(&emoticons::with_tone(glyph, tone), false, window, cx);214
self.pick(&emoticons::with_tone(glyph, tone), false, window, cx);200
}215
}201
216
217
fn open_customize(&mut self, window: &mut Window, cx: &mut Context<Self>) {218
if let Some(target) = self.target.take() {219
target220
.popover221
.update(cx, |state, cx| state.dismiss(window, cx))222
.ok();223
(target.on_done)(window, cx);224
}225
open_customize_reactions(self.app.clone(), window, cx);226
}227
228
fn customize_button(&self, cx: &mut Context<Self>) -> Option<AnyElement> {229
(!self.customizing).then(|| {230
div()231
.id("customize-reactions-trigger")232
.size(px(CELL_SIZE))233
.flex_none()234
.flex()235
.items_center()236
.justify_center()237
.rounded(px(8.))238
.cursor_pointer()239
.hover(|button| button.bg(theme::popup_hover()))240
.child(icon(IconName::Settings, 16., theme::text_soft()))241
.tooltip(|window, cx| Tooltip::new(CUSTOMIZE_TOOLTIP).build(window, cx))242
.on_click(cx.listener(|this, _, window, cx| this.open_customize(window, cx)))243
.into_any_element()244
})245
}246
202
fn tone_menu(&self, cx: &mut Context<Self>) -> Option<AnyElement> {247
fn tone_menu(&self, cx: &mut Context<Self>) -> Option<AnyElement> {203
let (base, position) = self.tone_menu.clone()?;248
let (base, position) = self.tone_menu.clone()?;204
let (pick_view, dismiss_view) = (cx.entity().downgrade(), cx.entity().downgrade());249
let (pick_view, dismiss_view) = (cx.entity().downgrade(), cx.entity().downgrade());@@ -303,14 +348,21 @@ impl Render for ReactionPicker {303
.p(px(8.))348
.p(px(8.))304
.child(h_flex().gap(px(2.)).children(quick))349
.child(h_flex().gap(px(2.)).children(quick))305
.child(350
.child(306
div()351
h_flex()307
.h(px(32.))352
.gap(px(4.))308
.px(px(8.))309
.flex()310
.items_center()353
.items_center()311
.rounded(px(8.))354
.child(312
.bg(theme::popup_hover())355
div()313
.child(Input::new(&self.input).appearance(false).bordered(false)),356
.flex_1()357
.h(px(32.))358
.px(px(8.))359
.flex()360
.items_center()361
.rounded(px(8.))362
.bg(theme::popup_hover())363
.child(Input::new(&self.input).appearance(false).bordered(false)),364
)365
.children(self.customize_button(cx)),314
)366
)315
.child(367
.child(316
div()368
div()@@ -24,6 +24,9 @@ use super::section_dialog::{SectionNameTarget, open_section_name_dialog};
24
24
use super::widgets::{count_badge, icon, page_header, unread_marker};
25
25
use crate::agents::AgentsPanel;
26
26
use crate::app_state::{AppEvent, AppState, Selection};
27
use crate::channel_menu::{
28
ChannelMenuItem, MenuEntry, TeamMenuItem, channel_menu_entries, team_menu_entries,
29
};
27
30
use crate::chat_actions::TITLE_LIMIT;
28
31
use crate::chat_filter::{ChatFilter, filtered_sections, has_no_matches};
29
32
use crate::data::{Directory, is_pending_folder};
@@ -31,9 +34,10 @@ use crate::format;
31
34
use crate::local_previews::LocalPreview;
32
35
use crate::notice::truncated;
33
36
use crate::sidebar_model::{
34
AvatarSpec, ChannelOrderInput, ChatItem, DELETED_CHAT_PREVIEW, EMPTY_FOLDER_HINT, NameStyle,
35
NameWeight, Preview, Section, SectionInput, SectionKind, Step, build_sections,
36
channel_name_style, older_chats_trigger_resets, step_id, team_name_style, visible_channel_ids,
37
AvatarSpec, ChannelOrderInput, ChatItem, DELETED_CHAT_PREVIEW, EMPTY_FOLDER_HINT, MentionBadge,
38
NameStyle, NameWeight, Preview, Section, SectionInput, SectionKind, Step, build_sections,
39
channel_badge, channel_name_style, channel_shown, older_chats_trigger_resets, step_id,
40
team_badge, team_channel_rows, team_hoisted, team_name_style, visible_channel_ids,
37
41
wants_older_chats,
38
42
};
39
43
use crate::theme;
@@ -58,12 +62,14 @@ const VIEWPORT_MARGIN: f32 = 300.;
58
62
const AVATAR_SIZE: f32 = 36.;
59
63
const PINNED_LABEL: &str = "Pinned";
60
64
const TEAMS_LABEL: &str = "Teams";
65
const MARK_ALL_READ_LABEL: &str = "Mark all as read";
61
66
const HIDDEN_TEAMS_LABEL: &str = "Hidden teams";
62
67
const TEAM_ROW_HEIGHT: f32 = 40.;
63
68
const REVEAL_ROW_HEIGHT: f32 = 32.;
64
69
const NEW_CHAT_BUTTON_SIZE: f32 = 32.;
65
70
const MENU_ICON_SIZE: f32 = 15.;
66
71
const NOTIFICATION_ICON_SIZE: f32 = 13.;
72
const MENTION_ICON_SIZE: f32 = 15.;
67
73
68
74
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
69
75
pub enum SidebarTab {
@@ -233,6 +239,17 @@ fn chat_menu(
233
239
hide_state.update(cx, |state, cx| state.hide_chat(&hide_id, cx));
234
240
}),
235
241
);
242
if !target.is_group {
243
let remove_state = context.state.clone();
244
let remove_id = target.id.clone();
245
popup = popup.item(
246
PopupMenuItem::new(REMOVE_HISTORY_LABEL)
247
.icon(menu_icon(IconName::Trash))
248
.on_click(move |_, window, cx| {
249
confirm_remove_history(&remove_state, &remove_id, window, cx);
250
}),
251
);
252
}
236
253
if target.is_group {
237
254
let leave_state = context.state.clone();
238
255
let leave_id = target.id.clone();
@@ -444,6 +461,40 @@ fn leave_description(member_count: usize) -> String {
444
461
format!("{who} {verb} that you left. You can only come back if someone adds you.")
445
462
}
446
463
464
const REMOVE_HISTORY_LABEL: &str = "Remove chat history";
465
const REMOVE_HISTORY_TITLE: &str = "Remove chat history?";
466
const REMOVE_HISTORY_TEXT: &str =
467
"This will remove the chat from your list and search. It affects you only.";
468
469
fn confirm_remove_history(
470
state: &Entity<AppState>,
471
chat_id: &str,
472
window: &mut Window,
473
cx: &mut App,
474
) {
475
let state = state.clone();
476
let chat_id = chat_id.to_owned();
477
window.open_alert_dialog(cx, move |alert, _, _| {
478
let state = state.clone();
479
let chat_id = chat_id.clone();
480
let cancel = Button::new("remove-history-cancel")
481
.label("Cancel")
482
.on_click(|_, window, cx| window.close_dialog(cx));
483
let remove = Button::new("remove-history-confirm")
484
.label("Remove")
485
.primary()
486
.on_click(move |_, window, cx| {
487
state.update(cx, |state, cx| state.remove_chat_history(&chat_id, cx));
488
window.close_dialog(cx);
489
});
490
alert
491
.title(REMOVE_HISTORY_TITLE)
492
.description(REMOVE_HISTORY_TEXT)
493
.footer(DialogFooter::new().child(cancel).child(remove))
494
.on_ok(|_, _, _| false)
495
});
496
}
497
447
498
pub(crate) fn confirm_leave(
448
499
state: &Entity<AppState>,
449
500
chat_id: &str,
@@ -778,6 +829,28 @@ impl SidebarView {
778
829
.dropdown_menu(move |menu, _, _| menu.item(new_section_item(&state, read_only)))
779
830
}
780
831
832
fn channel_list_menu_button(&self, cx: &mut Context<Self>) -> impl IntoElement {
833
let state = self.state.clone();
834
let read_only = self.state.read(cx).mode.read_only;
835
Button::new("channel-list-more")
836
.icon(IconName::Ellipsis)
837
.ghost()
838
.size(px(NEW_CHAT_BUTTON_SIZE))
839
.rounded(px(8.))
840
.tooltip("More options")
841
.dropdown_menu(move |menu, _, _| {
842
let state = state.clone();
843
menu.item(
844
PopupMenuItem::new(MARK_ALL_READ_LABEL)
845
.icon(menu_icon(IconName::CheckCheck))
846
.disabled(read_only)
847
.on_click(move |_, _, cx| {
848
state.update(cx, |state, cx| state.mark_all_channels_read(cx));
849
}),
850
)
851
})
852
}
853
781
854
fn draft_row(&self) -> impl IntoElement {
782
855
h_flex()
783
856
.id("new-chat-draft")
@@ -1277,6 +1350,7 @@ impl SidebarView {
1277
1350
channel: &ChannelRecord,
1278
1351
selected: bool,
1279
1352
notifications: ChannelNotifications,
1353
badge: Option<MentionBadge>,
1280
1354
) -> AnyElement {
1281
1355
let unread = channel.unread;
1282
1356
let name_style = channel_name_style(unread, true, selected);
@@ -1337,15 +1411,19 @@ impl SidebarView {
1337
1411
),
1338
1412
)
1339
1413
.child(
1340
h_flex().gap(px(8.)).items_center().child(
1341
div()
1342
.flex_1()
1343
.min_w_0()
1344
.truncate()
1345
.text_size(px(12.))
1346
.text_color(theme::text_muted())
1347
.child(team.name.clone()),
1348
),
1414
h_flex()
1415
.gap(px(8.))
1416
.items_center()
1417
.child(
1418
div()
1419
.flex_1()
1420
.min_w_0()
1421
.truncate()
1422
.text_size(px(12.))
1423
.text_color(theme::text_muted())
1424
.child(team.name.clone()),
1425
)
1426
.children(badge.map(mention_badge)),
1349
1427
),
1350
1428
)
1351
1429
.on_click(move |_, _, cx| {
@@ -1382,13 +1460,17 @@ impl SidebarView {
1382
1460
&self,
1383
1461
mut list: Div,
1384
1462
entry: &SidebarTeam,
1463
hoisted_only: bool,
1385
1464
selected: Option<&Selection>,
1386
1465
cx: &mut Context<Self>,
1387
1466
) -> Div {
1388
1467
let team_id = entry.team.id.clone();
1389
1468
let expanded = team_expanded(&team_id, &self.collapsed_teams);
1390
1469
let name_style = team_name_style(entry, expanded);
1470
let badge = team_badge(entry, expanded);
1391
1471
let toggle_id = team_id.clone();
1472
let (team_menu_state, team_menu_id, team_hidden) =
1473
(self.state.clone(), team_id.clone(), entry.hidden);
1392
1474
list = list.child(
1393
1475
h_flex()
1394
1476
.id(SharedString::from(format!("team-{team_id}")))
@@ -1421,45 +1503,45 @@ impl SidebarView {
1421
1503
.text_color(name_color(name_style))
1422
1504
.child(entry.team.name.clone()),
1423
1505
)
1506
.children(badge.map(mention_badge))
1424
1507
.on_click(cx.listener(move |this, _, _, cx| {
1425
1508
if !this.collapsed_teams.remove(&toggle_id) {
1426
1509
this.collapsed_teams.insert(toggle_id.clone());
1427
1510
}
1428
1511
save_collapsed_teams(&this.state.read(cx).store, &this.collapsed_teams);
1429
1512
cx.notify();
1430
})),
1513
}))
1514
.context_menu(move |popup, _, _| {
1515
team_menu(popup, team_menu_state.clone(), &team_menu_id, team_hidden)
1516
}),
1431
1517
);
1432
1518
if !expanded {
1433
1519
return list;
1434
1520
}
1435
let is_hidden = |channel: &ChannelRecord| entry.hidden_channel_ids.contains(&channel.id);
1436
1521
let is_selected =
1437
1522
|channel: &ChannelRecord| selected == Some(&Selection::Channel(channel.id.clone()));
1438
for channel in entry
1439
.channels
1440
.iter()
1441
.filter(|channel| !is_hidden(channel) || is_selected(channel))
1442
{
1523
let revealed = self.revealed_channel_teams.contains(&team_id);
1524
let rows = team_channel_rows(entry, hoisted_only, revealed, is_selected);
1525
for channel in &rows.shown {
1443
1526
list = list.child(self.team_channel_row(
1444
1527
channel,
1445
1528
is_selected(channel),
1446
channel_name_style(channel.unread, !is_hidden(channel), is_selected(channel)),
1529
channel_name_style(
1530
channel.unread,
1531
channel_shown(entry, &channel.id),
1532
is_selected(channel),
1533
),
1447
1534
entry.channel_notifications(&channel.id),
1535
channel_badge(entry, &channel.id),
1448
1536
));
1449
1537
}
1450
let hidden: Vec<&ChannelRecord> = entry
1451
.channels
1452
.iter()
1453
.filter(|channel| is_hidden(channel) && !is_selected(channel))
1454
.collect();
1455
if hidden.is_empty() {
1538
if rows.hidden_count == 0 {
1456
1539
return list;
1457
1540
}
1458
let revealed = self.revealed_channel_teams.contains(&team_id);
1459
1541
let toggle_id = team_id.clone();
1460
1542
list = list.child(self.reveal_row(
1461
1543
SharedString::from(format!("hidden-channels-{team_id}")),
1462
hidden_channels_label(hidden.len()),
1544
hidden_channels_label(rows.hidden_count),
1463
1545
revealed,
1464
1546
40.,
1465
1547
cx.listener(move |this, _, _, cx| {
@@ -1469,15 +1551,14 @@ impl SidebarView {
1469
1551
cx.notify();
1470
1552
}),
1471
1553
));
1472
if revealed {
1473
for channel in hidden {
1474
list = list.child(self.team_channel_row(
1475
channel,
1476
false,
1477
channel_name_style(channel.unread, false, false),
1478
entry.channel_notifications(&channel.id),
1479
));
1480
}
1554
for channel in rows.revealed {
1555
list = list.child(self.team_channel_row(
1556
channel,
1557
false,
1558
channel_name_style(channel.unread, false, false),
1559
entry.channel_notifications(&channel.id),
1560
channel_badge(entry, &channel.id),
1561
));
1481
1562
}
1482
1563
list
1483
1564
}
@@ -1526,6 +1607,7 @@ impl SidebarView {
1526
1607
is_selected: bool,
1527
1608
name_style: NameStyle,
1528
1609
notifications: ChannelNotifications,
1610
badge: Option<MentionBadge>,
1529
1611
) -> impl IntoElement {
1530
1612
let state = self.state.clone();
1531
1613
let menu_state = self.state.clone();
@@ -1566,6 +1648,7 @@ impl SidebarView {
1566
1648
.child(channel.name.clone()),
1567
1649
)
1568
1650
.children(notification_badge(notifications.level))
1651
.children(badge.map(mention_badge))
1569
1652
.on_click(move |_, _, cx| {
1570
1653
let selection = selection.clone();
1571
1654
state.update(cx, |state, cx| state.select(selection, cx));
@@ -1614,14 +1697,19 @@ impl SidebarView {
1614
1697
channel,
1615
1698
is_selected,
1616
1699
entry.channel_notifications(&channel.id),
1700
channel_badge(entry, &channel.id),
1617
1701
));
1618
1702
}
1619
1703
}
1620
1704
list = list.child(self.plain_header(TEAMS_LABEL));
1621
let (shown_teams, hidden_teams): (Vec<&SidebarTeam>, Vec<&SidebarTeam>) =
1622
sidebar.teams.iter().partition(|entry| !entry.hidden);
1623
for entry in shown_teams {
1624
list = self.team_block(list, entry, selected.as_ref(), cx);
1705
let hidden_teams: Vec<&SidebarTeam> =
1706
sidebar.teams.iter().filter(|entry| entry.hidden).collect();
1707
for entry in sidebar
1708
.teams
1709
.iter()
1710
.filter(|entry| !entry.hidden || team_hoisted(entry))
1711
{
1712
list = self.team_block(list, entry, entry.hidden, selected.as_ref(), cx);
1625
1713
}
1626
1714
if !hidden_teams.is_empty() {
1627
1715
let holds_selection = hidden_teams
@@ -1640,7 +1728,7 @@ impl SidebarView {
1640
1728
));
1641
1729
if open {
1642
1730
for entry in hidden_teams {
1643
list = self.team_block(list, entry, selected.as_ref(), cx);
1731
list = self.team_block(list, entry, false, selected.as_ref(), cx);
1644
1732
}
1645
1733
}
1646
1734
}
@@ -1671,6 +1759,18 @@ fn name_color(style: NameStyle) -> Hsla {
1671
1759
}
1672
1760
}
1673
1761
1762
fn mention_badge(badge: MentionBadge) -> AnyElement {
1763
match badge {
1764
MentionBadge::Count(count) => count_badge(count, false).into_any_element(),
1765
MentionBadge::Channel => {
1766
icon(IconName::Hash, MENTION_ICON_SIZE, theme::accent_text()).into_any_element()
1767
}
1768
MentionBadge::Team => {
1769
icon(IconName::Users, MENTION_ICON_SIZE, theme::accent_text()).into_any_element()
1770
}
1771
}
1772
}
1773
1674
1774
fn notification_badge(level: ChannelNotificationLevel) -> Option<impl IntoElement> {
1675
1775
let name = match level {
1676
1776
ChannelNotificationLevel::BannerAndFeed => IconName::Bell,
@@ -1688,7 +1788,87 @@ fn channel_menu(
1688
1788
channel_id: &str,
1689
1789
notifications: ChannelNotifications,
1690
1790
) -> PopupMenu {
1691
let channel_id = channel_id.to_owned();
1791
let menu_state = state.read(cx).channel_menu_state(channel_id);
1792
let mut popup = popup;
1793
for entry in channel_menu_entries(menu_state) {
1794
let item = match entry {
1795
MenuEntry::Separator => {
1796
popup = popup.separator();
1797
continue;
1798
}
1799
MenuEntry::Item(ChannelMenuItem::Notifications) => {
1800
popup = notifications_submenu(popup, window, cx, &state, channel_id, notifications);
1801
continue;
1802
}
1803
MenuEntry::Item(item) => item,
1804
};
1805
let (action_state, action_id) = (state.clone(), channel_id.to_owned());
1806
popup = popup.item(
1807
PopupMenuItem::new(item.label())
1808
.icon(menu_icon(channel_menu_icon(item)))
1809
.disabled(menu_state.disables(item))
1810
.on_click(move |_, _, cx| {
1811
action_state.update(cx, |state, cx| match item {
1812
ChannelMenuItem::Pin => state.set_channel_pinned(&action_id, true, cx),
1813
ChannelMenuItem::Unpin => state.set_channel_pinned(&action_id, false, cx),
1814
ChannelMenuItem::Show => state.set_channel_shown(&action_id, true, cx),
1815
ChannelMenuItem::Hide => state.set_channel_shown(&action_id, false, cx),
1816
ChannelMenuItem::CopyLink => state.copy_channel_link(&action_id, cx),
1817
ChannelMenuItem::Notifications => {}
1818
});
1819
}),
1820
);
1821
}
1822
popup
1823
}
1824
1825
fn channel_menu_icon(item: ChannelMenuItem) -> IconName {
1826
match item {
1827
ChannelMenuItem::Notifications => IconName::Bell,
1828
ChannelMenuItem::Pin => IconName::Pin,
1829
ChannelMenuItem::Unpin => IconName::PinOff,
1830
ChannelMenuItem::Show => IconName::Eye,
1831
ChannelMenuItem::Hide => IconName::EyeOff,
1832
ChannelMenuItem::CopyLink => IconName::Link,
1833
}
1834
}
1835
1836
fn team_menu(popup: PopupMenu, state: Entity<AppState>, team_id: &str, hidden: bool) -> PopupMenu {
1837
let mut popup = popup;
1838
for entry in team_menu_entries(hidden) {
1839
let MenuEntry::Item(item) = entry else {
1840
popup = popup.separator();
1841
continue;
1842
};
1843
let (action_state, action_id) = (state.clone(), team_id.to_owned());
1844
popup = popup.item(
1845
PopupMenuItem::new(item.label())
1846
.icon(menu_icon(match item {
1847
TeamMenuItem::Show => IconName::Eye,
1848
TeamMenuItem::Hide => IconName::EyeOff,
1849
TeamMenuItem::CopyLink => IconName::Link,
1850
}))
1851
.on_click(move |_, _, cx| {
1852
action_state.update(cx, |state, cx| match item {
1853
TeamMenuItem::Show => state.set_team_shown(&action_id, true, cx),
1854
TeamMenuItem::Hide => state.set_team_shown(&action_id, false, cx),
1855
TeamMenuItem::CopyLink => state.copy_team_link(&action_id, cx),
1856
});
1857
}),
1858
);
1859
}
1860
popup
1861
}
1862
1863
fn notifications_submenu(
1864
popup: PopupMenu,
1865
window: &mut Window,
1866
cx: &mut Context<PopupMenu>,
1867
state: &Entity<AppState>,
1868
channel_id: &str,
1869
notifications: ChannelNotifications,
1870
) -> PopupMenu {
1871
let (state, channel_id) = (state.clone(), channel_id.to_owned());
1692
1872
popup.submenu_with_icon(
1693
1873
Some(menu_icon(IconName::Bell)),
1694
1874
"Notifications",
@@ -1828,9 +2008,10 @@ impl Render for SidebarView {
1828
2008
)
1829
2009
.child(self.filter_bar(cx)),
1830
2010
),
1831
SidebarTab::Channels | SidebarTab::Calls | SidebarTab::Agents => {
1832
Some(v_flex().child(page_header(self.tab.title())))
2011
SidebarTab::Channels => {
2012
Some(page_header(self.tab.title()).child(self.channel_list_menu_button(cx)))
1833
2013
}
2014
SidebarTab::Calls | SidebarTab::Agents => Some(page_header(self.tab.title())),
1834
2015
SidebarTab::Activity | SidebarTab::Saved => None,
1835
2016
};
1836
2017
v_flex()
@@ -24,6 +24,9 @@ use super::section_dialog::{SectionNameTarget, open_section_name_dialog};24
use super::widgets::{count_badge, icon, page_header, unread_marker};24
use super::widgets::{count_badge, icon, page_header, unread_marker};25
use crate::agents::AgentsPanel;25
use crate::agents::AgentsPanel;26
use crate::app_state::{AppEvent, AppState, Selection};26
use crate::app_state::{AppEvent, AppState, Selection};27
use crate::channel_menu::{28
ChannelMenuItem, MenuEntry, TeamMenuItem, channel_menu_entries, team_menu_entries,29
};27
use crate::chat_actions::TITLE_LIMIT;30
use crate::chat_actions::TITLE_LIMIT;28
use crate::chat_filter::{ChatFilter, filtered_sections, has_no_matches};31
use crate::chat_filter::{ChatFilter, filtered_sections, has_no_matches};29
use crate::data::{Directory, is_pending_folder};32
use crate::data::{Directory, is_pending_folder};@@ -31,9 +34,10 @@ use crate::format;31
use crate::local_previews::LocalPreview;34
use crate::local_previews::LocalPreview;32
use crate::notice::truncated;35
use crate::notice::truncated;33
use crate::sidebar_model::{36
use crate::sidebar_model::{34
AvatarSpec, ChannelOrderInput, ChatItem, DELETED_CHAT_PREVIEW, EMPTY_FOLDER_HINT, NameStyle,37
AvatarSpec, ChannelOrderInput, ChatItem, DELETED_CHAT_PREVIEW, EMPTY_FOLDER_HINT, MentionBadge,35
NameWeight, Preview, Section, SectionInput, SectionKind, Step, build_sections,38
NameStyle, NameWeight, Preview, Section, SectionInput, SectionKind, Step, build_sections,36
channel_name_style, older_chats_trigger_resets, step_id, team_name_style, visible_channel_ids,39
channel_badge, channel_name_style, channel_shown, older_chats_trigger_resets, step_id,40
team_badge, team_channel_rows, team_hoisted, team_name_style, visible_channel_ids,37
wants_older_chats,41
wants_older_chats,38
};42
};39
use crate::theme;43
use crate::theme;@@ -58,12 +62,14 @@ const VIEWPORT_MARGIN: f32 = 300.;58
const AVATAR_SIZE: f32 = 36.;62
const AVATAR_SIZE: f32 = 36.;59
const PINNED_LABEL: &str = "Pinned";63
const PINNED_LABEL: &str = "Pinned";60
const TEAMS_LABEL: &str = "Teams";64
const TEAMS_LABEL: &str = "Teams";65
const MARK_ALL_READ_LABEL: &str = "Mark all as read";61
const HIDDEN_TEAMS_LABEL: &str = "Hidden teams";66
const HIDDEN_TEAMS_LABEL: &str = "Hidden teams";62
const TEAM_ROW_HEIGHT: f32 = 40.;67
const TEAM_ROW_HEIGHT: f32 = 40.;63
const REVEAL_ROW_HEIGHT: f32 = 32.;68
const REVEAL_ROW_HEIGHT: f32 = 32.;64
const NEW_CHAT_BUTTON_SIZE: f32 = 32.;69
const NEW_CHAT_BUTTON_SIZE: f32 = 32.;65
const MENU_ICON_SIZE: f32 = 15.;70
const MENU_ICON_SIZE: f32 = 15.;66
const NOTIFICATION_ICON_SIZE: f32 = 13.;71
const NOTIFICATION_ICON_SIZE: f32 = 13.;72
const MENTION_ICON_SIZE: f32 = 15.;67
73
68
#[derive(Debug, Clone, Copy, PartialEq, Eq)]74
#[derive(Debug, Clone, Copy, PartialEq, Eq)]69
pub enum SidebarTab {75
pub enum SidebarTab {@@ -233,6 +239,17 @@ fn chat_menu(233
hide_state.update(cx, |state, cx| state.hide_chat(&hide_id, cx));239
hide_state.update(cx, |state, cx| state.hide_chat(&hide_id, cx));234
}),240
}),235
);241
);242
if !target.is_group {243
let remove_state = context.state.clone();244
let remove_id = target.id.clone();245
popup = popup.item(246
PopupMenuItem::new(REMOVE_HISTORY_LABEL)247
.icon(menu_icon(IconName::Trash))248
.on_click(move |_, window, cx| {249
confirm_remove_history(&remove_state, &remove_id, window, cx);250
}),251
);252
}236
if target.is_group {253
if target.is_group {237
let leave_state = context.state.clone();254
let leave_state = context.state.clone();238
let leave_id = target.id.clone();255
let leave_id = target.id.clone();@@ -444,6 +461,40 @@ fn leave_description(member_count: usize) -> String {444
format!("{who} {verb} that you left. You can only come back if someone adds you.")461
format!("{who} {verb} that you left. You can only come back if someone adds you.")445
}462
}446
463
464
const REMOVE_HISTORY_LABEL: &str = "Remove chat history";465
const REMOVE_HISTORY_TITLE: &str = "Remove chat history?";466
const REMOVE_HISTORY_TEXT: &str =467
"This will remove the chat from your list and search. It affects you only.";468
469
fn confirm_remove_history(470
state: &Entity<AppState>,471
chat_id: &str,472
window: &mut Window,473
cx: &mut App,474
) {475
let state = state.clone();476
let chat_id = chat_id.to_owned();477
window.open_alert_dialog(cx, move |alert, _, _| {478
let state = state.clone();479
let chat_id = chat_id.clone();480
let cancel = Button::new("remove-history-cancel")481
.label("Cancel")482
.on_click(|_, window, cx| window.close_dialog(cx));483
let remove = Button::new("remove-history-confirm")484
.label("Remove")485
.primary()486
.on_click(move |_, window, cx| {487
state.update(cx, |state, cx| state.remove_chat_history(&chat_id, cx));488
window.close_dialog(cx);489
});490
alert491
.title(REMOVE_HISTORY_TITLE)492
.description(REMOVE_HISTORY_TEXT)493
.footer(DialogFooter::new().child(cancel).child(remove))494
.on_ok(|_, _, _| false)495
});496
}497
447
pub(crate) fn confirm_leave(498
pub(crate) fn confirm_leave(448
state: &Entity<AppState>,499
state: &Entity<AppState>,449
chat_id: &str,500
chat_id: &str,@@ -778,6 +829,28 @@ impl SidebarView {778
.dropdown_menu(move |menu, _, _| menu.item(new_section_item(&state, read_only)))829
.dropdown_menu(move |menu, _, _| menu.item(new_section_item(&state, read_only)))779
}830
}780
831
832
fn channel_list_menu_button(&self, cx: &mut Context<Self>) -> impl IntoElement {833
let state = self.state.clone();834
let read_only = self.state.read(cx).mode.read_only;835
Button::new("channel-list-more")836
.icon(IconName::Ellipsis)837
.ghost()838
.size(px(NEW_CHAT_BUTTON_SIZE))839
.rounded(px(8.))840
.tooltip("More options")841
.dropdown_menu(move |menu, _, _| {842
let state = state.clone();843
menu.item(844
PopupMenuItem::new(MARK_ALL_READ_LABEL)845
.icon(menu_icon(IconName::CheckCheck))846
.disabled(read_only)847
.on_click(move |_, _, cx| {848
state.update(cx, |state, cx| state.mark_all_channels_read(cx));849
}),850
)851
})852
}853
781
fn draft_row(&self) -> impl IntoElement {854
fn draft_row(&self) -> impl IntoElement {782
h_flex()855
h_flex()783
.id("new-chat-draft")856
.id("new-chat-draft")@@ -1277,6 +1350,7 @@ impl SidebarView {1277
channel: &ChannelRecord,1350
channel: &ChannelRecord,1278
selected: bool,1351
selected: bool,1279
notifications: ChannelNotifications,1352
notifications: ChannelNotifications,1353
badge: Option<MentionBadge>,1280
) -> AnyElement {1354
) -> AnyElement {1281
let unread = channel.unread;1355
let unread = channel.unread;1282
let name_style = channel_name_style(unread, true, selected);1356
let name_style = channel_name_style(unread, true, selected);@@ -1337,15 +1411,19 @@ impl SidebarView {1337
),1411
),1338
)1412
)1339
.child(1413
.child(1340
h_flex().gap(px(8.)).items_center().child(1414
h_flex()1341
div()1415
.gap(px(8.))1342
.flex_1()1416
.items_center()1343
.min_w_0()1417
.child(1344
.truncate()1418
div()1345
.text_size(px(12.))1419
.flex_1()1346
.text_color(theme::text_muted())1420
.min_w_0()1347
.child(team.name.clone()),1421
.truncate()1348
),1422
.text_size(px(12.))1423
.text_color(theme::text_muted())1424
.child(team.name.clone()),1425
)1426
.children(badge.map(mention_badge)),1349
),1427
),1350
)1428
)1351
.on_click(move |_, _, cx| {1429
.on_click(move |_, _, cx| {@@ -1382,13 +1460,17 @@ impl SidebarView {1382
&self,1460
&self,1383
mut list: Div,1461
mut list: Div,1384
entry: &SidebarTeam,1462
entry: &SidebarTeam,1463
hoisted_only: bool,1385
selected: Option<&Selection>,1464
selected: Option<&Selection>,1386
cx: &mut Context<Self>,1465
cx: &mut Context<Self>,1387
) -> Div {1466
) -> Div {1388
let team_id = entry.team.id.clone();1467
let team_id = entry.team.id.clone();1389
let expanded = team_expanded(&team_id, &self.collapsed_teams);1468
let expanded = team_expanded(&team_id, &self.collapsed_teams);1390
let name_style = team_name_style(entry, expanded);1469
let name_style = team_name_style(entry, expanded);1470
let badge = team_badge(entry, expanded);1391
let toggle_id = team_id.clone();1471
let toggle_id = team_id.clone();1472
let (team_menu_state, team_menu_id, team_hidden) =1473
(self.state.clone(), team_id.clone(), entry.hidden);1392
list = list.child(1474
list = list.child(1393
h_flex()1475
h_flex()1394
.id(SharedString::from(format!("team-{team_id}")))1476
.id(SharedString::from(format!("team-{team_id}")))@@ -1421,45 +1503,45 @@ impl SidebarView {1421
.text_color(name_color(name_style))1503
.text_color(name_color(name_style))1422
.child(entry.team.name.clone()),1504
.child(entry.team.name.clone()),1423
)1505
)1506
.children(badge.map(mention_badge))1424
.on_click(cx.listener(move |this, _, _, cx| {1507
.on_click(cx.listener(move |this, _, _, cx| {1425
if !this.collapsed_teams.remove(&toggle_id) {1508
if !this.collapsed_teams.remove(&toggle_id) {1426
this.collapsed_teams.insert(toggle_id.clone());1509
this.collapsed_teams.insert(toggle_id.clone());1427
}1510
}1428
save_collapsed_teams(&this.state.read(cx).store, &this.collapsed_teams);1511
save_collapsed_teams(&this.state.read(cx).store, &this.collapsed_teams);1429
cx.notify();1512
cx.notify();1430
})),1513
}))1514
.context_menu(move |popup, _, _| {1515
team_menu(popup, team_menu_state.clone(), &team_menu_id, team_hidden)1516
}),1431
);1517
);1432
if !expanded {1518
if !expanded {1433
return list;1519
return list;1434
}1520
}1435
let is_hidden = |channel: &ChannelRecord| entry.hidden_channel_ids.contains(&channel.id);1436
let is_selected =1521
let is_selected =1437
|channel: &ChannelRecord| selected == Some(&Selection::Channel(channel.id.clone()));1522
|channel: &ChannelRecord| selected == Some(&Selection::Channel(channel.id.clone()));1438
for channel in entry1523
let revealed = self.revealed_channel_teams.contains(&team_id);1439
.channels1524
let rows = team_channel_rows(entry, hoisted_only, revealed, is_selected);1440
.iter()1525
for channel in &rows.shown {1441
.filter(|channel| !is_hidden(channel) || is_selected(channel))1442
{1443
list = list.child(self.team_channel_row(1526
list = list.child(self.team_channel_row(1444
channel,1527
channel,1445
is_selected(channel),1528
is_selected(channel),1446
channel_name_style(channel.unread, !is_hidden(channel), is_selected(channel)),1529
channel_name_style(1530
channel.unread,1531
channel_shown(entry, &channel.id),1532
is_selected(channel),1533
),1447
entry.channel_notifications(&channel.id),1534
entry.channel_notifications(&channel.id),1535
channel_badge(entry, &channel.id),1448
));1536
));1449
}1537
}1450
let hidden: Vec<&ChannelRecord> = entry1538
if rows.hidden_count == 0 {1451
.channels1452
.iter()1453
.filter(|channel| is_hidden(channel) && !is_selected(channel))1454
.collect();1455
if hidden.is_empty() {1456
return list;1539
return list;1457
}1540
}1458
let revealed = self.revealed_channel_teams.contains(&team_id);1459
let toggle_id = team_id.clone();1541
let toggle_id = team_id.clone();1460
list = list.child(self.reveal_row(1542
list = list.child(self.reveal_row(1461
SharedString::from(format!("hidden-channels-{team_id}")),1543
SharedString::from(format!("hidden-channels-{team_id}")),1462
hidden_channels_label(hidden.len()),1544
hidden_channels_label(rows.hidden_count),1463
revealed,1545
revealed,1464
40.,1546
40.,1465
cx.listener(move |this, _, _, cx| {1547
cx.listener(move |this, _, _, cx| {@@ -1469,15 +1551,14 @@ impl SidebarView {1469
cx.notify();1551
cx.notify();1470
}),1552
}),1471
));1553
));1472
if revealed {1554
for channel in rows.revealed {1473
for channel in hidden {1555
list = list.child(self.team_channel_row(1474
list = list.child(self.team_channel_row(1556
channel,1475
channel,1557
false,1476
false,1558
channel_name_style(channel.unread, false, false),1477
channel_name_style(channel.unread, false, false),1559
entry.channel_notifications(&channel.id),1478
entry.channel_notifications(&channel.id),1560
channel_badge(entry, &channel.id),1479
));1561
));1480
}1481
}1562
}1482
list1563
list1483
}1564
}@@ -1526,6 +1607,7 @@ impl SidebarView {1526
is_selected: bool,1607
is_selected: bool,1527
name_style: NameStyle,1608
name_style: NameStyle,1528
notifications: ChannelNotifications,1609
notifications: ChannelNotifications,1610
badge: Option<MentionBadge>,1529
) -> impl IntoElement {1611
) -> impl IntoElement {1530
let state = self.state.clone();1612
let state = self.state.clone();1531
let menu_state = self.state.clone();1613
let menu_state = self.state.clone();@@ -1566,6 +1648,7 @@ impl SidebarView {1566
.child(channel.name.clone()),1648
.child(channel.name.clone()),1567
)1649
)1568
.children(notification_badge(notifications.level))1650
.children(notification_badge(notifications.level))1651
.children(badge.map(mention_badge))1569
.on_click(move |_, _, cx| {1652
.on_click(move |_, _, cx| {1570
let selection = selection.clone();1653
let selection = selection.clone();1571
state.update(cx, |state, cx| state.select(selection, cx));1654
state.update(cx, |state, cx| state.select(selection, cx));@@ -1614,14 +1697,19 @@ impl SidebarView {1614
channel,1697
channel,1615
is_selected,1698
is_selected,1616
entry.channel_notifications(&channel.id),1699
entry.channel_notifications(&channel.id),1700
channel_badge(entry, &channel.id),1617
));1701
));1618
}1702
}1619
}1703
}1620
list = list.child(self.plain_header(TEAMS_LABEL));1704
list = list.child(self.plain_header(TEAMS_LABEL));1621
let (shown_teams, hidden_teams): (Vec<&SidebarTeam>, Vec<&SidebarTeam>) =1705
let hidden_teams: Vec<&SidebarTeam> =1622
sidebar.teams.iter().partition(|entry| !entry.hidden);1706
sidebar.teams.iter().filter(|entry| entry.hidden).collect();1623
for entry in shown_teams {1707
for entry in sidebar1624
list = self.team_block(list, entry, selected.as_ref(), cx);1708
.teams1709
.iter()1710
.filter(|entry| !entry.hidden || team_hoisted(entry))1711
{1712
list = self.team_block(list, entry, entry.hidden, selected.as_ref(), cx);1625
}1713
}1626
if !hidden_teams.is_empty() {1714
if !hidden_teams.is_empty() {1627
let holds_selection = hidden_teams1715
let holds_selection = hidden_teams@@ -1640,7 +1728,7 @@ impl SidebarView {1640
));1728
));1641
if open {1729
if open {1642
for entry in hidden_teams {1730
for entry in hidden_teams {1643
list = self.team_block(list, entry, selected.as_ref(), cx);1731
list = self.team_block(list, entry, false, selected.as_ref(), cx);1644
}1732
}1645
}1733
}1646
}1734
}@@ -1671,6 +1759,18 @@ fn name_color(style: NameStyle) -> Hsla {1671
}1759
}1672
}1760
}1673
1761
1762
fn mention_badge(badge: MentionBadge) -> AnyElement {1763
match badge {1764
MentionBadge::Count(count) => count_badge(count, false).into_any_element(),1765
MentionBadge::Channel => {1766
icon(IconName::Hash, MENTION_ICON_SIZE, theme::accent_text()).into_any_element()1767
}1768
MentionBadge::Team => {1769
icon(IconName::Users, MENTION_ICON_SIZE, theme::accent_text()).into_any_element()1770
}1771
}1772
}1773
1674
fn notification_badge(level: ChannelNotificationLevel) -> Option<impl IntoElement> {1774
fn notification_badge(level: ChannelNotificationLevel) -> Option<impl IntoElement> {1675
let name = match level {1775
let name = match level {1676
ChannelNotificationLevel::BannerAndFeed => IconName::Bell,1776
ChannelNotificationLevel::BannerAndFeed => IconName::Bell,@@ -1688,7 +1788,87 @@ fn channel_menu(1688
channel_id: &str,1788
channel_id: &str,1689
notifications: ChannelNotifications,1789
notifications: ChannelNotifications,1690
) -> PopupMenu {1790
) -> PopupMenu {1691
let channel_id = channel_id.to_owned();1791
let menu_state = state.read(cx).channel_menu_state(channel_id);1792
let mut popup = popup;1793
for entry in channel_menu_entries(menu_state) {1794
let item = match entry {1795
MenuEntry::Separator => {1796
popup = popup.separator();1797
continue;1798
}1799
MenuEntry::Item(ChannelMenuItem::Notifications) => {1800
popup = notifications_submenu(popup, window, cx, &state, channel_id, notifications);1801
continue;1802
}1803
MenuEntry::Item(item) => item,1804
};1805
let (action_state, action_id) = (state.clone(), channel_id.to_owned());1806
popup = popup.item(1807
PopupMenuItem::new(item.label())1808
.icon(menu_icon(channel_menu_icon(item)))1809
.disabled(menu_state.disables(item))1810
.on_click(move |_, _, cx| {1811
action_state.update(cx, |state, cx| match item {1812
ChannelMenuItem::Pin => state.set_channel_pinned(&action_id, true, cx),1813
ChannelMenuItem::Unpin => state.set_channel_pinned(&action_id, false, cx),1814
ChannelMenuItem::Show => state.set_channel_shown(&action_id, true, cx),1815
ChannelMenuItem::Hide => state.set_channel_shown(&action_id, false, cx),1816
ChannelMenuItem::CopyLink => state.copy_channel_link(&action_id, cx),1817
ChannelMenuItem::Notifications => {}1818
});1819
}),1820
);1821
}1822
popup1823
}1824
1825
fn channel_menu_icon(item: ChannelMenuItem) -> IconName {1826
match item {1827
ChannelMenuItem::Notifications => IconName::Bell,1828
ChannelMenuItem::Pin => IconName::Pin,1829
ChannelMenuItem::Unpin => IconName::PinOff,1830
ChannelMenuItem::Show => IconName::Eye,1831
ChannelMenuItem::Hide => IconName::EyeOff,1832
ChannelMenuItem::CopyLink => IconName::Link,1833
}1834
}1835
1836
fn team_menu(popup: PopupMenu, state: Entity<AppState>, team_id: &str, hidden: bool) -> PopupMenu {1837
let mut popup = popup;1838
for entry in team_menu_entries(hidden) {1839
let MenuEntry::Item(item) = entry else {1840
popup = popup.separator();1841
continue;1842
};1843
let (action_state, action_id) = (state.clone(), team_id.to_owned());1844
popup = popup.item(1845
PopupMenuItem::new(item.label())1846
.icon(menu_icon(match item {1847
TeamMenuItem::Show => IconName::Eye,1848
TeamMenuItem::Hide => IconName::EyeOff,1849
TeamMenuItem::CopyLink => IconName::Link,1850
}))1851
.on_click(move |_, _, cx| {1852
action_state.update(cx, |state, cx| match item {1853
TeamMenuItem::Show => state.set_team_shown(&action_id, true, cx),1854
TeamMenuItem::Hide => state.set_team_shown(&action_id, false, cx),1855
TeamMenuItem::CopyLink => state.copy_team_link(&action_id, cx),1856
});1857
}),1858
);1859
}1860
popup1861
}1862
1863
fn notifications_submenu(1864
popup: PopupMenu,1865
window: &mut Window,1866
cx: &mut Context<PopupMenu>,1867
state: &Entity<AppState>,1868
channel_id: &str,1869
notifications: ChannelNotifications,1870
) -> PopupMenu {1871
let (state, channel_id) = (state.clone(), channel_id.to_owned());1692
popup.submenu_with_icon(1872
popup.submenu_with_icon(1693
Some(menu_icon(IconName::Bell)),1873
Some(menu_icon(IconName::Bell)),1694
"Notifications",1874
"Notifications",@@ -1828,9 +2008,10 @@ impl Render for SidebarView {1828
)2008
)1829
.child(self.filter_bar(cx)),2009
.child(self.filter_bar(cx)),1830
),2010
),1831
SidebarTab::Channels | SidebarTab::Calls | SidebarTab::Agents => {2011
SidebarTab::Channels => {1832
Some(v_flex().child(page_header(self.tab.title())))2012
Some(page_header(self.tab.title()).child(self.channel_list_menu_button(cx)))1833
}2013
}2014
SidebarTab::Calls | SidebarTab::Agents => Some(page_header(self.tab.title())),1834
SidebarTab::Activity | SidebarTab::Saved => None,2015
SidebarTab::Activity | SidebarTab::Saved => None,1835
};2016
};1836
v_flex()2017
v_flex()@@ -0,0 +1,38 @@
1
const cache = (window.__rustyTeamsSkype = window.__rustyTeamsSkype || {});
2
if (!cache.token || cache.expires <= Date.now() + 60000) {
3
const spaces = await acquire('https://api.spaces.skype.com', 'authorization.readwrite');
4
if (!spaces.token) return {status: 0, body: 'no token for authsvc'};
5
let response;
6
try {
7
response = await fetch('https://teams.cloud.microsoft/api/authsvc/v1.0/authz', {
8
method: 'POST',
9
headers: {Authorization: 'Bearer ' + spaces.token},
10
});
11
} catch (error) {
12
return {status: 0, body: 'authz_unreachable'};
13
}
14
if (!response.ok) return {status: 0, body: 'authz_http_' + response.status};
15
try {
16
const answer = await response.json();
17
cache.token = answer.tokens.skypeToken;
18
cache.expires = Date.now() + Number(answer.tokens.expiresIn || 0) * 1000;
19
cache.chatService = answer.regionGtms.chatService;
20
} catch (error) {
21
return {status: 0, body: 'authz_shape'};
22
}
23
}
24
const headers = {...args.headers, Authorization: 'Bearer ' + token, 'x-skypetoken': cache.token};
25
if (cache.chatService) headers['x-csendpoint'] = cache.chatService;
26
try {
27
const response = await fetch(args.url, {
28
method: args.method,
29
headers,
30
body: args.body === null ? undefined : JSON.stringify(args.body),
31
});
32
const text = await response.text();
33
let body = text;
34
try { body = text ? JSON.parse(text) : null; } catch (error) {}
35
return {status: response.status, retryAfter: response.headers.get('Retry-After'), body};
36
} catch (error) {
37
return {status: 0, body: String(error)};
38
}
@@ -0,0 +1,38 @@1
const cache = (window.__rustyTeamsSkype = window.__rustyTeamsSkype || {});2
if (!cache.token || cache.expires <= Date.now() + 60000) {3
const spaces = await acquire('https://api.spaces.skype.com', 'authorization.readwrite');4
if (!spaces.token) return {status: 0, body: 'no token for authsvc'};5
let response;6
try {7
response = await fetch('https://teams.cloud.microsoft/api/authsvc/v1.0/authz', {8
method: 'POST',9
headers: {Authorization: 'Bearer ' + spaces.token},10
});11
} catch (error) {12
return {status: 0, body: 'authz_unreachable'};13
}14
if (!response.ok) return {status: 0, body: 'authz_http_' + response.status};15
try {16
const answer = await response.json();17
cache.token = answer.tokens.skypeToken;18
cache.expires = Date.now() + Number(answer.tokens.expiresIn || 0) * 1000;19
cache.chatService = answer.regionGtms.chatService;20
} catch (error) {21
return {status: 0, body: 'authz_shape'};22
}23
}24
const headers = {...args.headers, Authorization: 'Bearer ' + token, 'x-skypetoken': cache.token};25
if (cache.chatService) headers['x-csendpoint'] = cache.chatService;26
try {27
const response = await fetch(args.url, {28
method: args.method,29
headers,30
body: args.body === null ? undefined : JSON.stringify(args.body),31
});32
const text = await response.text();33
let body = text;34
try { body = text ? JSON.parse(text) : null; } catch (error) {}35
return {status: response.status, retryAfter: response.headers.get('Retry-After'), body};36
} catch (error) {37
return {status: 0, body: String(error)};38
}@@ -0,0 +1,294 @@
1
use chrono::DateTime;
2
use serde_json::Value;
3
use session::{Request, Session};
4
5
use crate::error::{Error, Result};
6
use crate::messages::{MessageTransport, SessionMessageTransport, ensure_success};
7
use crate::pins::DEFAULT_REGION;
8
9
const PAGE_SIZE: usize = 200;
10
const MAX_PAGES: usize = 3;
11
const MENTION_TYPES: [&str; 2] = ["mention", "mentionInCommunity"];
12
13
/// Who an @mention addressed, as Teams splits them in `ChannelActivitiesPublisher`.
14
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
15
pub enum MentionKind {
16
Personal,
17
Channel,
18
Team,
19
}
20
21
#[derive(Debug, Clone, PartialEq, Eq)]
22
pub struct MentionActivity {
23
pub activity_id: String,
24
pub kind: MentionKind,
25
pub source_thread_id: String,
26
pub source_message_id: Option<String>,
27
pub timestamp_ms: i64,
28
pub is_read: bool,
29
}
30
31
pub struct ActivityFeed<T: MessageTransport = SessionMessageTransport> {
32
transport: T,
33
stream_url: String,
34
}
35
36
impl ActivityFeed<SessionMessageTransport> {
37
pub fn new(session: &Session) -> Self {
38
ActivityFeed::with_transport(SessionMessageTransport::new(session), DEFAULT_REGION)
39
}
40
}
41
42
impl<T: MessageTransport> ActivityFeed<T> {
43
pub fn with_transport(transport: T, region: &str) -> Self {
44
ActivityFeed {
45
transport,
46
stream_url: format!(
47
"https://teams.cloud.microsoft/api/chatsvc/{region}/v1/users/ME/streams/notifications/messages"
48
),
49
}
50
}
51
52
pub fn first_page_url(&self) -> String {
53
format!(
54
"{}?view=msnp24Equivalent|supportsMessageProperties&pageSize={PAGE_SIZE}&startTime=1",
55
self.stream_url
56
)
57
}
58
59
/// Newest activity pages, mentions only.
60
pub async fn mentions(&self) -> Result<Vec<MentionActivity>> {
61
let mut mentions = Vec::new();
62
let mut next_url = Some(self.first_page_url());
63
for _ in 0..MAX_PAGES {
64
let Some(url) = next_url.take() else {
65
break;
66
};
67
let answer = self.transport.send(Request::get(&url)).await?;
68
ensure_success(&answer)?;
69
mentions.extend(parse_mention_page(&answer.body)?);
70
next_url = answer
71
.body
72
.pointer("/_metadata/backwardLink")
73
.and_then(Value::as_str)
74
.filter(|link| !link.is_empty() && *link != url)
75
.map(str::to_owned);
76
}
77
Ok(mentions)
78
}
79
}
80
81
pub fn parse_mention_page(body: &Value) -> Result<Vec<MentionActivity>> {
82
let messages = body
83
.get("messages")
84
.and_then(Value::as_array)
85
.ok_or_else(|| Error::UnexpectedAnswer("activity messages missing".into()))?;
86
Ok(messages.iter().filter_map(mention_activity).collect())
87
}
88
89
fn object_property(properties: &Value, key: &str) -> Option<Value> {
90
match properties.get(key)? {
91
Value::String(text) => serde_json::from_str::<Value>(text)
92
.ok()
93
.filter(Value::is_object),
94
other if other.is_object() => Some(other.clone()),
95
_ => None,
96
}
97
}
98
99
fn text_of(value: &Value) -> Option<String> {
100
match value {
101
Value::String(text) if !text.is_empty() => Some(text.clone()),
102
Value::Number(number) => Some(number.to_string()),
103
_ => None,
104
}
105
}
106
107
fn flag(value: Option<&Value>) -> bool {
108
match value {
109
Some(Value::Bool(flag)) => *flag,
110
Some(Value::String(text)) => text.eq_ignore_ascii_case("true"),
111
_ => false,
112
}
113
}
114
115
fn timestamp_ms(value: &Value) -> Option<i64> {
116
match value {
117
Value::Number(number) => number.as_i64(),
118
Value::String(text) => text.parse::<i64>().ok().or_else(|| {
119
DateTime::parse_from_rfc3339(text)
120
.ok()
121
.map(|time| time.timestamp_millis())
122
}),
123
_ => None,
124
}
125
}
126
127
fn mention_kind(subtype: &str) -> Option<MentionKind> {
128
match subtype.to_ascii_lowercase().as_str() {
129
"person" | "tag" => Some(MentionKind::Personal),
130
"channel" => Some(MentionKind::Channel),
131
"team" => Some(MentionKind::Team),
132
_ => None,
133
}
134
}
135
136
fn mention_activity(message: &Value) -> Option<MentionActivity> {
137
let properties = message.get("properties")?;
138
let activity = object_property(properties, "activity")?;
139
let activity_type = activity.get("activityType")?.as_str()?;
140
if !MENTION_TYPES.contains(&activity_type) {
141
return None;
142
}
143
let kind = mention_kind(activity.get("activitySubtype")?.as_str()?)?;
144
Some(MentionActivity {
145
activity_id: activity
146
.get("activityId")
147
.and_then(text_of)
148
.or_else(|| message.get("id").and_then(text_of))?,
149
kind,
150
source_thread_id: activity.get("sourceThreadId")?.as_str()?.to_owned(),
151
source_message_id: activity.get("sourceMessageId").and_then(text_of),
152
timestamp_ms: activity
153
.get("activityTimestamp")
154
.and_then(timestamp_ms)
155
.unwrap_or(0),
156
is_read: flag(properties.get("isread")),
157
})
158
}
159
160
#[cfg(test)]
161
mod tests {
162
use std::collections::VecDeque;
163
use std::sync::Mutex;
164
165
use serde_json::json;
166
use session::ApiResponse;
167
168
use super::*;
169
170
struct Canned {
171
answers: Mutex<VecDeque<(u16, Value)>>,
172
requests: Mutex<Vec<Request>>,
173
}
174
175
impl MessageTransport for &Canned {
176
async fn send(&self, request: Request) -> Result<ApiResponse> {
177
self.requests.lock().unwrap().push(request);
178
let (status, body) = self.answers.lock().unwrap().pop_front().expect("exhausted");
179
Ok(ApiResponse {
180
status,
181
body,
182
retry_after: None,
183
})
184
}
185
}
186
187
fn activity_message(id: &str, activity: Value, isread: Option<&str>) -> Value {
188
let mut properties = json!({"activity": activity});
189
if let Some(isread) = isread {
190
properties["isread"] = json!(isread);
191
}
192
json!({"id": id, "messagetype": "Text", "properties": properties})
193
}
194
195
#[test]
196
fn keeps_mentions_and_maps_the_subtypes() {
197
let body = json!({"messages": [
198
activity_message("m1", json!({
199
"activityId": 101, "activityType": "mention", "activitySubtype": "person",
200
"sourceThreadId": "19:a@thread.tacv2", "sourceMessageId": 1791368000000_i64,
201
"activityTimestamp": "2026-10-17T08:00:00.000Z"
202
}), Some("true")),
203
activity_message("m2", json!({
204
"activityType": "mention", "activitySubtype": "tag",
205
"sourceThreadId": "19:a@thread.tacv2", "activityTimestamp": 1791368100000_i64
206
}), None),
207
activity_message("m3", json!({
208
"activityId": "103", "activityType": "mention", "activitySubtype": "channel",
209
"sourceThreadId": "19:b@thread.tacv2"
210
}), Some("false")),
211
activity_message("m4", json!({
212
"activityId": "104", "activityType": "mentionInCommunity", "activitySubtype": "team",
213
"sourceThreadId": "19:b@thread.tacv2"
214
}), None),
215
activity_message("m5", json!({
216
"activityId": "105", "activityType": "reply", "activitySubtype": "person",
217
"sourceThreadId": "19:b@thread.tacv2"
218
}), None),
219
activity_message("m6", json!({
220
"activityId": "106", "activityType": "mention", "activitySubtype": "everyone",
221
"sourceThreadId": "19:b@thread.tacv2"
222
}), None),
223
{"id": "m7", "properties": {}}
224
]});
225
let mentions = parse_mention_page(&body).unwrap();
226
let kinds: Vec<(&str, MentionKind)> = mentions
227
.iter()
228
.map(|mention| (mention.activity_id.as_str(), mention.kind))
229
.collect();
230
assert_eq!(
231
kinds,
232
[
233
("101", MentionKind::Personal),
234
("m2", MentionKind::Personal),
235
("103", MentionKind::Channel),
236
("104", MentionKind::Team),
237
]
238
);
239
assert!(mentions[0].is_read);
240
assert!(!mentions[1].is_read);
241
assert_eq!(
242
mentions[0].source_message_id.as_deref(),
243
Some("1791368000000")
244
);
245
assert_eq!(mentions[0].timestamp_ms, 1792224000000);
246
assert_eq!(mentions[1].timestamp_ms, 1791368100000);
247
assert_eq!(mentions[2].timestamp_ms, 0);
248
}
249
250
#[test]
251
fn reads_the_activity_when_it_is_a_json_string() {
252
let activity = json!({
253
"activityId": "7", "activityType": "mention", "activitySubtype": "person",
254
"sourceThreadId": "19:a@thread.tacv2"
255
});
256
let body = json!({"messages": [
257
activity_message("m1", Value::String(activity.to_string()), Some("True"))
258
]});
259
let mentions = parse_mention_page(&body).unwrap();
260
assert_eq!(mentions.len(), 1);
261
assert!(mentions[0].is_read);
262
}
263
264
#[test]
265
fn an_answer_without_messages_is_unexpected() {
266
assert!(parse_mention_page(&json!({})).is_err());
267
}
268
269
#[tokio::test]
270
async fn pages_backward_through_the_stream() {
271
let transport = Canned {
272
answers: Mutex::new(
273
vec![
274
(
275
200,
276
json!({"messages": [], "_metadata": {"backwardLink": "https://next"}}),
277
),
278
(200, json!({"messages": [], "_metadata": {"backwardLink": ""}})),
279
]
280
.into(),
281
),
282
requests: Mutex::new(Vec::new()),
283
};
284
let feed = ActivityFeed::with_transport(&transport, "emea");
285
assert!(feed.mentions().await.unwrap().is_empty());
286
let requests = transport.requests.lock().unwrap();
287
assert_eq!(
288
requests[0].url,
289
"https://teams.cloud.microsoft/api/chatsvc/emea/v1/users/ME/streams/notifications/messages?view=msnp24Equivalent|supportsMessageProperties&pageSize=200&startTime=1"
290
);
291
assert_eq!(requests[1].url, "https://next");
292
assert_eq!(requests.len(), 2);
293
}
294
}
@@ -0,0 +1,294 @@1
use chrono::DateTime;2
use serde_json::Value;3
use session::{Request, Session};4
5
use crate::error::{Error, Result};6
use crate::messages::{MessageTransport, SessionMessageTransport, ensure_success};7
use crate::pins::DEFAULT_REGION;8
9
const PAGE_SIZE: usize = 200;10
const MAX_PAGES: usize = 3;11
const MENTION_TYPES: [&str; 2] = ["mention", "mentionInCommunity"];12
13
/// Who an @mention addressed, as Teams splits them in `ChannelActivitiesPublisher`.14
#[derive(Debug, Clone, Copy, PartialEq, Eq)]15
pub enum MentionKind {16
Personal,17
Channel,18
Team,19
}20
21
#[derive(Debug, Clone, PartialEq, Eq)]22
pub struct MentionActivity {23
pub activity_id: String,24
pub kind: MentionKind,25
pub source_thread_id: String,26
pub source_message_id: Option<String>,27
pub timestamp_ms: i64,28
pub is_read: bool,29
}30
31
pub struct ActivityFeed<T: MessageTransport = SessionMessageTransport> {32
transport: T,33
stream_url: String,34
}35
36
impl ActivityFeed<SessionMessageTransport> {37
pub fn new(session: &Session) -> Self {38
ActivityFeed::with_transport(SessionMessageTransport::new(session), DEFAULT_REGION)39
}40
}41
42
impl<T: MessageTransport> ActivityFeed<T> {43
pub fn with_transport(transport: T, region: &str) -> Self {44
ActivityFeed {45
transport,46
stream_url: format!(47
"https://teams.cloud.microsoft/api/chatsvc/{region}/v1/users/ME/streams/notifications/messages"48
),49
}50
}51
52
pub fn first_page_url(&self) -> String {53
format!(54
"{}?view=msnp24Equivalent|supportsMessageProperties&pageSize={PAGE_SIZE}&startTime=1",55
self.stream_url56
)57
}58
59
/// Newest activity pages, mentions only.60
pub async fn mentions(&self) -> Result<Vec<MentionActivity>> {61
let mut mentions = Vec::new();62
let mut next_url = Some(self.first_page_url());63
for _ in 0..MAX_PAGES {64
let Some(url) = next_url.take() else {65
break;66
};67
let answer = self.transport.send(Request::get(&url)).await?;68
ensure_success(&answer)?;69
mentions.extend(parse_mention_page(&answer.body)?);70
next_url = answer71
.body72
.pointer("/_metadata/backwardLink")73
.and_then(Value::as_str)74
.filter(|link| !link.is_empty() && *link != url)75
.map(str::to_owned);76
}77
Ok(mentions)78
}79
}80
81
pub fn parse_mention_page(body: &Value) -> Result<Vec<MentionActivity>> {82
let messages = body83
.get("messages")84
.and_then(Value::as_array)85
.ok_or_else(|| Error::UnexpectedAnswer("activity messages missing".into()))?;86
Ok(messages.iter().filter_map(mention_activity).collect())87
}88
89
fn object_property(properties: &Value, key: &str) -> Option<Value> {90
match properties.get(key)? {91
Value::String(text) => serde_json::from_str::<Value>(text)92
.ok()93
.filter(Value::is_object),94
other if other.is_object() => Some(other.clone()),95
_ => None,96
}97
}98
99
fn text_of(value: &Value) -> Option<String> {100
match value {101
Value::String(text) if !text.is_empty() => Some(text.clone()),102
Value::Number(number) => Some(number.to_string()),103
_ => None,104
}105
}106
107
fn flag(value: Option<&Value>) -> bool {108
match value {109
Some(Value::Bool(flag)) => *flag,110
Some(Value::String(text)) => text.eq_ignore_ascii_case("true"),111
_ => false,112
}113
}114
115
fn timestamp_ms(value: &Value) -> Option<i64> {116
match value {117
Value::Number(number) => number.as_i64(),118
Value::String(text) => text.parse::<i64>().ok().or_else(|| {119
DateTime::parse_from_rfc3339(text)120
.ok()121
.map(|time| time.timestamp_millis())122
}),123
_ => None,124
}125
}126
127
fn mention_kind(subtype: &str) -> Option<MentionKind> {128
match subtype.to_ascii_lowercase().as_str() {129
"person" | "tag" => Some(MentionKind::Personal),130
"channel" => Some(MentionKind::Channel),131
"team" => Some(MentionKind::Team),132
_ => None,133
}134
}135
136
fn mention_activity(message: &Value) -> Option<MentionActivity> {137
let properties = message.get("properties")?;138
let activity = object_property(properties, "activity")?;139
let activity_type = activity.get("activityType")?.as_str()?;140
if !MENTION_TYPES.contains(&activity_type) {141
return None;142
}143
let kind = mention_kind(activity.get("activitySubtype")?.as_str()?)?;144
Some(MentionActivity {145
activity_id: activity146
.get("activityId")147
.and_then(text_of)148
.or_else(|| message.get("id").and_then(text_of))?,149
kind,150
source_thread_id: activity.get("sourceThreadId")?.as_str()?.to_owned(),151
source_message_id: activity.get("sourceMessageId").and_then(text_of),152
timestamp_ms: activity153
.get("activityTimestamp")154
.and_then(timestamp_ms)155
.unwrap_or(0),156
is_read: flag(properties.get("isread")),157
})158
}159
160
#[cfg(test)]161
mod tests {162
use std::collections::VecDeque;163
use std::sync::Mutex;164
165
use serde_json::json;166
use session::ApiResponse;167
168
use super::*;169
170
struct Canned {171
answers: Mutex<VecDeque<(u16, Value)>>,172
requests: Mutex<Vec<Request>>,173
}174
175
impl MessageTransport for &Canned {176
async fn send(&self, request: Request) -> Result<ApiResponse> {177
self.requests.lock().unwrap().push(request);178
let (status, body) = self.answers.lock().unwrap().pop_front().expect("exhausted");179
Ok(ApiResponse {180
status,181
body,182
retry_after: None,183
})184
}185
}186
187
fn activity_message(id: &str, activity: Value, isread: Option<&str>) -> Value {188
let mut properties = json!({"activity": activity});189
if let Some(isread) = isread {190
properties["isread"] = json!(isread);191
}192
json!({"id": id, "messagetype": "Text", "properties": properties})193
}194
195
#[test]196
fn keeps_mentions_and_maps_the_subtypes() {197
let body = json!({"messages": [198
activity_message("m1", json!({199
"activityId": 101, "activityType": "mention", "activitySubtype": "person",200
"sourceThreadId": "19:a@thread.tacv2", "sourceMessageId": 1791368000000_i64,201
"activityTimestamp": "2026-10-17T08:00:00.000Z"202
}), Some("true")),203
activity_message("m2", json!({204
"activityType": "mention", "activitySubtype": "tag",205
"sourceThreadId": "19:a@thread.tacv2", "activityTimestamp": 1791368100000_i64206
}), None),207
activity_message("m3", json!({208
"activityId": "103", "activityType": "mention", "activitySubtype": "channel",209
"sourceThreadId": "19:b@thread.tacv2"210
}), Some("false")),211
activity_message("m4", json!({212
"activityId": "104", "activityType": "mentionInCommunity", "activitySubtype": "team",213
"sourceThreadId": "19:b@thread.tacv2"214
}), None),215
activity_message("m5", json!({216
"activityId": "105", "activityType": "reply", "activitySubtype": "person",217
"sourceThreadId": "19:b@thread.tacv2"218
}), None),219
activity_message("m6", json!({220
"activityId": "106", "activityType": "mention", "activitySubtype": "everyone",221
"sourceThreadId": "19:b@thread.tacv2"222
}), None),223
{"id": "m7", "properties": {}}224
]});225
let mentions = parse_mention_page(&body).unwrap();226
let kinds: Vec<(&str, MentionKind)> = mentions227
.iter()228
.map(|mention| (mention.activity_id.as_str(), mention.kind))229
.collect();230
assert_eq!(231
kinds,232
[233
("101", MentionKind::Personal),234
("m2", MentionKind::Personal),235
("103", MentionKind::Channel),236
("104", MentionKind::Team),237
]238
);239
assert!(mentions[0].is_read);240
assert!(!mentions[1].is_read);241
assert_eq!(242
mentions[0].source_message_id.as_deref(),243
Some("1791368000000")244
);245
assert_eq!(mentions[0].timestamp_ms, 1792224000000);246
assert_eq!(mentions[1].timestamp_ms, 1791368100000);247
assert_eq!(mentions[2].timestamp_ms, 0);248
}249
250
#[test]251
fn reads_the_activity_when_it_is_a_json_string() {252
let activity = json!({253
"activityId": "7", "activityType": "mention", "activitySubtype": "person",254
"sourceThreadId": "19:a@thread.tacv2"255
});256
let body = json!({"messages": [257
activity_message("m1", Value::String(activity.to_string()), Some("True"))258
]});259
let mentions = parse_mention_page(&body).unwrap();260
assert_eq!(mentions.len(), 1);261
assert!(mentions[0].is_read);262
}263
264
#[test]265
fn an_answer_without_messages_is_unexpected() {266
assert!(parse_mention_page(&json!({})).is_err());267
}268
269
#[tokio::test]270
async fn pages_backward_through_the_stream() {271
let transport = Canned {272
answers: Mutex::new(273
vec![274
(275
200,276
json!({"messages": [], "_metadata": {"backwardLink": "https://next"}}),277
),278
(200, json!({"messages": [], "_metadata": {"backwardLink": ""}})),279
]280
.into(),281
),282
requests: Mutex::new(Vec::new()),283
};284
let feed = ActivityFeed::with_transport(&transport, "emea");285
assert!(feed.mentions().await.unwrap().is_empty());286
let requests = transport.requests.lock().unwrap();287
assert_eq!(288
requests[0].url,289
"https://teams.cloud.microsoft/api/chatsvc/emea/v1/users/ME/streams/notifications/messages?view=msnp24Equivalent|supportsMessageProperties&pageSize=200&startTime=1"290
);291
assert_eq!(requests[1].url, "https://next");292
assert_eq!(requests.len(), 2);293
}294
}@@ -0,0 +1,497 @@
1
use serde_json::{Value, json};
2
use session::{Method, Request, Session};
3
4
use crate::error::Result;
5
use crate::members::{threads_url, user_mri};
6
use crate::messages::{MessageTransport, SessionMessageTransport, encode, ensure_success};
7
use crate::pins::DEFAULT_REGION;
8
9
const FAVORITE_PROPERTY: &str = "favorite";
10
const GENERAL_FAVORITE_PROPERTY: &str = "isGeneralChannelFavorite";
11
const FOLLOWED_PROPERTY: &str = "isfollowed";
12
const PERMANENT_JOIN_QUERY: &str = "requirePermanentJoinedState=true";
13
const FAVORITE_MODE_HEADER: &str = "x-ms-favorite-mode";
14
const FAVORITE_MODE_MANUAL: &str = "manual";
15
const HIDDEN_MEMBERSHIP_SECONDS: i64 = 1_209_600;
16
17
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
18
pub enum ChannelKind {
19
Standard,
20
Private,
21
Shared,
22
}
23
24
impl ChannelKind {
25
pub fn from_membership_type(membership_type: Option<&str>) -> Self {
26
match membership_type.map(str::to_ascii_lowercase).as_deref() {
27
Some("private") => ChannelKind::Private,
28
Some("shared") => ChannelKind::Shared,
29
_ => ChannelKind::Standard,
30
}
31
}
32
}
33
34
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
35
pub struct ChannelTarget<'a> {
36
pub channel_id: &'a str,
37
pub general: bool,
38
pub kind: ChannelKind,
39
}
40
41
/// The own member state of a channel conversation that decides Teams' show and hide steps.
42
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
43
pub struct ChannelMembership {
44
pub moderator: bool,
45
pub explicitly_added: bool,
46
pub followed: bool,
47
}
48
49
fn truthy(value: Option<&Value>) -> bool {
50
match value {
51
Some(Value::Bool(flag)) => *flag,
52
Some(Value::String(text)) => !text.is_empty(),
53
Some(Value::Number(number)) => number.as_f64().is_some_and(|number| number != 0.),
54
Some(Value::Array(_) | Value::Object(_)) => true,
55
_ => false,
56
}
57
}
58
59
pub fn parse_channel_membership(conversation: &Value) -> ChannelMembership {
60
let member = conversation.get("memberProperties");
61
ChannelMembership {
62
moderator: truthy(member.and_then(|member| member.get("isModerator"))),
63
explicitly_added: truthy(member.and_then(|member| member.get("explicitlyAdded"))),
64
followed: truthy(conversation.pointer(&format!("/properties/{FOLLOWED_PROPERTY}"))),
65
}
66
}
67
68
/// Teams joins the user to a standard channel thread before it changes the channel's visibility.
69
pub fn joins_thread(kind: ChannelKind, membership: ChannelMembership) -> bool {
70
let permanently_joined = kind == ChannelKind::Private
71
|| (kind == ChannelKind::Shared && membership.explicitly_added)
72
|| membership.moderator;
73
!permanently_joined
74
}
75
76
pub fn membership_expiration(shown: bool, now_ms: i64) -> i64 {
77
if shown {
78
0
79
} else {
80
(now_ms + 999).div_euclid(1000) + HIDDEN_MEMBERSHIP_SECONDS
81
}
82
}
83
84
pub struct ChannelVisibility<T: MessageTransport = SessionMessageTransport> {
85
transport: T,
86
conversations_url: String,
87
threads_url: String,
88
}
89
90
impl ChannelVisibility<SessionMessageTransport> {
91
pub fn new(session: &Session) -> Self {
92
ChannelVisibility::with_transport(SessionMessageTransport::new(session), DEFAULT_REGION)
93
}
94
}
95
96
impl<T: MessageTransport> ChannelVisibility<T> {
97
pub fn with_transport(transport: T, region: &str) -> Self {
98
ChannelVisibility {
99
transport,
100
conversations_url: format!(
101
"https://teams.cloud.microsoft/api/chatsvc/{region}/v1/users/ME/conversations"
102
),
103
threads_url: threads_url(region),
104
}
105
}
106
107
pub fn conversation_request(&self, conversation_id: &str) -> Request {
108
Request::get(format!(
109
"{}/{}?view=msnp24Equivalent",
110
self.conversations_url,
111
encode(conversation_id)
112
))
113
}
114
115
fn property_request(&self, conversation_id: &str, name: &str, value: Value) -> Request {
116
Request::with_body(
117
Method::Put,
118
format!(
119
"{}/{}/properties?name={name}",
120
self.conversations_url,
121
encode(conversation_id)
122
),
123
json!({ name: value }),
124
)
125
}
126
127
pub fn favorite_request(&self, channel_id: &str, shown: bool) -> Request {
128
let mut request =
129
self.property_request(channel_id, FAVORITE_PROPERTY, json!(shown.to_string()));
130
if shown {
131
request.url = format!("{}&{PERMANENT_JOIN_QUERY}", request.url);
132
request
133
.headers
134
.push((FAVORITE_MODE_HEADER.into(), FAVORITE_MODE_MANUAL.into()));
135
}
136
request
137
}
138
139
pub fn general_favorite_request(&self, team_thread_id: &str, shown: bool) -> Request {
140
self.property_request(
141
team_thread_id,
142
GENERAL_FAVORITE_PROPERTY,
143
json!(shown.to_string()),
144
)
145
}
146
147
pub fn team_favorite_request(&self, team_thread_id: &str, shown: bool) -> Request {
148
self.property_request(team_thread_id, FAVORITE_PROPERTY, json!(shown.to_string()))
149
}
150
151
pub fn unfollow_request(&self, channel_id: &str) -> Request {
152
self.property_request(channel_id, FOLLOWED_PROPERTY, json!(false))
153
}
154
155
pub fn membership_request(
156
&self,
157
channel_id: &str,
158
own_user_id: &str,
159
shown: bool,
160
now_ms: i64,
161
) -> Request {
162
Request::with_body(
163
Method::Put,
164
format!(
165
"{}/{}/members/{}",
166
self.threads_url,
167
encode(channel_id),
168
user_mri(own_user_id)
169
),
170
json!({ "expiration": membership_expiration(shown, now_ms) }),
171
)
172
}
173
174
/// Teams' order for a channel other than General: join step, `favorite`, then `isfollowed`.
175
pub fn channel_requests(
176
&self,
177
target: &ChannelTarget<'_>,
178
membership: ChannelMembership,
179
own_user_id: &str,
180
shown: bool,
181
now_ms: i64,
182
) -> Vec<Request> {
183
if target.general {
184
return vec![self.general_favorite_request(target.channel_id, shown)];
185
}
186
let mut requests = Vec::new();
187
if joins_thread(target.kind, membership) {
188
requests.push(self.membership_request(target.channel_id, own_user_id, shown, now_ms));
189
}
190
requests.push(self.favorite_request(target.channel_id, shown));
191
if !shown || membership.followed {
192
requests.push(self.unfollow_request(target.channel_id));
193
}
194
requests
195
}
196
197
pub async fn set_channel_shown(
198
&self,
199
target: &ChannelTarget<'_>,
200
own_user_id: &str,
201
shown: bool,
202
now_ms: i64,
203
) -> Result<()> {
204
let membership = if target.general {
205
ChannelMembership::default()
206
} else {
207
let answer = self
208
.transport
209
.send(self.conversation_request(target.channel_id))
210
.await?;
211
ensure_success(&answer)?;
212
parse_channel_membership(&answer.body)
213
};
214
for request in self.channel_requests(target, membership, own_user_id, shown, now_ms) {
215
ensure_success(&self.transport.send(request).await?)?;
216
}
217
Ok(())
218
}
219
220
pub async fn set_team_shown(&self, team_thread_id: &str, shown: bool) -> Result<()> {
221
let answer = self
222
.transport
223
.send(self.team_favorite_request(team_thread_id, shown))
224
.await?;
225
ensure_success(&answer)
226
}
227
}
228
229
#[cfg(test)]
230
mod tests {
231
use std::collections::VecDeque;
232
use std::sync::Mutex;
233
234
use session::ApiResponse;
235
236
use super::*;
237
238
const BASE: &str = "https://teams.cloud.microsoft/api/chatsvc/emea/v1";
239
const CHANNEL: &str = "19:abc@thread.tacv2";
240
const ENCODED: &str = "19%3Aabc%40thread.tacv2";
241
const NOW_MS: i64 = 1_791_368_000_500;
242
243
struct Canned {
244
requests: Mutex<Vec<Request>>,
245
answers: Mutex<VecDeque<(u16, Value)>>,
246
}
247
248
impl MessageTransport for &Canned {
249
async fn send(&self, request: Request) -> Result<ApiResponse> {
250
self.requests.lock().unwrap().push(request);
251
let (status, body) = self
252
.answers
253
.lock()
254
.unwrap()
255
.pop_front()
256
.unwrap_or((200, Value::Null));
257
Ok(ApiResponse {
258
status,
259
body,
260
retry_after: None,
261
})
262
}
263
}
264
265
fn canned(answers: Vec<(u16, Value)>) -> Canned {
266
Canned {
267
requests: Mutex::new(Vec::new()),
268
answers: Mutex::new(answers.into()),
269
}
270
}
271
272
fn standard() -> ChannelTarget<'static> {
273
ChannelTarget {
274
channel_id: CHANNEL,
275
general: false,
276
kind: ChannelKind::Standard,
277
}
278
}
279
280
fn summary(request: &Request) -> (String, String, Option<Value>) {
281
(
282
request.method.as_str().to_owned(),
283
request.url.clone(),
284
request.body.clone(),
285
)
286
}
287
288
#[test]
289
fn showing_a_standard_channel_joins_then_favorites_with_the_manual_mode() {
290
let transport = canned(Vec::new());
291
let client = ChannelVisibility::with_transport(&transport, "emea");
292
let requests = client.channel_requests(
293
&standard(),
294
ChannelMembership::default(),
295
"user-1",
296
true,
297
NOW_MS,
298
);
299
let summaries: Vec<_> = requests.iter().map(summary).collect();
300
assert_eq!(
301
summaries,
302
vec![
303
(
304
"PUT".to_owned(),
305
format!("{BASE}/threads/{ENCODED}/members/8:orgid:user-1"),
306
Some(json!({"expiration": 0})),
307
),
308
(
309
"PUT".to_owned(),
310
format!(
311
"{BASE}/users/ME/conversations/{ENCODED}/properties?name=favorite&requirePermanentJoinedState=true"
312
),
313
Some(json!({"favorite": "true"})),
314
),
315
]
316
);
317
assert_eq!(
318
requests[1].headers,
319
vec![("x-ms-favorite-mode".to_owned(), "manual".to_owned())]
320
);
321
}
322
323
#[test]
324
fn hiding_sets_a_two_week_expiration_and_unfollows() {
325
let transport = canned(Vec::new());
326
let client = ChannelVisibility::with_transport(&transport, "emea");
327
let requests = client.channel_requests(
328
&standard(),
329
ChannelMembership::default(),
330
"8:orgid:user-1",
331
false,
332
NOW_MS,
333
);
334
let summaries: Vec<_> = requests.iter().map(summary).collect();
335
assert_eq!(
336
summaries,
337
vec![
338
(
339
"PUT".to_owned(),
340
format!("{BASE}/threads/{ENCODED}/members/8:orgid:user-1"),
341
Some(json!({"expiration": 1_791_368_001 + 1_209_600})),
342
),
343
(
344
"PUT".to_owned(),
345
format!("{BASE}/users/ME/conversations/{ENCODED}/properties?name=favorite"),
346
Some(json!({"favorite": "false"})),
347
),
348
(
349
"PUT".to_owned(),
350
format!("{BASE}/users/ME/conversations/{ENCODED}/properties?name=isfollowed"),
351
Some(json!({"isfollowed": false})),
352
),
353
]
354
);
355
assert!(requests[1].headers.is_empty());
356
}
357
358
#[test]
359
fn moderators_and_private_members_skip_the_join_step() {
360
let transport = canned(Vec::new());
361
let client = ChannelVisibility::with_transport(&transport, "emea");
362
let moderator = ChannelMembership {
363
moderator: true,
364
..ChannelMembership::default()
365
};
366
let requests = client.channel_requests(&standard(), moderator, "user-1", true, NOW_MS);
367
assert_eq!(requests.len(), 1);
368
assert!(requests[0].url.contains("name=favorite"));
369
let private = ChannelTarget {
370
kind: ChannelKind::Private,
371
..standard()
372
};
373
assert!(!joins_thread(private.kind, ChannelMembership::default()));
374
let shared = ChannelMembership {
375
explicitly_added: true,
376
..ChannelMembership::default()
377
};
378
assert!(!joins_thread(ChannelKind::Shared, shared));
379
assert!(joins_thread(
380
ChannelKind::Shared,
381
ChannelMembership::default()
382
));
383
}
384
385
#[test]
386
fn showing_a_followed_channel_also_clears_the_follow() {
387
let transport = canned(Vec::new());
388
let client = ChannelVisibility::with_transport(&transport, "emea");
389
let followed = ChannelMembership {
390
moderator: true,
391
followed: true,
392
..ChannelMembership::default()
393
};
394
let requests = client.channel_requests(&standard(), followed, "user-1", true, NOW_MS);
395
assert_eq!(requests.len(), 2);
396
assert!(requests[1].url.ends_with("name=isfollowed"));
397
}
398
399
#[test]
400
fn general_and_team_visibility_write_one_property() {
401
let transport = canned(Vec::new());
402
let client = ChannelVisibility::with_transport(&transport, "emea");
403
let general = ChannelTarget {
404
general: true,
405
..standard()
406
};
407
let requests =
408
client.channel_requests(&general, ChannelMembership::default(), "u", false, NOW_MS);
409
assert_eq!(
410
requests.iter().map(summary).collect::<Vec<_>>(),
411
vec![(
412
"PUT".to_owned(),
413
format!(
414
"{BASE}/users/ME/conversations/{ENCODED}/properties?name=isGeneralChannelFavorite"
415
),
416
Some(json!({"isGeneralChannelFavorite": "false"})),
417
)]
418
);
419
let team = client.team_favorite_request(CHANNEL, true);
420
assert_eq!(
421
summary(&team),
422
(
423
"PUT".to_owned(),
424
format!("{BASE}/users/ME/conversations/{ENCODED}/properties?name=favorite"),
425
Some(json!({"favorite": "true"})),
426
)
427
);
428
assert!(team.headers.is_empty());
429
}
430
431
#[test]
432
fn membership_follows_javascript_truthiness() {
433
let membership = parse_channel_membership(&json!({
434
"memberProperties": {"isModerator": true, "explicitlyAdded": "true"},
435
"properties": {"isfollowed": "false"},
436
}));
437
assert_eq!(
438
membership,
439
ChannelMembership {
440
moderator: true,
441
explicitly_added: true,
442
followed: true,
443
}
444
);
445
assert_eq!(
446
parse_channel_membership(&json!({"properties": {"isfollowed": ""}})),
447
ChannelMembership::default()
448
);
449
assert_eq!(
450
ChannelKind::from_membership_type(Some("private")),
451
ChannelKind::Private
452
);
453
assert_eq!(
454
ChannelKind::from_membership_type(None),
455
ChannelKind::Standard
456
);
457
}
458
459
#[tokio::test]
460
async fn set_channel_shown_reads_the_conversation_first() {
461
let transport = canned(vec![(
462
200,
463
json!({"memberProperties": {"isModerator": true}}),
464
)]);
465
let client = ChannelVisibility::with_transport(&transport, "emea");
466
client
467
.set_channel_shown(&standard(), "user-1", false, NOW_MS)
468
.await
469
.unwrap();
470
let urls: Vec<String> = transport
471
.requests
472
.lock()
473
.unwrap()
474
.iter()
475
.map(|request| request.url.clone())
476
.collect();
477
assert_eq!(
478
urls,
479
vec![
480
format!("{BASE}/users/ME/conversations/{ENCODED}?view=msnp24Equivalent"),
481
format!("{BASE}/users/ME/conversations/{ENCODED}/properties?name=favorite"),
482
format!("{BASE}/users/ME/conversations/{ENCODED}/properties?name=isfollowed"),
483
]
484
);
485
}
486
487
#[tokio::test]
488
async fn a_failed_step_stops_the_chain() {
489
let transport = canned(vec![(200, json!({})), (403, json!({}))]);
490
let client = ChannelVisibility::with_transport(&transport, "emea");
491
let outcome = client
492
.set_channel_shown(&standard(), "user-1", true, NOW_MS)
493
.await;
494
assert!(outcome.is_err());
495
assert_eq!(transport.requests.lock().unwrap().len(), 2);
496
}
497
}
@@ -0,0 +1,497 @@1
use serde_json::{Value, json};2
use session::{Method, Request, Session};3
4
use crate::error::Result;5
use crate::members::{threads_url, user_mri};6
use crate::messages::{MessageTransport, SessionMessageTransport, encode, ensure_success};7
use crate::pins::DEFAULT_REGION;8
9
const FAVORITE_PROPERTY: &str = "favorite";10
const GENERAL_FAVORITE_PROPERTY: &str = "isGeneralChannelFavorite";11
const FOLLOWED_PROPERTY: &str = "isfollowed";12
const PERMANENT_JOIN_QUERY: &str = "requirePermanentJoinedState=true";13
const FAVORITE_MODE_HEADER: &str = "x-ms-favorite-mode";14
const FAVORITE_MODE_MANUAL: &str = "manual";15
const HIDDEN_MEMBERSHIP_SECONDS: i64 = 1_209_600;16
17
#[derive(Debug, Clone, Copy, PartialEq, Eq)]18
pub enum ChannelKind {19
Standard,20
Private,21
Shared,22
}23
24
impl ChannelKind {25
pub fn from_membership_type(membership_type: Option<&str>) -> Self {26
match membership_type.map(str::to_ascii_lowercase).as_deref() {27
Some("private") => ChannelKind::Private,28
Some("shared") => ChannelKind::Shared,29
_ => ChannelKind::Standard,30
}31
}32
}33
34
#[derive(Debug, Clone, Copy, PartialEq, Eq)]35
pub struct ChannelTarget<'a> {36
pub channel_id: &'a str,37
pub general: bool,38
pub kind: ChannelKind,39
}40
41
/// The own member state of a channel conversation that decides Teams' show and hide steps.42
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]43
pub struct ChannelMembership {44
pub moderator: bool,45
pub explicitly_added: bool,46
pub followed: bool,47
}48
49
fn truthy(value: Option<&Value>) -> bool {50
match value {51
Some(Value::Bool(flag)) => *flag,52
Some(Value::String(text)) => !text.is_empty(),53
Some(Value::Number(number)) => number.as_f64().is_some_and(|number| number != 0.),54
Some(Value::Array(_) | Value::Object(_)) => true,55
_ => false,56
}57
}58
59
pub fn parse_channel_membership(conversation: &Value) -> ChannelMembership {60
let member = conversation.get("memberProperties");61
ChannelMembership {62
moderator: truthy(member.and_then(|member| member.get("isModerator"))),63
explicitly_added: truthy(member.and_then(|member| member.get("explicitlyAdded"))),64
followed: truthy(conversation.pointer(&format!("/properties/{FOLLOWED_PROPERTY}"))),65
}66
}67
68
/// Teams joins the user to a standard channel thread before it changes the channel's visibility.69
pub fn joins_thread(kind: ChannelKind, membership: ChannelMembership) -> bool {70
let permanently_joined = kind == ChannelKind::Private71
|| (kind == ChannelKind::Shared && membership.explicitly_added)72
|| membership.moderator;73
!permanently_joined74
}75
76
pub fn membership_expiration(shown: bool, now_ms: i64) -> i64 {77
if shown {78
079
} else {80
(now_ms + 999).div_euclid(1000) + HIDDEN_MEMBERSHIP_SECONDS81
}82
}83
84
pub struct ChannelVisibility<T: MessageTransport = SessionMessageTransport> {85
transport: T,86
conversations_url: String,87
threads_url: String,88
}89
90
impl ChannelVisibility<SessionMessageTransport> {91
pub fn new(session: &Session) -> Self {92
ChannelVisibility::with_transport(SessionMessageTransport::new(session), DEFAULT_REGION)93
}94
}95
96
impl<T: MessageTransport> ChannelVisibility<T> {97
pub fn with_transport(transport: T, region: &str) -> Self {98
ChannelVisibility {99
transport,100
conversations_url: format!(101
"https://teams.cloud.microsoft/api/chatsvc/{region}/v1/users/ME/conversations"102
),103
threads_url: threads_url(region),104
}105
}106
107
pub fn conversation_request(&self, conversation_id: &str) -> Request {108
Request::get(format!(109
"{}/{}?view=msnp24Equivalent",110
self.conversations_url,111
encode(conversation_id)112
))113
}114
115
fn property_request(&self, conversation_id: &str, name: &str, value: Value) -> Request {116
Request::with_body(117
Method::Put,118
format!(119
"{}/{}/properties?name={name}",120
self.conversations_url,121
encode(conversation_id)122
),123
json!({ name: value }),124
)125
}126
127
pub fn favorite_request(&self, channel_id: &str, shown: bool) -> Request {128
let mut request =129
self.property_request(channel_id, FAVORITE_PROPERTY, json!(shown.to_string()));130
if shown {131
request.url = format!("{}&{PERMANENT_JOIN_QUERY}", request.url);132
request133
.headers134
.push((FAVORITE_MODE_HEADER.into(), FAVORITE_MODE_MANUAL.into()));135
}136
request137
}138
139
pub fn general_favorite_request(&self, team_thread_id: &str, shown: bool) -> Request {140
self.property_request(141
team_thread_id,142
GENERAL_FAVORITE_PROPERTY,143
json!(shown.to_string()),144
)145
}146
147
pub fn team_favorite_request(&self, team_thread_id: &str, shown: bool) -> Request {148
self.property_request(team_thread_id, FAVORITE_PROPERTY, json!(shown.to_string()))149
}150
151
pub fn unfollow_request(&self, channel_id: &str) -> Request {152
self.property_request(channel_id, FOLLOWED_PROPERTY, json!(false))153
}154
155
pub fn membership_request(156
&self,157
channel_id: &str,158
own_user_id: &str,159
shown: bool,160
now_ms: i64,161
) -> Request {162
Request::with_body(163
Method::Put,164
format!(165
"{}/{}/members/{}",166
self.threads_url,167
encode(channel_id),168
user_mri(own_user_id)169
),170
json!({ "expiration": membership_expiration(shown, now_ms) }),171
)172
}173
174
/// Teams' order for a channel other than General: join step, `favorite`, then `isfollowed`.175
pub fn channel_requests(176
&self,177
target: &ChannelTarget<'_>,178
membership: ChannelMembership,179
own_user_id: &str,180
shown: bool,181
now_ms: i64,182
) -> Vec<Request> {183
if target.general {184
return vec![self.general_favorite_request(target.channel_id, shown)];185
}186
let mut requests = Vec::new();187
if joins_thread(target.kind, membership) {188
requests.push(self.membership_request(target.channel_id, own_user_id, shown, now_ms));189
}190
requests.push(self.favorite_request(target.channel_id, shown));191
if !shown || membership.followed {192
requests.push(self.unfollow_request(target.channel_id));193
}194
requests195
}196
197
pub async fn set_channel_shown(198
&self,199
target: &ChannelTarget<'_>,200
own_user_id: &str,201
shown: bool,202
now_ms: i64,203
) -> Result<()> {204
let membership = if target.general {205
ChannelMembership::default()206
} else {207
let answer = self208
.transport209
.send(self.conversation_request(target.channel_id))210
.await?;211
ensure_success(&answer)?;212
parse_channel_membership(&answer.body)213
};214
for request in self.channel_requests(target, membership, own_user_id, shown, now_ms) {215
ensure_success(&self.transport.send(request).await?)?;216
}217
Ok(())218
}219
220
pub async fn set_team_shown(&self, team_thread_id: &str, shown: bool) -> Result<()> {221
let answer = self222
.transport223
.send(self.team_favorite_request(team_thread_id, shown))224
.await?;225
ensure_success(&answer)226
}227
}228
229
#[cfg(test)]230
mod tests {231
use std::collections::VecDeque;232
use std::sync::Mutex;233
234
use session::ApiResponse;235
236
use super::*;237
238
const BASE: &str = "https://teams.cloud.microsoft/api/chatsvc/emea/v1";239
const CHANNEL: &str = "19:abc@thread.tacv2";240
const ENCODED: &str = "19%3Aabc%40thread.tacv2";241
const NOW_MS: i64 = 1_791_368_000_500;242
243
struct Canned {244
requests: Mutex<Vec<Request>>,245
answers: Mutex<VecDeque<(u16, Value)>>,246
}247
248
impl MessageTransport for &Canned {249
async fn send(&self, request: Request) -> Result<ApiResponse> {250
self.requests.lock().unwrap().push(request);251
let (status, body) = self252
.answers253
.lock()254
.unwrap()255
.pop_front()256
.unwrap_or((200, Value::Null));257
Ok(ApiResponse {258
status,259
body,260
retry_after: None,261
})262
}263
}264
265
fn canned(answers: Vec<(u16, Value)>) -> Canned {266
Canned {267
requests: Mutex::new(Vec::new()),268
answers: Mutex::new(answers.into()),269
}270
}271
272
fn standard() -> ChannelTarget<'static> {273
ChannelTarget {274
channel_id: CHANNEL,275
general: false,276
kind: ChannelKind::Standard,277
}278
}279
280
fn summary(request: &Request) -> (String, String, Option<Value>) {281
(282
request.method.as_str().to_owned(),283
request.url.clone(),284
request.body.clone(),285
)286
}287
288
#[test]289
fn showing_a_standard_channel_joins_then_favorites_with_the_manual_mode() {290
let transport = canned(Vec::new());291
let client = ChannelVisibility::with_transport(&transport, "emea");292
let requests = client.channel_requests(293
&standard(),294
ChannelMembership::default(),295
"user-1",296
true,297
NOW_MS,298
);299
let summaries: Vec<_> = requests.iter().map(summary).collect();300
assert_eq!(301
summaries,302
vec![303
(304
"PUT".to_owned(),305
format!("{BASE}/threads/{ENCODED}/members/8:orgid:user-1"),306
Some(json!({"expiration": 0})),307
),308
(309
"PUT".to_owned(),310
format!(311
"{BASE}/users/ME/conversations/{ENCODED}/properties?name=favorite&requirePermanentJoinedState=true"312
),313
Some(json!({"favorite": "true"})),314
),315
]316
);317
assert_eq!(318
requests[1].headers,319
vec![("x-ms-favorite-mode".to_owned(), "manual".to_owned())]320
);321
}322
323
#[test]324
fn hiding_sets_a_two_week_expiration_and_unfollows() {325
let transport = canned(Vec::new());326
let client = ChannelVisibility::with_transport(&transport, "emea");327
let requests = client.channel_requests(328
&standard(),329
ChannelMembership::default(),330
"8:orgid:user-1",331
false,332
NOW_MS,333
);334
let summaries: Vec<_> = requests.iter().map(summary).collect();335
assert_eq!(336
summaries,337
vec![338
(339
"PUT".to_owned(),340
format!("{BASE}/threads/{ENCODED}/members/8:orgid:user-1"),341
Some(json!({"expiration": 1_791_368_001 + 1_209_600})),342
),343
(344
"PUT".to_owned(),345
format!("{BASE}/users/ME/conversations/{ENCODED}/properties?name=favorite"),346
Some(json!({"favorite": "false"})),347
),348
(349
"PUT".to_owned(),350
format!("{BASE}/users/ME/conversations/{ENCODED}/properties?name=isfollowed"),351
Some(json!({"isfollowed": false})),352
),353
]354
);355
assert!(requests[1].headers.is_empty());356
}357
358
#[test]359
fn moderators_and_private_members_skip_the_join_step() {360
let transport = canned(Vec::new());361
let client = ChannelVisibility::with_transport(&transport, "emea");362
let moderator = ChannelMembership {363
moderator: true,364
..ChannelMembership::default()365
};366
let requests = client.channel_requests(&standard(), moderator, "user-1", true, NOW_MS);367
assert_eq!(requests.len(), 1);368
assert!(requests[0].url.contains("name=favorite"));369
let private = ChannelTarget {370
kind: ChannelKind::Private,371
..standard()372
};373
assert!(!joins_thread(private.kind, ChannelMembership::default()));374
let shared = ChannelMembership {375
explicitly_added: true,376
..ChannelMembership::default()377
};378
assert!(!joins_thread(ChannelKind::Shared, shared));379
assert!(joins_thread(380
ChannelKind::Shared,381
ChannelMembership::default()382
));383
}384
385
#[test]386
fn showing_a_followed_channel_also_clears_the_follow() {387
let transport = canned(Vec::new());388
let client = ChannelVisibility::with_transport(&transport, "emea");389
let followed = ChannelMembership {390
moderator: true,391
followed: true,392
..ChannelMembership::default()393
};394
let requests = client.channel_requests(&standard(), followed, "user-1", true, NOW_MS);395
assert_eq!(requests.len(), 2);396
assert!(requests[1].url.ends_with("name=isfollowed"));397
}398
399
#[test]400
fn general_and_team_visibility_write_one_property() {401
let transport = canned(Vec::new());402
let client = ChannelVisibility::with_transport(&transport, "emea");403
let general = ChannelTarget {404
general: true,405
..standard()406
};407
let requests =408
client.channel_requests(&general, ChannelMembership::default(), "u", false, NOW_MS);409
assert_eq!(410
requests.iter().map(summary).collect::<Vec<_>>(),411
vec![(412
"PUT".to_owned(),413
format!(414
"{BASE}/users/ME/conversations/{ENCODED}/properties?name=isGeneralChannelFavorite"415
),416
Some(json!({"isGeneralChannelFavorite": "false"})),417
)]418
);419
let team = client.team_favorite_request(CHANNEL, true);420
assert_eq!(421
summary(&team),422
(423
"PUT".to_owned(),424
format!("{BASE}/users/ME/conversations/{ENCODED}/properties?name=favorite"),425
Some(json!({"favorite": "true"})),426
)427
);428
assert!(team.headers.is_empty());429
}430
431
#[test]432
fn membership_follows_javascript_truthiness() {433
let membership = parse_channel_membership(&json!({434
"memberProperties": {"isModerator": true, "explicitlyAdded": "true"},435
"properties": {"isfollowed": "false"},436
}));437
assert_eq!(438
membership,439
ChannelMembership {440
moderator: true,441
explicitly_added: true,442
followed: true,443
}444
);445
assert_eq!(446
parse_channel_membership(&json!({"properties": {"isfollowed": ""}})),447
ChannelMembership::default()448
);449
assert_eq!(450
ChannelKind::from_membership_type(Some("private")),451
ChannelKind::Private452
);453
assert_eq!(454
ChannelKind::from_membership_type(None),455
ChannelKind::Standard456
);457
}458
459
#[tokio::test]460
async fn set_channel_shown_reads_the_conversation_first() {461
let transport = canned(vec![(462
200,463
json!({"memberProperties": {"isModerator": true}}),464
)]);465
let client = ChannelVisibility::with_transport(&transport, "emea");466
client467
.set_channel_shown(&standard(), "user-1", false, NOW_MS)468
.await469
.unwrap();470
let urls: Vec<String> = transport471
.requests472
.lock()473
.unwrap()474
.iter()475
.map(|request| request.url.clone())476
.collect();477
assert_eq!(478
urls,479
vec![480
format!("{BASE}/users/ME/conversations/{ENCODED}?view=msnp24Equivalent"),481
format!("{BASE}/users/ME/conversations/{ENCODED}/properties?name=favorite"),482
format!("{BASE}/users/ME/conversations/{ENCODED}/properties?name=isfollowed"),483
]484
);485
}486
487
#[tokio::test]488
async fn a_failed_step_stops_the_chain() {489
let transport = canned(vec![(200, json!({})), (403, json!({}))]);490
let client = ChannelVisibility::with_transport(&transport, "emea");491
let outcome = client492
.set_channel_shown(&standard(), "user-1", true, NOW_MS)493
.await;494
assert!(outcome.is_err());495
assert_eq!(transport.requests.lock().unwrap().len(), 2);496
}497
}@@ -10,6 +10,7 @@ use crate::read_horizon::{self, ReadHorizon};
10
10
const PAGE_SIZE: usize = 200;
11
11
const MAX_PAGES: usize = 100;
12
12
const ALERTS_OFF: &str = "false";
13
const CLEAR_HISTORY_PROPERTY: &str = "clearHistoryTime";
13
14
14
15
#[derive(Debug, Clone, PartialEq, Eq)]
15
16
pub struct ConversationState {
@@ -17,6 +18,7 @@ pub struct ConversationState {
17
18
pub muted: bool,
18
19
pub hidden: Option<bool>,
19
20
pub read: ReadHorizon,
21
pub history_cleared_ms: Option<i64>,
20
22
}
21
23
22
24
pub struct Conversations<T: MessageTransport = SessionMessageTransport> {
@@ -84,6 +86,19 @@ impl<T: MessageTransport> Conversations<T> {
84
86
ensure_success(&answer)
85
87
}
86
88
89
/// Teams' "Remove chat history": everything up to this time disappears for the current user only.
90
pub async fn clear_history(&self, conversation_id: &str, cleared_until_ms: i64) -> Result<()> {
91
let answer = self
92
.transport
93
.send(clear_history_request(
94
&self.base_url,
95
conversation_id,
96
cleared_until_ms,
97
))
98
.await?;
99
ensure_success(&answer)
100
}
101
87
102
pub async fn set_read_horizon(&self, conversation_id: &str, horizon: &str) -> Result<()> {
88
103
let url = format!(
89
104
"{}/{}/properties?name={}",
@@ -118,6 +133,29 @@ impl<T: MessageTransport> Conversations<T> {
118
133
}
119
134
}
120
135
136
pub fn clear_history_request(
137
base_url: &str,
138
conversation_id: &str,
139
cleared_until_ms: i64,
140
) -> Request {
141
Request::with_body(
142
Method::Put,
143
format!(
144
"{base_url}/{}/properties?name={CLEAR_HISTORY_PROPERTY}",
145
encode(conversation_id)
146
),
147
json!({ CLEAR_HISTORY_PROPERTY: cleared_until_ms }),
148
)
149
}
150
151
fn history_cleared_ms(conversation: &Value) -> Option<i64> {
152
let value = &conversation["properties"][CLEAR_HISTORY_PROPERTY];
153
value
154
.as_i64()
155
.or_else(|| value.as_str()?.parse().ok())
156
.filter(|millis| *millis > 0)
157
}
158
121
159
/// One conversation with its thread properties, as Teams reads a meeting or 1:1 thread.
122
160
pub fn thread_url(region: &str, thread_id: &str) -> String {
123
161
format!(
@@ -167,6 +205,7 @@ fn states_in_page(body: &Value) -> Result<Vec<ConversationState>> {
167
205
muted,
168
206
hidden: hidden_flag(conversation),
169
207
read: ReadHorizon::from_conversation(conversation),
208
history_cleared_ms: history_cleared_ms(conversation),
170
209
})
171
210
})
172
211
.collect())
@@ -211,6 +250,7 @@ mod tests {
211
250
muted,
212
251
hidden: None,
213
252
read: ReadHorizon::default(),
253
history_cleared_ms: None,
214
254
}
215
255
}
216
256
@@ -383,6 +423,52 @@ mod tests {
383
423
assert!(states[0].read.is_unread("8:orgid:me"));
384
424
}
385
425
426
#[tokio::test]
427
async fn clear_history_puts_the_time_as_a_number() {
428
let transport = canned(vec![(200, Value::Null)]);
429
Conversations::with_transport(&transport, "emea")
430
.clear_history("19:a_b@unq.gbl.spaces", 1_792_200_000_001)
431
.await
432
.unwrap();
433
let requests = transport.requests.lock().unwrap();
434
assert_eq!(requests[0].method, Method::Put);
435
assert_eq!(
436
requests[0].url,
437
format!("{BASE}/19%3Aa_b%40unq.gbl.spaces/properties?name=clearHistoryTime")
438
);
439
assert_eq!(
440
requests[0].body,
441
Some(json!({"clearHistoryTime": 1_792_200_000_001_i64}))
442
);
443
}
444
445
#[tokio::test]
446
async fn states_carry_the_clear_history_time_as_text_or_number() {
447
let transport = canned(vec![(
448
200,
449
json!({
450
"conversations": [
451
{"id": "19:a", "properties": {"clearHistoryTime": "1792200000001"}},
452
{"id": "19:b", "properties": {"clearHistoryTime": 1_792_200_000_002_i64}},
453
{"id": "19:c", "properties": {"clearHistoryTime": "0"}},
454
{"id": "19:d"},
455
],
456
}),
457
)]);
458
let states = Conversations::with_transport(&transport, "emea")
459
.conversation_states()
460
.await
461
.unwrap();
462
let cleared: Vec<Option<i64>> = states
463
.iter()
464
.map(|state| state.history_cleared_ms)
465
.collect();
466
assert_eq!(
467
cleared,
468
[Some(1_792_200_000_001), Some(1_792_200_000_002), None, None]
469
);
470
}
471
386
472
#[tokio::test]
387
473
async fn set_read_horizon_puts_the_consumption_horizon_property() {
388
474
let transport = canned(vec![(200, Value::Null)]);
@@ -10,6 +10,7 @@ use crate::read_horizon::{self, ReadHorizon};10
const PAGE_SIZE: usize = 200;10
const PAGE_SIZE: usize = 200;11
const MAX_PAGES: usize = 100;11
const MAX_PAGES: usize = 100;12
const ALERTS_OFF: &str = "false";12
const ALERTS_OFF: &str = "false";13
const CLEAR_HISTORY_PROPERTY: &str = "clearHistoryTime";13
14
14
#[derive(Debug, Clone, PartialEq, Eq)]15
#[derive(Debug, Clone, PartialEq, Eq)]15
pub struct ConversationState {16
pub struct ConversationState {@@ -17,6 +18,7 @@ pub struct ConversationState {17
pub muted: bool,18
pub muted: bool,18
pub hidden: Option<bool>,19
pub hidden: Option<bool>,19
pub read: ReadHorizon,20
pub read: ReadHorizon,21
pub history_cleared_ms: Option<i64>,20
}22
}21
23
22
pub struct Conversations<T: MessageTransport = SessionMessageTransport> {24
pub struct Conversations<T: MessageTransport = SessionMessageTransport> {@@ -84,6 +86,19 @@ impl<T: MessageTransport> Conversations<T> {84
ensure_success(&answer)86
ensure_success(&answer)85
}87
}86
88
89
/// Teams' "Remove chat history": everything up to this time disappears for the current user only.90
pub async fn clear_history(&self, conversation_id: &str, cleared_until_ms: i64) -> Result<()> {91
let answer = self92
.transport93
.send(clear_history_request(94
&self.base_url,95
conversation_id,96
cleared_until_ms,97
))98
.await?;99
ensure_success(&answer)100
}101
87
pub async fn set_read_horizon(&self, conversation_id: &str, horizon: &str) -> Result<()> {102
pub async fn set_read_horizon(&self, conversation_id: &str, horizon: &str) -> Result<()> {88
let url = format!(103
let url = format!(89
"{}/{}/properties?name={}",104
"{}/{}/properties?name={}",@@ -118,6 +133,29 @@ impl<T: MessageTransport> Conversations<T> {118
}133
}119
}134
}120
135
136
pub fn clear_history_request(137
base_url: &str,138
conversation_id: &str,139
cleared_until_ms: i64,140
) -> Request {141
Request::with_body(142
Method::Put,143
format!(144
"{base_url}/{}/properties?name={CLEAR_HISTORY_PROPERTY}",145
encode(conversation_id)146
),147
json!({ CLEAR_HISTORY_PROPERTY: cleared_until_ms }),148
)149
}150
151
fn history_cleared_ms(conversation: &Value) -> Option<i64> {152
let value = &conversation["properties"][CLEAR_HISTORY_PROPERTY];153
value154
.as_i64()155
.or_else(|| value.as_str()?.parse().ok())156
.filter(|millis| *millis > 0)157
}158
121
/// One conversation with its thread properties, as Teams reads a meeting or 1:1 thread.159
/// One conversation with its thread properties, as Teams reads a meeting or 1:1 thread.122
pub fn thread_url(region: &str, thread_id: &str) -> String {160
pub fn thread_url(region: &str, thread_id: &str) -> String {123
format!(161
format!(@@ -167,6 +205,7 @@ fn states_in_page(body: &Value) -> Result<Vec<ConversationState>> {167
muted,205
muted,168
hidden: hidden_flag(conversation),206
hidden: hidden_flag(conversation),169
read: ReadHorizon::from_conversation(conversation),207
read: ReadHorizon::from_conversation(conversation),208
history_cleared_ms: history_cleared_ms(conversation),170
})209
})171
})210
})172
.collect())211
.collect())@@ -211,6 +250,7 @@ mod tests {211
muted,250
muted,212
hidden: None,251
hidden: None,213
read: ReadHorizon::default(),252
read: ReadHorizon::default(),253
history_cleared_ms: None,214
}254
}215
}255
}216
256
@@ -383,6 +423,52 @@ mod tests {383
assert!(states[0].read.is_unread("8:orgid:me"));423
assert!(states[0].read.is_unread("8:orgid:me"));384
}424
}385
425
426
#[tokio::test]427
async fn clear_history_puts_the_time_as_a_number() {428
let transport = canned(vec![(200, Value::Null)]);429
Conversations::with_transport(&transport, "emea")430
.clear_history("19:a_b@unq.gbl.spaces", 1_792_200_000_001)431
.await432
.unwrap();433
let requests = transport.requests.lock().unwrap();434
assert_eq!(requests[0].method, Method::Put);435
assert_eq!(436
requests[0].url,437
format!("{BASE}/19%3Aa_b%40unq.gbl.spaces/properties?name=clearHistoryTime")438
);439
assert_eq!(440
requests[0].body,441
Some(json!({"clearHistoryTime": 1_792_200_000_001_i64}))442
);443
}444
445
#[tokio::test]446
async fn states_carry_the_clear_history_time_as_text_or_number() {447
let transport = canned(vec![(448
200,449
json!({450
"conversations": [451
{"id": "19:a", "properties": {"clearHistoryTime": "1792200000001"}},452
{"id": "19:b", "properties": {"clearHistoryTime": 1_792_200_000_002_i64}},453
{"id": "19:c", "properties": {"clearHistoryTime": "0"}},454
{"id": "19:d"},455
],456
}),457
)]);458
let states = Conversations::with_transport(&transport, "emea")459
.conversation_states()460
.await461
.unwrap();462
let cleared: Vec<Option<i64>> = states463
.iter()464
.map(|state| state.history_cleared_ms)465
.collect();466
assert_eq!(467
cleared,468
[Some(1_792_200_000_001), Some(1_792_200_000_002), None, None]469
);470
}471
386
#[tokio::test]472
#[tokio::test]387
async fn set_read_horizon_puts_the_consumption_horizon_property() {473
async fn set_read_horizon_puts_the_consumption_horizon_property() {388
let transport = canned(vec![(200, Value::Null)]);474
let transport = canned(vec![(200, Value::Null)]);@@ -1,8 +1,10 @@
1
pub mod activity_mentions;
1
2
pub mod bot_profiles;
2
3
pub mod calendar;
3
4
pub mod calllog;
4
5
pub mod cards;
5
6
pub mod channel_notifications;
7
pub mod channel_visibility;
6
8
pub mod conversations;
7
9
pub mod drafts;
8
10
pub mod emotions;
@@ -33,6 +35,7 @@ pub mod transcripts;
33
35
pub mod translate;
34
36
pub mod window;
35
37
38
pub use activity_mentions::{ActivityFeed, MentionActivity, MentionKind};
36
39
pub use bot_profiles::{BotProfile, BotProfiles, parse_bot_profiles};
37
40
pub use calendar::{
38
41
Attendee, Calendar, CalendarEvent, CreatedEvent, NewEvent, Reminder, Repeat, Reply,
@@ -43,6 +46,7 @@ pub use cards::{
43
46
CardActions, ChatApp, InvokeRequest, InvokeResponse, TaskContent, TaskContinue, TaskResponse,
44
47
};
45
48
pub use channel_notifications::{ChannelNotificationLevel, ChannelNotifications, ChannelSettings};
49
pub use channel_visibility::{ChannelKind, ChannelMembership, ChannelTarget, ChannelVisibility};
46
50
pub use conversations::{ConversationState, Conversations};
47
51
pub use drafts::{ScheduledDraft, ScheduledDrafts};
48
52
pub use emotions::{EmotionReaction, MessageEmotions, parse_message_emotions, user_id_from_mri};
@@ -55,7 +59,10 @@ pub use language_settings::{
55
59
};
56
60
pub use links::{LinkImage, LinkInfo, MessageLinks, is_link_image_url};
57
61
pub use mask::mask_conversation_id;
58
pub use members::{HistoryShare, MAX_HISTORY_DAYS, ThreadMembers};
62
pub use members::{
63
HistoryShare, INVALID_TOPIC_CHARACTER, MAX_HISTORY_DAYS, MAX_TOPIC_LENGTH, ThreadMembers,
64
TopicProblem, topic_problem,
65
};
59
66
pub use messages::{ConversationRef, Messages};
60
67
pub use pins::{
61
68
ChannelLayout, ChannelTab, Folder, FolderKind, Folders, PinnedChannels, PinnedChats,
@@ -83,7 +90,10 @@ pub use recap::{
83
90
pub use receipts::{MemberHorizon, Receipts};
84
91
pub use recording_policy::{RecordingPolicy, parse_recording_policy};
85
92
pub use saved::SavedMessage;
86
pub use settings::{ChatSection, ChatSectionSettings, UserSettings};
93
pub use settings::{
94
AppConsumptionHorizon, ChatSection, ChatSectionSettings, UserSettings,
95
parse_app_consumption_horizon,
96
};
87
97
pub use substrate_search::{
88
98
QueryRequest, QueryResults, QueryScope, SearchIdentity, SearchSession, SubstrateSearch,
89
99
Suggestions,
@@ -1,8 +1,10 @@1
pub mod activity_mentions;1
pub mod bot_profiles;2
pub mod bot_profiles;2
pub mod calendar;3
pub mod calendar;3
pub mod calllog;4
pub mod calllog;4
pub mod cards;5
pub mod cards;5
pub mod channel_notifications;6
pub mod channel_notifications;7
pub mod channel_visibility;6
pub mod conversations;8
pub mod conversations;7
pub mod drafts;9
pub mod drafts;8
pub mod emotions;10
pub mod emotions;@@ -33,6 +35,7 @@ pub mod transcripts;33
pub mod translate;35
pub mod translate;34
pub mod window;36
pub mod window;35
37
38
pub use activity_mentions::{ActivityFeed, MentionActivity, MentionKind};36
pub use bot_profiles::{BotProfile, BotProfiles, parse_bot_profiles};39
pub use bot_profiles::{BotProfile, BotProfiles, parse_bot_profiles};37
pub use calendar::{40
pub use calendar::{38
Attendee, Calendar, CalendarEvent, CreatedEvent, NewEvent, Reminder, Repeat, Reply,41
Attendee, Calendar, CalendarEvent, CreatedEvent, NewEvent, Reminder, Repeat, Reply,@@ -43,6 +46,7 @@ pub use cards::{43
CardActions, ChatApp, InvokeRequest, InvokeResponse, TaskContent, TaskContinue, TaskResponse,46
CardActions, ChatApp, InvokeRequest, InvokeResponse, TaskContent, TaskContinue, TaskResponse,44
};47
};45
pub use channel_notifications::{ChannelNotificationLevel, ChannelNotifications, ChannelSettings};48
pub use channel_notifications::{ChannelNotificationLevel, ChannelNotifications, ChannelSettings};49
pub use channel_visibility::{ChannelKind, ChannelMembership, ChannelTarget, ChannelVisibility};46
pub use conversations::{ConversationState, Conversations};50
pub use conversations::{ConversationState, Conversations};47
pub use drafts::{ScheduledDraft, ScheduledDrafts};51
pub use drafts::{ScheduledDraft, ScheduledDrafts};48
pub use emotions::{EmotionReaction, MessageEmotions, parse_message_emotions, user_id_from_mri};52
pub use emotions::{EmotionReaction, MessageEmotions, parse_message_emotions, user_id_from_mri};@@ -55,7 +59,10 @@ pub use language_settings::{55
};59
};56
pub use links::{LinkImage, LinkInfo, MessageLinks, is_link_image_url};60
pub use links::{LinkImage, LinkInfo, MessageLinks, is_link_image_url};57
pub use mask::mask_conversation_id;61
pub use mask::mask_conversation_id;58
pub use members::{HistoryShare, MAX_HISTORY_DAYS, ThreadMembers};62
pub use members::{63
HistoryShare, INVALID_TOPIC_CHARACTER, MAX_HISTORY_DAYS, MAX_TOPIC_LENGTH, ThreadMembers,64
TopicProblem, topic_problem,65
};59
pub use messages::{ConversationRef, Messages};66
pub use messages::{ConversationRef, Messages};60
pub use pins::{67
pub use pins::{61
ChannelLayout, ChannelTab, Folder, FolderKind, Folders, PinnedChannels, PinnedChats,68
ChannelLayout, ChannelTab, Folder, FolderKind, Folders, PinnedChannels, PinnedChats,@@ -83,7 +90,10 @@ pub use recap::{83
pub use receipts::{MemberHorizon, Receipts};90
pub use receipts::{MemberHorizon, Receipts};84
pub use recording_policy::{RecordingPolicy, parse_recording_policy};91
pub use recording_policy::{RecordingPolicy, parse_recording_policy};85
pub use saved::SavedMessage;92
pub use saved::SavedMessage;86
pub use settings::{ChatSection, ChatSectionSettings, UserSettings};93
pub use settings::{94
AppConsumptionHorizon, ChatSection, ChatSectionSettings, UserSettings,95
parse_app_consumption_horizon,96
};87
pub use substrate_search::{97
pub use substrate_search::{88
QueryRequest, QueryResults, QueryScope, SearchIdentity, SearchSession, SubstrateSearch,98
QueryRequest, QueryResults, QueryScope, SearchIdentity, SearchSession, SubstrateSearch,89
Suggestions,99
Suggestions,@@ -8,6 +8,9 @@ use crate::pins::DEFAULT_REGION;
8
8
const ORGID_PREFIX: &str = "8:orgid:";
9
9
const MEMBER_ROLE: &str = "Admin";
10
10
const DAY_MS: i64 = 86_400_000;
11
const TOPIC_PROPERTY: &str = "topic";
12
pub const MAX_TOPIC_LENGTH: usize = 250;
13
pub const INVALID_TOPIC_CHARACTER: char = ':';
11
14
pub const MAX_HISTORY_DAYS: u32 = 999;
12
15
13
16
/// How much chat history new members see, as the Teams add-people dialog offers it.
@@ -80,6 +83,35 @@ pub fn remove_member_request(region: &str, thread_id: &str, user_id: &str) -> Re
80
83
))
81
84
}
82
85
86
/// Teams renames a group chat by setting the thread property `topic`; an empty topic removes the name.
87
pub fn topic_request(region: &str, thread_id: &str, topic: &str) -> Request {
88
Request::with_body(
89
Method::Put,
90
format!(
91
"{}/{}/properties?name={TOPIC_PROPERTY}",
92
threads_url(region),
93
encode(thread_id)
94
),
95
json!({ TOPIC_PROPERTY: topic }),
96
)
97
}
98
99
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
100
pub enum TopicProblem {
101
TooLong,
102
InvalidCharacter,
103
}
104
105
pub fn topic_problem(topic: &str) -> Option<TopicProblem> {
106
if topic.chars().count() > MAX_TOPIC_LENGTH {
107
Some(TopicProblem::TooLong)
108
} else if topic.contains(INVALID_TOPIC_CHARACTER) {
109
Some(TopicProblem::InvalidCharacter)
110
} else {
111
None
112
}
113
}
114
83
115
pub struct ThreadMembers<T: MessageTransport = SessionMessageTransport> {
84
116
transport: T,
85
117
region: String,
@@ -114,6 +146,11 @@ impl<T: MessageTransport> ThreadMembers<T> {
114
146
let request = remove_member_request(&self.region, thread_id, user_id);
115
147
ensure_success(&self.transport.send(request).await?)
116
148
}
149
150
pub async fn set_topic(&self, thread_id: &str, topic: &str) -> Result<()> {
151
let request = topic_request(&self.region, thread_id, topic);
152
ensure_success(&self.transport.send(request).await?)
153
}
117
154
}
118
155
119
156
#[cfg(test)]
@@ -124,6 +161,35 @@ mod tests {
124
161
125
162
use super::*;
126
163
164
#[test]
165
fn topic_is_put_as_the_thread_property() {
166
let request = topic_request("emea", THREAD, "Release crew");
167
assert_eq!(request.method, Method::Put);
168
assert_eq!(
169
request.url,
170
"https://teams.cloud.microsoft/api/chatsvc/emea/v1/threads/19%3Aabc%40thread.v2/properties?name=topic"
171
);
172
assert_eq!(request.body, Some(json!({"topic": "Release crew"})));
173
assert_eq!(
174
topic_request("emea", THREAD, "").body,
175
Some(json!({"topic": ""}))
176
);
177
}
178
179
#[test]
180
fn topic_rules_follow_teams() {
181
assert_eq!(topic_problem("Release crew"), None);
182
assert_eq!(topic_problem(&"a".repeat(MAX_TOPIC_LENGTH)), None);
183
assert_eq!(
184
topic_problem(&"a".repeat(MAX_TOPIC_LENGTH + 1)),
185
Some(TopicProblem::TooLong)
186
);
187
assert_eq!(
188
topic_problem("Team: ops"),
189
Some(TopicProblem::InvalidCharacter)
190
);
191
}
192
127
193
const NOW: i64 = 1_792_200_000_000;
128
194
const THREAD: &str = "19:abc@thread.v2";
129
195
@@ -8,6 +8,9 @@ use crate::pins::DEFAULT_REGION;8
const ORGID_PREFIX: &str = "8:orgid:";8
const ORGID_PREFIX: &str = "8:orgid:";9
const MEMBER_ROLE: &str = "Admin";9
const MEMBER_ROLE: &str = "Admin";10
const DAY_MS: i64 = 86_400_000;10
const DAY_MS: i64 = 86_400_000;11
const TOPIC_PROPERTY: &str = "topic";12
pub const MAX_TOPIC_LENGTH: usize = 250;13
pub const INVALID_TOPIC_CHARACTER: char = ':';11
pub const MAX_HISTORY_DAYS: u32 = 999;14
pub const MAX_HISTORY_DAYS: u32 = 999;12
15
13
/// How much chat history new members see, as the Teams add-people dialog offers it.16
/// How much chat history new members see, as the Teams add-people dialog offers it.@@ -80,6 +83,35 @@ pub fn remove_member_request(region: &str, thread_id: &str, user_id: &str) -> Re80
))83
))81
}84
}82
85
86
/// Teams renames a group chat by setting the thread property `topic`; an empty topic removes the name.87
pub fn topic_request(region: &str, thread_id: &str, topic: &str) -> Request {88
Request::with_body(89
Method::Put,90
format!(91
"{}/{}/properties?name={TOPIC_PROPERTY}",92
threads_url(region),93
encode(thread_id)94
),95
json!({ TOPIC_PROPERTY: topic }),96
)97
}98
99
#[derive(Debug, Clone, Copy, PartialEq, Eq)]100
pub enum TopicProblem {101
TooLong,102
InvalidCharacter,103
}104
105
pub fn topic_problem(topic: &str) -> Option<TopicProblem> {106
if topic.chars().count() > MAX_TOPIC_LENGTH {107
Some(TopicProblem::TooLong)108
} else if topic.contains(INVALID_TOPIC_CHARACTER) {109
Some(TopicProblem::InvalidCharacter)110
} else {111
None112
}113
}114
83
pub struct ThreadMembers<T: MessageTransport = SessionMessageTransport> {115
pub struct ThreadMembers<T: MessageTransport = SessionMessageTransport> {84
transport: T,116
transport: T,85
region: String,117
region: String,@@ -114,6 +146,11 @@ impl<T: MessageTransport> ThreadMembers<T> {114
let request = remove_member_request(&self.region, thread_id, user_id);146
let request = remove_member_request(&self.region, thread_id, user_id);115
ensure_success(&self.transport.send(request).await?)147
ensure_success(&self.transport.send(request).await?)116
}148
}149
150
pub async fn set_topic(&self, thread_id: &str, topic: &str) -> Result<()> {151
let request = topic_request(&self.region, thread_id, topic);152
ensure_success(&self.transport.send(request).await?)153
}117
}154
}118
155
119
#[cfg(test)]156
#[cfg(test)]@@ -124,6 +161,35 @@ mod tests {124
161
125
use super::*;162
use super::*;126
163
164
#[test]165
fn topic_is_put_as_the_thread_property() {166
let request = topic_request("emea", THREAD, "Release crew");167
assert_eq!(request.method, Method::Put);168
assert_eq!(169
request.url,170
"https://teams.cloud.microsoft/api/chatsvc/emea/v1/threads/19%3Aabc%40thread.v2/properties?name=topic"171
);172
assert_eq!(request.body, Some(json!({"topic": "Release crew"})));173
assert_eq!(174
topic_request("emea", THREAD, "").body,175
Some(json!({"topic": ""}))176
);177
}178
179
#[test]180
fn topic_rules_follow_teams() {181
assert_eq!(topic_problem("Release crew"), None);182
assert_eq!(topic_problem(&"a".repeat(MAX_TOPIC_LENGTH)), None);183
assert_eq!(184
topic_problem(&"a".repeat(MAX_TOPIC_LENGTH + 1)),185
Some(TopicProblem::TooLong)186
);187
assert_eq!(188
topic_problem("Team: ops"),189
Some(TopicProblem::InvalidCharacter)190
);191
}192
127
const NOW: i64 = 1_792_200_000_000;193
const NOW: i64 = 1_792_200_000_000;128
const THREAD: &str = "19:abc@thread.v2";194
const THREAD: &str = "19:abc@thread.v2";129
195
@@ -2,6 +2,7 @@ mod channels;
2
2
mod chats;
3
3
mod folders;
4
4
mod pinbar;
5
mod posts;
5
6
mod state;
6
7
mod teams;
7
8
mod transport;
@@ -10,9 +11,10 @@ use session::Session;
10
11
11
12
pub use folders::{Folder, FolderKind, Folders};
12
13
pub use pinbar::PinnedMessage;
14
pub use posts::{PINNED_POSTS_PAGE_SIZE, PinnedPostsPage, parse_pinned_posts};
13
15
pub use state::{PinnedChannels, PinnedChats};
14
16
pub use teams::{ChannelLayout, ChannelTab, TeamLayout, parse_team_layout};
15
pub use transport::{CSA_RESOURCE, CSA_SCOPE, CsaTransport, SessionTransport};
17
pub use transport::{CSA_RESOURCE, CSA_SCOPE, CsaTransport, SessionTransport, SkypeTokenTransport};
16
18
17
19
pub const DEFAULT_REGION: &str = "emea";
18
20
@@ -32,6 +34,12 @@ impl Pins<SessionTransport> {
32
34
}
33
35
}
34
36
37
impl Pins<SkypeTokenTransport> {
38
pub fn with_skype_token(session: &Session) -> Self {
39
Pins::with_transport(SkypeTokenTransport::new(session), DEFAULT_REGION)
40
}
41
}
42
35
43
impl<T: CsaTransport> Pins<T> {
36
44
pub fn with_transport(transport: T, region: &str) -> Self {
37
45
Pins {
@@ -2,6 +2,7 @@ mod channels;2
mod chats;2
mod chats;3
mod folders;3
mod folders;4
mod pinbar;4
mod pinbar;5
mod posts;5
mod state;6
mod state;6
mod teams;7
mod teams;7
mod transport;8
mod transport;@@ -10,9 +11,10 @@ use session::Session;10
11
11
pub use folders::{Folder, FolderKind, Folders};12
pub use folders::{Folder, FolderKind, Folders};12
pub use pinbar::PinnedMessage;13
pub use pinbar::PinnedMessage;14
pub use posts::{PINNED_POSTS_PAGE_SIZE, PinnedPostsPage, parse_pinned_posts};13
pub use state::{PinnedChannels, PinnedChats};15
pub use state::{PinnedChannels, PinnedChats};14
pub use teams::{ChannelLayout, ChannelTab, TeamLayout, parse_team_layout};16
pub use teams::{ChannelLayout, ChannelTab, TeamLayout, parse_team_layout};15
pub use transport::{CSA_RESOURCE, CSA_SCOPE, CsaTransport, SessionTransport};17
pub use transport::{CSA_RESOURCE, CSA_SCOPE, CsaTransport, SessionTransport, SkypeTokenTransport};16
18
17
pub const DEFAULT_REGION: &str = "emea";19
pub const DEFAULT_REGION: &str = "emea";18
20
@@ -32,6 +34,12 @@ impl Pins<SessionTransport> {32
}34
}33
}35
}34
36
37
impl Pins<SkypeTokenTransport> {38
pub fn with_skype_token(session: &Session) -> Self {39
Pins::with_transport(SkypeTokenTransport::new(session), DEFAULT_REGION)40
}41
}42
35
impl<T: CsaTransport> Pins<T> {43
impl<T: CsaTransport> Pins<T> {36
pub fn with_transport(transport: T, region: &str) -> Self {44
pub fn with_transport(transport: T, region: &str) -> Self {37
Pins {45
Pins {@@ -0,0 +1,310 @@
1
use chrono::{DateTime, Utc};
2
use serde_json::Value;
3
use session::{Method, Request};
4
5
use super::Pins;
6
use super::chats::{api_error, ensure_success};
7
use super::pinbar::PinnedMessage;
8
use super::transport::CsaTransport;
9
use crate::error::{Error, Result};
10
use crate::messages::encode;
11
12
pub const PINNED_POSTS_PAGE_SIZE: usize = 20;
13
const MAX_PINNED_POST_PAGES: usize = 10;
14
const CONTINUATION_HEADER: &str = "x-ms-continuation";
15
16
#[derive(Debug, Clone, PartialEq, Eq)]
17
pub struct PinnedPostsPage {
18
pub pins: Vec<PinnedMessage>,
19
pub continuation_token: Option<String>,
20
}
21
22
fn pinned_time(message: &Value) -> Option<DateTime<Utc>> {
23
let pinned = message.pointer("/properties/pinned")?;
24
let parsed;
25
let pinned = match pinned {
26
Value::String(text) => {
27
parsed = serde_json::from_str::<Value>(text).ok()?;
28
&parsed
29
}
30
other => other,
31
};
32
let millis = match pinned.get("pinnedTime")? {
33
Value::String(text) => text.parse::<i64>().ok()?,
34
other => other.as_i64()?,
35
};
36
DateTime::from_timestamp_millis(millis)
37
}
38
39
fn pinned_post(message: &Value) -> Option<PinnedMessage> {
40
let message_id = match message.get("id")? {
41
Value::String(text) => text.clone(),
42
Value::Number(number) => number.to_string(),
43
_ => return None,
44
};
45
Some(PinnedMessage {
46
message_id,
47
pinned_at: pinned_time(message),
48
parent_id: None,
49
})
50
}
51
52
pub fn parse_pinned_posts(body: &Value) -> Result<PinnedPostsPage> {
53
let messages = body
54
.get("messages")
55
.and_then(Value::as_array)
56
.ok_or_else(|| Error::UnexpectedAnswer("pinned posts messages missing".into()))?;
57
Ok(PinnedPostsPage {
58
pins: messages.iter().filter_map(pinned_post).collect(),
59
continuation_token: body
60
.get("continuationToken")
61
.and_then(Value::as_str)
62
.filter(|token| !token.is_empty())
63
.map(str::to_owned),
64
})
65
}
66
67
impl<T: CsaTransport> Pins<T> {
68
pub fn channel_url(&self, team_thread_id: &str, channel_id: &str) -> String {
69
format!(
70
"{}/teams/{}/channels/{}",
71
self.api_url,
72
encode(team_thread_id),
73
encode(channel_id)
74
)
75
}
76
77
pub fn pinned_posts_request(
78
&self,
79
team_thread_id: &str,
80
channel_id: &str,
81
continuation_token: Option<&str>,
82
) -> Request {
83
let mut request = Request::get(format!(
84
"{}/pins?pageSize={PINNED_POSTS_PAGE_SIZE}",
85
self.channel_url(team_thread_id, channel_id)
86
));
87
if let Some(token) = continuation_token {
88
request
89
.headers
90
.push((CONTINUATION_HEADER.to_owned(), token.to_owned()));
91
}
92
request
93
}
94
95
pub fn post_pin_request(
96
&self,
97
team_thread_id: &str,
98
channel_id: &str,
99
post_id: &str,
100
pinned: bool,
101
) -> Request {
102
let url = format!(
103
"{}/posts/{post_id}/pin",
104
self.channel_url(team_thread_id, channel_id)
105
);
106
if pinned {
107
Request {
108
method: Method::Post,
109
..Request::get(url)
110
}
111
} else {
112
Request::delete(url)
113
}
114
}
115
116
/// Pinned root posts in service order; only roots can be pinned while `enablePinMessageV2` is off.
117
pub async fn channel_pinned_posts(
118
&self,
119
team_thread_id: &str,
120
channel_id: &str,
121
) -> Result<Vec<PinnedMessage>> {
122
let mut pins = Vec::new();
123
let mut continuation_token: Option<String> = None;
124
for _ in 0..MAX_PINNED_POST_PAGES {
125
let request = self.pinned_posts_request(
126
team_thread_id,
127
channel_id,
128
continuation_token.as_deref(),
129
);
130
let answer = self.transport.send(request).await?;
131
ensure_success(&answer)?;
132
let page = parse_pinned_posts(&answer.body)?;
133
pins.extend(page.pins);
134
match page.continuation_token {
135
Some(token) if Some(&token) != continuation_token.as_ref() => {
136
continuation_token = Some(token)
137
}
138
_ => break,
139
}
140
}
141
Ok(pins)
142
}
143
144
pub async fn set_post_pinned(
145
&self,
146
team_thread_id: &str,
147
channel_id: &str,
148
post_id: &str,
149
pinned: bool,
150
) -> Result<()> {
151
let request = self.post_pin_request(team_thread_id, channel_id, post_id, pinned);
152
let answer = self.transport.send(request).await?;
153
if answer.is_success() {
154
Ok(())
155
} else {
156
Err(api_error(&answer))
157
}
158
}
159
}
160
161
#[cfg(test)]
162
mod tests {
163
use std::collections::VecDeque;
164
use std::sync::Mutex;
165
166
use serde_json::json;
167
use session::ApiResponse;
168
169
use super::*;
170
171
const TEAM: &str = "19:team@thread.tacv2";
172
const CHANNEL: &str = "19:channel@thread.tacv2";
173
const CHANNEL_URL: &str = "https://teams.cloud.microsoft/api/csa/emea/api/v1/teams/19%3Ateam%40thread.tacv2/channels/19%3Achannel%40thread.tacv2";
174
175
struct Canned {
176
answers: Mutex<VecDeque<(u16, Value)>>,
177
requests: Mutex<Vec<Request>>,
178
}
179
180
impl CsaTransport for Canned {
181
async fn send(&self, request: Request) -> Result<ApiResponse> {
182
self.requests.lock().unwrap().push(request);
183
let (status, body) = self.answers.lock().unwrap().pop_front().expect("exhausted");
184
Ok(ApiResponse {
185
status,
186
body,
187
retry_after: None,
188
})
189
}
190
}
191
192
fn canned(answers: Vec<(u16, Value)>) -> Pins<Canned> {
193
Pins::with_transport(
194
Canned {
195
answers: Mutex::new(answers.into()),
196
requests: Mutex::new(Vec::new()),
197
},
198
"emea",
199
)
200
}
201
202
#[test]
203
fn parses_ids_pinned_time_and_the_continuation() {
204
let body = json!({
205
"messages": [
206
{"id": "1791368000000", "parentMessageId": "1791368000000",
207
"properties": {"pinned": "{\"pinnedTime\":1791368500000}"}},
208
{"id": 1791367000000_i64, "properties": {"pinned": {"pinnedTime": "1791367500000"}}},
209
{"id": "1791366000000"},
210
{"content": "no id"}
211
],
212
"continuationToken": "next-page"
213
});
214
let page = parse_pinned_posts(&body).unwrap();
215
let ids: Vec<&str> = page
216
.pins
217
.iter()
218
.map(|pin| pin.message_id.as_str())
219
.collect();
220
assert_eq!(ids, ["1791368000000", "1791367000000", "1791366000000"]);
221
assert_eq!(
222
page.pins[0].pinned_at.map(|time| time.timestamp_millis()),
223
Some(1791368500000)
224
);
225
assert_eq!(
226
page.pins[1].pinned_at.map(|time| time.timestamp_millis()),
227
Some(1791367500000)
228
);
229
assert_eq!(page.pins[2].pinned_at, None);
230
assert_eq!(page.continuation_token.as_deref(), Some("next-page"));
231
}
232
233
#[test]
234
fn an_answer_without_messages_is_unexpected() {
235
assert!(matches!(
236
parse_pinned_posts(&json!({"continuationToken": "x"})),
237
Err(Error::UnexpectedAnswer(_))
238
));
239
}
240
241
#[test]
242
fn pin_and_unpin_hit_the_post_pin_url_without_a_body() {
243
let pins = canned(Vec::new());
244
let pin = pins.post_pin_request(TEAM, CHANNEL, "1791368000000", true);
245
assert_eq!(pin.method, Method::Post);
246
assert_eq!(pin.url, format!("{CHANNEL_URL}/posts/1791368000000/pin"));
247
assert_eq!(pin.body, None);
248
let unpin = pins.post_pin_request(TEAM, CHANNEL, "1791368000000", false);
249
assert_eq!(unpin.method, Method::Delete);
250
assert_eq!(unpin.url, pin.url);
251
assert_eq!(unpin.body, None);
252
}
253
254
#[tokio::test]
255
async fn pinned_posts_follow_the_continuation_header() {
256
let pins = canned(vec![
257
(
258
200,
259
json!({"messages": [{"id": "3"}, {"id": "2"}], "continuationToken": "page-2"}),
260
),
261
(200, json!({"messages": [{"id": "1"}]})),
262
]);
263
let found = pins.channel_pinned_posts(TEAM, CHANNEL).await.unwrap();
264
let ids: Vec<&str> = found.iter().map(|pin| pin.message_id.as_str()).collect();
265
assert_eq!(ids, ["3", "2", "1"]);
266
let requests = pins.transport.requests.lock().unwrap();
267
assert_eq!(requests[0].url, format!("{CHANNEL_URL}/pins?pageSize=20"));
268
assert!(requests[0].headers.is_empty());
269
assert_eq!(
270
requests[1].headers,
271
[("x-ms-continuation".to_owned(), "page-2".to_owned())]
272
);
273
}
274
275
#[tokio::test]
276
async fn a_repeated_continuation_stops_paging() {
277
let pins = canned(vec![
278
(
279
200,
280
json!({"messages": [{"id": "2"}], "continuationToken": "same"}),
281
),
282
(
283
200,
284
json!({"messages": [{"id": "1"}], "continuationToken": "same"}),
285
),
286
]);
287
let found = pins.channel_pinned_posts(TEAM, CHANNEL).await.unwrap();
288
assert_eq!(found.len(), 2);
289
assert_eq!(pins.transport.requests.lock().unwrap().len(), 2);
290
}
291
292
#[tokio::test]
293
async fn failures_are_errors() {
294
let pins = canned(vec![(403, json!({})), (412, json!({}))]);
295
assert!(pins.channel_pinned_posts(TEAM, CHANNEL).await.is_err());
296
assert!(
297
pins.set_post_pinned(TEAM, CHANNEL, "1", true)
298
.await
299
.is_err()
300
);
301
}
302
303
#[tokio::test]
304
async fn unpin_accepts_no_content() {
305
let pins = canned(vec![(204, Value::Null)]);
306
pins.set_post_pinned(TEAM, CHANNEL, "1", false)
307
.await
308
.unwrap();
309
}
310
}
@@ -0,0 +1,310 @@1
use chrono::{DateTime, Utc};2
use serde_json::Value;3
use session::{Method, Request};4
5
use super::Pins;6
use super::chats::{api_error, ensure_success};7
use super::pinbar::PinnedMessage;8
use super::transport::CsaTransport;9
use crate::error::{Error, Result};10
use crate::messages::encode;11
12
pub const PINNED_POSTS_PAGE_SIZE: usize = 20;13
const MAX_PINNED_POST_PAGES: usize = 10;14
const CONTINUATION_HEADER: &str = "x-ms-continuation";15
16
#[derive(Debug, Clone, PartialEq, Eq)]17
pub struct PinnedPostsPage {18
pub pins: Vec<PinnedMessage>,19
pub continuation_token: Option<String>,20
}21
22
fn pinned_time(message: &Value) -> Option<DateTime<Utc>> {23
let pinned = message.pointer("/properties/pinned")?;24
let parsed;25
let pinned = match pinned {26
Value::String(text) => {27
parsed = serde_json::from_str::<Value>(text).ok()?;28
&parsed29
}30
other => other,31
};32
let millis = match pinned.get("pinnedTime")? {33
Value::String(text) => text.parse::<i64>().ok()?,34
other => other.as_i64()?,35
};36
DateTime::from_timestamp_millis(millis)37
}38
39
fn pinned_post(message: &Value) -> Option<PinnedMessage> {40
let message_id = match message.get("id")? {41
Value::String(text) => text.clone(),42
Value::Number(number) => number.to_string(),43
_ => return None,44
};45
Some(PinnedMessage {46
message_id,47
pinned_at: pinned_time(message),48
parent_id: None,49
})50
}51
52
pub fn parse_pinned_posts(body: &Value) -> Result<PinnedPostsPage> {53
let messages = body54
.get("messages")55
.and_then(Value::as_array)56
.ok_or_else(|| Error::UnexpectedAnswer("pinned posts messages missing".into()))?;57
Ok(PinnedPostsPage {58
pins: messages.iter().filter_map(pinned_post).collect(),59
continuation_token: body60
.get("continuationToken")61
.and_then(Value::as_str)62
.filter(|token| !token.is_empty())63
.map(str::to_owned),64
})65
}66
67
impl<T: CsaTransport> Pins<T> {68
pub fn channel_url(&self, team_thread_id: &str, channel_id: &str) -> String {69
format!(70
"{}/teams/{}/channels/{}",71
self.api_url,72
encode(team_thread_id),73
encode(channel_id)74
)75
}76
77
pub fn pinned_posts_request(78
&self,79
team_thread_id: &str,80
channel_id: &str,81
continuation_token: Option<&str>,82
) -> Request {83
let mut request = Request::get(format!(84
"{}/pins?pageSize={PINNED_POSTS_PAGE_SIZE}",85
self.channel_url(team_thread_id, channel_id)86
));87
if let Some(token) = continuation_token {88
request89
.headers90
.push((CONTINUATION_HEADER.to_owned(), token.to_owned()));91
}92
request93
}94
95
pub fn post_pin_request(96
&self,97
team_thread_id: &str,98
channel_id: &str,99
post_id: &str,100
pinned: bool,101
) -> Request {102
let url = format!(103
"{}/posts/{post_id}/pin",104
self.channel_url(team_thread_id, channel_id)105
);106
if pinned {107
Request {108
method: Method::Post,109
..Request::get(url)110
}111
} else {112
Request::delete(url)113
}114
}115
116
/// Pinned root posts in service order; only roots can be pinned while `enablePinMessageV2` is off.117
pub async fn channel_pinned_posts(118
&self,119
team_thread_id: &str,120
channel_id: &str,121
) -> Result<Vec<PinnedMessage>> {122
let mut pins = Vec::new();123
let mut continuation_token: Option<String> = None;124
for _ in 0..MAX_PINNED_POST_PAGES {125
let request = self.pinned_posts_request(126
team_thread_id,127
channel_id,128
continuation_token.as_deref(),129
);130
let answer = self.transport.send(request).await?;131
ensure_success(&answer)?;132
let page = parse_pinned_posts(&answer.body)?;133
pins.extend(page.pins);134
match page.continuation_token {135
Some(token) if Some(&token) != continuation_token.as_ref() => {136
continuation_token = Some(token)137
}138
_ => break,139
}140
}141
Ok(pins)142
}143
144
pub async fn set_post_pinned(145
&self,146
team_thread_id: &str,147
channel_id: &str,148
post_id: &str,149
pinned: bool,150
) -> Result<()> {151
let request = self.post_pin_request(team_thread_id, channel_id, post_id, pinned);152
let answer = self.transport.send(request).await?;153
if answer.is_success() {154
Ok(())155
} else {156
Err(api_error(&answer))157
}158
}159
}160
161
#[cfg(test)]162
mod tests {163
use std::collections::VecDeque;164
use std::sync::Mutex;165
166
use serde_json::json;167
use session::ApiResponse;168
169
use super::*;170
171
const TEAM: &str = "19:team@thread.tacv2";172
const CHANNEL: &str = "19:channel@thread.tacv2";173
const CHANNEL_URL: &str = "https://teams.cloud.microsoft/api/csa/emea/api/v1/teams/19%3Ateam%40thread.tacv2/channels/19%3Achannel%40thread.tacv2";174
175
struct Canned {176
answers: Mutex<VecDeque<(u16, Value)>>,177
requests: Mutex<Vec<Request>>,178
}179
180
impl CsaTransport for Canned {181
async fn send(&self, request: Request) -> Result<ApiResponse> {182
self.requests.lock().unwrap().push(request);183
let (status, body) = self.answers.lock().unwrap().pop_front().expect("exhausted");184
Ok(ApiResponse {185
status,186
body,187
retry_after: None,188
})189
}190
}191
192
fn canned(answers: Vec<(u16, Value)>) -> Pins<Canned> {193
Pins::with_transport(194
Canned {195
answers: Mutex::new(answers.into()),196
requests: Mutex::new(Vec::new()),197
},198
"emea",199
)200
}201
202
#[test]203
fn parses_ids_pinned_time_and_the_continuation() {204
let body = json!({205
"messages": [206
{"id": "1791368000000", "parentMessageId": "1791368000000",207
"properties": {"pinned": "{\"pinnedTime\":1791368500000}"}},208
{"id": 1791367000000_i64, "properties": {"pinned": {"pinnedTime": "1791367500000"}}},209
{"id": "1791366000000"},210
{"content": "no id"}211
],212
"continuationToken": "next-page"213
});214
let page = parse_pinned_posts(&body).unwrap();215
let ids: Vec<&str> = page216
.pins217
.iter()218
.map(|pin| pin.message_id.as_str())219
.collect();220
assert_eq!(ids, ["1791368000000", "1791367000000", "1791366000000"]);221
assert_eq!(222
page.pins[0].pinned_at.map(|time| time.timestamp_millis()),223
Some(1791368500000)224
);225
assert_eq!(226
page.pins[1].pinned_at.map(|time| time.timestamp_millis()),227
Some(1791367500000)228
);229
assert_eq!(page.pins[2].pinned_at, None);230
assert_eq!(page.continuation_token.as_deref(), Some("next-page"));231
}232
233
#[test]234
fn an_answer_without_messages_is_unexpected() {235
assert!(matches!(236
parse_pinned_posts(&json!({"continuationToken": "x"})),237
Err(Error::UnexpectedAnswer(_))238
));239
}240
241
#[test]242
fn pin_and_unpin_hit_the_post_pin_url_without_a_body() {243
let pins = canned(Vec::new());244
let pin = pins.post_pin_request(TEAM, CHANNEL, "1791368000000", true);245
assert_eq!(pin.method, Method::Post);246
assert_eq!(pin.url, format!("{CHANNEL_URL}/posts/1791368000000/pin"));247
assert_eq!(pin.body, None);248
let unpin = pins.post_pin_request(TEAM, CHANNEL, "1791368000000", false);249
assert_eq!(unpin.method, Method::Delete);250
assert_eq!(unpin.url, pin.url);251
assert_eq!(unpin.body, None);252
}253
254
#[tokio::test]255
async fn pinned_posts_follow_the_continuation_header() {256
let pins = canned(vec![257
(258
200,259
json!({"messages": [{"id": "3"}, {"id": "2"}], "continuationToken": "page-2"}),260
),261
(200, json!({"messages": [{"id": "1"}]})),262
]);263
let found = pins.channel_pinned_posts(TEAM, CHANNEL).await.unwrap();264
let ids: Vec<&str> = found.iter().map(|pin| pin.message_id.as_str()).collect();265
assert_eq!(ids, ["3", "2", "1"]);266
let requests = pins.transport.requests.lock().unwrap();267
assert_eq!(requests[0].url, format!("{CHANNEL_URL}/pins?pageSize=20"));268
assert!(requests[0].headers.is_empty());269
assert_eq!(270
requests[1].headers,271
[("x-ms-continuation".to_owned(), "page-2".to_owned())]272
);273
}274
275
#[tokio::test]276
async fn a_repeated_continuation_stops_paging() {277
let pins = canned(vec![278
(279
200,280
json!({"messages": [{"id": "2"}], "continuationToken": "same"}),281
),282
(283
200,284
json!({"messages": [{"id": "1"}], "continuationToken": "same"}),285
),286
]);287
let found = pins.channel_pinned_posts(TEAM, CHANNEL).await.unwrap();288
assert_eq!(found.len(), 2);289
assert_eq!(pins.transport.requests.lock().unwrap().len(), 2);290
}291
292
#[tokio::test]293
async fn failures_are_errors() {294
let pins = canned(vec![(403, json!({})), (412, json!({}))]);295
assert!(pins.channel_pinned_posts(TEAM, CHANNEL).await.is_err());296
assert!(297
pins.set_post_pinned(TEAM, CHANNEL, "1", true)298
.await299
.is_err()300
);301
}302
303
#[tokio::test]304
async fn unpin_accepts_no_content() {305
let pins = canned(vec![(204, Value::Null)]);306
pins.set_post_pinned(TEAM, CHANNEL, "1", false)307
.await308
.unwrap();309
}310
}@@ -1,4 +1,5 @@
1
use session::{ApiResponse, Request, Scope, Session};
1
use serde_json::{Value, json};
2
use session::{ApiResponse, App, Request, Scope, Session};
2
3
3
4
use crate::error::Result;
4
5
@@ -33,3 +34,104 @@ impl CsaTransport for SessionTransport {
33
34
Ok(answers.remove(0))
34
35
}
35
36
}
37
38
const SKYPE_FETCH_BODY: &str = include_str!("../../assets/csa_skype_fetch.js");
39
40
/// Teams sends the skype token and the chat service endpoint next to the CSA bearer on the pinned post routes.
41
pub struct SkypeTokenTransport {
42
session: Session,
43
scope: Scope,
44
}
45
46
impl SkypeTokenTransport {
47
pub fn new(session: &Session) -> Self {
48
SkypeTokenTransport {
49
session: session.clone(),
50
scope: Scope::new(CSA_RESOURCE, CSA_SCOPE),
51
}
52
}
53
}
54
55
pub fn skype_fetch_args(request: &Request) -> Value {
56
let headers: serde_json::Map<String, Value> = request
57
.headers
58
.iter()
59
.map(|(name, value)| (name.clone(), Value::String(value.clone())))
60
.collect();
61
json!({
62
"method": request.method.as_str(),
63
"url": request.url,
64
"headers": headers,
65
"body": request.body,
66
})
67
}
68
69
pub fn skype_fetch_answer(answer: Value) -> ApiResponse {
70
ApiResponse {
71
status: answer
72
.get("status")
73
.and_then(Value::as_u64)
74
.and_then(|status| u16::try_from(status).ok())
75
.unwrap_or(0),
76
retry_after: answer
77
.get("retryAfter")
78
.and_then(Value::as_str)
79
.map(str::to_owned),
80
body: answer.get("body").cloned().unwrap_or(Value::Null),
81
}
82
}
83
84
impl CsaTransport for SkypeTokenTransport {
85
async fn send(&self, request: Request) -> Result<ApiResponse> {
86
let answer = self
87
.session
88
.run_with_token(
89
App::Teams,
90
&self.scope,
91
SKYPE_FETCH_BODY,
92
&skype_fetch_args(&request),
93
false,
94
)
95
.await?;
96
Ok(skype_fetch_answer(answer))
97
}
98
}
99
100
#[cfg(test)]
101
mod tests {
102
use session::Method;
103
104
use super::*;
105
106
#[test]
107
fn skype_fetch_args_carry_method_url_headers_and_body() {
108
let mut request = Request::delete("https://csa/pin");
109
request
110
.headers
111
.push(("x-ms-continuation".to_owned(), "next".to_owned()));
112
assert_eq!(
113
skype_fetch_args(&request),
114
json!({
115
"method": "DELETE",
116
"url": "https://csa/pin",
117
"headers": {"x-ms-continuation": "next"},
118
"body": null,
119
})
120
);
121
let post = Request {
122
method: Method::Post,
123
..Request::get("https://csa/pin")
124
};
125
assert_eq!(skype_fetch_args(&post)["method"], "POST");
126
}
127
128
#[test]
129
fn page_answers_become_api_responses() {
130
let answer = skype_fetch_answer(json!({"status": 204, "retryAfter": null, "body": null}));
131
assert_eq!(answer.status, 204);
132
assert!(answer.is_success());
133
let failed = skype_fetch_answer(json!({"status": 0, "body": "authz_http_401"}));
134
assert!(!failed.is_success());
135
assert_eq!(failed.body, json!("authz_http_401"));
136
}
137
}
@@ -1,4 +1,5 @@1
use session::{ApiResponse, Request, Scope, Session};1
use serde_json::{Value, json};2
use session::{ApiResponse, App, Request, Scope, Session};2
3
3
use crate::error::Result;4
use crate::error::Result;4
5
@@ -33,3 +34,104 @@ impl CsaTransport for SessionTransport {33
Ok(answers.remove(0))34
Ok(answers.remove(0))34
}35
}35
}36
}37
38
const SKYPE_FETCH_BODY: &str = include_str!("../../assets/csa_skype_fetch.js");39
40
/// Teams sends the skype token and the chat service endpoint next to the CSA bearer on the pinned post routes.41
pub struct SkypeTokenTransport {42
session: Session,43
scope: Scope,44
}45
46
impl SkypeTokenTransport {47
pub fn new(session: &Session) -> Self {48
SkypeTokenTransport {49
session: session.clone(),50
scope: Scope::new(CSA_RESOURCE, CSA_SCOPE),51
}52
}53
}54
55
pub fn skype_fetch_args(request: &Request) -> Value {56
let headers: serde_json::Map<String, Value> = request57
.headers58
.iter()59
.map(|(name, value)| (name.clone(), Value::String(value.clone())))60
.collect();61
json!({62
"method": request.method.as_str(),63
"url": request.url,64
"headers": headers,65
"body": request.body,66
})67
}68
69
pub fn skype_fetch_answer(answer: Value) -> ApiResponse {70
ApiResponse {71
status: answer72
.get("status")73
.and_then(Value::as_u64)74
.and_then(|status| u16::try_from(status).ok())75
.unwrap_or(0),76
retry_after: answer77
.get("retryAfter")78
.and_then(Value::as_str)79
.map(str::to_owned),80
body: answer.get("body").cloned().unwrap_or(Value::Null),81
}82
}83
84
impl CsaTransport for SkypeTokenTransport {85
async fn send(&self, request: Request) -> Result<ApiResponse> {86
let answer = self87
.session88
.run_with_token(89
App::Teams,90
&self.scope,91
SKYPE_FETCH_BODY,92
&skype_fetch_args(&request),93
false,94
)95
.await?;96
Ok(skype_fetch_answer(answer))97
}98
}99
100
#[cfg(test)]101
mod tests {102
use session::Method;103
104
use super::*;105
106
#[test]107
fn skype_fetch_args_carry_method_url_headers_and_body() {108
let mut request = Request::delete("https://csa/pin");109
request110
.headers111
.push(("x-ms-continuation".to_owned(), "next".to_owned()));112
assert_eq!(113
skype_fetch_args(&request),114
json!({115
"method": "DELETE",116
"url": "https://csa/pin",117
"headers": {"x-ms-continuation": "next"},118
"body": null,119
})120
);121
let post = Request {122
method: Method::Post,123
..Request::get("https://csa/pin")124
};125
assert_eq!(skype_fetch_args(&post)["method"], "POST");126
}127
128
#[test]129
fn page_answers_become_api_responses() {130
let answer = skype_fetch_answer(json!({"status": 204, "retryAfter": null, "body": null}));131
assert_eq!(answer.status, 204);132
assert!(answer.is_success());133
let failed = skype_fetch_answer(json!({"status": 0, "body": "authz_http_401"}));134
assert!(!failed.is_success());135
assert_eq!(failed.body, json!("authz_http_401"));136
}137
}@@ -8,6 +8,7 @@ pub const PROPERTY_NAME: &str = "consumptionhorizon";
8
8
pub struct ReadHorizon {
9
9
pub consumed_until_ms: i64,
10
10
pub bookmark_ms: i64,
11
pub bookmark_timestamp_ms: i64,
11
12
pub bookmark_message_set: bool,
12
13
pub last_message_ms: i64,
13
14
pub last_message_from: Option<String>,
@@ -22,6 +23,7 @@ impl ReadHorizon {
22
23
ReadHorizon {
23
24
consumed_until_ms: horizon.arrival_ms,
24
25
bookmark_ms: bookmark.arrival_ms,
26
bookmark_timestamp_ms: bookmark.timestamp_ms,
25
27
bookmark_message_set: bookmark.message_set,
26
28
last_message_ms: last_message_ms(conversation),
27
29
last_message_from: last_message["from"]
@@ -33,10 +35,19 @@ impl ReadHorizon {
33
35
}
34
36
35
37
pub fn is_unread(&self, my_user_id: &str) -> bool {
36
if self.bookmark_ms != 0 && self.bookmark_message_set {
38
self.is_unread_after(my_user_id, 0)
39
}
40
41
/// `app_horizon_ms` is the `appConsumptionHorizon` entry of the conversation's app ("Mark all as read").
42
pub fn is_unread_after(&self, my_user_id: &str, app_horizon_ms: i64) -> bool {
43
let app_horizon_set = app_horizon_ms > 0;
44
let bookmark_cleared = app_horizon_set && app_horizon_ms >= self.bookmark_timestamp_ms;
45
let bookmark_ms = if bookmark_cleared { 0 } else { self.bookmark_ms };
46
if bookmark_ms != 0 && self.bookmark_message_set {
37
47
return true;
38
48
}
39
let unread = self.bookmark_ms != 0 || self.last_message_ms > self.consumed_until_ms;
49
let consumed_until_ms = self.consumed_until_ms.max(app_horizon_ms);
50
let unread = bookmark_ms != 0 || self.last_message_ms > consumed_until_ms;
40
51
let from_me = self
41
52
.last_message_from
42
53
.as_deref()
@@ -62,6 +73,7 @@ pub fn read_up_to(last_message_at: DateTime<Utc>, now: DateTime<Utc>) -> String
62
73
63
74
struct ParsedHorizon {
64
75
arrival_ms: i64,
76
timestamp_ms: i64,
65
77
message_set: bool,
66
78
}
67
79
@@ -70,6 +82,7 @@ fn parse_horizon(text: Option<&str>) -> ParsedHorizon {
70
82
let number = |part: &str| part.trim().parse::<i64>().ok();
71
83
let unset = ParsedHorizon {
72
84
arrival_ms: 0,
85
timestamp_ms: 0,
73
86
message_set: false,
74
87
};
75
88
let [arrival, timestamp, message_id] = parts.as_slice() else {
@@ -77,8 +90,9 @@ fn parse_horizon(text: Option<&str>) -> ParsedHorizon {
77
90
};
78
91
let message_id = message_id.trim();
79
92
match (number(arrival), number(timestamp)) {
80
(Some(arrival_ms), Some(_)) if !message_id.is_empty() => ParsedHorizon {
93
(Some(arrival_ms), Some(timestamp_ms)) if !message_id.is_empty() => ParsedHorizon {
81
94
arrival_ms,
95
timestamp_ms,
82
96
message_set: message_id != "0",
83
97
},
84
98
_ => unset,
@@ -192,6 +206,31 @@ mod tests {
192
206
assert!(unread(&value));
193
207
}
194
208
209
#[test]
210
fn app_horizon_reads_everything_that_arrived_before_it() {
211
let value = conversation(
212
Some("1791884440747;1791885752824;1"),
213
None,
214
Some(("2026-10-16T09:42:25.6780000Z", "8:orgid:other")),
215
);
216
let horizon = ReadHorizon::from_conversation(&value);
217
assert!(horizon.is_unread_after(ME, 0));
218
assert!(horizon.is_unread_after(ME, horizon.last_message_ms - 1));
219
assert!(!horizon.is_unread_after(ME, horizon.last_message_ms));
220
}
221
222
#[test]
223
fn app_horizon_clears_an_older_bookmark_only() {
224
let value = conversation(
225
Some("1792171970947;1792171971513;1"),
226
Some("1792171970000;1792171971513;42"),
227
Some(("2026-10-16T17:32:50.9470000Z", "8:orgid:other")),
228
);
229
let horizon = ReadHorizon::from_conversation(&value);
230
assert!(horizon.is_unread_after(ME, 1792171971512));
231
assert!(!horizon.is_unread_after(ME, 1792171971513));
232
}
233
195
234
#[test]
196
235
fn read_value_carries_the_last_arrival_and_now() {
197
236
let last = DateTime::from_timestamp_millis(1792182658901).unwrap();
@@ -8,6 +8,7 @@ pub const PROPERTY_NAME: &str = "consumptionhorizon";8
pub struct ReadHorizon {8
pub struct ReadHorizon {9
pub consumed_until_ms: i64,9
pub consumed_until_ms: i64,10
pub bookmark_ms: i64,10
pub bookmark_ms: i64,11
pub bookmark_timestamp_ms: i64,11
pub bookmark_message_set: bool,12
pub bookmark_message_set: bool,12
pub last_message_ms: i64,13
pub last_message_ms: i64,13
pub last_message_from: Option<String>,14
pub last_message_from: Option<String>,@@ -22,6 +23,7 @@ impl ReadHorizon {22
ReadHorizon {23
ReadHorizon {23
consumed_until_ms: horizon.arrival_ms,24
consumed_until_ms: horizon.arrival_ms,24
bookmark_ms: bookmark.arrival_ms,25
bookmark_ms: bookmark.arrival_ms,26
bookmark_timestamp_ms: bookmark.timestamp_ms,25
bookmark_message_set: bookmark.message_set,27
bookmark_message_set: bookmark.message_set,26
last_message_ms: last_message_ms(conversation),28
last_message_ms: last_message_ms(conversation),27
last_message_from: last_message["from"]29
last_message_from: last_message["from"]@@ -33,10 +35,19 @@ impl ReadHorizon {33
}35
}34
36
35
pub fn is_unread(&self, my_user_id: &str) -> bool {37
pub fn is_unread(&self, my_user_id: &str) -> bool {36
if self.bookmark_ms != 0 && self.bookmark_message_set {38
self.is_unread_after(my_user_id, 0)39
}40
41
/// `app_horizon_ms` is the `appConsumptionHorizon` entry of the conversation's app ("Mark all as read").42
pub fn is_unread_after(&self, my_user_id: &str, app_horizon_ms: i64) -> bool {43
let app_horizon_set = app_horizon_ms > 0;44
let bookmark_cleared = app_horizon_set && app_horizon_ms >= self.bookmark_timestamp_ms;45
let bookmark_ms = if bookmark_cleared { 0 } else { self.bookmark_ms };46
if bookmark_ms != 0 && self.bookmark_message_set {37
return true;47
return true;38
}48
}39
let unread = self.bookmark_ms != 0 || self.last_message_ms > self.consumed_until_ms;49
let consumed_until_ms = self.consumed_until_ms.max(app_horizon_ms);50
let unread = bookmark_ms != 0 || self.last_message_ms > consumed_until_ms;40
let from_me = self51
let from_me = self41
.last_message_from52
.last_message_from42
.as_deref()53
.as_deref()@@ -62,6 +73,7 @@ pub fn read_up_to(last_message_at: DateTime<Utc>, now: DateTime<Utc>) -> String62
73
63
struct ParsedHorizon {74
struct ParsedHorizon {64
arrival_ms: i64,75
arrival_ms: i64,76
timestamp_ms: i64,65
message_set: bool,77
message_set: bool,66
}78
}67
79
@@ -70,6 +82,7 @@ fn parse_horizon(text: Option<&str>) -> ParsedHorizon {70
let number = |part: &str| part.trim().parse::<i64>().ok();82
let number = |part: &str| part.trim().parse::<i64>().ok();71
let unset = ParsedHorizon {83
let unset = ParsedHorizon {72
arrival_ms: 0,84
arrival_ms: 0,85
timestamp_ms: 0,73
message_set: false,86
message_set: false,74
};87
};75
let [arrival, timestamp, message_id] = parts.as_slice() else {88
let [arrival, timestamp, message_id] = parts.as_slice() else {@@ -77,8 +90,9 @@ fn parse_horizon(text: Option<&str>) -> ParsedHorizon {77
};90
};78
let message_id = message_id.trim();91
let message_id = message_id.trim();79
match (number(arrival), number(timestamp)) {92
match (number(arrival), number(timestamp)) {80
(Some(arrival_ms), Some(_)) if !message_id.is_empty() => ParsedHorizon {93
(Some(arrival_ms), Some(timestamp_ms)) if !message_id.is_empty() => ParsedHorizon {81
arrival_ms,94
arrival_ms,95
timestamp_ms,82
message_set: message_id != "0",96
message_set: message_id != "0",83
},97
},84
_ => unset,98
_ => unset,@@ -192,6 +206,31 @@ mod tests {192
assert!(unread(&value));206
assert!(unread(&value));193
}207
}194
208
209
#[test]210
fn app_horizon_reads_everything_that_arrived_before_it() {211
let value = conversation(212
Some("1791884440747;1791885752824;1"),213
None,214
Some(("2026-10-16T09:42:25.6780000Z", "8:orgid:other")),215
);216
let horizon = ReadHorizon::from_conversation(&value);217
assert!(horizon.is_unread_after(ME, 0));218
assert!(horizon.is_unread_after(ME, horizon.last_message_ms - 1));219
assert!(!horizon.is_unread_after(ME, horizon.last_message_ms));220
}221
222
#[test]223
fn app_horizon_clears_an_older_bookmark_only() {224
let value = conversation(225
Some("1792171970947;1792171971513;1"),226
Some("1792171970000;1792171971513;42"),227
Some(("2026-10-16T17:32:50.9470000Z", "8:orgid:other")),228
);229
let horizon = ReadHorizon::from_conversation(&value);230
assert!(horizon.is_unread_after(ME, 1792171971512));231
assert!(!horizon.is_unread_after(ME, 1792171971513));232
}233
195
#[test]234
#[test]196
fn read_value_carries_the_last_arrival_and_now() {235
fn read_value_carries_the_last_arrival_and_now() {197
let last = DateTime::from_timestamp_millis(1792182658901).unwrap();236
let last = DateTime::from_timestamp_millis(1792182658901).unwrap();@@ -9,6 +9,9 @@ const SETTINGS_KEY: &str = "simpleCollabUserSettings";
9
9
const SETTINGS_ID: &str = "simpleCollabUserSettingsId";
10
10
const TEAMS_ORDER_KEY: &str = "teamsOrder";
11
11
const SKIN_TONE_KEY: &str = "preferredSkinToneIndex";
12
const DEFAULT_REACTIONS_KEY: &str = "defaultMessageReactions";
13
const APP_HORIZON_KEY: &str = "appConsumptionHorizon";
14
const APP_HORIZON_APPS: [&str; 3] = ["chat", "channel", "engage_community"];
12
15
const MAX_SKIN_TONE: u8 = 5;
13
16
const MUTED_FIELD: &str = "hasUserEnabledMutedChatSection";
14
17
const MEETING_FIELD: &str = "hasUserEnabledMeetingChatSection";
@@ -98,6 +101,23 @@ impl<T: MessageTransport> UserSettings<T> {
98
101
.await
99
102
}
100
103
104
pub async fn set_default_reactions(&self, reaction_ids: &[String]) -> Result<()> {
105
self.set_property(DEFAULT_REACTIONS_KEY, default_reactions_value(reaction_ids))
106
.await
107
}
108
109
/// Teams' "Mark all as read" for channels: one write, the channel entry of `appConsumptionHorizon` moves to now.
110
pub async fn mark_all_channels_read(&self, now_ms: i64) -> Result<AppConsumptionHorizon> {
111
let properties = self.properties().await?;
112
let horizon = AppConsumptionHorizon {
113
channel_ms: now_ms,
114
..parse_app_consumption_horizon(&properties)
115
};
116
self.set_property(APP_HORIZON_KEY, Value::String(horizon.property_value()))
117
.await?;
118
Ok(horizon)
119
}
120
101
121
pub async fn set_property(&self, name: &str, value: Value) -> Result<()> {
102
122
let url = format!("{}?name={name}", self.base_url);
103
123
let mut body = Map::new();
@@ -147,6 +167,25 @@ pub fn parse_skin_tone(properties: &Value) -> Option<u8> {
147
167
(tone <= MAX_SKIN_TONE).then_some(tone)
148
168
}
149
169
170
pub fn parse_default_reactions(properties: &Value) -> Option<Vec<String>> {
171
let entries = match properties.get(DEFAULT_REACTIONS_KEY)? {
172
Value::String(text) => serde_json::from_str::<Value>(text).ok()?,
173
other => other.clone(),
174
};
175
entries.as_array().map(|entries| {
176
entries
177
.iter()
178
.filter_map(Value::as_str)
179
.filter(|reaction_id| !reaction_id.is_empty())
180
.map(str::to_owned)
181
.collect()
182
})
183
}
184
185
pub fn default_reactions_value(reaction_ids: &[String]) -> Value {
186
Value::String(Value::from(reaction_ids.to_vec()).to_string())
187
}
188
150
189
pub fn parse_teams_order(properties: &Value) -> Vec<(String, i64)> {
151
190
let entries = match properties.get(TEAMS_ORDER_KEY) {
152
191
Some(Value::String(text)) => serde_json::from_str::<Value>(text).ok(),
@@ -175,6 +214,54 @@ pub fn parse_teams_order(properties: &Value) -> Vec<(String, i64)> {
175
214
order
176
215
}
177
216
217
/// Per app "read everything before" times in ms; Teams treats a conversation of that app as read up to it.
218
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
219
pub struct AppConsumptionHorizon {
220
pub chat_ms: i64,
221
pub channel_ms: i64,
222
pub engage_community_ms: i64,
223
}
224
225
impl AppConsumptionHorizon {
226
pub fn property_value(&self) -> String {
227
let values = [self.chat_ms, self.channel_ms, self.engage_community_ms];
228
let mut fields = Map::new();
229
for (app, value) in APP_HORIZON_APPS.iter().zip(values) {
230
fields.insert((*app).to_owned(), Value::from(value));
231
}
232
Value::Object(fields).to_string()
233
}
234
}
235
236
pub fn parse_app_consumption_horizon(properties: &Value) -> AppConsumptionHorizon {
237
let parsed = match properties.get(APP_HORIZON_KEY) {
238
Some(Value::String(text)) => serde_json::from_str::<Value>(text).ok(),
239
Some(other) => Some(other.clone()),
240
None => None,
241
};
242
let Some(fields) = parsed.as_ref().and_then(Value::as_object) else {
243
return AppConsumptionHorizon::default();
244
};
245
let valid = (fields.contains_key("chat") || fields.contains_key("channel"))
246
&& fields
247
.values()
248
.all(|value| value.as_f64().is_some_and(|number| number >= 0.0));
249
if !valid {
250
return AppConsumptionHorizon::default();
251
}
252
let read = |app: &str| {
253
fields
254
.get(app)
255
.and_then(Value::as_f64)
256
.map_or(0, |number| number as i64)
257
};
258
AppConsumptionHorizon {
259
chat_ms: read("chat"),
260
channel_ms: read("channel"),
261
engage_community_ms: read("engage_community"),
262
}
263
}
264
178
265
pub fn merge_chat_section(properties: &Value, section: ChatSection, enabled: bool) -> String {
179
266
let mut settings = stored_settings(properties);
180
267
settings
@@ -228,6 +315,53 @@ mod tests {
228
315
assert_eq!(parse_skin_tone(&json!({})), None);
229
316
}
230
317
318
#[test]
319
fn default_reactions_are_read_from_the_json_string_or_an_array() {
320
assert_eq!(
321
parse_default_reactions(&json!({DEFAULT_REACTIONS_KEY: r#"["like","heart","fire"]"#})),
322
Some(vec![
323
"like".to_owned(),
324
"heart".to_owned(),
325
"fire".to_owned()
326
])
327
);
328
assert_eq!(
329
parse_default_reactions(&json!({DEFAULT_REACTIONS_KEY: ["yes", "", 3]})),
330
Some(vec!["yes".to_owned()])
331
);
332
assert_eq!(
333
parse_default_reactions(&json!({DEFAULT_REACTIONS_KEY: "[]"})),
334
Some(Vec::new())
335
);
336
assert_eq!(parse_default_reactions(&json!({})), None);
337
assert_eq!(
338
parse_default_reactions(&json!({DEFAULT_REACTIONS_KEY: "not json"})),
339
None
340
);
341
}
342
343
#[tokio::test]
344
async fn default_reactions_are_put_as_a_json_string() {
345
let transport = Canned {
346
answers: Mutex::new(vec![(200, Value::Null)].into()),
347
requests: Mutex::new(Vec::new()),
348
};
349
UserSettings::with_transport(&transport, "emea")
350
.set_default_reactions(&["like".to_owned(), "fire".to_owned()])
351
.await
352
.unwrap();
353
let requests = transport.requests.lock().unwrap();
354
assert_eq!(requests[0].method, Method::Put);
355
assert_eq!(
356
requests[0].url,
357
"https://teams.cloud.microsoft/api/chatsvc/emea/v1/users/ME/properties?name=defaultMessageReactions"
358
);
359
assert_eq!(
360
requests[0].body,
361
Some(json!({"defaultMessageReactions": r#"["like","fire"]"#}))
362
);
363
}
364
231
365
#[test]
232
366
fn unset_fields_use_the_teams_defaults() {
233
367
let parsed = parse_chat_sections(&json!({}));
@@ -334,4 +468,63 @@ mod tests {
334
468
assert_eq!(value["keep"], json!(1));
335
469
assert_eq!(value["hasUserEnabledMutedChatSection"], json!(false));
336
470
}
471
472
#[test]
473
fn app_horizon_reads_the_string_and_ignores_invalid_values() {
474
let parsed = parse_app_consumption_horizon(&json!({
475
"appConsumptionHorizon": "{\"chat\":1791368000000,\"channel\":1791369000000,\"engage_community\":0}"
476
}));
477
assert_eq!(
478
parsed,
479
AppConsumptionHorizon {
480
chat_ms: 1791368000000,
481
channel_ms: 1791369000000,
482
engage_community_ms: 0,
483
}
484
);
485
let object = parse_app_consumption_horizon(&json!({"appConsumptionHorizon": {"channel": 5}}));
486
assert_eq!(object.channel_ms, 5);
487
for broken in [
488
json!({}),
489
json!({"appConsumptionHorizon": "not json"}),
490
json!({"appConsumptionHorizon": "{\"engage_community\":5}"}),
491
json!({"appConsumptionHorizon": "{\"channel\":-1}"}),
492
json!({"appConsumptionHorizon": "{\"channel\":\"5\"}"}),
493
] {
494
assert_eq!(
495
parse_app_consumption_horizon(&broken),
496
AppConsumptionHorizon::default()
497
);
498
}
499
}
500
501
#[tokio::test]
502
async fn mark_all_channels_read_moves_only_the_channel_entry() {
503
let stored = json!({
504
"appConsumptionHorizon": "{\"chat\":100,\"channel\":200,\"engage_community\":300}"
505
});
506
let transport = Canned {
507
answers: Mutex::new(vec![(200, stored), (200, Value::Null)].into()),
508
requests: Mutex::new(Vec::new()),
509
};
510
let horizon = UserSettings::with_transport(&transport, "emea")
511
.mark_all_channels_read(1791368000000)
512
.await
513
.unwrap();
514
assert_eq!(horizon.channel_ms, 1791368000000);
515
let requests = transport.requests.lock().unwrap();
516
assert_eq!(requests[1].method, Method::Put);
517
assert_eq!(
518
requests[1].url,
519
"https://teams.cloud.microsoft/api/chatsvc/emea/v1/users/ME/properties?name=appConsumptionHorizon"
520
);
521
let sent = requests[1].body.as_ref().unwrap()["appConsumptionHorizon"]
522
.as_str()
523
.unwrap();
524
let value: Value = serde_json::from_str(sent).unwrap();
525
assert_eq!(
526
value,
527
json!({"chat": 100, "channel": 1791368000000_i64, "engage_community": 300})
528
);
529
}
337
530
}
@@ -9,6 +9,9 @@ const SETTINGS_KEY: &str = "simpleCollabUserSettings";9
const SETTINGS_ID: &str = "simpleCollabUserSettingsId";9
const SETTINGS_ID: &str = "simpleCollabUserSettingsId";10
const TEAMS_ORDER_KEY: &str = "teamsOrder";10
const TEAMS_ORDER_KEY: &str = "teamsOrder";11
const SKIN_TONE_KEY: &str = "preferredSkinToneIndex";11
const SKIN_TONE_KEY: &str = "preferredSkinToneIndex";12
const DEFAULT_REACTIONS_KEY: &str = "defaultMessageReactions";13
const APP_HORIZON_KEY: &str = "appConsumptionHorizon";14
const APP_HORIZON_APPS: [&str; 3] = ["chat", "channel", "engage_community"];12
const MAX_SKIN_TONE: u8 = 5;15
const MAX_SKIN_TONE: u8 = 5;13
const MUTED_FIELD: &str = "hasUserEnabledMutedChatSection";16
const MUTED_FIELD: &str = "hasUserEnabledMutedChatSection";14
const MEETING_FIELD: &str = "hasUserEnabledMeetingChatSection";17
const MEETING_FIELD: &str = "hasUserEnabledMeetingChatSection";@@ -98,6 +101,23 @@ impl<T: MessageTransport> UserSettings<T> {98
.await101
.await99
}102
}100
103
104
pub async fn set_default_reactions(&self, reaction_ids: &[String]) -> Result<()> {105
self.set_property(DEFAULT_REACTIONS_KEY, default_reactions_value(reaction_ids))106
.await107
}108
109
/// Teams' "Mark all as read" for channels: one write, the channel entry of `appConsumptionHorizon` moves to now.110
pub async fn mark_all_channels_read(&self, now_ms: i64) -> Result<AppConsumptionHorizon> {111
let properties = self.properties().await?;112
let horizon = AppConsumptionHorizon {113
channel_ms: now_ms,114
..parse_app_consumption_horizon(&properties)115
};116
self.set_property(APP_HORIZON_KEY, Value::String(horizon.property_value()))117
.await?;118
Ok(horizon)119
}120
101
pub async fn set_property(&self, name: &str, value: Value) -> Result<()> {121
pub async fn set_property(&self, name: &str, value: Value) -> Result<()> {102
let url = format!("{}?name={name}", self.base_url);122
let url = format!("{}?name={name}", self.base_url);103
let mut body = Map::new();123
let mut body = Map::new();@@ -147,6 +167,25 @@ pub fn parse_skin_tone(properties: &Value) -> Option<u8> {147
(tone <= MAX_SKIN_TONE).then_some(tone)167
(tone <= MAX_SKIN_TONE).then_some(tone)148
}168
}149
169
170
pub fn parse_default_reactions(properties: &Value) -> Option<Vec<String>> {171
let entries = match properties.get(DEFAULT_REACTIONS_KEY)? {172
Value::String(text) => serde_json::from_str::<Value>(text).ok()?,173
other => other.clone(),174
};175
entries.as_array().map(|entries| {176
entries177
.iter()178
.filter_map(Value::as_str)179
.filter(|reaction_id| !reaction_id.is_empty())180
.map(str::to_owned)181
.collect()182
})183
}184
185
pub fn default_reactions_value(reaction_ids: &[String]) -> Value {186
Value::String(Value::from(reaction_ids.to_vec()).to_string())187
}188
150
pub fn parse_teams_order(properties: &Value) -> Vec<(String, i64)> {189
pub fn parse_teams_order(properties: &Value) -> Vec<(String, i64)> {151
let entries = match properties.get(TEAMS_ORDER_KEY) {190
let entries = match properties.get(TEAMS_ORDER_KEY) {152
Some(Value::String(text)) => serde_json::from_str::<Value>(text).ok(),191
Some(Value::String(text)) => serde_json::from_str::<Value>(text).ok(),@@ -175,6 +214,54 @@ pub fn parse_teams_order(properties: &Value) -> Vec<(String, i64)> {175
order214
order176
}215
}177
216
217
/// Per app "read everything before" times in ms; Teams treats a conversation of that app as read up to it.218
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]219
pub struct AppConsumptionHorizon {220
pub chat_ms: i64,221
pub channel_ms: i64,222
pub engage_community_ms: i64,223
}224
225
impl AppConsumptionHorizon {226
pub fn property_value(&self) -> String {227
let values = [self.chat_ms, self.channel_ms, self.engage_community_ms];228
let mut fields = Map::new();229
for (app, value) in APP_HORIZON_APPS.iter().zip(values) {230
fields.insert((*app).to_owned(), Value::from(value));231
}232
Value::Object(fields).to_string()233
}234
}235
236
pub fn parse_app_consumption_horizon(properties: &Value) -> AppConsumptionHorizon {237
let parsed = match properties.get(APP_HORIZON_KEY) {238
Some(Value::String(text)) => serde_json::from_str::<Value>(text).ok(),239
Some(other) => Some(other.clone()),240
None => None,241
};242
let Some(fields) = parsed.as_ref().and_then(Value::as_object) else {243
return AppConsumptionHorizon::default();244
};245
let valid = (fields.contains_key("chat") || fields.contains_key("channel"))246
&& fields247
.values()248
.all(|value| value.as_f64().is_some_and(|number| number >= 0.0));249
if !valid {250
return AppConsumptionHorizon::default();251
}252
let read = |app: &str| {253
fields254
.get(app)255
.and_then(Value::as_f64)256
.map_or(0, |number| number as i64)257
};258
AppConsumptionHorizon {259
chat_ms: read("chat"),260
channel_ms: read("channel"),261
engage_community_ms: read("engage_community"),262
}263
}264
178
pub fn merge_chat_section(properties: &Value, section: ChatSection, enabled: bool) -> String {265
pub fn merge_chat_section(properties: &Value, section: ChatSection, enabled: bool) -> String {179
let mut settings = stored_settings(properties);266
let mut settings = stored_settings(properties);180
settings267
settings@@ -228,6 +315,53 @@ mod tests {228
assert_eq!(parse_skin_tone(&json!({})), None);315
assert_eq!(parse_skin_tone(&json!({})), None);229
}316
}230
317
318
#[test]319
fn default_reactions_are_read_from_the_json_string_or_an_array() {320
assert_eq!(321
parse_default_reactions(&json!({DEFAULT_REACTIONS_KEY: r#"["like","heart","fire"]"#})),322
Some(vec![323
"like".to_owned(),324
"heart".to_owned(),325
"fire".to_owned()326
])327
);328
assert_eq!(329
parse_default_reactions(&json!({DEFAULT_REACTIONS_KEY: ["yes", "", 3]})),330
Some(vec!["yes".to_owned()])331
);332
assert_eq!(333
parse_default_reactions(&json!({DEFAULT_REACTIONS_KEY: "[]"})),334
Some(Vec::new())335
);336
assert_eq!(parse_default_reactions(&json!({})), None);337
assert_eq!(338
parse_default_reactions(&json!({DEFAULT_REACTIONS_KEY: "not json"})),339
None340
);341
}342
343
#[tokio::test]344
async fn default_reactions_are_put_as_a_json_string() {345
let transport = Canned {346
answers: Mutex::new(vec![(200, Value::Null)].into()),347
requests: Mutex::new(Vec::new()),348
};349
UserSettings::with_transport(&transport, "emea")350
.set_default_reactions(&["like".to_owned(), "fire".to_owned()])351
.await352
.unwrap();353
let requests = transport.requests.lock().unwrap();354
assert_eq!(requests[0].method, Method::Put);355
assert_eq!(356
requests[0].url,357
"https://teams.cloud.microsoft/api/chatsvc/emea/v1/users/ME/properties?name=defaultMessageReactions"358
);359
assert_eq!(360
requests[0].body,361
Some(json!({"defaultMessageReactions": r#"["like","fire"]"#}))362
);363
}364
231
#[test]365
#[test]232
fn unset_fields_use_the_teams_defaults() {366
fn unset_fields_use_the_teams_defaults() {233
let parsed = parse_chat_sections(&json!({}));367
let parsed = parse_chat_sections(&json!({}));@@ -334,4 +468,63 @@ mod tests {334
assert_eq!(value["keep"], json!(1));468
assert_eq!(value["keep"], json!(1));335
assert_eq!(value["hasUserEnabledMutedChatSection"], json!(false));469
assert_eq!(value["hasUserEnabledMutedChatSection"], json!(false));336
}470
}471
472
#[test]473
fn app_horizon_reads_the_string_and_ignores_invalid_values() {474
let parsed = parse_app_consumption_horizon(&json!({475
"appConsumptionHorizon": "{\"chat\":1791368000000,\"channel\":1791369000000,\"engage_community\":0}"476
}));477
assert_eq!(478
parsed,479
AppConsumptionHorizon {480
chat_ms: 1791368000000,481
channel_ms: 1791369000000,482
engage_community_ms: 0,483
}484
);485
let object = parse_app_consumption_horizon(&json!({"appConsumptionHorizon": {"channel": 5}}));486
assert_eq!(object.channel_ms, 5);487
for broken in [488
json!({}),489
json!({"appConsumptionHorizon": "not json"}),490
json!({"appConsumptionHorizon": "{\"engage_community\":5}"}),491
json!({"appConsumptionHorizon": "{\"channel\":-1}"}),492
json!({"appConsumptionHorizon": "{\"channel\":\"5\"}"}),493
] {494
assert_eq!(495
parse_app_consumption_horizon(&broken),496
AppConsumptionHorizon::default()497
);498
}499
}500
501
#[tokio::test]502
async fn mark_all_channels_read_moves_only_the_channel_entry() {503
let stored = json!({504
"appConsumptionHorizon": "{\"chat\":100,\"channel\":200,\"engage_community\":300}"505
});506
let transport = Canned {507
answers: Mutex::new(vec![(200, stored), (200, Value::Null)].into()),508
requests: Mutex::new(Vec::new()),509
};510
let horizon = UserSettings::with_transport(&transport, "emea")511
.mark_all_channels_read(1791368000000)512
.await513
.unwrap();514
assert_eq!(horizon.channel_ms, 1791368000000);515
let requests = transport.requests.lock().unwrap();516
assert_eq!(requests[1].method, Method::Put);517
assert_eq!(518
requests[1].url,519
"https://teams.cloud.microsoft/api/chatsvc/emea/v1/users/ME/properties?name=appConsumptionHorizon"520
);521
let sent = requests[1].body.as_ref().unwrap()["appConsumptionHorizon"]522
.as_str()523
.unwrap();524
let value: Value = serde_json::from_str(sent).unwrap();525
assert_eq!(526
value,527
json!({"chat": 100, "channel": 1791368000000_i64, "engage_community": 300})528
);529
}337
}530
}@@ -9,6 +9,7 @@ use store::MessageRecord;
9
9
use crate::engine::{Conversation, META_USER_ID, SyncEngine};
10
10
use crate::error::{Error, Result};
11
11
use crate::external_image::external_image_url;
12
use crate::hidden_chats::cleared_until_ms;
12
13
use crate::links::LinkPreview;
13
14
use crate::mapping::message_record;
14
15
use crate::markdown::markdown_to_html;
@@ -391,6 +392,18 @@ impl<R: Remote> SyncEngine<R> {
391
392
)
392
393
.await?;
393
394
self.store.mark_channel_read(channel_id)?;
395
self.store.clear_channel_mentions(channel_id)?;
396
let _ = self.events.send(crate::events::CoreEvent::SidebarChanged);
397
Ok(())
398
}
399
400
pub async fn mark_all_channels_read(&self) -> Result<()> {
401
let horizon = self
402
.remote
403
.mark_all_channels_read(Utc::now().timestamp_millis())
404
.await?;
405
*self.app_channel_horizon_ms.lock().unwrap() = horizon.channel_ms;
406
self.store.mark_all_channels_read()?;
394
407
let _ = self.events.send(crate::events::CoreEvent::SidebarChanged);
395
408
Ok(())
396
409
}
@@ -470,6 +483,34 @@ impl<R: Remote> SyncEngine<R> {
470
483
Ok(())
471
484
}
472
485
486
/// Teams' "Remove chat history": the chat stays hidden until a message newer than the last one.
487
pub async fn remove_chat_history(&self, chat_id: &str) -> Result<()> {
488
let last_message_at = self
489
.store
490
.chat(chat_id)?
491
.and_then(|chat| chat.last_message_at);
492
let cleared_until_ms = cleared_until_ms(last_message_at, Utc::now());
493
self.remote
494
.clear_chat_history(chat_id, cleared_until_ms)
495
.await?;
496
self.with_locally_hidden(|locally| {
497
locally.hide(chat_id, last_message_at.unwrap_or_else(Utc::now))
498
})?;
499
self.store.remove_chats(&[chat_id.to_owned()])?;
500
let _ = self.events.send(crate::events::CoreEvent::SidebarChanged);
501
Ok(())
502
}
503
504
pub async fn rename_chat(&self, chat_id: &str, topic: &str) -> Result<()> {
505
self.remote.set_chat_topic(chat_id, topic).await?;
506
if let Some(mut chat) = self.store.chat(chat_id)? {
507
chat.title = topic.to_owned();
508
self.store.upsert_chats(std::slice::from_ref(&chat))?;
509
}
510
let _ = self.events.send(crate::events::CoreEvent::SidebarChanged);
511
Ok(())
512
}
513
473
514
pub async fn leave_chat(&self, chat_id: &str) -> Result<()> {
474
515
let user_id = self.my_user_id().await?;
475
516
self.remote.remove_chat_member(chat_id, &user_id).await?;
@@ -9,6 +9,7 @@ use store::MessageRecord;9
use crate::engine::{Conversation, META_USER_ID, SyncEngine};9
use crate::engine::{Conversation, META_USER_ID, SyncEngine};10
use crate::error::{Error, Result};10
use crate::error::{Error, Result};11
use crate::external_image::external_image_url;11
use crate::external_image::external_image_url;12
use crate::hidden_chats::cleared_until_ms;12
use crate::links::LinkPreview;13
use crate::links::LinkPreview;13
use crate::mapping::message_record;14
use crate::mapping::message_record;14
use crate::markdown::markdown_to_html;15
use crate::markdown::markdown_to_html;@@ -391,6 +392,18 @@ impl<R: Remote> SyncEngine<R> {391
)392
)392
.await?;393
.await?;393
self.store.mark_channel_read(channel_id)?;394
self.store.mark_channel_read(channel_id)?;395
self.store.clear_channel_mentions(channel_id)?;396
let _ = self.events.send(crate::events::CoreEvent::SidebarChanged);397
Ok(())398
}399
400
pub async fn mark_all_channels_read(&self) -> Result<()> {401
let horizon = self402
.remote403
.mark_all_channels_read(Utc::now().timestamp_millis())404
.await?;405
*self.app_channel_horizon_ms.lock().unwrap() = horizon.channel_ms;406
self.store.mark_all_channels_read()?;394
let _ = self.events.send(crate::events::CoreEvent::SidebarChanged);407
let _ = self.events.send(crate::events::CoreEvent::SidebarChanged);395
Ok(())408
Ok(())396
}409
}@@ -470,6 +483,34 @@ impl<R: Remote> SyncEngine<R> {470
Ok(())483
Ok(())471
}484
}472
485
486
/// Teams' "Remove chat history": the chat stays hidden until a message newer than the last one.487
pub async fn remove_chat_history(&self, chat_id: &str) -> Result<()> {488
let last_message_at = self489
.store490
.chat(chat_id)?491
.and_then(|chat| chat.last_message_at);492
let cleared_until_ms = cleared_until_ms(last_message_at, Utc::now());493
self.remote494
.clear_chat_history(chat_id, cleared_until_ms)495
.await?;496
self.with_locally_hidden(|locally| {497
locally.hide(chat_id, last_message_at.unwrap_or_else(Utc::now))498
})?;499
self.store.remove_chats(&[chat_id.to_owned()])?;500
let _ = self.events.send(crate::events::CoreEvent::SidebarChanged);501
Ok(())502
}503
504
pub async fn rename_chat(&self, chat_id: &str, topic: &str) -> Result<()> {505
self.remote.set_chat_topic(chat_id, topic).await?;506
if let Some(mut chat) = self.store.chat(chat_id)? {507
chat.title = topic.to_owned();508
self.store.upsert_chats(std::slice::from_ref(&chat))?;509
}510
let _ = self.events.send(crate::events::CoreEvent::SidebarChanged);511
Ok(())512
}513
473
pub async fn leave_chat(&self, chat_id: &str) -> Result<()> {514
pub async fn leave_chat(&self, chat_id: &str) -> Result<()> {474
let user_id = self.my_user_id().await?;515
let user_id = self.my_user_id().await?;475
self.remote.remove_chat_member(chat_id, &user_id).await?;516
self.remote.remove_chat_member(chat_id, &user_id).await?;@@ -0,0 +1,132 @@
1
use std::collections::{HashMap, HashSet};
2
3
use chatsvc::{ConversationState, MentionActivity, MentionKind};
4
use store::ChannelMentions;
5
6
/// Teams counts a mention only while its channel is unread, it is newer than the read horizon and not read.
7
pub fn channel_mentions(
8
activities: &[MentionActivity],
9
states: &[ConversationState],
10
my_user_id: &str,
11
app_horizon_ms: i64,
12
) -> Vec<(String, ChannelMentions)> {
13
let states: HashMap<&str, &ConversationState> = states
14
.iter()
15
.map(|state| (state.id.as_str(), state))
16
.collect();
17
let mut counted_activity_ids = HashSet::new();
18
let mut mentions: HashMap<String, ChannelMentions> = HashMap::new();
19
for activity in activities {
20
if activity.is_read || !counted_activity_ids.insert(activity.activity_id.as_str()) {
21
continue;
22
}
23
let Some(state) = states.get(activity.source_thread_id.as_str()) else {
24
continue;
25
};
26
let horizon_ms = state.read.consumed_until_ms.max(app_horizon_ms);
27
if activity.timestamp_ms <= horizon_ms
28
|| !state.read.is_unread_after(my_user_id, app_horizon_ms)
29
{
30
continue;
31
}
32
let counts = mentions
33
.entry(activity.source_thread_id.clone())
34
.or_default();
35
match activity.kind {
36
MentionKind::Personal => counts.personal += 1,
37
MentionKind::Channel => counts.channel += 1,
38
MentionKind::Team => counts.team += 1,
39
}
40
}
41
let mut mentions: Vec<(String, ChannelMentions)> = mentions.into_iter().collect();
42
mentions.sort_by(|left, right| left.0.cmp(&right.0));
43
mentions
44
}
45
46
#[cfg(test)]
47
mod tests {
48
use chatsvc::ReadHorizon;
49
50
use super::*;
51
52
const ME: &str = "8:orgid:me";
53
54
fn state(id: &str, consumed_until_ms: i64, last_message_ms: i64) -> ConversationState {
55
ConversationState {
56
id: id.to_owned(),
57
muted: false,
58
hidden: None,
59
read: ReadHorizon {
60
consumed_until_ms,
61
last_message_ms,
62
last_message_from: Some("8:orgid:someone".to_owned()),
63
..ReadHorizon::default()
64
},
65
}
66
}
67
68
fn activity(id: &str, thread: &str, kind: MentionKind, timestamp_ms: i64) -> MentionActivity {
69
MentionActivity {
70
activity_id: id.to_owned(),
71
kind,
72
source_thread_id: thread.to_owned(),
73
source_message_id: None,
74
timestamp_ms,
75
is_read: false,
76
}
77
}
78
79
fn counts(personal: u32, channel: u32, team: u32) -> ChannelMentions {
80
ChannelMentions {
81
personal,
82
channel,
83
team,
84
}
85
}
86
87
#[test]
88
fn counts_unread_mentions_after_the_horizon_per_kind() {
89
let states = [state("19:a", 100, 500), state("19:b", 100, 500)];
90
let activities = [
91
activity("1", "19:a", MentionKind::Personal, 200),
92
activity("2", "19:a", MentionKind::Personal, 300),
93
activity("2", "19:a", MentionKind::Personal, 300),
94
activity("3", "19:a", MentionKind::Channel, 300),
95
activity("4", "19:b", MentionKind::Team, 400),
96
activity("5", "19:a", MentionKind::Personal, 50),
97
MentionActivity {
98
is_read: true,
99
..activity("6", "19:b", MentionKind::Personal, 400)
100
},
101
activity("7", "19:unknown", MentionKind::Personal, 400),
102
];
103
assert_eq!(
104
channel_mentions(&activities, &states, ME, 0),
105
[
106
("19:a".to_owned(), counts(2, 1, 0)),
107
("19:b".to_owned(), counts(0, 0, 1)),
108
]
109
);
110
}
111
112
#[test]
113
fn a_read_channel_has_no_mentions() {
114
let states = [state("19:a", 600, 500)];
115
let activities = [activity("1", "19:a", MentionKind::Personal, 550)];
116
assert!(channel_mentions(&activities, &states, ME, 0).is_empty());
117
}
118
119
#[test]
120
fn mark_all_as_read_hides_older_mentions() {
121
let states = [state("19:a", 100, 900)];
122
let activities = [
123
activity("1", "19:a", MentionKind::Personal, 300),
124
activity("2", "19:a", MentionKind::Personal, 800),
125
];
126
assert_eq!(
127
channel_mentions(&activities, &states, ME, 500),
128
[("19:a".to_owned(), counts(1, 0, 0))]
129
);
130
assert!(channel_mentions(&activities, &states, ME, 950).is_empty());
131
}
132
}
@@ -0,0 +1,132 @@1
use std::collections::{HashMap, HashSet};2
3
use chatsvc::{ConversationState, MentionActivity, MentionKind};4
use store::ChannelMentions;5
6
/// Teams counts a mention only while its channel is unread, it is newer than the read horizon and not read.7
pub fn channel_mentions(8
activities: &[MentionActivity],9
states: &[ConversationState],10
my_user_id: &str,11
app_horizon_ms: i64,12
) -> Vec<(String, ChannelMentions)> {13
let states: HashMap<&str, &ConversationState> = states14
.iter()15
.map(|state| (state.id.as_str(), state))16
.collect();17
let mut counted_activity_ids = HashSet::new();18
let mut mentions: HashMap<String, ChannelMentions> = HashMap::new();19
for activity in activities {20
if activity.is_read || !counted_activity_ids.insert(activity.activity_id.as_str()) {21
continue;22
}23
let Some(state) = states.get(activity.source_thread_id.as_str()) else {24
continue;25
};26
let horizon_ms = state.read.consumed_until_ms.max(app_horizon_ms);27
if activity.timestamp_ms <= horizon_ms28
|| !state.read.is_unread_after(my_user_id, app_horizon_ms)29
{30
continue;31
}32
let counts = mentions33
.entry(activity.source_thread_id.clone())34
.or_default();35
match activity.kind {36
MentionKind::Personal => counts.personal += 1,37
MentionKind::Channel => counts.channel += 1,38
MentionKind::Team => counts.team += 1,39
}40
}41
let mut mentions: Vec<(String, ChannelMentions)> = mentions.into_iter().collect();42
mentions.sort_by(|left, right| left.0.cmp(&right.0));43
mentions44
}45
46
#[cfg(test)]47
mod tests {48
use chatsvc::ReadHorizon;49
50
use super::*;51
52
const ME: &str = "8:orgid:me";53
54
fn state(id: &str, consumed_until_ms: i64, last_message_ms: i64) -> ConversationState {55
ConversationState {56
id: id.to_owned(),57
muted: false,58
hidden: None,59
read: ReadHorizon {60
consumed_until_ms,61
last_message_ms,62
last_message_from: Some("8:orgid:someone".to_owned()),63
..ReadHorizon::default()64
},65
}66
}67
68
fn activity(id: &str, thread: &str, kind: MentionKind, timestamp_ms: i64) -> MentionActivity {69
MentionActivity {70
activity_id: id.to_owned(),71
kind,72
source_thread_id: thread.to_owned(),73
source_message_id: None,74
timestamp_ms,75
is_read: false,76
}77
}78
79
fn counts(personal: u32, channel: u32, team: u32) -> ChannelMentions {80
ChannelMentions {81
personal,82
channel,83
team,84
}85
}86
87
#[test]88
fn counts_unread_mentions_after_the_horizon_per_kind() {89
let states = [state("19:a", 100, 500), state("19:b", 100, 500)];90
let activities = [91
activity("1", "19:a", MentionKind::Personal, 200),92
activity("2", "19:a", MentionKind::Personal, 300),93
activity("2", "19:a", MentionKind::Personal, 300),94
activity("3", "19:a", MentionKind::Channel, 300),95
activity("4", "19:b", MentionKind::Team, 400),96
activity("5", "19:a", MentionKind::Personal, 50),97
MentionActivity {98
is_read: true,99
..activity("6", "19:b", MentionKind::Personal, 400)100
},101
activity("7", "19:unknown", MentionKind::Personal, 400),102
];103
assert_eq!(104
channel_mentions(&activities, &states, ME, 0),105
[106
("19:a".to_owned(), counts(2, 1, 0)),107
("19:b".to_owned(), counts(0, 0, 1)),108
]109
);110
}111
112
#[test]113
fn a_read_channel_has_no_mentions() {114
let states = [state("19:a", 600, 500)];115
let activities = [activity("1", "19:a", MentionKind::Personal, 550)];116
assert!(channel_mentions(&activities, &states, ME, 0).is_empty());117
}118
119
#[test]120
fn mark_all_as_read_hides_older_mentions() {121
let states = [state("19:a", 100, 900)];122
let activities = [123
activity("1", "19:a", MentionKind::Personal, 300),124
activity("2", "19:a", MentionKind::Personal, 800),125
];126
assert_eq!(127
channel_mentions(&activities, &states, ME, 500),128
[("19:a".to_owned(), counts(1, 0, 0))]129
);130
assert!(channel_mentions(&activities, &states, ME, 950).is_empty());131
}132
}@@ -0,0 +1,76 @@
1
use chatsvc::{ChannelKind, ChannelTarget};
2
use chrono::Utc;
3
4
use crate::engine::SyncEngine;
5
use crate::error::{Error, Result};
6
use crate::events::CoreEvent;
7
use crate::message_link::{ChannelAddress, channel_link, team_link};
8
use crate::remote::Remote;
9
10
impl<R: Remote> SyncEngine<R> {
11
pub async fn set_channel_pinned(&self, channel_id: &str, pinned: bool) -> Result<()> {
12
let channel_ids = self
13
.folder_source()?
14
.set_channel_pinned(channel_id, pinned)
15
.await?;
16
self.store.replace_pinned_channels(&channel_ids)?;
17
let _ = self.events.send(CoreEvent::FoldersChanged);
18
Ok(())
19
}
20
21
pub async fn set_channel_shown(&self, channel_id: &str, shown: bool) -> Result<()> {
22
let channel = self
23
.store
24
.channel(channel_id)?
25
.ok_or_else(|| Error::UnknownConversation(channel_id.to_owned()))?;
26
let general = self.store.team_thread_id(&channel.team_id)?.as_deref() == Some(channel_id);
27
let own_user_id = self.my_user_id().await?;
28
let target = ChannelTarget {
29
channel_id,
30
general,
31
kind: ChannelKind::from_membership_type(channel.membership_type.as_deref()),
32
};
33
self.folder_source()?
34
.set_channel_shown(target, &own_user_id, shown, Utc::now().timestamp_millis())
35
.await?;
36
self.store.set_channel_hidden(channel_id, !shown)?;
37
let _ = self.events.send(CoreEvent::SidebarChanged);
38
Ok(())
39
}
40
41
pub async fn set_team_shown(&self, team_id: &str, shown: bool) -> Result<()> {
42
let team_thread_id = self.known_team_thread_id(team_id)?;
43
self.folder_source()?
44
.set_team_shown(&team_thread_id, shown)
45
.await?;
46
self.store.set_team_hidden(team_id, !shown)?;
47
let _ = self.events.send(CoreEvent::SidebarChanged);
48
Ok(())
49
}
50
51
pub async fn channel_link(&self, channel_id: &str) -> Result<String> {
52
let channel = self
53
.store
54
.channel(channel_id)?
55
.ok_or_else(|| Error::UnknownConversation(channel_id.to_owned()))?;
56
Ok(channel_link(&ChannelAddress {
57
tenant_id: self.my_tenant_id_from_any_chat().await?,
58
group_id: channel.team_id,
59
channel_id: channel.id,
60
channel_name: channel.name,
61
membership_type: channel.membership_type,
62
}))
63
}
64
65
pub async fn team_link(&self, team_id: &str) -> Result<String> {
66
let team_thread_id = self.known_team_thread_id(team_id)?;
67
let tenant_id = self.my_tenant_id_from_any_chat().await?;
68
Ok(team_link(&team_thread_id, team_id, &tenant_id))
69
}
70
71
fn known_team_thread_id(&self, team_id: &str) -> Result<String> {
72
self.store
73
.team_thread_id(team_id)?
74
.ok_or_else(|| Error::UnknownConversation(team_id.to_owned()))
75
}
76
}
@@ -0,0 +1,76 @@1
use chatsvc::{ChannelKind, ChannelTarget};2
use chrono::Utc;3
4
use crate::engine::SyncEngine;5
use crate::error::{Error, Result};6
use crate::events::CoreEvent;7
use crate::message_link::{ChannelAddress, channel_link, team_link};8
use crate::remote::Remote;9
10
impl<R: Remote> SyncEngine<R> {11
pub async fn set_channel_pinned(&self, channel_id: &str, pinned: bool) -> Result<()> {12
let channel_ids = self13
.folder_source()?14
.set_channel_pinned(channel_id, pinned)15
.await?;16
self.store.replace_pinned_channels(&channel_ids)?;17
let _ = self.events.send(CoreEvent::FoldersChanged);18
Ok(())19
}20
21
pub async fn set_channel_shown(&self, channel_id: &str, shown: bool) -> Result<()> {22
let channel = self23
.store24
.channel(channel_id)?25
.ok_or_else(|| Error::UnknownConversation(channel_id.to_owned()))?;26
let general = self.store.team_thread_id(&channel.team_id)?.as_deref() == Some(channel_id);27
let own_user_id = self.my_user_id().await?;28
let target = ChannelTarget {29
channel_id,30
general,31
kind: ChannelKind::from_membership_type(channel.membership_type.as_deref()),32
};33
self.folder_source()?34
.set_channel_shown(target, &own_user_id, shown, Utc::now().timestamp_millis())35
.await?;36
self.store.set_channel_hidden(channel_id, !shown)?;37
let _ = self.events.send(CoreEvent::SidebarChanged);38
Ok(())39
}40
41
pub async fn set_team_shown(&self, team_id: &str, shown: bool) -> Result<()> {42
let team_thread_id = self.known_team_thread_id(team_id)?;43
self.folder_source()?44
.set_team_shown(&team_thread_id, shown)45
.await?;46
self.store.set_team_hidden(team_id, !shown)?;47
let _ = self.events.send(CoreEvent::SidebarChanged);48
Ok(())49
}50
51
pub async fn channel_link(&self, channel_id: &str) -> Result<String> {52
let channel = self53
.store54
.channel(channel_id)?55
.ok_or_else(|| Error::UnknownConversation(channel_id.to_owned()))?;56
Ok(channel_link(&ChannelAddress {57
tenant_id: self.my_tenant_id_from_any_chat().await?,58
group_id: channel.team_id,59
channel_id: channel.id,60
channel_name: channel.name,61
membership_type: channel.membership_type,62
}))63
}64
65
pub async fn team_link(&self, team_id: &str) -> Result<String> {66
let team_thread_id = self.known_team_thread_id(team_id)?;67
let tenant_id = self.my_tenant_id_from_any_chat().await?;68
Ok(team_link(&team_thread_id, team_id, &tenant_id))69
}70
71
fn known_team_thread_id(&self, team_id: &str) -> Result<String> {72
self.store73
.team_thread_id(team_id)?74
.ok_or_else(|| Error::UnknownConversation(team_id.to_owned()))75
}76
}@@ -0,0 +1,51 @@
1
use store::Store;
2
3
use crate::error::Result;
4
5
const META_ACCOUNT_DEFAULT_REACTIONS: &str = "default_reactions_account";
6
pub const TEAMS_DEFAULT_REACTIONS: [&str; 4] = ["like", "heart", "laugh", "surprised"];
7
pub const DEFAULT_REACTION_SLOTS: usize = 5;
8
9
pub fn store_account_default_reactions(
10
store: &Store,
11
reaction_ids: Option<&[String]>,
12
) -> Result<()> {
13
let value = reaction_ids
14
.map(|reaction_ids| serde_json::Value::from(reaction_ids.to_vec()).to_string())
15
.unwrap_or_default();
16
Ok(store.set_meta(META_ACCOUNT_DEFAULT_REACTIONS, &value)?)
17
}
18
19
/// The account setting `defaultMessageReactions`, Teams' own default set when it was never saved.
20
pub fn default_reactions(store: &Store) -> Vec<String> {
21
store
22
.meta(META_ACCOUNT_DEFAULT_REACTIONS)
23
.ok()
24
.flatten()
25
.filter(|stored| !stored.is_empty())
26
.and_then(|stored| serde_json::from_str::<Vec<String>>(&stored).ok())
27
.unwrap_or_else(|| {
28
TEAMS_DEFAULT_REACTIONS
29
.iter()
30
.map(|reaction_id| (*reaction_id).to_owned())
31
.collect()
32
})
33
}
34
35
#[cfg(test)]
36
mod tests {
37
use super::*;
38
39
#[test]
40
fn falls_back_to_the_teams_set_until_the_account_has_one() {
41
let store = Store::open_in_memory().unwrap();
42
assert_eq!(default_reactions(&store), TEAMS_DEFAULT_REACTIONS);
43
let saved = vec!["fire".to_owned(), "like".to_owned()];
44
store_account_default_reactions(&store, Some(&saved)).unwrap();
45
assert_eq!(default_reactions(&store), saved);
46
store_account_default_reactions(&store, Some(&[])).unwrap();
47
assert!(default_reactions(&store).is_empty());
48
store_account_default_reactions(&store, None).unwrap();
49
assert_eq!(default_reactions(&store), TEAMS_DEFAULT_REACTIONS);
50
}
51
}
@@ -0,0 +1,51 @@1
use store::Store;2
3
use crate::error::Result;4
5
const META_ACCOUNT_DEFAULT_REACTIONS: &str = "default_reactions_account";6
pub const TEAMS_DEFAULT_REACTIONS: [&str; 4] = ["like", "heart", "laugh", "surprised"];7
pub const DEFAULT_REACTION_SLOTS: usize = 5;8
9
pub fn store_account_default_reactions(10
store: &Store,11
reaction_ids: Option<&[String]>,12
) -> Result<()> {13
let value = reaction_ids14
.map(|reaction_ids| serde_json::Value::from(reaction_ids.to_vec()).to_string())15
.unwrap_or_default();16
Ok(store.set_meta(META_ACCOUNT_DEFAULT_REACTIONS, &value)?)17
}18
19
/// The account setting `defaultMessageReactions`, Teams' own default set when it was never saved.20
pub fn default_reactions(store: &Store) -> Vec<String> {21
store22
.meta(META_ACCOUNT_DEFAULT_REACTIONS)23
.ok()24
.flatten()25
.filter(|stored| !stored.is_empty())26
.and_then(|stored| serde_json::from_str::<Vec<String>>(&stored).ok())27
.unwrap_or_else(|| {28
TEAMS_DEFAULT_REACTIONS29
.iter()30
.map(|reaction_id| (*reaction_id).to_owned())31
.collect()32
})33
}34
35
#[cfg(test)]36
mod tests {37
use super::*;38
39
#[test]40
fn falls_back_to_the_teams_set_until_the_account_has_one() {41
let store = Store::open_in_memory().unwrap();42
assert_eq!(default_reactions(&store), TEAMS_DEFAULT_REACTIONS);43
let saved = vec!["fire".to_owned(), "like".to_owned()];44
store_account_default_reactions(&store, Some(&saved)).unwrap();45
assert_eq!(default_reactions(&store), saved);46
store_account_default_reactions(&store, Some(&[])).unwrap();47
assert!(default_reactions(&store).is_empty());48
store_account_default_reactions(&store, None).unwrap();49
assert_eq!(default_reactions(&store), TEAMS_DEFAULT_REACTIONS);50
}51
}@@ -131,6 +131,7 @@ pub struct SyncEngine<R: Remote = Graph> {
131
131
pub(crate) links_backfilled: Mutex<HashSet<String>>,
132
132
pub(crate) forwards_healed: Mutex<HashSet<String>>,
133
133
pub(crate) chat_states: Mutex<HashMap<String, ConversationState>>,
134
pub(crate) app_channel_horizon_ms: Mutex<i64>,
134
135
pub(crate) chat_paging: Mutex<ChatPaging>,
135
136
pub(crate) locally_hidden_lock: Mutex<()>,
136
137
pub(crate) bot_partners: Mutex<crate::bot_partners::BotPartners>,
@@ -167,6 +168,7 @@ impl<R: Remote> SyncEngine<R> {
167
168
links_backfilled: Mutex::new(HashSet::new()),
168
169
forwards_healed: Mutex::new(HashSet::new()),
169
170
chat_states: Mutex::new(HashMap::new()),
171
app_channel_horizon_ms: Mutex::new(0),
170
172
chat_paging,
171
173
locally_hidden_lock: Mutex::new(()),
172
174
bot_partners: Mutex::default(),
@@ -131,6 +131,7 @@ pub struct SyncEngine<R: Remote = Graph> {131
pub(crate) links_backfilled: Mutex<HashSet<String>>,131
pub(crate) links_backfilled: Mutex<HashSet<String>>,132
pub(crate) forwards_healed: Mutex<HashSet<String>>,132
pub(crate) forwards_healed: Mutex<HashSet<String>>,133
pub(crate) chat_states: Mutex<HashMap<String, ConversationState>>,133
pub(crate) chat_states: Mutex<HashMap<String, ConversationState>>,134
pub(crate) app_channel_horizon_ms: Mutex<i64>,134
pub(crate) chat_paging: Mutex<ChatPaging>,135
pub(crate) chat_paging: Mutex<ChatPaging>,135
pub(crate) locally_hidden_lock: Mutex<()>,136
pub(crate) locally_hidden_lock: Mutex<()>,136
pub(crate) bot_partners: Mutex<crate::bot_partners::BotPartners>,137
pub(crate) bot_partners: Mutex<crate::bot_partners::BotPartners>,@@ -167,6 +168,7 @@ impl<R: Remote> SyncEngine<R> {167
links_backfilled: Mutex::new(HashSet::new()),168
links_backfilled: Mutex::new(HashSet::new()),168
forwards_healed: Mutex::new(HashSet::new()),169
forwards_healed: Mutex::new(HashSet::new()),169
chat_states: Mutex::new(HashMap::new()),170
chat_states: Mutex::new(HashMap::new()),171
app_channel_horizon_ms: Mutex::new(0),170
chat_paging,172
chat_paging,171
locally_hidden_lock: Mutex::new(()),173
locally_hidden_lock: Mutex::new(()),172
bot_partners: Mutex::default(),174
bot_partners: Mutex::default(),@@ -3,10 +3,13 @@ use std::future::Future;
3
3
use std::pin::Pin;
4
4
use std::sync::{Arc, Mutex};
5
5
6
use chatsvc::settings::{parse_chat_sections, parse_skin_tone, parse_teams_order};
6
use chatsvc::settings::{
7
parse_chat_sections, parse_default_reactions, parse_skin_tone, parse_teams_order,
8
};
7
9
use chatsvc::{
8
ChannelNotificationLevel, ChannelNotifications, ChannelSettings, ChatSection,
9
ChatSectionSettings, Pins, UserSettings, pins::SessionTransport,
10
ChannelNotificationLevel, ChannelNotifications, ChannelSettings, ChannelTarget,
11
ChannelVisibility, ChatSection, ChatSectionSettings, Pins, UserSettings,
12
pins::SessionTransport,
10
13
};
11
14
use chrono::Utc;
12
15
use serde_json::Value;
@@ -70,6 +73,15 @@ pub trait FolderSource: Send + Sync {
70
73
fn set_skin_tone(&self, _tone: u8) -> BoxFuture<'_, Result<()>> {
71
74
Box::pin(async { Ok(()) })
72
75
}
76
fn default_reactions(&self) -> Option<Vec<String>> {
77
None
78
}
79
fn set_default_reactions<'a>(
80
&'a self,
81
_reaction_ids: &'a [String],
82
) -> BoxFuture<'a, Result<()>> {
83
Box::pin(async { Ok(()) })
84
}
73
85
fn set_section_enabled(&self, section: ChatSection, enabled: bool)
74
86
-> BoxFuture<'_, Result<()>>;
75
87
fn set_folder_expanded<'a>(
@@ -89,14 +101,39 @@ pub trait FolderSource: Send + Sync {
89
101
folder_id: &'a str,
90
102
) -> BoxFuture<'a, Result<Vec<ChatFolder>>>;
91
103
fn change_folders(&self, change: FolderChange) -> BoxFuture<'_, Result<Vec<ChatFolder>>>;
104
fn set_channel_pinned<'a>(
105
&'a self,
106
_channel_id: &'a str,
107
_pinned: bool,
108
) -> BoxFuture<'a, Result<Vec<String>>> {
109
Box::pin(async { Err(Error::Unsupported("channel pins without chatsvc")) })
110
}
111
fn set_channel_shown<'a>(
112
&'a self,
113
_target: ChannelTarget<'a>,
114
_own_user_id: &'a str,
115
_shown: bool,
116
_now_ms: i64,
117
) -> BoxFuture<'a, Result<()>> {
118
Box::pin(async { Err(Error::Unsupported("channel visibility without chatsvc")) })
119
}
120
fn set_team_shown<'a>(
121
&'a self,
122
_team_thread_id: &'a str,
123
_shown: bool,
124
) -> BoxFuture<'a, Result<()>> {
125
Box::pin(async { Err(Error::Unsupported("team visibility without chatsvc")) })
126
}
92
127
}
93
128
94
129
pub struct ChatsvcFolderSource {
95
130
pins: Pins<SessionTransport>,
131
visibility: ChannelVisibility,
96
132
settings: UserSettings,
97
133
channel_settings: ChannelSettings,
98
134
properties: Mutex<Option<Value>>,
99
135
skin_tone: Mutex<Option<u8>>,
136
default_reactions: Mutex<Option<Vec<String>>>,
100
137
group_ids: Mutex<HashMap<String, String>>,
101
138
}
102
139
@@ -104,10 +141,12 @@ impl ChatsvcFolderSource {
104
141
pub fn new(session: &Session) -> Self {
105
142
ChatsvcFolderSource {
106
143
pins: Pins::new(session),
144
visibility: ChannelVisibility::new(session),
107
145
settings: UserSettings::new(session),
108
146
channel_settings: ChannelSettings::new(session),
109
147
properties: Mutex::new(None),
110
148
skin_tone: Mutex::new(None),
149
default_reactions: Mutex::new(None),
111
150
group_ids: Mutex::new(HashMap::new()),
112
151
}
113
152
}
@@ -122,6 +161,49 @@ impl FolderSource for ChatsvcFolderSource {
122
161
Box::pin(async { Ok(self.pins.pinned_channels().await?.channel_ids) })
123
162
}
124
163
164
fn set_channel_pinned<'a>(
165
&'a self,
166
channel_id: &'a str,
167
pinned: bool,
168
) -> BoxFuture<'a, Result<Vec<String>>> {
169
Box::pin(async move {
170
let answer = if pinned {
171
self.pins.pin_channel(channel_id).await?
172
} else {
173
self.pins.unpin_channel(channel_id).await?
174
};
175
Ok(answer.channel_ids)
176
})
177
}
178
179
fn set_channel_shown<'a>(
180
&'a self,
181
target: ChannelTarget<'a>,
182
own_user_id: &'a str,
183
shown: bool,
184
now_ms: i64,
185
) -> BoxFuture<'a, Result<()>> {
186
Box::pin(async move {
187
Ok(self
188
.visibility
189
.set_channel_shown(&target, own_user_id, shown, now_ms)
190
.await?)
191
})
192
}
193
194
fn set_team_shown<'a>(
195
&'a self,
196
team_thread_id: &'a str,
197
shown: bool,
198
) -> BoxFuture<'a, Result<()>> {
199
Box::pin(async move {
200
Ok(self
201
.visibility
202
.set_team_shown(team_thread_id, shown)
203
.await?)
204
})
205
}
206
125
207
fn team_layout(&self) -> BoxFuture<'_, Result<Vec<TeamLayoutRecord>>> {
126
208
Box::pin(async {
127
209
let layout = self.pins.team_layout().await?;
@@ -152,6 +234,7 @@ impl FolderSource for ChatsvcFolderSource {
152
234
let properties = self.settings.properties().await?;
153
235
let sections = parse_chat_sections(&properties);
154
236
*self.skin_tone.lock().unwrap() = parse_skin_tone(&properties);
237
*self.default_reactions.lock().unwrap() = parse_default_reactions(&properties);
155
238
*self.properties.lock().unwrap() = Some(properties);
156
239
Ok(sections)
157
240
})
@@ -165,6 +248,17 @@ impl FolderSource for ChatsvcFolderSource {
165
248
Box::pin(async move { Ok(self.settings.set_skin_tone(tone).await?) })
166
249
}
167
250
251
fn default_reactions(&self) -> Option<Vec<String>> {
252
self.default_reactions.lock().unwrap().clone()
253
}
254
255
fn set_default_reactions<'a>(
256
&'a self,
257
reaction_ids: &'a [String],
258
) -> BoxFuture<'a, Result<()>> {
259
Box::pin(async move { Ok(self.settings.set_default_reactions(reaction_ids).await?) })
260
}
261
168
262
fn teams_order(&self) -> BoxFuture<'_, Result<Vec<(String, i64)>>> {
169
263
Box::pin(async {
170
264
let cached = self.properties.lock().unwrap().take();
@@ -480,12 +574,18 @@ impl<R: Remote> SyncEngine<R> {
480
574
481
575
async fn refresh_section_settings(&self, source: &Arc<dyn FolderSource>) {
482
576
let outcome = match source.section_settings().await {
483
Ok(settings) => self.apply_section_settings(&settings).and_then(|()| {
484
match source.preferred_skin_tone() {
577
Ok(settings) => self
578
.apply_section_settings(&settings)
579
.and_then(|()| match source.preferred_skin_tone() {
485
580
Some(tone) => crate::skin_tone::store_account_skin_tone(&self.store, tone),
486
581
None => Ok(()),
487
}
488
}),
582
})
583
.and_then(|()| {
584
crate::default_reactions::store_account_default_reactions(
585
&self.store,
586
source.default_reactions().as_deref(),
587
)
588
}),
489
589
Err(error) => Err(error),
490
590
};
491
591
if let Err(error) = outcome {
@@ -512,6 +612,13 @@ impl<R: Remote> SyncEngine<R> {
512
612
crate::skin_tone::store_account_skin_tone(&self.store, tone)
513
613
}
514
614
615
pub async fn set_default_reactions(&self, reaction_ids: &[String]) -> Result<()> {
616
self.folder_source()?
617
.set_default_reactions(reaction_ids)
618
.await?;
619
crate::default_reactions::store_account_default_reactions(&self.store, Some(reaction_ids))
620
}
621
515
622
pub async fn set_folder_expanded(&self, folder_id: &str, expanded: bool) -> Result<()> {
516
623
self.folder_source()?
517
624
.set_folder_expanded(folder_id, expanded)
@@ -567,13 +674,17 @@ impl<R: Remote> SyncEngine<R> {
567
674
self.store_folders(&folders, &self.store.pinned_channel_ids()?)
568
675
}
569
676
570
fn folder_source(&self) -> Result<&Arc<dyn FolderSource>> {
677
pub(crate) fn folder_source(&self) -> Result<&Arc<dyn FolderSource>> {
571
678
self.folder_source
572
679
.as_ref()
573
680
.ok_or(Error::Unsupported("chat folders without a folder source"))
574
681
}
575
682
576
fn store_folders(&self, folders: &[ChatFolder], channel_ids: &[String]) -> Result<()> {
683
pub(crate) fn store_folders(
684
&self,
685
folders: &[ChatFolder],
686
channel_ids: &[String],
687
) -> Result<()> {
577
688
let previous = (self.chat_folders()?, self.store.pinned_channel_ids()?);
578
689
let records: Vec<FolderRecord> = folders.iter().map(to_record).collect();
579
690
self.store.replace_folders(&records, channel_ids)?;
@@ -3,10 +3,13 @@ use std::future::Future;3
use std::pin::Pin;3
use std::pin::Pin;4
use std::sync::{Arc, Mutex};4
use std::sync::{Arc, Mutex};5
5
6
use chatsvc::settings::{parse_chat_sections, parse_skin_tone, parse_teams_order};6
use chatsvc::settings::{7
parse_chat_sections, parse_default_reactions, parse_skin_tone, parse_teams_order,8
};7
use chatsvc::{9
use chatsvc::{8
ChannelNotificationLevel, ChannelNotifications, ChannelSettings, ChatSection,10
ChannelNotificationLevel, ChannelNotifications, ChannelSettings, ChannelTarget,9
ChatSectionSettings, Pins, UserSettings, pins::SessionTransport,11
ChannelVisibility, ChatSection, ChatSectionSettings, Pins, UserSettings,12
pins::SessionTransport,10
};13
};11
use chrono::Utc;14
use chrono::Utc;12
use serde_json::Value;15
use serde_json::Value;@@ -70,6 +73,15 @@ pub trait FolderSource: Send + Sync {70
fn set_skin_tone(&self, _tone: u8) -> BoxFuture<'_, Result<()>> {73
fn set_skin_tone(&self, _tone: u8) -> BoxFuture<'_, Result<()>> {71
Box::pin(async { Ok(()) })74
Box::pin(async { Ok(()) })72
}75
}76
fn default_reactions(&self) -> Option<Vec<String>> {77
None78
}79
fn set_default_reactions<'a>(80
&'a self,81
_reaction_ids: &'a [String],82
) -> BoxFuture<'a, Result<()>> {83
Box::pin(async { Ok(()) })84
}73
fn set_section_enabled(&self, section: ChatSection, enabled: bool)85
fn set_section_enabled(&self, section: ChatSection, enabled: bool)74
-> BoxFuture<'_, Result<()>>;86
-> BoxFuture<'_, Result<()>>;75
fn set_folder_expanded<'a>(87
fn set_folder_expanded<'a>(@@ -89,14 +101,39 @@ pub trait FolderSource: Send + Sync {89
folder_id: &'a str,101
folder_id: &'a str,90
) -> BoxFuture<'a, Result<Vec<ChatFolder>>>;102
) -> BoxFuture<'a, Result<Vec<ChatFolder>>>;91
fn change_folders(&self, change: FolderChange) -> BoxFuture<'_, Result<Vec<ChatFolder>>>;103
fn change_folders(&self, change: FolderChange) -> BoxFuture<'_, Result<Vec<ChatFolder>>>;104
fn set_channel_pinned<'a>(105
&'a self,106
_channel_id: &'a str,107
_pinned: bool,108
) -> BoxFuture<'a, Result<Vec<String>>> {109
Box::pin(async { Err(Error::Unsupported("channel pins without chatsvc")) })110
}111
fn set_channel_shown<'a>(112
&'a self,113
_target: ChannelTarget<'a>,114
_own_user_id: &'a str,115
_shown: bool,116
_now_ms: i64,117
) -> BoxFuture<'a, Result<()>> {118
Box::pin(async { Err(Error::Unsupported("channel visibility without chatsvc")) })119
}120
fn set_team_shown<'a>(121
&'a self,122
_team_thread_id: &'a str,123
_shown: bool,124
) -> BoxFuture<'a, Result<()>> {125
Box::pin(async { Err(Error::Unsupported("team visibility without chatsvc")) })126
}92
}127
}93
128
94
pub struct ChatsvcFolderSource {129
pub struct ChatsvcFolderSource {95
pins: Pins<SessionTransport>,130
pins: Pins<SessionTransport>,131
visibility: ChannelVisibility,96
settings: UserSettings,132
settings: UserSettings,97
channel_settings: ChannelSettings,133
channel_settings: ChannelSettings,98
properties: Mutex<Option<Value>>,134
properties: Mutex<Option<Value>>,99
skin_tone: Mutex<Option<u8>>,135
skin_tone: Mutex<Option<u8>>,136
default_reactions: Mutex<Option<Vec<String>>>,100
group_ids: Mutex<HashMap<String, String>>,137
group_ids: Mutex<HashMap<String, String>>,101
}138
}102
139
@@ -104,10 +141,12 @@ impl ChatsvcFolderSource {104
pub fn new(session: &Session) -> Self {141
pub fn new(session: &Session) -> Self {105
ChatsvcFolderSource {142
ChatsvcFolderSource {106
pins: Pins::new(session),143
pins: Pins::new(session),144
visibility: ChannelVisibility::new(session),107
settings: UserSettings::new(session),145
settings: UserSettings::new(session),108
channel_settings: ChannelSettings::new(session),146
channel_settings: ChannelSettings::new(session),109
properties: Mutex::new(None),147
properties: Mutex::new(None),110
skin_tone: Mutex::new(None),148
skin_tone: Mutex::new(None),149
default_reactions: Mutex::new(None),111
group_ids: Mutex::new(HashMap::new()),150
group_ids: Mutex::new(HashMap::new()),112
}151
}113
}152
}@@ -122,6 +161,49 @@ impl FolderSource for ChatsvcFolderSource {122
Box::pin(async { Ok(self.pins.pinned_channels().await?.channel_ids) })161
Box::pin(async { Ok(self.pins.pinned_channels().await?.channel_ids) })123
}162
}124
163
164
fn set_channel_pinned<'a>(165
&'a self,166
channel_id: &'a str,167
pinned: bool,168
) -> BoxFuture<'a, Result<Vec<String>>> {169
Box::pin(async move {170
let answer = if pinned {171
self.pins.pin_channel(channel_id).await?172
} else {173
self.pins.unpin_channel(channel_id).await?174
};175
Ok(answer.channel_ids)176
})177
}178
179
fn set_channel_shown<'a>(180
&'a self,181
target: ChannelTarget<'a>,182
own_user_id: &'a str,183
shown: bool,184
now_ms: i64,185
) -> BoxFuture<'a, Result<()>> {186
Box::pin(async move {187
Ok(self188
.visibility189
.set_channel_shown(&target, own_user_id, shown, now_ms)190
.await?)191
})192
}193
194
fn set_team_shown<'a>(195
&'a self,196
team_thread_id: &'a str,197
shown: bool,198
) -> BoxFuture<'a, Result<()>> {199
Box::pin(async move {200
Ok(self201
.visibility202
.set_team_shown(team_thread_id, shown)203
.await?)204
})205
}206
125
fn team_layout(&self) -> BoxFuture<'_, Result<Vec<TeamLayoutRecord>>> {207
fn team_layout(&self) -> BoxFuture<'_, Result<Vec<TeamLayoutRecord>>> {126
Box::pin(async {208
Box::pin(async {127
let layout = self.pins.team_layout().await?;209
let layout = self.pins.team_layout().await?;@@ -152,6 +234,7 @@ impl FolderSource for ChatsvcFolderSource {152
let properties = self.settings.properties().await?;234
let properties = self.settings.properties().await?;153
let sections = parse_chat_sections(&properties);235
let sections = parse_chat_sections(&properties);154
*self.skin_tone.lock().unwrap() = parse_skin_tone(&properties);236
*self.skin_tone.lock().unwrap() = parse_skin_tone(&properties);237
*self.default_reactions.lock().unwrap() = parse_default_reactions(&properties);155
*self.properties.lock().unwrap() = Some(properties);238
*self.properties.lock().unwrap() = Some(properties);156
Ok(sections)239
Ok(sections)157
})240
})@@ -165,6 +248,17 @@ impl FolderSource for ChatsvcFolderSource {165
Box::pin(async move { Ok(self.settings.set_skin_tone(tone).await?) })248
Box::pin(async move { Ok(self.settings.set_skin_tone(tone).await?) })166
}249
}167
250
251
fn default_reactions(&self) -> Option<Vec<String>> {252
self.default_reactions.lock().unwrap().clone()253
}254
255
fn set_default_reactions<'a>(256
&'a self,257
reaction_ids: &'a [String],258
) -> BoxFuture<'a, Result<()>> {259
Box::pin(async move { Ok(self.settings.set_default_reactions(reaction_ids).await?) })260
}261
168
fn teams_order(&self) -> BoxFuture<'_, Result<Vec<(String, i64)>>> {262
fn teams_order(&self) -> BoxFuture<'_, Result<Vec<(String, i64)>>> {169
Box::pin(async {263
Box::pin(async {170
let cached = self.properties.lock().unwrap().take();264
let cached = self.properties.lock().unwrap().take();@@ -480,12 +574,18 @@ impl<R: Remote> SyncEngine<R> {480
574
481
async fn refresh_section_settings(&self, source: &Arc<dyn FolderSource>) {575
async fn refresh_section_settings(&self, source: &Arc<dyn FolderSource>) {482
let outcome = match source.section_settings().await {576
let outcome = match source.section_settings().await {483
Ok(settings) => self.apply_section_settings(&settings).and_then(|()| {577
Ok(settings) => self484
match source.preferred_skin_tone() {578
.apply_section_settings(&settings)579
.and_then(|()| match source.preferred_skin_tone() {485
Some(tone) => crate::skin_tone::store_account_skin_tone(&self.store, tone),580
Some(tone) => crate::skin_tone::store_account_skin_tone(&self.store, tone),486
None => Ok(()),581
None => Ok(()),487
}582
})488
}),583
.and_then(|()| {584
crate::default_reactions::store_account_default_reactions(585
&self.store,586
source.default_reactions().as_deref(),587
)588
}),489
Err(error) => Err(error),589
Err(error) => Err(error),490
};590
};491
if let Err(error) = outcome {591
if let Err(error) = outcome {@@ -512,6 +612,13 @@ impl<R: Remote> SyncEngine<R> {512
crate::skin_tone::store_account_skin_tone(&self.store, tone)612
crate::skin_tone::store_account_skin_tone(&self.store, tone)513
}613
}514
614
615
pub async fn set_default_reactions(&self, reaction_ids: &[String]) -> Result<()> {616
self.folder_source()?617
.set_default_reactions(reaction_ids)618
.await?;619
crate::default_reactions::store_account_default_reactions(&self.store, Some(reaction_ids))620
}621
515
pub async fn set_folder_expanded(&self, folder_id: &str, expanded: bool) -> Result<()> {622
pub async fn set_folder_expanded(&self, folder_id: &str, expanded: bool) -> Result<()> {516
self.folder_source()?623
self.folder_source()?517
.set_folder_expanded(folder_id, expanded)624
.set_folder_expanded(folder_id, expanded)@@ -567,13 +674,17 @@ impl<R: Remote> SyncEngine<R> {567
self.store_folders(&folders, &self.store.pinned_channel_ids()?)674
self.store_folders(&folders, &self.store.pinned_channel_ids()?)568
}675
}569
676
570
fn folder_source(&self) -> Result<&Arc<dyn FolderSource>> {677
pub(crate) fn folder_source(&self) -> Result<&Arc<dyn FolderSource>> {571
self.folder_source678
self.folder_source572
.as_ref()679
.as_ref()573
.ok_or(Error::Unsupported("chat folders without a folder source"))680
.ok_or(Error::Unsupported("chat folders without a folder source"))574
}681
}575
682
576
fn store_folders(&self, folders: &[ChatFolder], channel_ids: &[String]) -> Result<()> {683
pub(crate) fn store_folders(684
&self,685
folders: &[ChatFolder],686
channel_ids: &[String],687
) -> Result<()> {577
let previous = (self.chat_folders()?, self.store.pinned_channel_ids()?);688
let previous = (self.chat_folders()?, self.store.pinned_channel_ids()?);578
let records: Vec<FolderRecord> = folders.iter().map(to_record).collect();689
let records: Vec<FolderRecord> = folders.iter().map(to_record).collect();579
self.store.replace_folders(&records, channel_ids)?;690
self.store.replace_folders(&records, channel_ids)?;@@ -11,8 +11,11 @@ mod card_layout;
11
11
mod card_table;
12
12
mod card_widgets;
13
13
mod card_width;
14
mod channel_mentions;
14
15
mod channel_sync;
16
mod channel_visibility;
15
17
mod chat_paging;
18
mod default_reactions;
16
19
mod download;
17
20
mod draft;
18
21
mod emoticon_tags;
@@ -106,6 +109,10 @@ pub use chatsvc::{
106
109
TranslationStatus, TranslationTrigger, authoring_patch, behavior_patch, language_code,
107
110
parse_language_settings, target_patch,
108
111
};
112
pub use default_reactions::{
113
DEFAULT_REACTION_SLOTS, TEAMS_DEFAULT_REACTIONS, default_reactions,
114
store_account_default_reactions,
115
};
109
116
pub use download::LibraryFile;
110
117
pub use draft::{
111
118
Draft, DraftLine, Edit, FormatState, LineKind, MAX_DEPTH, Mark, MarkKind, OBJECT_MARK,
@@ -139,7 +146,8 @@ pub use meeting_join::{
139
146
};
140
147
pub use mentions::{MentionInput, apply_mentions, plain_mention_spans};
141
148
pub use message_link::{
142
ChannelLinkInput, channel_message_link, channel_tab_link, chat_message_link,
149
ChannelAddress, ChannelLinkInput, channel_link, channel_message_link, channel_tab_link,
150
chat_message_link, team_link,
143
151
};
144
152
pub use message_window::{JumpPlan, WINDOW_PAGE_SIZE, WindowPage, jump_plan, without_islands};
145
153
pub use notes_chat::{is_notes_chat, notes_chat_title};
@@ -11,8 +11,11 @@ mod card_layout;11
mod card_table;11
mod card_table;12
mod card_widgets;12
mod card_widgets;13
mod card_width;13
mod card_width;14
mod channel_mentions;14
mod channel_sync;15
mod channel_sync;16
mod channel_visibility;15
mod chat_paging;17
mod chat_paging;18
mod default_reactions;16
mod download;19
mod download;17
mod draft;20
mod draft;18
mod emoticon_tags;21
mod emoticon_tags;@@ -106,6 +109,10 @@ pub use chatsvc::{106
TranslationStatus, TranslationTrigger, authoring_patch, behavior_patch, language_code,109
TranslationStatus, TranslationTrigger, authoring_patch, behavior_patch, language_code,107
parse_language_settings, target_patch,110
parse_language_settings, target_patch,108
};111
};112
pub use default_reactions::{113
DEFAULT_REACTION_SLOTS, TEAMS_DEFAULT_REACTIONS, default_reactions,114
store_account_default_reactions,115
};109
pub use download::LibraryFile;116
pub use download::LibraryFile;110
pub use draft::{117
pub use draft::{111
Draft, DraftLine, Edit, FormatState, LineKind, MAX_DEPTH, Mark, MarkKind, OBJECT_MARK,118
Draft, DraftLine, Edit, FormatState, LineKind, MAX_DEPTH, Mark, MarkKind, OBJECT_MARK,@@ -139,7 +146,8 @@ pub use meeting_join::{139
};146
};140
pub use mentions::{MentionInput, apply_mentions, plain_mention_spans};147
pub use mentions::{MentionInput, apply_mentions, plain_mention_spans};141
pub use message_link::{148
pub use message_link::{142
ChannelLinkInput, channel_message_link, channel_tab_link, chat_message_link,149
ChannelAddress, ChannelLinkInput, channel_link, channel_message_link, channel_tab_link,150
chat_message_link, team_link,143
};151
};144
pub use message_window::{JumpPlan, WINDOW_PAGE_SIZE, WindowPage, jump_plan, without_islands};152
pub use message_window::{JumpPlan, WINDOW_PAGE_SIZE, WindowPage, jump_plan, without_islands};145
pub use notes_chat::{is_notes_chat, notes_chat_title};153
pub use notes_chat::{is_notes_chat, notes_chat_title};@@ -68,32 +68,78 @@ impl<R: Remote> SyncEngine<R> {
68
68
self.remote.list_call_logs().await
69
69
}
70
70
71
pub async fn chat_pins(&self, chat_id: &str) -> Result<Vec<PinnedMessage>> {
72
self.ensure_chat(chat_id)?;
73
self.remote.chat_pins(chat_id).await
71
pub async fn chat_pins(&self, conversation_id: &str) -> Result<Vec<PinnedMessage>> {
72
match self.resolve_stored(conversation_id)? {
73
Conversation::Chat => self.remote.chat_pins(conversation_id).await,
74
Conversation::Channel { team_id } => {
75
let team_thread_id = self.team_thread_id(&team_id)?;
76
self.remote
77
.channel_pinned_posts(&team_thread_id, conversation_id)
78
.await
79
}
80
}
74
81
}
75
82
76
pub async fn pin_message(&self, chat_id: &str, message_id: &str) -> Result<()> {
77
self.ensure_chat(chat_id)?;
78
self.remote.pin_message(chat_id, message_id).await?;
79
self.announce_pins(chat_id);
83
pub async fn pin_message(&self, conversation_id: &str, message_id: &str) -> Result<()> {
84
match self.resolve_stored(conversation_id)? {
85
Conversation::Chat => self.remote.pin_message(conversation_id, message_id).await?,
86
Conversation::Channel { team_id } => {
87
self.set_post_pinned(&team_id, conversation_id, message_id, true)
88
.await?
89
}
90
}
91
self.announce_pins(conversation_id);
80
92
Ok(())
81
93
}
82
94
83
95
pub async fn unpin_message(
84
96
&self,
85
chat_id: &str,
97
conversation_id: &str,
86
98
message_id: &str,
87
99
parent_id: Option<&str>,
88
100
) -> Result<()> {
89
self.ensure_chat(chat_id)?;
90
self.remote
91
.unpin_message(chat_id, message_id, parent_id)
92
.await?;
93
self.announce_pins(chat_id);
101
match self.resolve_stored(conversation_id)? {
102
Conversation::Chat => {
103
self.remote
104
.unpin_message(conversation_id, message_id, parent_id)
105
.await?
106
}
107
Conversation::Channel { team_id } => {
108
self.set_post_pinned(&team_id, conversation_id, message_id, false)
109
.await?
110
}
111
}
112
self.announce_pins(conversation_id);
94
113
Ok(())
95
114
}
96
115
116
async fn set_post_pinned(
117
&self,
118
team_id: &str,
119
channel_id: &str,
120
post_id: &str,
121
pinned: bool,
122
) -> Result<()> {
123
let is_reply = self
124
.store
125
.messages_by_id(channel_id, &[post_id.to_owned()])?
126
.get(post_id)
127
.is_some_and(|record| record.reply_to_id.is_some());
128
if is_reply {
129
return Err(Error::Unsupported("pinning a channel reply"));
130
}
131
let team_thread_id = self.team_thread_id(team_id)?;
132
self.remote
133
.set_post_pinned(&team_thread_id, channel_id, post_id, pinned)
134
.await
135
}
136
137
fn team_thread_id(&self, team_id: &str) -> Result<String> {
138
self.store
139
.team_thread_id(team_id)?
140
.ok_or_else(|| Error::UnknownConversation(team_id.to_owned()))
141
}
142
97
143
pub async fn message_link(&self, conversation_id: &str, message_id: &str) -> Result<String> {
98
144
let Conversation::Channel { team_id } = self.resolve(conversation_id).await? else {
99
145
let notes_oid = if conversation_id == NOTES_CHAT_ID {
@@ -153,13 +199,6 @@ impl<R: Remote> SyncEngine<R> {
153
199
}
154
200
}
155
201
156
fn ensure_chat(&self, conversation_id: &str) -> Result<()> {
157
match self.resolve_stored(conversation_id)? {
158
Conversation::Chat => Ok(()),
159
Conversation::Channel { .. } => Err(Error::Unsupported("pinned messages in a channel")),
160
}
161
}
162
163
202
fn announce_pins(&self, conversation_id: &str) {
164
203
let _ = self.events.send(CoreEvent::PinsChanged {
165
204
conversation_id: conversation_id.to_owned(),
@@ -68,32 +68,78 @@ impl<R: Remote> SyncEngine<R> {68
self.remote.list_call_logs().await68
self.remote.list_call_logs().await69
}69
}70
70
71
pub async fn chat_pins(&self, chat_id: &str) -> Result<Vec<PinnedMessage>> {71
pub async fn chat_pins(&self, conversation_id: &str) -> Result<Vec<PinnedMessage>> {72
self.ensure_chat(chat_id)?;72
match self.resolve_stored(conversation_id)? {73
self.remote.chat_pins(chat_id).await73
Conversation::Chat => self.remote.chat_pins(conversation_id).await,74
Conversation::Channel { team_id } => {75
let team_thread_id = self.team_thread_id(&team_id)?;76
self.remote77
.channel_pinned_posts(&team_thread_id, conversation_id)78
.await79
}80
}74
}81
}75
82
76
pub async fn pin_message(&self, chat_id: &str, message_id: &str) -> Result<()> {83
pub async fn pin_message(&self, conversation_id: &str, message_id: &str) -> Result<()> {77
self.ensure_chat(chat_id)?;84
match self.resolve_stored(conversation_id)? {78
self.remote.pin_message(chat_id, message_id).await?;85
Conversation::Chat => self.remote.pin_message(conversation_id, message_id).await?,79
self.announce_pins(chat_id);86
Conversation::Channel { team_id } => {87
self.set_post_pinned(&team_id, conversation_id, message_id, true)88
.await?89
}90
}91
self.announce_pins(conversation_id);80
Ok(())92
Ok(())81
}93
}82
94
83
pub async fn unpin_message(95
pub async fn unpin_message(84
&self,96
&self,85
chat_id: &str,97
conversation_id: &str,86
message_id: &str,98
message_id: &str,87
parent_id: Option<&str>,99
parent_id: Option<&str>,88
) -> Result<()> {100
) -> Result<()> {89
self.ensure_chat(chat_id)?;101
match self.resolve_stored(conversation_id)? {90
self.remote102
Conversation::Chat => {91
.unpin_message(chat_id, message_id, parent_id)103
self.remote92
.await?;104
.unpin_message(conversation_id, message_id, parent_id)93
self.announce_pins(chat_id);105
.await?106
}107
Conversation::Channel { team_id } => {108
self.set_post_pinned(&team_id, conversation_id, message_id, false)109
.await?110
}111
}112
self.announce_pins(conversation_id);94
Ok(())113
Ok(())95
}114
}96
115
116
async fn set_post_pinned(117
&self,118
team_id: &str,119
channel_id: &str,120
post_id: &str,121
pinned: bool,122
) -> Result<()> {123
let is_reply = self124
.store125
.messages_by_id(channel_id, &[post_id.to_owned()])?126
.get(post_id)127
.is_some_and(|record| record.reply_to_id.is_some());128
if is_reply {129
return Err(Error::Unsupported("pinning a channel reply"));130
}131
let team_thread_id = self.team_thread_id(team_id)?;132
self.remote133
.set_post_pinned(&team_thread_id, channel_id, post_id, pinned)134
.await135
}136
137
fn team_thread_id(&self, team_id: &str) -> Result<String> {138
self.store139
.team_thread_id(team_id)?140
.ok_or_else(|| Error::UnknownConversation(team_id.to_owned()))141
}142
97
pub async fn message_link(&self, conversation_id: &str, message_id: &str) -> Result<String> {143
pub async fn message_link(&self, conversation_id: &str, message_id: &str) -> Result<String> {98
let Conversation::Channel { team_id } = self.resolve(conversation_id).await? else {144
let Conversation::Channel { team_id } = self.resolve(conversation_id).await? else {99
let notes_oid = if conversation_id == NOTES_CHAT_ID {145
let notes_oid = if conversation_id == NOTES_CHAT_ID {@@ -153,13 +199,6 @@ impl<R: Remote> SyncEngine<R> {153
}199
}154
}200
}155
201
156
fn ensure_chat(&self, conversation_id: &str) -> Result<()> {157
match self.resolve_stored(conversation_id)? {158
Conversation::Chat => Ok(()),159
Conversation::Channel { .. } => Err(Error::Unsupported("pinned messages in a channel")),160
}161
}162
163
fn announce_pins(&self, conversation_id: &str) {202
fn announce_pins(&self, conversation_id: &str) {164
let _ = self.events.send(CoreEvent::PinsChanged {203
let _ = self.events.send(CoreEvent::PinsChanged {165
conversation_id: conversation_id.to_owned(),204
conversation_id: conversation_id.to_owned(),@@ -2,6 +2,7 @@ use percent_encoding::{AsciiSet, NON_ALPHANUMERIC, utf8_percent_encode};
2
2
use serde_json::json;
3
3
4
4
const LINK_HOST: &str = "https://teams.microsoft.com";
5
const DEEP_LINK_HOST: &str = "https://teams.cloud.microsoft";
5
6
6
7
const ENCODE_COMPONENT: &AsciiSet = &NON_ALPHANUMERIC
7
8
.remove(b'-')
@@ -68,6 +69,38 @@ pub fn channel_tab_link(channel_id: &str, tab_id: &str, label: &str) -> String {
68
69
)
69
70
}
70
71
72
#[derive(Debug, Clone, PartialEq, Eq)]
73
pub struct ChannelAddress {
74
pub tenant_id: String,
75
pub group_id: String,
76
pub channel_id: String,
77
pub channel_name: String,
78
pub membership_type: Option<String>,
79
}
80
81
pub fn channel_link(address: &ChannelAddress) -> String {
82
let separate_roster = address.membership_type.as_deref().is_some_and(|kind| {
83
kind.eq_ignore_ascii_case("private") || kind.eq_ignore_ascii_case("shared")
84
});
85
format!(
86
"{DEEP_LINK_HOST}/l/channel/{}/{}?groupId={}&tenantId={}{}",
87
encode(&address.channel_id),
88
encode(&address.channel_name),
89
encode(&address.group_id),
90
encode(&address.tenant_id),
91
if separate_roster { "&ngc=true" } else { "" }
92
)
93
}
94
95
pub fn team_link(team_thread_id: &str, group_id: &str, tenant_id: &str) -> String {
96
format!(
97
"{DEEP_LINK_HOST}/l/team/{}/conversations?groupId={}&tenantId={}",
98
encode(team_thread_id),
99
encode(group_id),
100
encode(tenant_id)
101
)
102
}
103
71
104
#[cfg(test)]
72
105
mod tests {
73
106
use super::*;
@@ -113,4 +146,38 @@ mod tests {
113
146
"https://teams.microsoft.com/l/channel/19:chan@thread.tacv2/tab%3A%3Aa1-b2?label=Sprint%20board"
114
147
);
115
148
}
149
150
fn address(membership_type: Option<&str>) -> ChannelAddress {
151
ChannelAddress {
152
tenant_id: "tenant-1".into(),
153
group_id: "group-1".into(),
154
channel_id: "19:chan@thread.tacv2".into(),
155
channel_name: "R&D News".into(),
156
membership_type: membership_type.map(str::to_owned),
157
}
158
}
159
160
#[test]
161
fn channel_link_encodes_the_id_and_name_like_teams() {
162
assert_eq!(
163
channel_link(&address(Some("standard"))),
164
"https://teams.cloud.microsoft/l/channel/19%3Achan%40thread.tacv2/R%26D%20News?groupId=group-1&tenantId=tenant-1"
165
);
166
}
167
168
#[test]
169
fn private_and_shared_channel_links_carry_ngc() {
170
for kind in ["private", "shared"] {
171
assert!(channel_link(&address(Some(kind))).ends_with("&tenantId=tenant-1&ngc=true"));
172
}
173
assert!(!channel_link(&address(None)).contains("ngc"));
174
}
175
176
#[test]
177
fn team_link_points_at_the_conversations_of_the_team_thread() {
178
assert_eq!(
179
team_link("19:general@thread.tacv2", "group-1", "tenant-1"),
180
"https://teams.cloud.microsoft/l/team/19%3Ageneral%40thread.tacv2/conversations?groupId=group-1&tenantId=tenant-1"
181
);
182
}
116
183
}
@@ -2,6 +2,7 @@ use percent_encoding::{AsciiSet, NON_ALPHANUMERIC, utf8_percent_encode};2
use serde_json::json;2
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
6
6
const ENCODE_COMPONENT: &AsciiSet = &NON_ALPHANUMERIC7
const ENCODE_COMPONENT: &AsciiSet = &NON_ALPHANUMERIC7
.remove(b'-')8
.remove(b'-')@@ -68,6 +69,38 @@ pub fn channel_tab_link(channel_id: &str, tab_id: &str, label: &str) -> String {68
)69
)69
}70
}70
71
72
#[derive(Debug, Clone, PartialEq, Eq)]73
pub struct ChannelAddress {74
pub tenant_id: String,75
pub group_id: String,76
pub channel_id: String,77
pub channel_name: String,78
pub membership_type: Option<String>,79
}80
81
pub fn channel_link(address: &ChannelAddress) -> String {82
let separate_roster = address.membership_type.as_deref().is_some_and(|kind| {83
kind.eq_ignore_ascii_case("private") || kind.eq_ignore_ascii_case("shared")84
});85
format!(86
"{DEEP_LINK_HOST}/l/channel/{}/{}?groupId={}&tenantId={}{}",87
encode(&address.channel_id),88
encode(&address.channel_name),89
encode(&address.group_id),90
encode(&address.tenant_id),91
if separate_roster { "&ngc=true" } else { "" }92
)93
}94
95
pub fn team_link(team_thread_id: &str, group_id: &str, tenant_id: &str) -> String {96
format!(97
"{DEEP_LINK_HOST}/l/team/{}/conversations?groupId={}&tenantId={}",98
encode(team_thread_id),99
encode(group_id),100
encode(tenant_id)101
)102
}103
71
#[cfg(test)]104
#[cfg(test)]72
mod tests {105
mod tests {73
use super::*;106
use super::*;@@ -113,4 +146,38 @@ mod tests {113
"https://teams.microsoft.com/l/channel/19:chan@thread.tacv2/tab%3A%3Aa1-b2?label=Sprint%20board"146
"https://teams.microsoft.com/l/channel/19:chan@thread.tacv2/tab%3A%3Aa1-b2?label=Sprint%20board"114
);147
);115
}148
}149
150
fn address(membership_type: Option<&str>) -> ChannelAddress {151
ChannelAddress {152
tenant_id: "tenant-1".into(),153
group_id: "group-1".into(),154
channel_id: "19:chan@thread.tacv2".into(),155
channel_name: "R&D News".into(),156
membership_type: membership_type.map(str::to_owned),157
}158
}159
160
#[test]161
fn channel_link_encodes_the_id_and_name_like_teams() {162
assert_eq!(163
channel_link(&address(Some("standard"))),164
"https://teams.cloud.microsoft/l/channel/19%3Achan%40thread.tacv2/R%26D%20News?groupId=group-1&tenantId=tenant-1"165
);166
}167
168
#[test]169
fn private_and_shared_channel_links_carry_ngc() {170
for kind in ["private", "shared"] {171
assert!(channel_link(&address(Some(kind))).ends_with("&tenantId=tenant-1&ngc=true"));172
}173
assert!(!channel_link(&address(None)).contains("ngc"));174
}175
176
#[test]177
fn team_link_points_at_the_conversations_of_the_team_thread() {178
assert_eq!(179
team_link("19:general@thread.tacv2", "group-1", "tenant-1"),180
"https://teams.cloud.microsoft/l/team/19%3Ageneral%40thread.tacv2/conversations?groupId=group-1&tenantId=tenant-1"181
);182
}116
}183
}@@ -116,6 +116,7 @@ mod tests {
116
116
last_message_from: Some(format!("8:orgid:{from}")),
117
117
..ReadHorizon::default()
118
118
},
119
history_cleared_ms: None,
119
120
}
120
121
}
121
122
@@ -116,6 +116,7 @@ mod tests {116
last_message_from: Some(format!("8:orgid:{from}")),116
last_message_from: Some(format!("8:orgid:{from}")),117
..ReadHorizon::default()117
..ReadHorizon::default()118
},118
},119
history_cleared_ms: None,119
}120
}120
}121
}121
122
@@ -2,6 +2,10 @@ use chatsvc::sound_settings::{SoundSettings, SoundSettingsClient};
2
2
use chatsvc::substrate_search::{
3
3
QueryRequest, QueryResults, SearchIdentity, SearchSession, SubstrateSearch, Suggestions,
4
4
};
5
use chatsvc::{
6
ActivityFeed, AppConsumptionHorizon, MentionActivity, UserSettings,
7
parse_app_consumption_horizon,
8
};
5
9
use chatsvc::{
6
10
BotProfile, BotProfiles, CallLogEntry, CardActions, ChatApp, ConversationRef,
7
11
ConversationState, Conversations, ForcedAvailability, ForwardResult, Gif, Gifs, HistoryShare,
@@ -134,6 +138,12 @@ pub trait Remote {
134
138
share: HistoryShare,
135
139
) -> Result<()>;
136
140
async fn chat_states(&self) -> Result<Vec<ConversationState>>;
141
async fn clear_chat_history(&self, _chat_id: &str, _cleared_until_ms: i64) -> Result<()> {
142
Err(Error::Unsupported("removing chat history"))
143
}
144
async fn set_chat_topic(&self, _chat_id: &str, _topic: &str) -> Result<()> {
145
Err(Error::Unsupported("renaming a chat"))
146
}
137
147
async fn set_chat_muted(&self, chat_id: &str, muted: bool) -> Result<()>;
138
148
async fn set_read_horizon(&self, conversation_id: &str, horizon: &str) -> Result<()>;
139
149
async fn set_channel_notifications(
@@ -353,6 +363,36 @@ pub trait Remote {
353
363
Err(Error::Unsupported("pinning messages"))
354
364
}
355
365
366
async fn channel_pinned_posts(
367
&self,
368
_team_thread_id: &str,
369
_channel_id: &str,
370
) -> Result<Vec<PinnedMessage>> {
371
Err(Error::Unsupported("pinned channel posts"))
372
}
373
374
async fn set_post_pinned(
375
&self,
376
_team_thread_id: &str,
377
_channel_id: &str,
378
_post_id: &str,
379
_pinned: bool,
380
) -> Result<()> {
381
Err(Error::Unsupported("pinning channel posts"))
382
}
383
384
async fn mention_activities(&self) -> Result<Vec<MentionActivity>> {
385
Err(Error::Unsupported("the activity feed"))
386
}
387
388
async fn app_consumption_horizon(&self) -> Result<AppConsumptionHorizon> {
389
Ok(AppConsumptionHorizon::default())
390
}
391
392
async fn mark_all_channels_read(&self, _now_ms: i64) -> Result<AppConsumptionHorizon> {
393
Err(Error::Unsupported("marking all channels as read"))
394
}
395
356
396
async fn chat_apps(&self, _chat_id: &str) -> Result<Vec<ChatApp>> {
357
397
Err(Error::Unsupported("chat apps"))
358
398
}
@@ -700,6 +740,18 @@ impl Remote for Graph {
700
740
.await?)
701
741
}
702
742
743
async fn clear_chat_history(&self, chat_id: &str, cleared_until_ms: i64) -> Result<()> {
744
Ok(Conversations::new(self.session())
745
.clear_history(chat_id, cleared_until_ms)
746
.await?)
747
}
748
749
async fn set_chat_topic(&self, chat_id: &str, topic: &str) -> Result<()> {
750
Ok(ThreadMembers::new(self.session())
751
.set_topic(chat_id, topic)
752
.await?)
753
}
754
703
755
async fn set_chat_muted(&self, chat_id: &str, muted: bool) -> Result<()> {
704
756
Ok(Conversations::new(self.session())
705
757
.set_alerts(chat_id, !muted)
@@ -1049,6 +1101,43 @@ impl Remote for Graph {
1049
1101
.await?)
1050
1102
}
1051
1103
1104
async fn channel_pinned_posts(
1105
&self,
1106
team_thread_id: &str,
1107
channel_id: &str,
1108
) -> Result<Vec<PinnedMessage>> {
1109
Ok(Pins::with_skype_token(self.session())
1110
.channel_pinned_posts(team_thread_id, channel_id)
1111
.await?)
1112
}
1113
1114
async fn set_post_pinned(
1115
&self,
1116
team_thread_id: &str,
1117
channel_id: &str,
1118
post_id: &str,
1119
pinned: bool,
1120
) -> Result<()> {
1121
Ok(Pins::with_skype_token(self.session())
1122
.set_post_pinned(team_thread_id, channel_id, post_id, pinned)
1123
.await?)
1124
}
1125
1126
async fn mention_activities(&self) -> Result<Vec<MentionActivity>> {
1127
Ok(ActivityFeed::new(self.session()).mentions().await?)
1128
}
1129
1130
async fn app_consumption_horizon(&self) -> Result<AppConsumptionHorizon> {
1131
let properties = UserSettings::new(self.session()).properties().await?;
1132
Ok(parse_app_consumption_horizon(&properties))
1133
}
1134
1135
async fn mark_all_channels_read(&self, now_ms: i64) -> Result<AppConsumptionHorizon> {
1136
Ok(UserSettings::new(self.session())
1137
.mark_all_channels_read(now_ms)
1138
.await?)
1139
}
1140
1052
1141
async fn chat_apps(&self, chat_id: &str) -> Result<Vec<ChatApp>> {
1053
1142
Ok(CardActions::new(self.session()).chat_apps(chat_id).await?)
1054
1143
}
@@ -2,6 +2,10 @@ use chatsvc::sound_settings::{SoundSettings, SoundSettingsClient};2
use chatsvc::substrate_search::{2
use chatsvc::substrate_search::{3
QueryRequest, QueryResults, SearchIdentity, SearchSession, SubstrateSearch, Suggestions,3
QueryRequest, QueryResults, SearchIdentity, SearchSession, SubstrateSearch, Suggestions,4
};4
};5
use chatsvc::{6
ActivityFeed, AppConsumptionHorizon, MentionActivity, UserSettings,7
parse_app_consumption_horizon,8
};5
use chatsvc::{9
use chatsvc::{6
BotProfile, BotProfiles, CallLogEntry, CardActions, ChatApp, ConversationRef,10
BotProfile, BotProfiles, CallLogEntry, CardActions, ChatApp, ConversationRef,7
ConversationState, Conversations, ForcedAvailability, ForwardResult, Gif, Gifs, HistoryShare,11
ConversationState, Conversations, ForcedAvailability, ForwardResult, Gif, Gifs, HistoryShare,@@ -134,6 +138,12 @@ pub trait Remote {134
share: HistoryShare,138
share: HistoryShare,135
) -> Result<()>;139
) -> Result<()>;136
async fn chat_states(&self) -> Result<Vec<ConversationState>>;140
async fn chat_states(&self) -> Result<Vec<ConversationState>>;141
async fn clear_chat_history(&self, _chat_id: &str, _cleared_until_ms: i64) -> Result<()> {142
Err(Error::Unsupported("removing chat history"))143
}144
async fn set_chat_topic(&self, _chat_id: &str, _topic: &str) -> Result<()> {145
Err(Error::Unsupported("renaming a chat"))146
}137
async fn set_chat_muted(&self, chat_id: &str, muted: bool) -> Result<()>;147
async fn set_chat_muted(&self, chat_id: &str, muted: bool) -> Result<()>;138
async fn set_read_horizon(&self, conversation_id: &str, horizon: &str) -> Result<()>;148
async fn set_read_horizon(&self, conversation_id: &str, horizon: &str) -> Result<()>;139
async fn set_channel_notifications(149
async fn set_channel_notifications(@@ -353,6 +363,36 @@ pub trait Remote {353
Err(Error::Unsupported("pinning messages"))363
Err(Error::Unsupported("pinning messages"))354
}364
}355
365
366
async fn channel_pinned_posts(367
&self,368
_team_thread_id: &str,369
_channel_id: &str,370
) -> Result<Vec<PinnedMessage>> {371
Err(Error::Unsupported("pinned channel posts"))372
}373
374
async fn set_post_pinned(375
&self,376
_team_thread_id: &str,377
_channel_id: &str,378
_post_id: &str,379
_pinned: bool,380
) -> Result<()> {381
Err(Error::Unsupported("pinning channel posts"))382
}383
384
async fn mention_activities(&self) -> Result<Vec<MentionActivity>> {385
Err(Error::Unsupported("the activity feed"))386
}387
388
async fn app_consumption_horizon(&self) -> Result<AppConsumptionHorizon> {389
Ok(AppConsumptionHorizon::default())390
}391
392
async fn mark_all_channels_read(&self, _now_ms: i64) -> Result<AppConsumptionHorizon> {393
Err(Error::Unsupported("marking all channels as read"))394
}395
356
async fn chat_apps(&self, _chat_id: &str) -> Result<Vec<ChatApp>> {396
async fn chat_apps(&self, _chat_id: &str) -> Result<Vec<ChatApp>> {357
Err(Error::Unsupported("chat apps"))397
Err(Error::Unsupported("chat apps"))358
}398
}@@ -700,6 +740,18 @@ impl Remote for Graph {700
.await?)740
.await?)701
}741
}702
742
743
async fn clear_chat_history(&self, chat_id: &str, cleared_until_ms: i64) -> Result<()> {744
Ok(Conversations::new(self.session())745
.clear_history(chat_id, cleared_until_ms)746
.await?)747
}748
749
async fn set_chat_topic(&self, chat_id: &str, topic: &str) -> Result<()> {750
Ok(ThreadMembers::new(self.session())751
.set_topic(chat_id, topic)752
.await?)753
}754
703
async fn set_chat_muted(&self, chat_id: &str, muted: bool) -> Result<()> {755
async fn set_chat_muted(&self, chat_id: &str, muted: bool) -> Result<()> {704
Ok(Conversations::new(self.session())756
Ok(Conversations::new(self.session())705
.set_alerts(chat_id, !muted)757
.set_alerts(chat_id, !muted)@@ -1049,6 +1101,43 @@ impl Remote for Graph {1049
.await?)1101
.await?)1050
}1102
}1051
1103
1104
async fn channel_pinned_posts(1105
&self,1106
team_thread_id: &str,1107
channel_id: &str,1108
) -> Result<Vec<PinnedMessage>> {1109
Ok(Pins::with_skype_token(self.session())1110
.channel_pinned_posts(team_thread_id, channel_id)1111
.await?)1112
}1113
1114
async fn set_post_pinned(1115
&self,1116
team_thread_id: &str,1117
channel_id: &str,1118
post_id: &str,1119
pinned: bool,1120
) -> Result<()> {1121
Ok(Pins::with_skype_token(self.session())1122
.set_post_pinned(team_thread_id, channel_id, post_id, pinned)1123
.await?)1124
}1125
1126
async fn mention_activities(&self) -> Result<Vec<MentionActivity>> {1127
Ok(ActivityFeed::new(self.session()).mentions().await?)1128
}1129
1130
async fn app_consumption_horizon(&self) -> Result<AppConsumptionHorizon> {1131
let properties = UserSettings::new(self.session()).properties().await?;1132
Ok(parse_app_consumption_horizon(&properties))1133
}1134
1135
async fn mark_all_channels_read(&self, now_ms: i64) -> Result<AppConsumptionHorizon> {1136
Ok(UserSettings::new(self.session())1137
.mark_all_channels_read(now_ms)1138
.await?)1139
}1140
1052
async fn chat_apps(&self, chat_id: &str) -> Result<Vec<ChatApp>> {1141
async fn chat_apps(&self, chat_id: &str) -> Result<Vec<ChatApp>> {1053
Ok(CardActions::new(self.session()).chat_apps(chat_id).await?)1142
Ok(CardActions::new(self.session()).chat_apps(chat_id).await?)1054
}1143
}@@ -6,6 +6,7 @@ use store::{MemberRecord, MessageRecord};
6
6
const MEMBERS_ADDED_TYPE: &str = "#microsoft.graph.membersAddedEventMessageDetail";
7
7
const MEMBERS_DELETED_TYPE: &str = "#microsoft.graph.membersDeletedEventMessageDetail";
8
8
const MEMBERS_LEFT_TYPE: &str = "#microsoft.graph.membersLeftEventMessageDetail";
9
const CHAT_RENAMED_TYPE: &str = "#microsoft.graph.chatRenamedEventMessageDetail";
9
10
const UNRESOLVED_NAME_PREFIX: &str = "orgid:";
10
11
const DAY_SECONDS: i64 = 86_400;
11
12
@@ -14,6 +15,7 @@ pub enum RosterChange {
14
15
Added,
15
16
Removed,
16
17
Left,
18
Renamed,
17
19
}
18
20
19
21
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
@@ -33,6 +35,8 @@ pub struct RosterEvent {
33
35
pub member_names: Vec<Option<String>>,
34
36
#[serde(default)]
35
37
pub history: SharedHistory,
38
#[serde(default)]
39
pub topic: Option<String>,
36
40
}
37
41
38
42
#[derive(Serialize, Deserialize)]
@@ -67,6 +71,7 @@ impl RosterEvent {
67
71
MEMBERS_LEFT_TYPE => RosterChange::Left,
68
72
MEMBERS_DELETED_TYPE if only_initiator => RosterChange::Left,
69
73
MEMBERS_DELETED_TYPE => RosterChange::Removed,
74
CHAT_RENAMED_TYPE => RosterChange::Renamed,
70
75
_ => return None,
71
76
};
72
77
let history = match change {
@@ -86,6 +91,12 @@ impl RosterEvent {
86
91
member_ids,
87
92
member_names,
88
93
history,
94
topic: (change == RosterChange::Renamed)
95
.then(|| detail.get("chatDisplayName").and_then(Value::as_str))
96
.flatten()
97
.map(str::trim)
98
.filter(|topic| !topic.is_empty())
99
.map(str::to_owned),
89
100
})
90
101
}
91
102
@@ -114,6 +125,10 @@ impl RosterEvent {
114
125
let targets = join_targets(&targets);
115
126
match self.change {
116
127
RosterChange::Left => format!("{initiator} left the chat."),
128
RosterChange::Renamed => match &self.topic {
129
Some(topic) => format!("{initiator} changed the group name to {topic}."),
130
None => format!("{initiator} removed the group name for this conversation."),
131
},
117
132
RosterChange::Removed => format!("{initiator} removed {targets} from the chat."),
118
133
RosterChange::Added => match self.history {
119
134
SharedHistory::None => format!("{initiator} added {targets} to the chat."),
@@ -210,6 +225,32 @@ mod tests {
210
225
name.or(user_id).unwrap_or("Unknown").to_owned()
211
226
}
212
227
228
#[test]
229
fn a_rename_reads_like_teams() {
230
let renamed = |name: Value| {
231
RosterEvent::from_graph(
232
&json!({
233
"@odata.type": CHAT_RENAMED_TYPE,
234
"chatDisplayName": name,
235
"initiator": {"user": {"id": "me", "displayName": "Daniel"}},
236
}),
237
created(),
238
)
239
.unwrap()
240
};
241
let event = renamed(json!("Release crew"));
242
assert_eq!(event.change, RosterChange::Renamed);
243
assert_eq!(
244
event.text(plain_names),
245
"Daniel changed the group name to Release crew."
246
);
247
assert_eq!(RosterEvent::from_json(&event.to_json()).unwrap(), event);
248
assert_eq!(
249
renamed(json!(null)).text(plain_names),
250
"Daniel removed the group name for this conversation."
251
);
252
}
253
213
254
#[test]
214
255
fn added_without_history_reads_like_teams() {
215
256
let event = added(
@@ -6,6 +6,7 @@ use store::{MemberRecord, MessageRecord};6
const MEMBERS_ADDED_TYPE: &str = "#microsoft.graph.membersAddedEventMessageDetail";6
const MEMBERS_ADDED_TYPE: &str = "#microsoft.graph.membersAddedEventMessageDetail";7
const MEMBERS_DELETED_TYPE: &str = "#microsoft.graph.membersDeletedEventMessageDetail";7
const MEMBERS_DELETED_TYPE: &str = "#microsoft.graph.membersDeletedEventMessageDetail";8
const MEMBERS_LEFT_TYPE: &str = "#microsoft.graph.membersLeftEventMessageDetail";8
const MEMBERS_LEFT_TYPE: &str = "#microsoft.graph.membersLeftEventMessageDetail";9
const CHAT_RENAMED_TYPE: &str = "#microsoft.graph.chatRenamedEventMessageDetail";9
const UNRESOLVED_NAME_PREFIX: &str = "orgid:";10
const UNRESOLVED_NAME_PREFIX: &str = "orgid:";10
const DAY_SECONDS: i64 = 86_400;11
const DAY_SECONDS: i64 = 86_400;11
12
@@ -14,6 +15,7 @@ pub enum RosterChange {14
Added,15
Added,15
Removed,16
Removed,16
Left,17
Left,18
Renamed,17
}19
}18
20
19
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]21
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]@@ -33,6 +35,8 @@ pub struct RosterEvent {33
pub member_names: Vec<Option<String>>,35
pub member_names: Vec<Option<String>>,34
#[serde(default)]36
#[serde(default)]35
pub history: SharedHistory,37
pub history: SharedHistory,38
#[serde(default)]39
pub topic: Option<String>,36
}40
}37
41
38
#[derive(Serialize, Deserialize)]42
#[derive(Serialize, Deserialize)]@@ -67,6 +71,7 @@ impl RosterEvent {67
MEMBERS_LEFT_TYPE => RosterChange::Left,71
MEMBERS_LEFT_TYPE => RosterChange::Left,68
MEMBERS_DELETED_TYPE if only_initiator => RosterChange::Left,72
MEMBERS_DELETED_TYPE if only_initiator => RosterChange::Left,69
MEMBERS_DELETED_TYPE => RosterChange::Removed,73
MEMBERS_DELETED_TYPE => RosterChange::Removed,74
CHAT_RENAMED_TYPE => RosterChange::Renamed,70
_ => return None,75
_ => return None,71
};76
};72
let history = match change {77
let history = match change {@@ -86,6 +91,12 @@ impl RosterEvent {86
member_ids,91
member_ids,87
member_names,92
member_names,88
history,93
history,94
topic: (change == RosterChange::Renamed)95
.then(|| detail.get("chatDisplayName").and_then(Value::as_str))96
.flatten()97
.map(str::trim)98
.filter(|topic| !topic.is_empty())99
.map(str::to_owned),89
})100
})90
}101
}91
102
@@ -114,6 +125,10 @@ impl RosterEvent {114
let targets = join_targets(&targets);125
let targets = join_targets(&targets);115
match self.change {126
match self.change {116
RosterChange::Left => format!("{initiator} left the chat."),127
RosterChange::Left => format!("{initiator} left the chat."),128
RosterChange::Renamed => match &self.topic {129
Some(topic) => format!("{initiator} changed the group name to {topic}."),130
None => format!("{initiator} removed the group name for this conversation."),131
},117
RosterChange::Removed => format!("{initiator} removed {targets} from the chat."),132
RosterChange::Removed => format!("{initiator} removed {targets} from the chat."),118
RosterChange::Added => match self.history {133
RosterChange::Added => match self.history {119
SharedHistory::None => format!("{initiator} added {targets} to the chat."),134
SharedHistory::None => format!("{initiator} added {targets} to the chat."),@@ -210,6 +225,32 @@ mod tests {210
name.or(user_id).unwrap_or("Unknown").to_owned()225
name.or(user_id).unwrap_or("Unknown").to_owned()211
}226
}212
227
228
#[test]229
fn a_rename_reads_like_teams() {230
let renamed = |name: Value| {231
RosterEvent::from_graph(232
&json!({233
"@odata.type": CHAT_RENAMED_TYPE,234
"chatDisplayName": name,235
"initiator": {"user": {"id": "me", "displayName": "Daniel"}},236
}),237
created(),238
)239
.unwrap()240
};241
let event = renamed(json!("Release crew"));242
assert_eq!(event.change, RosterChange::Renamed);243
assert_eq!(244
event.text(plain_names),245
"Daniel changed the group name to Release crew."246
);247
assert_eq!(RosterEvent::from_json(&event.to_json()).unwrap(), event);248
assert_eq!(249
renamed(json!(null)).text(plain_names),250
"Daniel removed the group name for this conversation."251
);252
}253
213
#[test]254
#[test]214
fn added_without_history_reads_like_teams() {255
fn added_without_history_reads_like_teams() {215
let event = added(256
let event = added(@@ -1,13 +1,14 @@
1
1
use std::collections::HashMap;
2
2
3
use chatsvc::ConversationState;
3
use chatsvc::{ConversationState, MentionActivity};
4
4
use chrono::{DateTime, Duration, Utc};
5
5
use store::{ChatRecord, Store};
6
6
7
7
use crate::bot_partners::BotPartners;
8
use crate::channel_mentions::channel_mentions;
8
9
use crate::chat_paging::ChatPaging;
9
10
use crate::engine::{SidebarSummary, SyncEngine};
10
use crate::error::Result;
11
use crate::error::{Error, Result};
11
12
use crate::events::CoreEvent;
12
13
use crate::hidden_chats::{LocallyHidden, resolve_hidden};
13
14
use crate::mapping::{channel_record, team_record};
@@ -69,7 +70,11 @@ impl<R: Remote> SyncEngine<R> {
69
70
let mut hidden_ids = Vec::new();
70
71
let mut complete = false;
71
72
let mut continuation = None;
72
let states = self.refresh_chat_states().await;
73
let (states, app_horizon_ms, mentions) = tokio::join!(
74
self.refresh_chat_states(),
75
self.refresh_app_channel_horizon(),
76
self.remote.mention_activities()
77
);
73
78
self.drop_chats_hidden_by_chatsvc(states.as_deref())?;
74
79
let mut page = self.remote.chats_page(self.config.chat_page_size).await?;
75
80
loop {
@@ -98,7 +103,8 @@ impl<R: Remote> SyncEngine<R> {
98
103
self.refresh_notes_chat(states.as_deref(), &my_user_id)
99
104
.await,
100
105
);
101
self.apply_channel_read_states(states.as_deref(), &my_user_id);
106
self.apply_channel_read_states(states.as_deref(), &my_user_id, app_horizon_ms);
107
self.apply_channel_mentions(states.as_deref(), mentions, &my_user_id, app_horizon_ms);
102
108
self.apply_muted_chats(states);
103
109
if full {
104
110
if complete {
@@ -145,7 +151,49 @@ impl<R: Remote> SyncEngine<R> {
145
151
Ok(())
146
152
}
147
153
148
fn apply_channel_read_states(&self, states: Option<&[ConversationState]>, my_user_id: &str) {
154
async fn refresh_app_channel_horizon(&self) -> i64 {
155
match self.remote.app_consumption_horizon().await {
156
Ok(horizon) => {
157
let mut known = self.app_channel_horizon_ms.lock().unwrap();
158
*known = horizon.channel_ms.max(*known);
159
*known
160
}
161
Err(error) => {
162
self.report(format!("cannot read the mark all as read horizon: {error}"));
163
*self.app_channel_horizon_ms.lock().unwrap()
164
}
165
}
166
}
167
168
fn apply_channel_mentions(
169
&self,
170
states: Option<&[ConversationState]>,
171
mentions: Result<Vec<MentionActivity>>,
172
my_user_id: &str,
173
app_horizon_ms: i64,
174
) {
175
let (Some(states), Ok(mentions)) = (
176
states,
177
mentions.inspect_err(|error| {
178
if !matches!(error, Error::Unsupported(_)) {
179
self.report(format!("cannot refresh channel mentions: {error}"));
180
}
181
}),
182
) else {
183
return;
184
};
185
let counts = channel_mentions(&mentions, states, my_user_id, app_horizon_ms);
186
if let Err(error) = self.store.replace_channel_mentions(&counts) {
187
self.report(format!("cannot store channel mentions: {error}"));
188
}
189
}
190
191
fn apply_channel_read_states(
192
&self,
193
states: Option<&[ConversationState]>,
194
my_user_id: &str,
195
app_horizon_ms: i64,
196
) {
149
197
let Some(states) = states else {
150
198
return;
151
199
};
@@ -154,7 +202,7 @@ impl<R: Remote> SyncEngine<R> {
154
202
.map(|state| {
155
203
(
156
204
state.id.clone(),
157
state.read.is_unread(my_user_id),
205
state.read.is_unread_after(my_user_id, app_horizon_ms),
158
206
state.read.last_message_at(),
159
207
)
160
208
})
@@ -1,13 +1,14 @@1
use std::collections::HashMap;1
use std::collections::HashMap;2
2
3
use chatsvc::ConversationState;3
use chatsvc::{ConversationState, MentionActivity};4
use chrono::{DateTime, Duration, Utc};4
use chrono::{DateTime, Duration, Utc};5
use store::{ChatRecord, Store};5
use store::{ChatRecord, Store};6
6
7
use crate::bot_partners::BotPartners;7
use crate::bot_partners::BotPartners;8
use crate::channel_mentions::channel_mentions;8
use crate::chat_paging::ChatPaging;9
use crate::chat_paging::ChatPaging;9
use crate::engine::{SidebarSummary, SyncEngine};10
use crate::engine::{SidebarSummary, SyncEngine};10
use crate::error::Result;11
use crate::error::{Error, Result};11
use crate::events::CoreEvent;12
use crate::events::CoreEvent;12
use crate::hidden_chats::{LocallyHidden, resolve_hidden};13
use crate::hidden_chats::{LocallyHidden, resolve_hidden};13
use crate::mapping::{channel_record, team_record};14
use crate::mapping::{channel_record, team_record};@@ -69,7 +70,11 @@ impl<R: Remote> SyncEngine<R> {69
let mut hidden_ids = Vec::new();70
let mut hidden_ids = Vec::new();70
let mut complete = false;71
let mut complete = false;71
let mut continuation = None;72
let mut continuation = None;72
let states = self.refresh_chat_states().await;73
let (states, app_horizon_ms, mentions) = tokio::join!(74
self.refresh_chat_states(),75
self.refresh_app_channel_horizon(),76
self.remote.mention_activities()77
);73
self.drop_chats_hidden_by_chatsvc(states.as_deref())?;78
self.drop_chats_hidden_by_chatsvc(states.as_deref())?;74
let mut page = self.remote.chats_page(self.config.chat_page_size).await?;79
let mut page = self.remote.chats_page(self.config.chat_page_size).await?;75
loop {80
loop {@@ -98,7 +103,8 @@ impl<R: Remote> SyncEngine<R> {98
self.refresh_notes_chat(states.as_deref(), &my_user_id)103
self.refresh_notes_chat(states.as_deref(), &my_user_id)99
.await,104
.await,100
);105
);101
self.apply_channel_read_states(states.as_deref(), &my_user_id);106
self.apply_channel_read_states(states.as_deref(), &my_user_id, app_horizon_ms);107
self.apply_channel_mentions(states.as_deref(), mentions, &my_user_id, app_horizon_ms);102
self.apply_muted_chats(states);108
self.apply_muted_chats(states);103
if full {109
if full {104
if complete {110
if complete {@@ -145,7 +151,49 @@ impl<R: Remote> SyncEngine<R> {145
Ok(())151
Ok(())146
}152
}147
153
148
fn apply_channel_read_states(&self, states: Option<&[ConversationState]>, my_user_id: &str) {154
async fn refresh_app_channel_horizon(&self) -> i64 {155
match self.remote.app_consumption_horizon().await {156
Ok(horizon) => {157
let mut known = self.app_channel_horizon_ms.lock().unwrap();158
*known = horizon.channel_ms.max(*known);159
*known160
}161
Err(error) => {162
self.report(format!("cannot read the mark all as read horizon: {error}"));163
*self.app_channel_horizon_ms.lock().unwrap()164
}165
}166
}167
168
fn apply_channel_mentions(169
&self,170
states: Option<&[ConversationState]>,171
mentions: Result<Vec<MentionActivity>>,172
my_user_id: &str,173
app_horizon_ms: i64,174
) {175
let (Some(states), Ok(mentions)) = (176
states,177
mentions.inspect_err(|error| {178
if !matches!(error, Error::Unsupported(_)) {179
self.report(format!("cannot refresh channel mentions: {error}"));180
}181
}),182
) else {183
return;184
};185
let counts = channel_mentions(&mentions, states, my_user_id, app_horizon_ms);186
if let Err(error) = self.store.replace_channel_mentions(&counts) {187
self.report(format!("cannot store channel mentions: {error}"));188
}189
}190
191
fn apply_channel_read_states(192
&self,193
states: Option<&[ConversationState]>,194
my_user_id: &str,195
app_horizon_ms: i64,196
) {149
let Some(states) = states else {197
let Some(states) = states else {150
return;198
return;151
};199
};@@ -154,7 +202,7 @@ impl<R: Remote> SyncEngine<R> {154
.map(|state| {202
.map(|state| {155
(203
(156
state.id.clone(),204
state.id.clone(),157
state.read.is_unread(my_user_id),205
state.read.is_unread_after(my_user_id, app_horizon_ms),158
state.read.last_message_at(),206
state.read.last_message_at(),159
)207
)160
})208
})@@ -135,6 +135,8 @@ struct Fake {
135
135
window_requests: Mutex<Vec<(String, chatsvc::WindowDirection)>>,
136
136
search_identities: Mutex<Vec<substrate_search::SearchIdentity>>,
137
137
member_requests: Mutex<Vec<String>>,
138
mention_activities: Mutex<Vec<chatsvc::MentionActivity>>,
139
app_channel_horizon_ms: Mutex<i64>,
138
140
}
139
141
140
142
impl Fake {
@@ -582,6 +584,7 @@ impl Remote for Handle {
582
584
muted,
583
585
hidden: None,
584
586
read: chatsvc::ReadHorizon::default(),
587
history_cleared_ms: None,
585
588
})
586
589
.collect();
587
590
states.extend(
@@ -592,6 +595,7 @@ impl Remote for Handle {
592
595
muted: false,
593
596
hidden: Some(hidden),
594
597
read: chatsvc::ReadHorizon::default(),
598
history_cleared_ms: None,
595
599
}),
596
600
);
597
601
let read = self.read_states.lock().unwrap().clone();
@@ -602,6 +606,7 @@ impl Remote for Handle {
602
606
muted: false,
603
607
hidden: None,
604
608
read,
609
history_cleared_ms: None,
605
610
}),
606
611
);
607
612
Ok(states)
@@ -878,6 +883,49 @@ impl Remote for Handle {
878
883
Ok(())
879
884
}
880
885
886
async fn channel_pinned_posts(
887
&self,
888
team_thread_id: &str,
889
channel_id: &str,
890
) -> Result<Vec<chatsvc::PinnedMessage>> {
891
self.record(format!("channel pins {team_thread_id} {channel_id}"));
892
Ok(vec![chatsvc::PinnedMessage {
893
message_id: "30".to_owned(),
894
pinned_at: None,
895
parent_id: None,
896
}])
897
}
898
899
async fn set_post_pinned(
900
&self,
901
team_thread_id: &str,
902
channel_id: &str,
903
post_id: &str,
904
pinned: bool,
905
) -> Result<()> {
906
self.record(format!(
907
"post pin {team_thread_id} {channel_id} {post_id} {pinned}"
908
));
909
Ok(())
910
}
911
912
async fn mention_activities(&self) -> Result<Vec<chatsvc::MentionActivity>> {
913
Ok(self.mention_activities.lock().unwrap().clone())
914
}
915
916
async fn app_consumption_horizon(&self) -> Result<chatsvc::AppConsumptionHorizon> {
917
Ok(chatsvc::AppConsumptionHorizon {
918
channel_ms: *self.app_channel_horizon_ms.lock().unwrap(),
919
..chatsvc::AppConsumptionHorizon::default()
920
})
921
}
922
923
async fn mark_all_channels_read(&self, now_ms: i64) -> Result<chatsvc::AppConsumptionHorizon> {
924
self.record("mark all channels read".to_owned());
925
*self.app_channel_horizon_ms.lock().unwrap() = now_ms;
926
self.app_consumption_horizon().await
927
}
928
881
929
async fn chat_apps(&self, _chat_id: &str) -> Result<Vec<chatsvc::ChatApp>> {
882
930
*self.app_calls.lock().unwrap() += 1;
883
931
Ok(self.apps.lock().unwrap().clone())
@@ -3161,6 +3209,137 @@ impl FolderSource for FakeFolders {
3161
3209
Ok(state.clone())
3162
3210
})
3163
3211
}
3212
3213
fn set_channel_pinned<'a>(
3214
&'a self,
3215
channel_id: &'a str,
3216
pinned: bool,
3217
) -> BoxFuture<'a, Result<Vec<String>>> {
3218
Box::pin(async move {
3219
self.calls
3220
.lock()
3221
.unwrap()
3222
.push(format!("pin channel {channel_id} {pinned}"));
3223
let mut channel_ids = self.channels.clone();
3224
channel_ids.retain(|id| id != channel_id);
3225
if pinned {
3226
channel_ids.push(channel_id.to_owned());
3227
}
3228
Ok(channel_ids)
3229
})
3230
}
3231
3232
fn set_channel_shown<'a>(
3233
&'a self,
3234
target: chatsvc::ChannelTarget<'a>,
3235
own_user_id: &'a str,
3236
shown: bool,
3237
_now_ms: i64,
3238
) -> BoxFuture<'a, Result<()>> {
3239
Box::pin(async move {
3240
self.calls.lock().unwrap().push(format!(
3241
"show channel {} general={} {:?} {own_user_id} {shown}",
3242
target.channel_id, target.general, target.kind
3243
));
3244
Ok(())
3245
})
3246
}
3247
3248
fn set_team_shown<'a>(
3249
&'a self,
3250
team_thread_id: &'a str,
3251
shown: bool,
3252
) -> BoxFuture<'a, Result<()>> {
3253
Box::pin(async move {
3254
self.calls
3255
.lock()
3256
.unwrap()
3257
.push(format!("show team {team_thread_id} {shown}"));
3258
Ok(())
3259
})
3260
}
3261
}
3262
3263
fn store_alpha_team(engine: &SyncEngine<Handle>) {
3264
engine
3265
.store()
3266
.upsert_teams(&[TeamRecord {
3267
id: "alpha".into(),
3268
name: "Alpha".into(),
3269
}])
3270
.unwrap();
3271
let channel = |id: &str, name: &str, membership_type: Option<&str>| ChannelRecord {
3272
id: id.into(),
3273
team_id: "alpha".into(),
3274
name: name.into(),
3275
membership_type: membership_type.map(str::to_owned),
3276
last_message_at: None,
3277
unread: false,
3278
};
3279
engine
3280
.store()
3281
.upsert_channels(&[
3282
channel("19:general@thread.tacv2", "General", Some("standard")),
3283
channel("19:secret@thread.tacv2", "Secret", Some("private")),
3284
])
3285
.unwrap();
3286
}
3287
3288
#[tokio::test]
3289
async fn channel_pin_and_show_hide_go_through_the_source_and_cache() {
3290
let fake = Arc::new(Fake::default());
3291
let source = FakeFolders::new();
3292
let engine = engine_with(&fake, SyncConfig::default()).with_folder_source(source.clone());
3293
store_alpha_team(&engine);
3294
let mut events = engine.subscribe();
3295
3296
engine.set_channel_pinned("ch3", true).await.unwrap();
3297
assert_eq!(
3298
engine.pinned_channels().unwrap(),
3299
ids(&["ch1", "ch2", "ch3"])
3300
);
3301
assert_eq!(events.try_recv().unwrap(), CoreEvent::FoldersChanged);
3302
engine.set_channel_pinned("ch1", false).await.unwrap();
3303
assert_eq!(engine.pinned_channels().unwrap(), ids(&["ch2"]));
3304
3305
engine
3306
.set_channel_shown("19:secret@thread.tacv2", false)
3307
.await
3308
.unwrap();
3309
engine
3310
.set_channel_shown("19:general@thread.tacv2", false)
3311
.await
3312
.unwrap();
3313
engine.set_team_shown("alpha", false).await.unwrap();
3314
let team = engine.store().sidebar().unwrap().teams.remove(0);
3315
assert!(team.hidden);
3316
assert_eq!(team.hidden_channel_ids.len(), 2);
3317
let calls = source.calls.lock().unwrap().clone();
3318
assert_eq!(
3319
calls[2..],
3320
[
3321
format!("show channel 19:secret@thread.tacv2 general=false Private {ME} false"),
3322
format!("show channel 19:general@thread.tacv2 general=true Standard {ME} false"),
3323
"show team 19:general@thread.tacv2 false".to_owned(),
3324
]
3325
);
3326
}
3327
3328
#[tokio::test]
3329
async fn channel_and_team_links_use_the_cached_tenant() {
3330
let fake = Arc::new(Fake::default());
3331
let engine = engine_with(&fake, SyncConfig::default());
3332
store_alpha_team(&engine);
3333
engine.store().set_meta("me_tenant_id", "tenant-1").unwrap();
3334
3335
assert_eq!(
3336
engine.channel_link("19:secret@thread.tacv2").await.unwrap(),
3337
"https://teams.cloud.microsoft/l/channel/19%3Asecret%40thread.tacv2/Secret?groupId=alpha&tenantId=tenant-1&ngc=true"
3338
);
3339
assert_eq!(
3340
engine.team_link("alpha").await.unwrap(),
3341
"https://teams.cloud.microsoft/l/team/19%3Ageneral%40thread.tacv2/conversations?groupId=alpha&tenantId=tenant-1"
3342
);
3164
3343
}
3165
3344
3166
3345
#[tokio::test]
@@ -4678,7 +4857,7 @@ async fn save_uses_the_message_id_as_root_in_chats() {
4678
4857
}
4679
4858
4680
4859
#[tokio::test]
4681
async fn pinning_announces_and_is_refused_in_channels() {
4860
async fn pinning_announces_in_chats() {
4682
4861
let fake = Arc::new(Fake::default());
4683
4862
let engine = channel_engine(&fake).await;
4684
4863
*fake.chats.lock().unwrap() = vec![chat(CHAT, Some("Planning"), 5, 5, ME, false)];
@@ -4699,10 +4878,83 @@ async fn pinning_announces_and_is_refused_in_channels() {
4699
4878
fake.calls().last().unwrap(),
4700
4879
&format!("unpin {CHAT} 5 Some(\"folder-1\")")
4701
4880
);
4702
assert!(matches!(
4703
engine.pin_message(CHANNEL, "5").await,
4704
Err(Error::Unsupported(_))
4881
}
4882
4883
#[tokio::test]
4884
async fn channel_pins_use_the_post_pin_routes_of_the_team_thread() {
4885
let fake = Arc::new(Fake::default());
4886
let engine = channel_engine(&fake).await;
4887
engine.fetch_newer(CHANNEL).await.unwrap();
4888
let pins = engine.chat_pins(CHANNEL).await.unwrap();
4889
assert_eq!(pins[0].message_id, "30");
4890
assert_eq!(
4891
fake.calls().last().unwrap(),
4892
&format!("channel pins {CHANNEL} {CHANNEL}")
4893
);
4894
let mut events = engine.subscribe();
4895
engine.pin_message(CHANNEL, "30").await.unwrap();
4896
assert_eq!(
4897
fake.calls().last().unwrap(),
4898
&format!("post pin {CHANNEL} {CHANNEL} 30 true")
4899
);
4900
assert_eq!(
4901
events.try_recv().unwrap(),
4902
CoreEvent::PinsChanged {
4903
conversation_id: CHANNEL.to_owned()
4904
}
4905
);
4906
engine.unpin_message(CHANNEL, "30", None).await.unwrap();
4907
assert_eq!(
4908
fake.calls().last().unwrap(),
4909
&format!("post pin {CHANNEL} {CHANNEL} 30 false")
4910
);
4911
}
4912
4913
#[tokio::test]
4914
async fn channel_mentions_follow_the_activity_feed_and_mark_all_as_read() {
4915
let fake = Arc::new(Fake::default());
4916
fake.read_states.lock().unwrap().push((
4917
CHANNEL.to_owned(),
4918
chatsvc::ReadHorizon {
4919
consumed_until_ms: 5,
4920
last_message_ms: 9,
4921
last_message_from: Some("8:orgid:user-ada".to_owned()),
4922
..chatsvc::ReadHorizon::default()
4923
},
4705
4924
));
4925
let mention = |activity_id: &str, kind: chatsvc::MentionKind| chatsvc::MentionActivity {
4926
activity_id: activity_id.to_owned(),
4927
kind,
4928
source_thread_id: CHANNEL.to_owned(),
4929
source_message_id: None,
4930
timestamp_ms: 8,
4931
is_read: false,
4932
};
4933
*fake.mention_activities.lock().unwrap() = vec![
4934
mention("1", chatsvc::MentionKind::Personal),
4935
mention("2", chatsvc::MentionKind::Team),
4936
];
4937
let engine = channel_engine(&fake).await;
4938
engine.refresh_sidebar().await.unwrap();
4939
let mentions = engine.store().sidebar().unwrap().teams[0].channel_mentions(CHANNEL);
4940
assert_eq!((mentions.personal, mentions.team), (1, 1));
4941
4942
engine.mark_all_channels_read().await.unwrap();
4943
4944
assert_eq!(fake.calls().last().unwrap(), "mark all channels read");
4945
assert!(!engine.store().channel(CHANNEL).unwrap().unwrap().unread);
4946
assert!(
4947
engine.store().sidebar().unwrap().teams[0]
4948
.mentions
4949
.is_empty()
4950
);
4951
engine.refresh_sidebar().await.unwrap();
4952
assert!(!engine.store().channel(CHANNEL).unwrap().unwrap().unread);
4953
assert!(
4954
engine.store().sidebar().unwrap().teams[0]
4955
.mentions
4956
.is_empty()
4957
);
4706
4958
}
4707
4959
4708
4960
#[tokio::test]
@@ -135,6 +135,8 @@ struct Fake {135
window_requests: Mutex<Vec<(String, chatsvc::WindowDirection)>>,135
window_requests: Mutex<Vec<(String, chatsvc::WindowDirection)>>,136
search_identities: Mutex<Vec<substrate_search::SearchIdentity>>,136
search_identities: Mutex<Vec<substrate_search::SearchIdentity>>,137
member_requests: Mutex<Vec<String>>,137
member_requests: Mutex<Vec<String>>,138
mention_activities: Mutex<Vec<chatsvc::MentionActivity>>,139
app_channel_horizon_ms: Mutex<i64>,138
}140
}139
141
140
impl Fake {142
impl Fake {@@ -582,6 +584,7 @@ impl Remote for Handle {582
muted,584
muted,583
hidden: None,585
hidden: None,584
read: chatsvc::ReadHorizon::default(),586
read: chatsvc::ReadHorizon::default(),587
history_cleared_ms: None,585
})588
})586
.collect();589
.collect();587
states.extend(590
states.extend(@@ -592,6 +595,7 @@ impl Remote for Handle {592
muted: false,595
muted: false,593
hidden: Some(hidden),596
hidden: Some(hidden),594
read: chatsvc::ReadHorizon::default(),597
read: chatsvc::ReadHorizon::default(),598
history_cleared_ms: None,595
}),599
}),596
);600
);597
let read = self.read_states.lock().unwrap().clone();601
let read = self.read_states.lock().unwrap().clone();@@ -602,6 +606,7 @@ impl Remote for Handle {602
muted: false,606
muted: false,603
hidden: None,607
hidden: None,604
read,608
read,609
history_cleared_ms: None,605
}),610
}),606
);611
);607
Ok(states)612
Ok(states)@@ -878,6 +883,49 @@ impl Remote for Handle {878
Ok(())883
Ok(())879
}884
}880
885
886
async fn channel_pinned_posts(887
&self,888
team_thread_id: &str,889
channel_id: &str,890
) -> Result<Vec<chatsvc::PinnedMessage>> {891
self.record(format!("channel pins {team_thread_id} {channel_id}"));892
Ok(vec![chatsvc::PinnedMessage {893
message_id: "30".to_owned(),894
pinned_at: None,895
parent_id: None,896
}])897
}898
899
async fn set_post_pinned(900
&self,901
team_thread_id: &str,902
channel_id: &str,903
post_id: &str,904
pinned: bool,905
) -> Result<()> {906
self.record(format!(907
"post pin {team_thread_id} {channel_id} {post_id} {pinned}"908
));909
Ok(())910
}911
912
async fn mention_activities(&self) -> Result<Vec<chatsvc::MentionActivity>> {913
Ok(self.mention_activities.lock().unwrap().clone())914
}915
916
async fn app_consumption_horizon(&self) -> Result<chatsvc::AppConsumptionHorizon> {917
Ok(chatsvc::AppConsumptionHorizon {918
channel_ms: *self.app_channel_horizon_ms.lock().unwrap(),919
..chatsvc::AppConsumptionHorizon::default()920
})921
}922
923
async fn mark_all_channels_read(&self, now_ms: i64) -> Result<chatsvc::AppConsumptionHorizon> {924
self.record("mark all channels read".to_owned());925
*self.app_channel_horizon_ms.lock().unwrap() = now_ms;926
self.app_consumption_horizon().await927
}928
881
async fn chat_apps(&self, _chat_id: &str) -> Result<Vec<chatsvc::ChatApp>> {929
async fn chat_apps(&self, _chat_id: &str) -> Result<Vec<chatsvc::ChatApp>> {882
*self.app_calls.lock().unwrap() += 1;930
*self.app_calls.lock().unwrap() += 1;883
Ok(self.apps.lock().unwrap().clone())931
Ok(self.apps.lock().unwrap().clone())@@ -3161,6 +3209,137 @@ impl FolderSource for FakeFolders {3161
Ok(state.clone())3209
Ok(state.clone())3162
})3210
})3163
}3211
}3212
3213
fn set_channel_pinned<'a>(3214
&'a self,3215
channel_id: &'a str,3216
pinned: bool,3217
) -> BoxFuture<'a, Result<Vec<String>>> {3218
Box::pin(async move {3219
self.calls3220
.lock()3221
.unwrap()3222
.push(format!("pin channel {channel_id} {pinned}"));3223
let mut channel_ids = self.channels.clone();3224
channel_ids.retain(|id| id != channel_id);3225
if pinned {3226
channel_ids.push(channel_id.to_owned());3227
}3228
Ok(channel_ids)3229
})3230
}3231
3232
fn set_channel_shown<'a>(3233
&'a self,3234
target: chatsvc::ChannelTarget<'a>,3235
own_user_id: &'a str,3236
shown: bool,3237
_now_ms: i64,3238
) -> BoxFuture<'a, Result<()>> {3239
Box::pin(async move {3240
self.calls.lock().unwrap().push(format!(3241
"show channel {} general={} {:?} {own_user_id} {shown}",3242
target.channel_id, target.general, target.kind3243
));3244
Ok(())3245
})3246
}3247
3248
fn set_team_shown<'a>(3249
&'a self,3250
team_thread_id: &'a str,3251
shown: bool,3252
) -> BoxFuture<'a, Result<()>> {3253
Box::pin(async move {3254
self.calls3255
.lock()3256
.unwrap()3257
.push(format!("show team {team_thread_id} {shown}"));3258
Ok(())3259
})3260
}3261
}3262
3263
fn store_alpha_team(engine: &SyncEngine<Handle>) {3264
engine3265
.store()3266
.upsert_teams(&[TeamRecord {3267
id: "alpha".into(),3268
name: "Alpha".into(),3269
}])3270
.unwrap();3271
let channel = |id: &str, name: &str, membership_type: Option<&str>| ChannelRecord {3272
id: id.into(),3273
team_id: "alpha".into(),3274
name: name.into(),3275
membership_type: membership_type.map(str::to_owned),3276
last_message_at: None,3277
unread: false,3278
};3279
engine3280
.store()3281
.upsert_channels(&[3282
channel("19:general@thread.tacv2", "General", Some("standard")),3283
channel("19:secret@thread.tacv2", "Secret", Some("private")),3284
])3285
.unwrap();3286
}3287
3288
#[tokio::test]3289
async fn channel_pin_and_show_hide_go_through_the_source_and_cache() {3290
let fake = Arc::new(Fake::default());3291
let source = FakeFolders::new();3292
let engine = engine_with(&fake, SyncConfig::default()).with_folder_source(source.clone());3293
store_alpha_team(&engine);3294
let mut events = engine.subscribe();3295
3296
engine.set_channel_pinned("ch3", true).await.unwrap();3297
assert_eq!(3298
engine.pinned_channels().unwrap(),3299
ids(&["ch1", "ch2", "ch3"])3300
);3301
assert_eq!(events.try_recv().unwrap(), CoreEvent::FoldersChanged);3302
engine.set_channel_pinned("ch1", false).await.unwrap();3303
assert_eq!(engine.pinned_channels().unwrap(), ids(&["ch2"]));3304
3305
engine3306
.set_channel_shown("19:secret@thread.tacv2", false)3307
.await3308
.unwrap();3309
engine3310
.set_channel_shown("19:general@thread.tacv2", false)3311
.await3312
.unwrap();3313
engine.set_team_shown("alpha", false).await.unwrap();3314
let team = engine.store().sidebar().unwrap().teams.remove(0);3315
assert!(team.hidden);3316
assert_eq!(team.hidden_channel_ids.len(), 2);3317
let calls = source.calls.lock().unwrap().clone();3318
assert_eq!(3319
calls[2..],3320
[3321
format!("show channel 19:secret@thread.tacv2 general=false Private {ME} false"),3322
format!("show channel 19:general@thread.tacv2 general=true Standard {ME} false"),3323
"show team 19:general@thread.tacv2 false".to_owned(),3324
]3325
);3326
}3327
3328
#[tokio::test]3329
async fn channel_and_team_links_use_the_cached_tenant() {3330
let fake = Arc::new(Fake::default());3331
let engine = engine_with(&fake, SyncConfig::default());3332
store_alpha_team(&engine);3333
engine.store().set_meta("me_tenant_id", "tenant-1").unwrap();3334
3335
assert_eq!(3336
engine.channel_link("19:secret@thread.tacv2").await.unwrap(),3337
"https://teams.cloud.microsoft/l/channel/19%3Asecret%40thread.tacv2/Secret?groupId=alpha&tenantId=tenant-1&ngc=true"3338
);3339
assert_eq!(3340
engine.team_link("alpha").await.unwrap(),3341
"https://teams.cloud.microsoft/l/team/19%3Ageneral%40thread.tacv2/conversations?groupId=alpha&tenantId=tenant-1"3342
);3164
}3343
}3165
3344
3166
#[tokio::test]3345
#[tokio::test]@@ -4678,7 +4857,7 @@ async fn save_uses_the_message_id_as_root_in_chats() {4678
}4857
}4679
4858
4680
#[tokio::test]4859
#[tokio::test]4681
async fn pinning_announces_and_is_refused_in_channels() {4860
async fn pinning_announces_in_chats() {4682
let fake = Arc::new(Fake::default());4861
let fake = Arc::new(Fake::default());4683
let engine = channel_engine(&fake).await;4862
let engine = channel_engine(&fake).await;4684
*fake.chats.lock().unwrap() = vec![chat(CHAT, Some("Planning"), 5, 5, ME, false)];4863
*fake.chats.lock().unwrap() = vec![chat(CHAT, Some("Planning"), 5, 5, ME, false)];@@ -4699,10 +4878,83 @@ async fn pinning_announces_and_is_refused_in_channels() {4699
fake.calls().last().unwrap(),4878
fake.calls().last().unwrap(),4700
&format!("unpin {CHAT} 5 Some(\"folder-1\")")4879
&format!("unpin {CHAT} 5 Some(\"folder-1\")")4701
);4880
);4702
assert!(matches!(4881
}4703
engine.pin_message(CHANNEL, "5").await,4882
4704
Err(Error::Unsupported(_))4883
#[tokio::test]4884
async fn channel_pins_use_the_post_pin_routes_of_the_team_thread() {4885
let fake = Arc::new(Fake::default());4886
let engine = channel_engine(&fake).await;4887
engine.fetch_newer(CHANNEL).await.unwrap();4888
let pins = engine.chat_pins(CHANNEL).await.unwrap();4889
assert_eq!(pins[0].message_id, "30");4890
assert_eq!(4891
fake.calls().last().unwrap(),4892
&format!("channel pins {CHANNEL} {CHANNEL}")4893
);4894
let mut events = engine.subscribe();4895
engine.pin_message(CHANNEL, "30").await.unwrap();4896
assert_eq!(4897
fake.calls().last().unwrap(),4898
&format!("post pin {CHANNEL} {CHANNEL} 30 true")4899
);4900
assert_eq!(4901
events.try_recv().unwrap(),4902
CoreEvent::PinsChanged {4903
conversation_id: CHANNEL.to_owned()4904
}4905
);4906
engine.unpin_message(CHANNEL, "30", None).await.unwrap();4907
assert_eq!(4908
fake.calls().last().unwrap(),4909
&format!("post pin {CHANNEL} {CHANNEL} 30 false")4910
);4911
}4912
4913
#[tokio::test]4914
async fn channel_mentions_follow_the_activity_feed_and_mark_all_as_read() {4915
let fake = Arc::new(Fake::default());4916
fake.read_states.lock().unwrap().push((4917
CHANNEL.to_owned(),4918
chatsvc::ReadHorizon {4919
consumed_until_ms: 5,4920
last_message_ms: 9,4921
last_message_from: Some("8:orgid:user-ada".to_owned()),4922
..chatsvc::ReadHorizon::default()4923
},4705
));4924
));4925
let mention = |activity_id: &str, kind: chatsvc::MentionKind| chatsvc::MentionActivity {4926
activity_id: activity_id.to_owned(),4927
kind,4928
source_thread_id: CHANNEL.to_owned(),4929
source_message_id: None,4930
timestamp_ms: 8,4931
is_read: false,4932
};4933
*fake.mention_activities.lock().unwrap() = vec![4934
mention("1", chatsvc::MentionKind::Personal),4935
mention("2", chatsvc::MentionKind::Team),4936
];4937
let engine = channel_engine(&fake).await;4938
engine.refresh_sidebar().await.unwrap();4939
let mentions = engine.store().sidebar().unwrap().teams[0].channel_mentions(CHANNEL);4940
assert_eq!((mentions.personal, mentions.team), (1, 1));4941
4942
engine.mark_all_channels_read().await.unwrap();4943
4944
assert_eq!(fake.calls().last().unwrap(), "mark all channels read");4945
assert!(!engine.store().channel(CHANNEL).unwrap().unwrap().unread);4946
assert!(4947
engine.store().sidebar().unwrap().teams[0]4948
.mentions4949
.is_empty()4950
);4951
engine.refresh_sidebar().await.unwrap();4952
assert!(!engine.store().channel(CHANNEL).unwrap().unwrap().unread);4953
assert!(4954
engine.store().sidebar().unwrap().teams[0]4955
.mentions4956
.is_empty()4957
);4706
}4958
}4707
4959
4708
#[tokio::test]4960
#[tokio::test]@@ -89,4 +89,19 @@ impl Store {
89
89
let rows = statement.query_map([], |row| row.get::<_, String>(0))?;
90
90
Ok(rows.collect::<rusqlite::Result<_>>()?)
91
91
}
92
93
pub fn replace_pinned_channels(&self, channel_ids: &[String]) -> Result<()> {
94
let mut connection = self.lock()?;
95
let transaction = connection.transaction()?;
96
transaction.execute("DELETE FROM pinned_channels", [])?;
97
{
98
let mut insert_channel = transaction.prepare_cached(
99
"INSERT INTO pinned_channels (position, channel_id) VALUES (?1, ?2)",
100
)?;
101
for (position, channel_id) in channel_ids.iter().enumerate() {
102
insert_channel.execute(params![position as i64, channel_id])?;
103
}
104
}
105
Ok(transaction.commit()?)
106
}
92
107
}
@@ -89,4 +89,19 @@ impl Store {89
let rows = statement.query_map([], |row| row.get::<_, String>(0))?;89
let rows = statement.query_map([], |row| row.get::<_, String>(0))?;90
Ok(rows.collect::<rusqlite::Result<_>>()?)90
Ok(rows.collect::<rusqlite::Result<_>>()?)91
}91
}92
93
pub fn replace_pinned_channels(&self, channel_ids: &[String]) -> Result<()> {94
let mut connection = self.lock()?;95
let transaction = connection.transaction()?;96
transaction.execute("DELETE FROM pinned_channels", [])?;97
{98
let mut insert_channel = transaction.prepare_cached(99
"INSERT INTO pinned_channels (position, channel_id) VALUES (?1, ?2)",100
)?;101
for (position, channel_id) in channel_ids.iter().enumerate() {102
insert_channel.execute(params![position as i64, channel_id])?;103
}104
}105
Ok(transaction.commit()?)106
}92
}107
}@@ -27,7 +27,7 @@ pub use error::{Error, Result};
27
27
pub use image_files::ImageFileCache;
28
28
pub use models::{
29
29
ActivityRecord, AgentProposalMention, AgentProposalRecord, AgentReactionRecord,
30
AttachmentImage, AvatarRecord, BOT_MRI_PREFIX, ChannelLayoutRecord, ChannelNotificationLevel,
30
AttachmentImage, AvatarRecord, BOT_MRI_PREFIX, ChannelLayoutRecord, ChannelMentions, ChannelNotificationLevel,
31
31
ChannelNotifications, ChannelRecord, ChannelTabRecord, ChatPreview, ChatRecord,
32
32
ConversationHit, DraftRecord, FolderRecord, ImageRecord, MemberRecord, MessageRecord,
33
33
OutboxRecord, OutboxState, OutboxTarget, ReadHorizonRecord, RecentScope, SearchHit, Sidebar,
@@ -27,7 +27,7 @@ pub use error::{Error, Result};27
pub use image_files::ImageFileCache;27
pub use image_files::ImageFileCache;28
pub use models::{28
pub use models::{29
ActivityRecord, AgentProposalMention, AgentProposalRecord, AgentReactionRecord,29
ActivityRecord, AgentProposalMention, AgentProposalRecord, AgentReactionRecord,30
AttachmentImage, AvatarRecord, BOT_MRI_PREFIX, ChannelLayoutRecord, ChannelNotificationLevel,30
AttachmentImage, AvatarRecord, BOT_MRI_PREFIX, ChannelLayoutRecord, ChannelMentions, ChannelNotificationLevel,31
ChannelNotifications, ChannelRecord, ChannelTabRecord, ChatPreview, ChatRecord,31
ChannelNotifications, ChannelRecord, ChannelTabRecord, ChatPreview, ChatRecord,32
ConversationHit, DraftRecord, FolderRecord, ImageRecord, MemberRecord, MessageRecord,32
ConversationHit, DraftRecord, FolderRecord, ImageRecord, MemberRecord, MessageRecord,33
OutboxRecord, OutboxState, OutboxTarget, ReadHorizonRecord, RecentScope, SearchHit, Sidebar,33
OutboxRecord, OutboxState, OutboxTarget, ReadHorizonRecord, RecentScope, SearchHit, Sidebar,@@ -97,6 +97,10 @@ const MIGRATIONS: &[Migration] = &[
97
97
script: include_str!("migrations/0022_read_horizons.sql"),
98
98
after: None,
99
99
},
100
Migration {
101
script: include_str!("migrations/0023_channel_mentions.sql"),
102
after: None,
103
},
100
104
];
101
105
102
106
pub fn latest_version() -> i64 {
@@ -97,6 +97,10 @@ const MIGRATIONS: &[Migration] = &[97
script: include_str!("migrations/0022_read_horizons.sql"),97
script: include_str!("migrations/0022_read_horizons.sql"),98
after: None,98
after: None,99
},99
},100
Migration {101
script: include_str!("migrations/0023_channel_mentions.sql"),102
after: None,103
},100
];104
];101
105
102
pub fn latest_version() -> i64 {106
pub fn latest_version() -> i64 {@@ -0,0 +1,6 @@
1
CREATE TABLE IF NOT EXISTS channel_mentions (
2
channel_id TEXT PRIMARY KEY NOT NULL,
3
personal INTEGER NOT NULL DEFAULT 0,
4
channel INTEGER NOT NULL DEFAULT 0,
5
team INTEGER NOT NULL DEFAULT 0
6
);
@@ -0,0 +1,6 @@1
CREATE TABLE IF NOT EXISTS channel_mentions (2
channel_id TEXT PRIMARY KEY NOT NULL,3
personal INTEGER NOT NULL DEFAULT 0,4
channel INTEGER NOT NULL DEFAULT 0,5
team INTEGER NOT NULL DEFAULT 06
);@@ -147,6 +147,7 @@ pub struct SidebarTeam {
147
147
pub hidden: bool,
148
148
pub hidden_channel_ids: Vec<String>,
149
149
pub notifications: HashMap<String, ChannelNotifications>,
150
pub mentions: HashMap<String, ChannelMentions>,
150
151
}
151
152
152
153
impl SidebarTeam {
@@ -156,6 +157,24 @@ impl SidebarTeam {
156
157
.copied()
157
158
.unwrap_or_default()
158
159
}
160
161
pub fn channel_mentions(&self, channel_id: &str) -> ChannelMentions {
162
self.mentions.get(channel_id).copied().unwrap_or_default()
163
}
164
}
165
166
/// Unread @mentions of one channel: personal (person or tag), @channel, @team.
167
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
168
pub struct ChannelMentions {
169
pub personal: u32,
170
pub channel: u32,
171
pub team: u32,
172
}
173
174
impl ChannelMentions {
175
pub fn is_empty(&self) -> bool {
176
*self == ChannelMentions::default()
177
}
159
178
}
160
179
161
180
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
@@ -147,6 +147,7 @@ pub struct SidebarTeam {147
pub hidden: bool,147
pub hidden: bool,148
pub hidden_channel_ids: Vec<String>,148
pub hidden_channel_ids: Vec<String>,149
pub notifications: HashMap<String, ChannelNotifications>,149
pub notifications: HashMap<String, ChannelNotifications>,150
pub mentions: HashMap<String, ChannelMentions>,150
}151
}151
152
152
impl SidebarTeam {153
impl SidebarTeam {@@ -156,6 +157,24 @@ impl SidebarTeam {156
.copied()157
.copied()157
.unwrap_or_default()158
.unwrap_or_default()158
}159
}160
161
pub fn channel_mentions(&self, channel_id: &str) -> ChannelMentions {162
self.mentions.get(channel_id).copied().unwrap_or_default()163
}164
}165
166
/// Unread @mentions of one channel: personal (person or tag), @channel, @team.167
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]168
pub struct ChannelMentions {169
pub personal: u32,170
pub channel: u32,171
pub team: u32,172
}173
174
impl ChannelMentions {175
pub fn is_empty(&self) -> bool {176
*self == ChannelMentions::default()177
}159
}178
}160
179
161
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]180
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]@@ -5,8 +5,8 @@ use rusqlite::params;
5
5
6
6
use crate::error::Result;
7
7
use crate::models::{
8
ChannelNotificationLevel, ChannelNotifications, ChannelRecord, ChannelTabRecord, Sidebar,
9
SidebarTeam, TeamLayoutRecord, TeamRecord,
8
ChannelMentions, ChannelNotificationLevel, ChannelNotifications, ChannelRecord,
9
ChannelTabRecord, Sidebar, SidebarTeam, TeamLayoutRecord, TeamRecord,
10
10
};
11
11
use crate::store::Store;
12
12
use crate::teams::channel_from_row;
@@ -83,6 +83,19 @@ impl Store {
83
83
.then_with(|| compare_names(&left.channel.name, &right.channel.name))
84
84
.then_with(|| left.channel.id.cmp(&right.channel.id))
85
85
});
86
let mut mentions: HashMap<String, ChannelMentions> = connection
87
.prepare_cached("SELECT channel_id, personal, channel, team FROM channel_mentions")?
88
.query_map([], |row| {
89
Ok((
90
row.get::<_, String>(0)?,
91
ChannelMentions {
92
personal: row.get(1)?,
93
channel: row.get(2)?,
94
team: row.get(3)?,
95
},
96
))
97
})?
98
.collect::<rusqlite::Result<_>>()?;
86
99
let mut teams: Vec<SidebarTeam> = team_rows
87
100
.into_iter()
88
101
.map(|row| SidebarTeam {
@@ -91,6 +104,7 @@ impl Store {
91
104
hidden: row.hidden,
92
105
hidden_channel_ids: Vec::new(),
93
106
notifications: HashMap::new(),
107
mentions: HashMap::new(),
94
108
})
95
109
.collect();
96
110
for row in channel_rows {
@@ -105,6 +119,9 @@ impl Store {
105
119
team.notifications
106
120
.insert(row.channel.id.clone(), row.notifications);
107
121
}
122
if let Some(found) = mentions.remove(&row.channel.id) {
123
team.mentions.insert(row.channel.id.clone(), found);
124
}
108
125
team.channels.push(row.channel);
109
126
}
110
127
}
@@ -156,6 +173,47 @@ impl Store {
156
173
Ok(transaction.commit()?)
157
174
}
158
175
176
/// Replaces every stored mention count; channels left out have none.
177
pub fn replace_channel_mentions(&self, mentions: &[(String, ChannelMentions)]) -> Result<()> {
178
let mut connection = self.lock()?;
179
let transaction = connection.transaction()?;
180
transaction.execute("DELETE FROM channel_mentions", [])?;
181
{
182
let mut insert = transaction.prepare_cached(
183
"INSERT OR REPLACE INTO channel_mentions (channel_id, personal, channel, team)
184
VALUES (?1, ?2, ?3, ?4)",
185
)?;
186
for (channel_id, counts) in mentions.iter().filter(|(_, counts)| !counts.is_empty()) {
187
insert.execute(params![channel_id, counts.personal, counts.channel, counts.team])?;
188
}
189
}
190
Ok(transaction.commit()?)
191
}
192
193
pub fn clear_channel_mentions(&self, channel_id: &str) -> Result<()> {
194
self.lock()?.execute(
195
"DELETE FROM channel_mentions WHERE channel_id = ?1",
196
[channel_id],
197
)?;
198
Ok(())
199
}
200
201
/// The team's own thread id, which Teams' CSA routes take: the id of its General channel.
202
pub fn team_thread_id(&self, team_id: &str) -> Result<Option<String>> {
203
let connection = self.lock()?;
204
Ok(connection
205
.prepare_cached(
206
"SELECT channels.id FROM channels
207
LEFT JOIN channel_layout ON channel_layout.channel_id = channels.id
208
WHERE channels.team_id = ?1
209
AND COALESCE(channel_layout.general, channels.name = ?2)
210
ORDER BY channels.id LIMIT 1",
211
)?
212
.query_map(params![team_id, GENERAL_FALLBACK_NAME], |row| row.get(0))?
213
.next()
214
.transpose()?)
215
}
216
159
217
pub fn set_channel_notifications(
160
218
&self,
161
219
channel_id: &str,
@@ -176,6 +234,26 @@ impl Store {
176
234
)?;
177
235
Ok(())
178
236
}
237
238
pub fn set_channel_hidden(&self, channel_id: &str, hidden: bool) -> Result<()> {
239
self.lock()?.execute(
240
"INSERT INTO channel_layout (channel_id, general, hidden)
241
SELECT id, name = ?2, ?3 FROM channels WHERE id = ?1
242
ON CONFLICT (channel_id) DO UPDATE SET hidden = excluded.hidden",
243
params![channel_id, GENERAL_FALLBACK_NAME, hidden],
244
)?;
245
Ok(())
246
}
247
248
pub fn set_team_hidden(&self, team_id: &str, hidden: bool) -> Result<()> {
249
self.lock()?.execute(
250
"INSERT INTO team_layout (team_id, position, hidden)
251
SELECT ?1, COALESCE(MAX(position) + 1, 0), ?2 FROM team_layout WHERE true
252
ON CONFLICT (team_id) DO UPDATE SET hidden = excluded.hidden",
253
params![team_id, hidden],
254
)?;
255
Ok(())
256
}
179
257
}
180
258
181
259
impl Store {
@@ -5,8 +5,8 @@ use rusqlite::params;5
5
6
use crate::error::Result;6
use crate::error::Result;7
use crate::models::{7
use crate::models::{8
ChannelNotificationLevel, ChannelNotifications, ChannelRecord, ChannelTabRecord, Sidebar,8
ChannelMentions, ChannelNotificationLevel, ChannelNotifications, ChannelRecord,9
SidebarTeam, TeamLayoutRecord, TeamRecord,9
ChannelTabRecord, Sidebar, SidebarTeam, TeamLayoutRecord, TeamRecord,10
};10
};11
use crate::store::Store;11
use crate::store::Store;12
use crate::teams::channel_from_row;12
use crate::teams::channel_from_row;@@ -83,6 +83,19 @@ impl Store {83
.then_with(|| compare_names(&left.channel.name, &right.channel.name))83
.then_with(|| compare_names(&left.channel.name, &right.channel.name))84
.then_with(|| left.channel.id.cmp(&right.channel.id))84
.then_with(|| left.channel.id.cmp(&right.channel.id))85
});85
});86
let mut mentions: HashMap<String, ChannelMentions> = connection87
.prepare_cached("SELECT channel_id, personal, channel, team FROM channel_mentions")?88
.query_map([], |row| {89
Ok((90
row.get::<_, String>(0)?,91
ChannelMentions {92
personal: row.get(1)?,93
channel: row.get(2)?,94
team: row.get(3)?,95
},96
))97
})?98
.collect::<rusqlite::Result<_>>()?;86
let mut teams: Vec<SidebarTeam> = team_rows99
let mut teams: Vec<SidebarTeam> = team_rows87
.into_iter()100
.into_iter()88
.map(|row| SidebarTeam {101
.map(|row| SidebarTeam {@@ -91,6 +104,7 @@ impl Store {91
hidden: row.hidden,104
hidden: row.hidden,92
hidden_channel_ids: Vec::new(),105
hidden_channel_ids: Vec::new(),93
notifications: HashMap::new(),106
notifications: HashMap::new(),107
mentions: HashMap::new(),94
})108
})95
.collect();109
.collect();96
for row in channel_rows {110
for row in channel_rows {@@ -105,6 +119,9 @@ impl Store {105
team.notifications119
team.notifications106
.insert(row.channel.id.clone(), row.notifications);120
.insert(row.channel.id.clone(), row.notifications);107
}121
}122
if let Some(found) = mentions.remove(&row.channel.id) {123
team.mentions.insert(row.channel.id.clone(), found);124
}108
team.channels.push(row.channel);125
team.channels.push(row.channel);109
}126
}110
}127
}@@ -156,6 +173,47 @@ impl Store {156
Ok(transaction.commit()?)173
Ok(transaction.commit()?)157
}174
}158
175
176
/// Replaces every stored mention count; channels left out have none.177
pub fn replace_channel_mentions(&self, mentions: &[(String, ChannelMentions)]) -> Result<()> {178
let mut connection = self.lock()?;179
let transaction = connection.transaction()?;180
transaction.execute("DELETE FROM channel_mentions", [])?;181
{182
let mut insert = transaction.prepare_cached(183
"INSERT OR REPLACE INTO channel_mentions (channel_id, personal, channel, team)184
VALUES (?1, ?2, ?3, ?4)",185
)?;186
for (channel_id, counts) in mentions.iter().filter(|(_, counts)| !counts.is_empty()) {187
insert.execute(params![channel_id, counts.personal, counts.channel, counts.team])?;188
}189
}190
Ok(transaction.commit()?)191
}192
193
pub fn clear_channel_mentions(&self, channel_id: &str) -> Result<()> {194
self.lock()?.execute(195
"DELETE FROM channel_mentions WHERE channel_id = ?1",196
[channel_id],197
)?;198
Ok(())199
}200
201
/// The team's own thread id, which Teams' CSA routes take: the id of its General channel.202
pub fn team_thread_id(&self, team_id: &str) -> Result<Option<String>> {203
let connection = self.lock()?;204
Ok(connection205
.prepare_cached(206
"SELECT channels.id FROM channels207
LEFT JOIN channel_layout ON channel_layout.channel_id = channels.id208
WHERE channels.team_id = ?1209
AND COALESCE(channel_layout.general, channels.name = ?2)210
ORDER BY channels.id LIMIT 1",211
)?212
.query_map(params![team_id, GENERAL_FALLBACK_NAME], |row| row.get(0))?213
.next()214
.transpose()?)215
}216
159
pub fn set_channel_notifications(217
pub fn set_channel_notifications(160
&self,218
&self,161
channel_id: &str,219
channel_id: &str,@@ -176,6 +234,26 @@ impl Store {176
)?;234
)?;177
Ok(())235
Ok(())178
}236
}237
238
pub fn set_channel_hidden(&self, channel_id: &str, hidden: bool) -> Result<()> {239
self.lock()?.execute(240
"INSERT INTO channel_layout (channel_id, general, hidden)241
SELECT id, name = ?2, ?3 FROM channels WHERE id = ?1242
ON CONFLICT (channel_id) DO UPDATE SET hidden = excluded.hidden",243
params![channel_id, GENERAL_FALLBACK_NAME, hidden],244
)?;245
Ok(())246
}247
248
pub fn set_team_hidden(&self, team_id: &str, hidden: bool) -> Result<()> {249
self.lock()?.execute(250
"INSERT INTO team_layout (team_id, position, hidden)251
SELECT ?1, COALESCE(MAX(position) + 1, 0), ?2 FROM team_layout WHERE true252
ON CONFLICT (team_id) DO UPDATE SET hidden = excluded.hidden",253
params![team_id, hidden],254
)?;255
Ok(())256
}179
}257
}180
258
181
impl Store {259
impl Store {@@ -78,6 +78,14 @@ impl Store {
78
78
Ok(())
79
79
}
80
80
81
pub fn mark_all_channels_read(&self) -> Result<()> {
82
let mut connection = self.lock()?;
83
let transaction = connection.transaction()?;
84
transaction.execute("UPDATE channels SET unread = 0 WHERE unread != 0", [])?;
85
transaction.execute("DELETE FROM channel_mentions", [])?;
86
Ok(transaction.commit()?)
87
}
88
81
89
pub fn remove_teams_except(&self, kept_team_ids: &[String]) -> Result<usize> {
82
90
let mut connection = self.lock()?;
83
91
let transaction = connection.transaction()?;
@@ -78,6 +78,14 @@ impl Store {78
Ok(())78
Ok(())79
}79
}80
80
81
pub fn mark_all_channels_read(&self) -> Result<()> {82
let mut connection = self.lock()?;83
let transaction = connection.transaction()?;84
transaction.execute("UPDATE channels SET unread = 0 WHERE unread != 0", [])?;85
transaction.execute("DELETE FROM channel_mentions", [])?;86
Ok(transaction.commit()?)87
}88
81
pub fn remove_teams_except(&self, kept_team_ids: &[String]) -> Result<usize> {89
pub fn remove_teams_except(&self, kept_team_ids: &[String]) -> Result<usize> {82
let mut connection = self.lock()?;90
let mut connection = self.lock()?;83
let transaction = connection.transaction()?;91
let transaction = connection.transaction()?;@@ -1,10 +1,10 @@
1
1
use chrono::{DateTime, TimeZone, Utc};
2
2
use rusqlite::Connection;
3
3
use store::{
4
AvatarRecord, ChannelLayoutRecord, ChannelNotificationLevel, ChannelNotifications,
5
ChannelRecord, ChannelTabRecord, ChatPreview, ChatRecord, FolderRecord, MemberRecord,
6
MessageRecord, ReadHorizonRecord, RecentScope, Store, SyncState, TeamLayoutRecord,
7
TeamRecord, UNKNOWN_USER_NAME,
4
AvatarRecord, ChannelLayoutRecord, ChannelMentions, ChannelNotificationLevel,
5
ChannelNotifications, ChannelRecord, ChannelTabRecord, ChatPreview, ChatRecord, FolderRecord,
6
MemberRecord, MessageRecord, ReadHorizonRecord, RecentScope, Store, SyncState,
7
TeamLayoutRecord, TeamRecord, UNKNOWN_USER_NAME,
8
8
};
9
9
10
10
#[test]
@@ -546,11 +546,11 @@ fn file_database_uses_wal_persists_and_migrates_once() {
546
546
let path = directory.path().join("nested").join("cache.sqlite3");
547
547
{
548
548
let store = Store::open(&path).unwrap();
549
assert_eq!(store.schema_version().unwrap(), 22);
549
assert_eq!(store.schema_version().unwrap(), 23);
550
550
store.upsert_messages(&[message("c", "m1", 1)]).unwrap();
551
551
}
552
552
let reopened = Store::open(&path).unwrap();
553
assert_eq!(reopened.schema_version().unwrap(), 22);
553
assert_eq!(reopened.schema_version().unwrap(), 23);
554
554
assert_eq!(reopened.message_count("c").unwrap(), 1);
555
555
drop(reopened);
556
556
let mode: String = rusqlite_open(&path)
@@ -582,7 +582,7 @@ fn old_schema_is_upgraded_in_place() {
582
582
connection.execute_batch("DROP TABLE messages; DROP TABLE sync_state; DROP TABLE chats; DROP TABLE chat_members; DROP TABLE channels; DROP TABLE teams; DROP TABLE meta; DROP TABLE avatars; DROP TABLE folder_items; DROP TABLE folders; DROP TABLE pinned_channels; DROP TABLE images; DROP TABLE search_keys; DROP TABLE message_search; DROP TABLE title_search; DROP TABLE team_layout; DROP TABLE channel_layout; DROP TABLE channel_tabs; DROP TABLE presence; DROP TABLE activity; DROP TABLE outbox; DROP TABLE drafts; DROP TABLE attachment_images; DROP TABLE agent_reaction_proposals; DROP TABLE agent_proposals; PRAGMA user_version = 0").unwrap();
583
583
drop(connection);
584
584
let store = Store::open(&path).unwrap();
585
assert_eq!(store.schema_version().unwrap(), 22);
585
assert_eq!(store.schema_version().unwrap(), 23);
586
586
store.upsert_messages(&[message("c", "m1", 1)]).unwrap();
587
587
}
588
588
@@ -648,7 +648,7 @@ fn migration_to_v2_keeps_existing_sync_state() {
648
648
let store = Store::open(&path).unwrap();
649
649
let state = store.sync_state("c").unwrap().unwrap();
650
650
assert_eq!(state.delta_link, None);
651
assert_eq!(store.schema_version().unwrap(), 22);
651
assert_eq!(store.schema_version().unwrap(), 23);
652
652
}
653
653
654
654
#[test]
@@ -677,7 +677,10 @@ fn migration_to_v13_clears_channel_delta_links_only() {
677
677
}
678
678
let store = Store::open(&path).unwrap();
679
679
assert_eq!(
680
store.sync_state("ch").unwrap().and_then(|state| state.delta_link),
680
store
681
.sync_state("ch")
682
.unwrap()
683
.and_then(|state| state.delta_link),
681
684
None
682
685
);
683
686
assert_eq!(
@@ -1302,6 +1305,98 @@ fn channel_notifications_default_to_feed_and_survive_layout_and_local_writes() {
1302
1305
assert_eq!(team().channel_notifications("c2"), off);
1303
1306
}
1304
1307
1308
#[test]
1309
fn channel_mentions_are_replaced_whole_and_cleared_per_channel() {
1310
let store = Store::open_in_memory().unwrap();
1311
store
1312
.upsert_teams(&[TeamRecord {
1313
id: "t1".to_owned(),
1314
name: "Alpha".to_owned(),
1315
}])
1316
.unwrap();
1317
let channel = |id: &str, name: &str| ChannelRecord {
1318
id: id.to_owned(),
1319
team_id: "t1".to_owned(),
1320
name: name.to_owned(),
1321
membership_type: None,
1322
last_message_at: None,
1323
unread: true,
1324
};
1325
store
1326
.upsert_channels(&[channel("c1", "General"), channel("c2", "Random")])
1327
.unwrap();
1328
let counts = |personal, channel, team| ChannelMentions {
1329
personal,
1330
channel,
1331
team,
1332
};
1333
store
1334
.replace_channel_mentions(&[
1335
("c1".to_owned(), counts(2, 0, 1)),
1336
("c2".to_owned(), counts(0, 0, 0)),
1337
])
1338
.unwrap();
1339
let team = || store.sidebar().unwrap().teams.remove(0);
1340
assert_eq!(team().channel_mentions("c1"), counts(2, 0, 1));
1341
assert!(!team().mentions.contains_key("c2"));
1342
store
1343
.replace_channel_mentions(&[("c2".to_owned(), counts(0, 1, 0))])
1344
.unwrap();
1345
assert_eq!(team().channel_mentions("c1"), ChannelMentions::default());
1346
assert_eq!(team().channel_mentions("c2"), counts(0, 1, 0));
1347
store.clear_channel_mentions("c2").unwrap();
1348
assert!(team().mentions.is_empty());
1349
}
1350
1351
#[test]
1352
fn the_team_thread_id_is_the_general_channel_id() {
1353
let store = Store::open_in_memory().unwrap();
1354
store
1355
.upsert_teams(&["group-a", "group-b"].map(|id| TeamRecord {
1356
id: id.to_owned(),
1357
name: id.to_owned(),
1358
}))
1359
.unwrap();
1360
let channel = |id: &str, team_id: &str, name: &str| ChannelRecord {
1361
id: id.to_owned(),
1362
team_id: team_id.to_owned(),
1363
name: name.to_owned(),
1364
membership_type: None,
1365
last_message_at: None,
1366
unread: false,
1367
};
1368
store
1369
.upsert_channels(&[
1370
channel("19:a-random", "group-a", "Random"),
1371
channel("19:a-general", "group-a", "General"),
1372
channel("19:b-renamed", "group-b", "Allgemein"),
1373
channel("19:b-other", "group-b", "Other"),
1374
])
1375
.unwrap();
1376
store
1377
.replace_team_layout(&[TeamLayoutRecord {
1378
team_id: "group-b".to_owned(),
1379
hidden: false,
1380
channels: vec![ChannelLayoutRecord {
1381
channel_id: "19:b-renamed".to_owned(),
1382
general: true,
1383
hidden: false,
1384
tabs: Vec::new(),
1385
notifications: ChannelNotifications::default(),
1386
}],
1387
}])
1388
.unwrap();
1389
assert_eq!(
1390
store.team_thread_id("group-a").unwrap().as_deref(),
1391
Some("19:a-general")
1392
);
1393
assert_eq!(
1394
store.team_thread_id("group-b").unwrap().as_deref(),
1395
Some("19:b-renamed")
1396
);
1397
assert_eq!(store.team_thread_id("group-c").unwrap(), None);
1398
}
1399
1305
1400
#[test]
1306
1401
fn recent_messages_run_newest_first_across_scopes_with_a_cursor() {
1307
1402
let store = Store::open_in_memory().unwrap();
@@ -1411,23 +1506,33 @@ fn migration_to_v20_adds_the_call_event_column() {
1411
1506
{
1412
1507
let store = Store::open(&path).unwrap();
1413
1508
store.upsert_messages(&[message("c", "old", 1)]).unwrap();
1414
store.upsert_chats(&[chat("c", "Chat", Some(at(1)))]).unwrap();
1509
store
1510
.upsert_chats(&[chat("c", "Chat", Some(at(1)))])
1511
.unwrap();
1415
1512
store.set_sync_state("c", &SyncState::default()).unwrap();
1416
store.set_sync_state("channel", &SyncState::default()).unwrap();
1513
store
1514
.set_sync_state("channel", &SyncState::default())
1515
.unwrap();
1417
1516
drop(store);
1418
1517
Connection::open(&path)
1419
1518
.unwrap()
1420
.execute_batch("ALTER TABLE messages DROP COLUMN call_event_json; PRAGMA user_version = 19")
1519
.execute_batch(
1520
"ALTER TABLE messages DROP COLUMN call_event_json; PRAGMA user_version = 19",
1521
)
1421
1522
.unwrap();
1422
1523
}
1423
1524
let store = Store::open(&path).unwrap();
1424
assert_eq!(store.schema_version().unwrap(), 22);
1525
assert_eq!(store.schema_version().unwrap(), 23);
1425
1526
let old = store.messages("c", None, 10).unwrap();
1426
1527
assert_eq!(old[0].call_event_json, None);
1427
1528
assert!(store.sync_state("c").unwrap().is_none());
1428
1529
assert!(store.sync_state("channel").unwrap().is_some());
1429
1530
store.upsert_messages(&[call_message("call", 2)]).unwrap();
1430
assert!(store.messages("c", None, 10).unwrap()[1].call_event_json.is_some());
1531
assert!(
1532
store.messages("c", None, 10).unwrap()[1]
1533
.call_event_json
1534
.is_some()
1535
);
1431
1536
}
1432
1537
1433
1538
#[test]
@@ -1436,7 +1541,9 @@ fn migration_to_v21_refetches_chats_and_channels_for_recordings() {
1436
1541
let path = directory.path().join("old.sqlite3");
1437
1542
{
1438
1543
let store = Store::open(&path).unwrap();
1439
store.upsert_chats(&[chat("c", "Chat", Some(at(1)))]).unwrap();
1544
store
1545
.upsert_chats(&[chat("c", "Chat", Some(at(1)))])
1546
.unwrap();
1440
1547
store
1441
1548
.upsert_teams(&[TeamRecord {
1442
1549
id: "team".to_owned(),
@@ -1465,7 +1572,7 @@ fn migration_to_v21_refetches_chats_and_channels_for_recordings() {
1465
1572
.unwrap();
1466
1573
}
1467
1574
let store = Store::open(&path).unwrap();
1468
assert_eq!(store.schema_version().unwrap(), 22);
1575
assert_eq!(store.schema_version().unwrap(), 23);
1469
1576
assert!(store.sync_state("c").unwrap().is_none());
1470
1577
assert!(store.sync_state("channel").unwrap().is_none());
1471
1578
assert!(store.sync_state("other").unwrap().is_some());
@@ -1485,7 +1592,9 @@ fn migration_to_v22_adds_read_horizons_that_survive_a_reopen() {
1485
1592
let path = directory.path().join("old.sqlite3");
1486
1593
{
1487
1594
let store = Store::open(&path).unwrap();
1488
store.upsert_chats(&[chat("c", "Chat", Some(at(1)))]).unwrap();
1595
store
1596
.upsert_chats(&[chat("c", "Chat", Some(at(1)))])
1597
.unwrap();
1489
1598
drop(store);
1490
1599
Connection::open(&path)
1491
1600
.unwrap()
@@ -1493,9 +1602,12 @@ fn migration_to_v22_adds_read_horizons_that_survive_a_reopen() {
1493
1602
.unwrap();
1494
1603
}
1495
1604
let store = Store::open(&path).unwrap();
1496
assert_eq!(store.schema_version().unwrap(), 22);
1605
assert_eq!(store.schema_version().unwrap(), 23);
1497
1606
assert!(store.read_horizons("c").unwrap().is_empty());
1498
let horizons = [horizon("8:orgid:ada", 3, Some(4)), horizon("8:orgid:bob", 2, None)];
1607
let horizons = [
1608
horizon("8:orgid:ada", 3, Some(4)),
1609
horizon("8:orgid:bob", 2, None),
1610
];
1499
1611
store.set_read_horizons("c", &horizons).unwrap();
1500
1612
drop(store);
1501
1613
let reopened = Store::open(&path).unwrap();
@@ -1505,11 +1617,57 @@ fn migration_to_v22_adds_read_horizons_that_survive_a_reopen() {
1505
1617
#[test]
1506
1618
fn setting_read_horizons_replaces_the_conversation_only() {
1507
1619
let store = Store::open_in_memory().unwrap();
1508
let first = [horizon("8:orgid:ada", 3, None), horizon("8:orgid:bob", 2, None)];
1620
let first = [
1621
horizon("8:orgid:ada", 3, None),
1622
horizon("8:orgid:bob", 2, None),
1623
];
1509
1624
store.set_read_horizons("c", &first).unwrap();
1510
store.set_read_horizons("other", &[horizon("8:orgid:cy", 1, None)]).unwrap();
1625
store
1626
.set_read_horizons("other", &[horizon("8:orgid:cy", 1, None)])
1627
.unwrap();
1511
1628
let second = [horizon("8:orgid:ada", 5, Some(6))];
1512
1629
store.set_read_horizons("c", &second).unwrap();
1513
1630
assert_eq!(store.read_horizons("c").unwrap(), second);
1514
1631
assert_eq!(store.read_horizons("other").unwrap().len(), 1);
1515
1632
}
1633
1634
#[test]
1635
fn local_show_hide_and_channel_pin_writes_reach_the_sidebar() {
1636
let store = Store::open_in_memory().unwrap();
1637
store
1638
.upsert_teams(&[TeamRecord {
1639
id: "t1".to_owned(),
1640
name: "Alpha".to_owned(),
1641
}])
1642
.unwrap();
1643
let channel = |id: &str, name: &str| ChannelRecord {
1644
id: id.to_owned(),
1645
team_id: "t1".to_owned(),
1646
name: name.to_owned(),
1647
membership_type: None,
1648
last_message_at: None,
1649
unread: false,
1650
};
1651
store
1652
.upsert_channels(&[channel("c1", "General"), channel("c2", "Random")])
1653
.unwrap();
1654
let team = || store.sidebar().unwrap().teams.remove(0);
1655
1656
store.set_channel_hidden("c2", true).unwrap();
1657
store.set_team_hidden("t1", true).unwrap();
1658
let hidden = team();
1659
assert_eq!(hidden.hidden_channel_ids, vec!["c2".to_owned()]);
1660
assert!(hidden.hidden);
1661
assert_eq!(hidden.channels[0].name, "General");
1662
1663
store.set_channel_hidden("c2", false).unwrap();
1664
store.set_team_hidden("t1", false).unwrap();
1665
let shown = team();
1666
assert!(shown.hidden_channel_ids.is_empty());
1667
assert!(!shown.hidden);
1668
1669
store
1670
.replace_pinned_channels(&["c2".to_owned(), "c1".to_owned()])
1671
.unwrap();
1672
assert_eq!(store.pinned_channel_ids().unwrap(), vec!["c2", "c1"]);
1673
}
@@ -1,10 +1,10 @@1
use chrono::{DateTime, TimeZone, Utc};1
use chrono::{DateTime, TimeZone, Utc};2
use rusqlite::Connection;2
use rusqlite::Connection;3
use store::{3
use store::{4
AvatarRecord, ChannelLayoutRecord, ChannelNotificationLevel, ChannelNotifications,4
AvatarRecord, ChannelLayoutRecord, ChannelMentions, ChannelNotificationLevel,5
ChannelRecord, ChannelTabRecord, ChatPreview, ChatRecord, FolderRecord, MemberRecord,5
ChannelNotifications, ChannelRecord, ChannelTabRecord, ChatPreview, ChatRecord, FolderRecord,6
MessageRecord, ReadHorizonRecord, RecentScope, Store, SyncState, TeamLayoutRecord,6
MemberRecord, MessageRecord, ReadHorizonRecord, RecentScope, Store, SyncState,7
TeamRecord, UNKNOWN_USER_NAME,7
TeamLayoutRecord, TeamRecord, UNKNOWN_USER_NAME,8
};8
};9
9
10
#[test]10
#[test]@@ -546,11 +546,11 @@ fn file_database_uses_wal_persists_and_migrates_once() {546
let path = directory.path().join("nested").join("cache.sqlite3");546
let path = directory.path().join("nested").join("cache.sqlite3");547
{547
{548
let store = Store::open(&path).unwrap();548
let store = Store::open(&path).unwrap();549
assert_eq!(store.schema_version().unwrap(), 22);549
assert_eq!(store.schema_version().unwrap(), 23);550
store.upsert_messages(&[message("c", "m1", 1)]).unwrap();550
store.upsert_messages(&[message("c", "m1", 1)]).unwrap();551
}551
}552
let reopened = Store::open(&path).unwrap();552
let reopened = Store::open(&path).unwrap();553
assert_eq!(reopened.schema_version().unwrap(), 22);553
assert_eq!(reopened.schema_version().unwrap(), 23);554
assert_eq!(reopened.message_count("c").unwrap(), 1);554
assert_eq!(reopened.message_count("c").unwrap(), 1);555
drop(reopened);555
drop(reopened);556
let mode: String = rusqlite_open(&path)556
let mode: String = rusqlite_open(&path)@@ -582,7 +582,7 @@ fn old_schema_is_upgraded_in_place() {582
connection.execute_batch("DROP TABLE messages; DROP TABLE sync_state; DROP TABLE chats; DROP TABLE chat_members; DROP TABLE channels; DROP TABLE teams; DROP TABLE meta; DROP TABLE avatars; DROP TABLE folder_items; DROP TABLE folders; DROP TABLE pinned_channels; DROP TABLE images; DROP TABLE search_keys; DROP TABLE message_search; DROP TABLE title_search; DROP TABLE team_layout; DROP TABLE channel_layout; DROP TABLE channel_tabs; DROP TABLE presence; DROP TABLE activity; DROP TABLE outbox; DROP TABLE drafts; DROP TABLE attachment_images; DROP TABLE agent_reaction_proposals; DROP TABLE agent_proposals; PRAGMA user_version = 0").unwrap();582
connection.execute_batch("DROP TABLE messages; DROP TABLE sync_state; DROP TABLE chats; DROP TABLE chat_members; DROP TABLE channels; DROP TABLE teams; DROP TABLE meta; DROP TABLE avatars; DROP TABLE folder_items; DROP TABLE folders; DROP TABLE pinned_channels; DROP TABLE images; DROP TABLE search_keys; DROP TABLE message_search; DROP TABLE title_search; DROP TABLE team_layout; DROP TABLE channel_layout; DROP TABLE channel_tabs; DROP TABLE presence; DROP TABLE activity; DROP TABLE outbox; DROP TABLE drafts; DROP TABLE attachment_images; DROP TABLE agent_reaction_proposals; DROP TABLE agent_proposals; PRAGMA user_version = 0").unwrap();583
drop(connection);583
drop(connection);584
let store = Store::open(&path).unwrap();584
let store = Store::open(&path).unwrap();585
assert_eq!(store.schema_version().unwrap(), 22);585
assert_eq!(store.schema_version().unwrap(), 23);586
store.upsert_messages(&[message("c", "m1", 1)]).unwrap();586
store.upsert_messages(&[message("c", "m1", 1)]).unwrap();587
}587
}588
588
@@ -648,7 +648,7 @@ fn migration_to_v2_keeps_existing_sync_state() {648
let store = Store::open(&path).unwrap();648
let store = Store::open(&path).unwrap();649
let state = store.sync_state("c").unwrap().unwrap();649
let state = store.sync_state("c").unwrap().unwrap();650
assert_eq!(state.delta_link, None);650
assert_eq!(state.delta_link, None);651
assert_eq!(store.schema_version().unwrap(), 22);651
assert_eq!(store.schema_version().unwrap(), 23);652
}652
}653
653
654
#[test]654
#[test]@@ -677,7 +677,10 @@ fn migration_to_v13_clears_channel_delta_links_only() {677
}677
}678
let store = Store::open(&path).unwrap();678
let store = Store::open(&path).unwrap();679
assert_eq!(679
assert_eq!(680
store.sync_state("ch").unwrap().and_then(|state| state.delta_link),680
store681
.sync_state("ch")682
.unwrap()683
.and_then(|state| state.delta_link),681
None684
None682
);685
);683
assert_eq!(686
assert_eq!(@@ -1302,6 +1305,98 @@ fn channel_notifications_default_to_feed_and_survive_layout_and_local_writes() {1302
assert_eq!(team().channel_notifications("c2"), off);1305
assert_eq!(team().channel_notifications("c2"), off);1303
}1306
}1304
1307
1308
#[test]1309
fn channel_mentions_are_replaced_whole_and_cleared_per_channel() {1310
let store = Store::open_in_memory().unwrap();1311
store1312
.upsert_teams(&[TeamRecord {1313
id: "t1".to_owned(),1314
name: "Alpha".to_owned(),1315
}])1316
.unwrap();1317
let channel = |id: &str, name: &str| ChannelRecord {1318
id: id.to_owned(),1319
team_id: "t1".to_owned(),1320
name: name.to_owned(),1321
membership_type: None,1322
last_message_at: None,1323
unread: true,1324
};1325
store1326
.upsert_channels(&[channel("c1", "General"), channel("c2", "Random")])1327
.unwrap();1328
let counts = |personal, channel, team| ChannelMentions {1329
personal,1330
channel,1331
team,1332
};1333
store1334
.replace_channel_mentions(&[1335
("c1".to_owned(), counts(2, 0, 1)),1336
("c2".to_owned(), counts(0, 0, 0)),1337
])1338
.unwrap();1339
let team = || store.sidebar().unwrap().teams.remove(0);1340
assert_eq!(team().channel_mentions("c1"), counts(2, 0, 1));1341
assert!(!team().mentions.contains_key("c2"));1342
store1343
.replace_channel_mentions(&[("c2".to_owned(), counts(0, 1, 0))])1344
.unwrap();1345
assert_eq!(team().channel_mentions("c1"), ChannelMentions::default());1346
assert_eq!(team().channel_mentions("c2"), counts(0, 1, 0));1347
store.clear_channel_mentions("c2").unwrap();1348
assert!(team().mentions.is_empty());1349
}1350
1351
#[test]1352
fn the_team_thread_id_is_the_general_channel_id() {1353
let store = Store::open_in_memory().unwrap();1354
store1355
.upsert_teams(&["group-a", "group-b"].map(|id| TeamRecord {1356
id: id.to_owned(),1357
name: id.to_owned(),1358
}))1359
.unwrap();1360
let channel = |id: &str, team_id: &str, name: &str| ChannelRecord {1361
id: id.to_owned(),1362
team_id: team_id.to_owned(),1363
name: name.to_owned(),1364
membership_type: None,1365
last_message_at: None,1366
unread: false,1367
};1368
store1369
.upsert_channels(&[1370
channel("19:a-random", "group-a", "Random"),1371
channel("19:a-general", "group-a", "General"),1372
channel("19:b-renamed", "group-b", "Allgemein"),1373
channel("19:b-other", "group-b", "Other"),1374
])1375
.unwrap();1376
store1377
.replace_team_layout(&[TeamLayoutRecord {1378
team_id: "group-b".to_owned(),1379
hidden: false,1380
channels: vec![ChannelLayoutRecord {1381
channel_id: "19:b-renamed".to_owned(),1382
general: true,1383
hidden: false,1384
tabs: Vec::new(),1385
notifications: ChannelNotifications::default(),1386
}],1387
}])1388
.unwrap();1389
assert_eq!(1390
store.team_thread_id("group-a").unwrap().as_deref(),1391
Some("19:a-general")1392
);1393
assert_eq!(1394
store.team_thread_id("group-b").unwrap().as_deref(),1395
Some("19:b-renamed")1396
);1397
assert_eq!(store.team_thread_id("group-c").unwrap(), None);1398
}1399
1305
#[test]1400
#[test]1306
fn recent_messages_run_newest_first_across_scopes_with_a_cursor() {1401
fn recent_messages_run_newest_first_across_scopes_with_a_cursor() {1307
let store = Store::open_in_memory().unwrap();1402
let store = Store::open_in_memory().unwrap();@@ -1411,23 +1506,33 @@ fn migration_to_v20_adds_the_call_event_column() {1411
{1506
{1412
let store = Store::open(&path).unwrap();1507
let store = Store::open(&path).unwrap();1413
store.upsert_messages(&[message("c", "old", 1)]).unwrap();1508
store.upsert_messages(&[message("c", "old", 1)]).unwrap();1414
store.upsert_chats(&[chat("c", "Chat", Some(at(1)))]).unwrap();1509
store1510
.upsert_chats(&[chat("c", "Chat", Some(at(1)))])1511
.unwrap();1415
store.set_sync_state("c", &SyncState::default()).unwrap();1512
store.set_sync_state("c", &SyncState::default()).unwrap();1416
store.set_sync_state("channel", &SyncState::default()).unwrap();1513
store1514
.set_sync_state("channel", &SyncState::default())1515
.unwrap();1417
drop(store);1516
drop(store);1418
Connection::open(&path)1517
Connection::open(&path)1419
.unwrap()1518
.unwrap()1420
.execute_batch("ALTER TABLE messages DROP COLUMN call_event_json; PRAGMA user_version = 19")1519
.execute_batch(1520
"ALTER TABLE messages DROP COLUMN call_event_json; PRAGMA user_version = 19",1521
)1421
.unwrap();1522
.unwrap();1422
}1523
}1423
let store = Store::open(&path).unwrap();1524
let store = Store::open(&path).unwrap();1424
assert_eq!(store.schema_version().unwrap(), 22);1525
assert_eq!(store.schema_version().unwrap(), 23);1425
let old = store.messages("c", None, 10).unwrap();1526
let old = store.messages("c", None, 10).unwrap();1426
assert_eq!(old[0].call_event_json, None);1527
assert_eq!(old[0].call_event_json, None);1427
assert!(store.sync_state("c").unwrap().is_none());1528
assert!(store.sync_state("c").unwrap().is_none());1428
assert!(store.sync_state("channel").unwrap().is_some());1529
assert!(store.sync_state("channel").unwrap().is_some());1429
store.upsert_messages(&[call_message("call", 2)]).unwrap();1530
store.upsert_messages(&[call_message("call", 2)]).unwrap();1430
assert!(store.messages("c", None, 10).unwrap()[1].call_event_json.is_some());1531
assert!(1532
store.messages("c", None, 10).unwrap()[1]1533
.call_event_json1534
.is_some()1535
);1431
}1536
}1432
1537
1433
#[test]1538
#[test]@@ -1436,7 +1541,9 @@ fn migration_to_v21_refetches_chats_and_channels_for_recordings() {1436
let path = directory.path().join("old.sqlite3");1541
let path = directory.path().join("old.sqlite3");1437
{1542
{1438
let store = Store::open(&path).unwrap();1543
let store = Store::open(&path).unwrap();1439
store.upsert_chats(&[chat("c", "Chat", Some(at(1)))]).unwrap();1544
store1545
.upsert_chats(&[chat("c", "Chat", Some(at(1)))])1546
.unwrap();1440
store1547
store1441
.upsert_teams(&[TeamRecord {1548
.upsert_teams(&[TeamRecord {1442
id: "team".to_owned(),1549
id: "team".to_owned(),@@ -1465,7 +1572,7 @@ fn migration_to_v21_refetches_chats_and_channels_for_recordings() {1465
.unwrap();1572
.unwrap();1466
}1573
}1467
let store = Store::open(&path).unwrap();1574
let store = Store::open(&path).unwrap();1468
assert_eq!(store.schema_version().unwrap(), 22);1575
assert_eq!(store.schema_version().unwrap(), 23);1469
assert!(store.sync_state("c").unwrap().is_none());1576
assert!(store.sync_state("c").unwrap().is_none());1470
assert!(store.sync_state("channel").unwrap().is_none());1577
assert!(store.sync_state("channel").unwrap().is_none());1471
assert!(store.sync_state("other").unwrap().is_some());1578
assert!(store.sync_state("other").unwrap().is_some());@@ -1485,7 +1592,9 @@ fn migration_to_v22_adds_read_horizons_that_survive_a_reopen() {1485
let path = directory.path().join("old.sqlite3");1592
let path = directory.path().join("old.sqlite3");1486
{1593
{1487
let store = Store::open(&path).unwrap();1594
let store = Store::open(&path).unwrap();1488
store.upsert_chats(&[chat("c", "Chat", Some(at(1)))]).unwrap();1595
store1596
.upsert_chats(&[chat("c", "Chat", Some(at(1)))])1597
.unwrap();1489
drop(store);1598
drop(store);1490
Connection::open(&path)1599
Connection::open(&path)1491
.unwrap()1600
.unwrap()@@ -1493,9 +1602,12 @@ fn migration_to_v22_adds_read_horizons_that_survive_a_reopen() {1493
.unwrap();1602
.unwrap();1494
}1603
}1495
let store = Store::open(&path).unwrap();1604
let store = Store::open(&path).unwrap();1496
assert_eq!(store.schema_version().unwrap(), 22);1605
assert_eq!(store.schema_version().unwrap(), 23);1497
assert!(store.read_horizons("c").unwrap().is_empty());1606
assert!(store.read_horizons("c").unwrap().is_empty());1498
let horizons = [horizon("8:orgid:ada", 3, Some(4)), horizon("8:orgid:bob", 2, None)];1607
let horizons = [1608
horizon("8:orgid:ada", 3, Some(4)),1609
horizon("8:orgid:bob", 2, None),1610
];1499
store.set_read_horizons("c", &horizons).unwrap();1611
store.set_read_horizons("c", &horizons).unwrap();1500
drop(store);1612
drop(store);1501
let reopened = Store::open(&path).unwrap();1613
let reopened = Store::open(&path).unwrap();@@ -1505,11 +1617,57 @@ fn migration_to_v22_adds_read_horizons_that_survive_a_reopen() {1505
#[test]1617
#[test]1506
fn setting_read_horizons_replaces_the_conversation_only() {1618
fn setting_read_horizons_replaces_the_conversation_only() {1507
let store = Store::open_in_memory().unwrap();1619
let store = Store::open_in_memory().unwrap();1508
let first = [horizon("8:orgid:ada", 3, None), horizon("8:orgid:bob", 2, None)];1620
let first = [1621
horizon("8:orgid:ada", 3, None),1622
horizon("8:orgid:bob", 2, None),1623
];1509
store.set_read_horizons("c", &first).unwrap();1624
store.set_read_horizons("c", &first).unwrap();1510
store.set_read_horizons("other", &[horizon("8:orgid:cy", 1, None)]).unwrap();1625
store1626
.set_read_horizons("other", &[horizon("8:orgid:cy", 1, None)])1627
.unwrap();1511
let second = [horizon("8:orgid:ada", 5, Some(6))];1628
let second = [horizon("8:orgid:ada", 5, Some(6))];1512
store.set_read_horizons("c", &second).unwrap();1629
store.set_read_horizons("c", &second).unwrap();1513
assert_eq!(store.read_horizons("c").unwrap(), second);1630
assert_eq!(store.read_horizons("c").unwrap(), second);1514
assert_eq!(store.read_horizons("other").unwrap().len(), 1);1631
assert_eq!(store.read_horizons("other").unwrap().len(), 1);1515
}1632
}1633
1634
#[test]1635
fn local_show_hide_and_channel_pin_writes_reach_the_sidebar() {1636
let store = Store::open_in_memory().unwrap();1637
store1638
.upsert_teams(&[TeamRecord {1639
id: "t1".to_owned(),1640
name: "Alpha".to_owned(),1641
}])1642
.unwrap();1643
let channel = |id: &str, name: &str| ChannelRecord {1644
id: id.to_owned(),1645
team_id: "t1".to_owned(),1646
name: name.to_owned(),1647
membership_type: None,1648
last_message_at: None,1649
unread: false,1650
};1651
store1652
.upsert_channels(&[channel("c1", "General"), channel("c2", "Random")])1653
.unwrap();1654
let team = || store.sidebar().unwrap().teams.remove(0);1655
1656
store.set_channel_hidden("c2", true).unwrap();1657
store.set_team_hidden("t1", true).unwrap();1658
let hidden = team();1659
assert_eq!(hidden.hidden_channel_ids, vec!["c2".to_owned()]);1660
assert!(hidden.hidden);1661
assert_eq!(hidden.channels[0].name, "General");1662
1663
store.set_channel_hidden("c2", false).unwrap();1664
store.set_team_hidden("t1", false).unwrap();1665
let shown = team();1666
assert!(shown.hidden_channel_ids.is_empty());1667
assert!(!shown.hidden);1668
1669
store1670
.replace_pinned_channels(&["c2".to_owned(), "c1".to_owned()])1671
.unwrap();1672
assert_eq!(store.pinned_channel_ids().unwrap(), vec!["c2", "c1"]);1673
}