BlueGit

ict rusty-teams

feat(channels): turn notifications for a post on and off

- post menu on channel root posts: "Turn off notifications" / "Turn on notifications" (posts layout labels, canFollow path)
- write like Teams: chatsvc PUT users/{mri}/.../rcmetadata/{root} {"f":1|3}, then the "follow" emotion 1|0 on the root post
- state: getrcmetadata read on first hover, else followed when I wrote the root or a reply
- toasts "Notifications turned on/off", errors "Couldn't turn on/off notifications"
- deviations: no follow-annotation, followAllRc or L1-author fallback in the state read; menu position after Pin inferred; threads layout "Follow thread" not built

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

metis Daniel Däschle · pushed by metis

Authored 2026-11-04 · 3 weeks ago

Hash
86c378055575a943fb26d7f982c095bdd6882427
Parent
e8895ea5
12 files changed +593 −5
crates/app-state/src/app_state.rs +2 −0
@@ -132,6 +132,7 @@ pub struct AppState {
132 132 pub calendar_nudge: Option<tokio::sync::mpsc::UnboundedSender<()>>,
133 133 pub calls_list: crate::call::CallsList,
134 134 pub pins: HashMap<String, Vec<PinnedMessage>>,
135 pub post_follows: crate::post_follow::PostFollows,
135 136 pub forward_request: Option<ForwardSource>,
136 137 pub forward_selection: Option<ForwardSelection>,
137 138 pub image_viewer_request: Option<ViewerRequest>,
@@ -295,6 +296,7 @@ impl AppState {
295 296 calendar_nudge: None,
296 297 calls_list: crate::call::CallsList::default(),
297 298 pins: HashMap::new(),
299 post_follows: Default::default(),
298 300 forward_request: None,
299 301 forward_selection: None,
300 302 image_viewer_request: None,
@@ -132,6 +132,7 @@ pub struct AppState {
132 pub calendar_nudge: Option<tokio::sync::mpsc::UnboundedSender<()>>,
132 pub calendar_nudge: Option<tokio::sync::mpsc::UnboundedSender<()>>,
133 pub calls_list: crate::call::CallsList,
133 pub calls_list: crate::call::CallsList,
134 pub pins: HashMap<String, Vec<PinnedMessage>>,
134 pub pins: HashMap<String, Vec<PinnedMessage>>,
135 pub post_follows: crate::post_follow::PostFollows,
135 pub forward_request: Option<ForwardSource>,
136 pub forward_request: Option<ForwardSource>,
136 pub forward_selection: Option<ForwardSelection>,
137 pub forward_selection: Option<ForwardSelection>,
137 pub image_viewer_request: Option<ViewerRequest>,
138 pub image_viewer_request: Option<ViewerRequest>,
@@ -295,6 +296,7 @@ impl AppState {
295 calendar_nudge: None,
296 calendar_nudge: None,
296 calls_list: crate::call::CallsList::default(),
297 calls_list: crate::call::CallsList::default(),
297 pins: HashMap::new(),
298 pins: HashMap::new(),
299 post_follows: Default::default(),
298 forward_request: None,
300 forward_request: None,
299 forward_selection: None,
301 forward_selection: None,
300 image_viewer_request: None,
302 image_viewer_request: None,
crates/app-state/src/lib.rs +1 −0
@@ -37,6 +37,7 @@ pub mod own_status;
37 37 pub mod presence_follow;
38 38 pub mod pending_rows;
39 39 pub mod people;
40 pub mod post_follow;
40 41 pub mod profile_model;
41 42 pub mod profile_state;
42 43 pub mod reaction_model;
@@ -37,6 +37,7 @@ pub mod own_status;
37pub mod presence_follow;
37pub mod presence_follow;
38pub mod pending_rows;
38pub mod pending_rows;
39pub mod people;
39pub mod people;
40pub mod post_follow;
40pub mod profile_model;
41pub mod profile_model;
41pub mod profile_state;
42pub mod profile_state;
42pub mod reaction_model;
43pub mod reaction_model;
crates/app-state/src/post_follow.rs added +170 −0
@@ -0,0 +1,170 @@
1 use std::collections::{HashMap, HashSet};
2
3 use gpui_kit::*;
4 use teams_core::PostFollowState;
5
6 use crate::app_state::AppState;
7 use crate::runtime;
8
9 pub const TURN_OFF_NOTIFICATIONS: &str = "Turn off notifications";
10 pub const TURN_ON_NOTIFICATIONS: &str = "Turn on notifications";
11
12 type PostKey = (String, String);
13
14 #[derive(Default)]
15 pub struct PostFollows {
16 states: HashMap<PostKey, PostFollowState>,
17 requested: HashSet<PostKey>,
18 }
19
20 fn post_key(channel_id: &str, root_id: &str) -> PostKey {
21 (channel_id.to_owned(), root_id.to_owned())
22 }
23
24 /// Teams reads the explicit reply chain state first, then implicit participation.
25 pub fn post_followed(state: Option<PostFollowState>, participated: bool) -> bool {
26 match state {
27 Some(state) => state.followed(),
28 None => participated,
29 }
30 }
31
32 pub fn follow_label(followed: bool) -> &'static str {
33 if followed {
34 TURN_OFF_NOTIFICATIONS
35 } else {
36 TURN_ON_NOTIFICATIONS
37 }
38 }
39
40 pub fn follow_notice(followed: bool) -> &'static str {
41 if followed {
42 "Notifications turned on"
43 } else {
44 "Notifications turned off"
45 }
46 }
47
48 pub fn follow_failure(followed: bool) -> &'static str {
49 if followed {
50 "Couldn't turn on notifications"
51 } else {
52 "Couldn't turn off notifications"
53 }
54 }
55
56 impl AppState {
57 pub fn post_follow_state(&self, channel_id: &str, root_id: &str) -> Option<PostFollowState> {
58 self.post_follows
59 .states
60 .get(&post_key(channel_id, root_id))
61 .copied()
62 }
63
64 pub fn request_post_follow_state(
65 &mut self,
66 channel_id: &str,
67 root_id: &str,
68 cx: &mut Context<Self>,
69 ) {
70 let key = post_key(channel_id, root_id);
71 if !self.post_follows.requested.insert(key) {
72 return;
73 }
74 let Some(engine) = self.engine.clone() else {
75 return;
76 };
77 let (channel, root) = (channel_id.to_owned(), root_id.to_owned());
78 let requested = vec![root.clone()];
79 let requested_channel = channel.clone();
80 let receiver = runtime::spawn(async move {
81 engine
82 .post_follow_states(&requested_channel, &requested)
83 .await
84 });
85 cx.spawn(async move |this, cx| {
86 let outcome = receiver.await;
87 this.update(cx, |state, cx| match outcome {
88 Ok(Ok(states)) => {
89 if let Some(follow_state) = states.get(&root) {
90 state
91 .post_follows
92 .states
93 .insert(post_key(&channel, &root), *follow_state);
94 cx.notify();
95 }
96 }
97 _ => {
98 state.post_follows.requested.remove(&post_key(&channel, &root));
99 }
100 })
101 .ok();
102 })
103 .detach();
104 }
105
106 pub fn set_post_followed(
107 &mut self,
108 channel_id: &str,
109 root_id: &str,
110 followed: bool,
111 cx: &mut Context<Self>,
112 ) {
113 let Some(engine_or_demo) = self.chat_action_engine(cx) else {
114 return;
115 };
116 let key = post_key(channel_id, root_id);
117 let previous = self.post_follows.states.get(&key).copied();
118 let next = if followed {
119 PostFollowState::ExplicitFollow
120 } else {
121 PostFollowState::ExplicitUnfollow
122 };
123 self.post_follows.states.insert(key.clone(), next);
124 cx.notify();
125 let Some(engine) = engine_or_demo else {
126 self.raise_notice(follow_notice(followed).to_owned(), None, cx);
127 return;
128 };
129 let (channel, root) = (channel_id.to_owned(), root_id.to_owned());
130 self.run_channel_action(
131 follow_failure(followed),
132 async move { engine.set_post_followed(&channel, &root, followed).await },
133 move |state, cx| {
134 match previous {
135 Some(previous) => state.post_follows.states.insert(key, previous),
136 None => state.post_follows.states.remove(&key),
137 };
138 cx.notify();
139 },
140 Some(follow_notice(followed)),
141 cx,
142 );
143 }
144 }
145
146 #[cfg(test)]
147 mod tests {
148 use teams_core::PostFollowState;
149
150 use super::{follow_failure, follow_label, follow_notice, post_followed};
151
152 #[test]
153 fn explicit_state_wins_over_participation() {
154 assert!(!post_followed(Some(PostFollowState::ExplicitUnfollow), true));
155 assert!(post_followed(Some(PostFollowState::ExplicitFollow), false));
156 assert!(post_followed(Some(PostFollowState::ImplicitFollow), false));
157 assert!(post_followed(None, true));
158 assert!(!post_followed(None, false));
159 }
160
161 #[test]
162 fn labels_and_notices_use_teams_strings() {
163 assert_eq!(follow_label(true), "Turn off notifications");
164 assert_eq!(follow_label(false), "Turn on notifications");
165 assert_eq!(follow_notice(false), "Notifications turned off");
166 assert_eq!(follow_notice(true), "Notifications turned on");
167 assert_eq!(follow_failure(false), "Couldn't turn off notifications");
168 assert_eq!(follow_failure(true), "Couldn't turn on notifications");
169 }
170 }
@@ -0,0 +1,170 @@
1use std::collections::{HashMap, HashSet};
2
3use gpui_kit::*;
4use teams_core::PostFollowState;
5
6use crate::app_state::AppState;
7use crate::runtime;
8
9pub const TURN_OFF_NOTIFICATIONS: &str = "Turn off notifications";
10pub const TURN_ON_NOTIFICATIONS: &str = "Turn on notifications";
11
12type PostKey = (String, String);
13
14#[derive(Default)]
15pub struct PostFollows {
16 states: HashMap<PostKey, PostFollowState>,
17 requested: HashSet<PostKey>,
18}
19
20fn post_key(channel_id: &str, root_id: &str) -> PostKey {
21 (channel_id.to_owned(), root_id.to_owned())
22}
23
24/// Teams reads the explicit reply chain state first, then implicit participation.
25pub fn post_followed(state: Option<PostFollowState>, participated: bool) -> bool {
26 match state {
27 Some(state) => state.followed(),
28 None => participated,
29 }
30}
31
32pub fn follow_label(followed: bool) -> &'static str {
33 if followed {
34 TURN_OFF_NOTIFICATIONS
35 } else {
36 TURN_ON_NOTIFICATIONS
37 }
38}
39
40pub fn follow_notice(followed: bool) -> &'static str {
41 if followed {
42 "Notifications turned on"
43 } else {
44 "Notifications turned off"
45 }
46}
47
48pub fn follow_failure(followed: bool) -> &'static str {
49 if followed {
50 "Couldn't turn on notifications"
51 } else {
52 "Couldn't turn off notifications"
53 }
54}
55
56impl AppState {
57 pub fn post_follow_state(&self, channel_id: &str, root_id: &str) -> Option<PostFollowState> {
58 self.post_follows
59 .states
60 .get(&post_key(channel_id, root_id))
61 .copied()
62 }
63
64 pub fn request_post_follow_state(
65 &mut self,
66 channel_id: &str,
67 root_id: &str,
68 cx: &mut Context<Self>,
69 ) {
70 let key = post_key(channel_id, root_id);
71 if !self.post_follows.requested.insert(key) {
72 return;
73 }
74 let Some(engine) = self.engine.clone() else {
75 return;
76 };
77 let (channel, root) = (channel_id.to_owned(), root_id.to_owned());
78 let requested = vec![root.clone()];
79 let requested_channel = channel.clone();
80 let receiver = runtime::spawn(async move {
81 engine
82 .post_follow_states(&requested_channel, &requested)
83 .await
84 });
85 cx.spawn(async move |this, cx| {
86 let outcome = receiver.await;
87 this.update(cx, |state, cx| match outcome {
88 Ok(Ok(states)) => {
89 if let Some(follow_state) = states.get(&root) {
90 state
91 .post_follows
92 .states
93 .insert(post_key(&channel, &root), *follow_state);
94 cx.notify();
95 }
96 }
97 _ => {
98 state.post_follows.requested.remove(&post_key(&channel, &root));
99 }
100 })
101 .ok();
102 })
103 .detach();
104 }
105
106 pub fn set_post_followed(
107 &mut self,
108 channel_id: &str,
109 root_id: &str,
110 followed: bool,
111 cx: &mut Context<Self>,
112 ) {
113 let Some(engine_or_demo) = self.chat_action_engine(cx) else {
114 return;
115 };
116 let key = post_key(channel_id, root_id);
117 let previous = self.post_follows.states.get(&key).copied();
118 let next = if followed {
119 PostFollowState::ExplicitFollow
120 } else {
121 PostFollowState::ExplicitUnfollow
122 };
123 self.post_follows.states.insert(key.clone(), next);
124 cx.notify();
125 let Some(engine) = engine_or_demo else {
126 self.raise_notice(follow_notice(followed).to_owned(), None, cx);
127 return;
128 };
129 let (channel, root) = (channel_id.to_owned(), root_id.to_owned());
130 self.run_channel_action(
131 follow_failure(followed),
132 async move { engine.set_post_followed(&channel, &root, followed).await },
133 move |state, cx| {
134 match previous {
135 Some(previous) => state.post_follows.states.insert(key, previous),
136 None => state.post_follows.states.remove(&key),
137 };
138 cx.notify();
139 },
140 Some(follow_notice(followed)),
141 cx,
142 );
143 }
144}
145
146#[cfg(test)]
147mod tests {
148 use teams_core::PostFollowState;
149
150 use super::{follow_failure, follow_label, follow_notice, post_followed};
151
152 #[test]
153 fn explicit_state_wins_over_participation() {
154 assert!(!post_followed(Some(PostFollowState::ExplicitUnfollow), true));
155 assert!(post_followed(Some(PostFollowState::ExplicitFollow), false));
156 assert!(post_followed(Some(PostFollowState::ImplicitFollow), false));
157 assert!(post_followed(None, true));
158 assert!(!post_followed(None, false));
159 }
160
161 #[test]
162 fn labels_and_notices_use_teams_strings() {
163 assert_eq!(follow_label(true), "Turn off notifications");
164 assert_eq!(follow_label(false), "Turn on notifications");
165 assert_eq!(follow_notice(false), "Notifications turned off");
166 assert_eq!(follow_notice(true), "Notifications turned on");
167 assert_eq!(follow_failure(false), "Couldn't turn off notifications");
168 assert_eq!(follow_failure(true), "Couldn't turn on notifications");
169 }
170}
crates/app/src/views/conversation.rs +7 −0
@@ -2574,6 +2574,9 @@ impl ConversationView {
2574 2574 }
2575 2575
2576 2576 fn set_hover(&mut self, slot: HoverSlot, key: &str, hovered: bool, cx: &mut Context<Self>) {
2577 if hovered && matches!(slot, HoverSlot::Row) {
2578 self.request_post_follow(key, cx);
2579 }
2577 2580 let target = match slot {
2578 2581 HoverSlot::Row => &mut self.hovered_message,
2579 2582 HoverSlot::Toolbar => &mut self.toolbar_hovered,
@@ -3145,6 +3148,7 @@ impl ConversationView {
3145 3148 .is_some_and(|record| record.reply_to_id.is_none())
3146 3149 });
3147 3150 let (delegate, manage_agents) = self.delegate_entries(key, cx);
3151 let post_followed = self.post_follow(key, cx);
3148 3152 MessageMenu {
3149 3153 key: key.to_owned(),
3150 3154 react,
@@ -3164,6 +3168,9 @@ impl ConversationView {
3164 3168 toggle_pinned: pinnable
3165 3169 .then(|| action(|this, key, window, cx| this.toggle_pinned(key, window, cx))),
3166 3170 pinned,
3171 toggle_follow: post_followed
3172 .map(|_| action(|this, key, _, cx| this.toggle_post_follow(key, cx))),
3173 followed: post_followed.unwrap_or_default(),
3167 3174 edit: own.then(|| action(|this, key, window, cx| this.begin_edit(key, window, cx))),
3168 3175 delete: own.then(|| action(|this, key, _, cx| this.delete(key, cx))),
3169 3176 mark_unread: (in_chat && !own)
@@ -2574,6 +2574,9 @@ impl ConversationView {
2574 }
2574 }
2575
2575
2576 fn set_hover(&mut self, slot: HoverSlot, key: &str, hovered: bool, cx: &mut Context<Self>) {
2576 fn set_hover(&mut self, slot: HoverSlot, key: &str, hovered: bool, cx: &mut Context<Self>) {
2577 if hovered && matches!(slot, HoverSlot::Row) {
2578 self.request_post_follow(key, cx);
2579 }
2577 let target = match slot {
2580 let target = match slot {
2578 HoverSlot::Row => &mut self.hovered_message,
2581 HoverSlot::Row => &mut self.hovered_message,
2579 HoverSlot::Toolbar => &mut self.toolbar_hovered,
2582 HoverSlot::Toolbar => &mut self.toolbar_hovered,
@@ -3145,6 +3148,7 @@ impl ConversationView {
3145 .is_some_and(|record| record.reply_to_id.is_none())
3148 .is_some_and(|record| record.reply_to_id.is_none())
3146 });
3149 });
3147 let (delegate, manage_agents) = self.delegate_entries(key, cx);
3150 let (delegate, manage_agents) = self.delegate_entries(key, cx);
3151 let post_followed = self.post_follow(key, cx);
3148 MessageMenu {
3152 MessageMenu {
3149 key: key.to_owned(),
3153 key: key.to_owned(),
3150 react,
3154 react,
@@ -3164,6 +3168,9 @@ impl ConversationView {
3164 toggle_pinned: pinnable
3168 toggle_pinned: pinnable
3165 .then(|| action(|this, key, window, cx| this.toggle_pinned(key, window, cx))),
3169 .then(|| action(|this, key, window, cx| this.toggle_pinned(key, window, cx))),
3166 pinned,
3170 pinned,
3171 toggle_follow: post_followed
3172 .map(|_| action(|this, key, _, cx| this.toggle_post_follow(key, cx))),
3173 followed: post_followed.unwrap_or_default(),
3167 edit: own.then(|| action(|this, key, window, cx| this.begin_edit(key, window, cx))),
3174 edit: own.then(|| action(|this, key, window, cx| this.begin_edit(key, window, cx))),
3168 delete: own.then(|| action(|this, key, _, cx| this.delete(key, cx))),
3175 delete: own.then(|| action(|this, key, _, cx| this.delete(key, cx))),
3169 mark_unread: (in_chat && !own)
3176 mark_unread: (in_chat && !own)
crates/app/src/views/conversation/pins.rs +40 −1
@@ -11,7 +11,8 @@ use gpui_kit::component::dialog::DialogFooter;
11 11
12 12 use crate::app_state::{AppState, Selection, selection_title};
13 13 use crate::channel_menu::post_pin_dialog;
14 use crate::rows::reply_excerpt;
14 use crate::post_follow::post_followed;
15 use crate::rows::{Row, reply_excerpt};
15 16 use crate::runtime;
16 17 use crate::views::message_actions::Action;
17 18 use crate::views::pin_banner::{PinBannerActions, PinBannerData, cycle_pin, render_pin_banner};
@@ -291,6 +292,44 @@ impl ConversationView {
291 292 confirm_post_pin(&self.app, &conversation_id, message_id, pin, window, cx);
292 293 }
293 294
295 /// `Some(followed)` for a channel root post, `None` for everything else.
296 pub(super) fn post_follow(&self, message_id: &str, cx: &App) -> Option<bool> {
297 let Selection::Channel(ref channel_id) = self.current.as_ref()?.selection else {
298 return None;
299 };
300 let participated = self.rows.borrow().iter().find_map(|row| match row {
301 Row::Post(post) if post.root.key == message_id => {
302 Some(post.messages().any(|message| message.own))
303 }
304 _ => None,
305 })?;
306 let state = self.app.read(cx).post_follow_state(channel_id, message_id);
307 Some(post_followed(state, participated))
308 }
309
310 pub(super) fn request_post_follow(&mut self, message_id: &str, cx: &mut Context<Self>) {
311 if let Some(Selection::Channel(channel_id)) =
312 self.current.as_ref().map(|current| current.selection.clone())
313 && self.post_follow(message_id, cx).is_some()
314 {
315 self.app.update(cx, |state, cx| {
316 state.request_post_follow_state(&channel_id, message_id, cx)
317 });
318 }
319 }
320
321 pub(super) fn toggle_post_follow(&mut self, message_id: &str, cx: &mut Context<Self>) {
322 let Some(followed) = self.post_follow(message_id, cx) else {
323 return;
324 };
325 let Some(channel_id) = self.pin_conversation_id() else {
326 return;
327 };
328 self.app.update(cx, |state, cx| {
329 state.set_post_followed(&channel_id, message_id, !followed, cx)
330 });
331 }
332
294 333 pub(super) fn mark_unread_from(&mut self, message_id: &str, cx: &mut Context<Self>) {
295 334 if let Some(chat_id) = self.chat_id() {
296 335 self.app.update(cx, |state, cx| {
@@ -11,7 +11,8 @@ use gpui_kit::component::dialog::DialogFooter;
11
11
12use crate::app_state::{AppState, Selection, selection_title};
12use crate::app_state::{AppState, Selection, selection_title};
13use crate::channel_menu::post_pin_dialog;
13use crate::channel_menu::post_pin_dialog;
14use crate::rows::reply_excerpt;
14use crate::post_follow::post_followed;
15use crate::rows::{Row, reply_excerpt};
15use crate::runtime;
16use crate::runtime;
16use crate::views::message_actions::Action;
17use crate::views::message_actions::Action;
17use crate::views::pin_banner::{PinBannerActions, PinBannerData, cycle_pin, render_pin_banner};
18use crate::views::pin_banner::{PinBannerActions, PinBannerData, cycle_pin, render_pin_banner};
@@ -291,6 +292,44 @@ impl ConversationView {
291 confirm_post_pin(&self.app, &conversation_id, message_id, pin, window, cx);
292 confirm_post_pin(&self.app, &conversation_id, message_id, pin, window, cx);
292 }
293 }
293
294
295 /// `Some(followed)` for a channel root post, `None` for everything else.
296 pub(super) fn post_follow(&self, message_id: &str, cx: &App) -> Option<bool> {
297 let Selection::Channel(ref channel_id) = self.current.as_ref()?.selection else {
298 return None;
299 };
300 let participated = self.rows.borrow().iter().find_map(|row| match row {
301 Row::Post(post) if post.root.key == message_id => {
302 Some(post.messages().any(|message| message.own))
303 }
304 _ => None,
305 })?;
306 let state = self.app.read(cx).post_follow_state(channel_id, message_id);
307 Some(post_followed(state, participated))
308 }
309
310 pub(super) fn request_post_follow(&mut self, message_id: &str, cx: &mut Context<Self>) {
311 if let Some(Selection::Channel(channel_id)) =
312 self.current.as_ref().map(|current| current.selection.clone())
313 && self.post_follow(message_id, cx).is_some()
314 {
315 self.app.update(cx, |state, cx| {
316 state.request_post_follow_state(&channel_id, message_id, cx)
317 });
318 }
319 }
320
321 pub(super) fn toggle_post_follow(&mut self, message_id: &str, cx: &mut Context<Self>) {
322 let Some(followed) = self.post_follow(message_id, cx) else {
323 return;
324 };
325 let Some(channel_id) = self.pin_conversation_id() else {
326 return;
327 };
328 self.app.update(cx, |state, cx| {
329 state.set_post_followed(&channel_id, message_id, !followed, cx)
330 });
331 }
332
294 pub(super) fn mark_unread_from(&mut self, message_id: &str, cx: &mut Context<Self>) {
333 pub(super) fn mark_unread_from(&mut self, message_id: &str, cx: &mut Context<Self>) {
295 if let Some(chat_id) = self.chat_id() {
334 if let Some(chat_id) = self.chat_id() {
296 self.app.update(cx, |state, cx| {
335 self.app.update(cx, |state, cx| {
crates/app/src/views/message_actions.rs +14 −1
@@ -15,6 +15,7 @@ use gpui_kit::*;
15 15 use super::reaction_picker::{DoneHandler, PickHandler, ReactionPicker};
16 16 use super::toolbar_placement::{HoverChange, TOOLBAR_HEIGHT, toolbar_slot};
17 17 use super::widgets::{icon, symbol};
18 use crate::post_follow::follow_label;
18 19 use crate::forward_selection::{FORWARD_LABEL, MULTIPLE_MESSAGES_LABEL, THIS_MESSAGE_LABEL};
19 20 use crate::rows::reaction_glyph;
20 21 use crate::share_outlook::SHARE_TO_OUTLOOK_LABEL;
@@ -53,6 +54,8 @@ pub struct MessageMenu {
53 54 pub saved: bool,
54 55 pub toggle_pinned: Option<Action>,
55 56 pub pinned: bool,
57 pub toggle_follow: Option<Action>,
58 pub followed: bool,
56 59 pub edit: Option<Action>,
57 60 pub delete: Option<Action>,
58 61 pub mark_unread: Option<Action>,
@@ -197,6 +200,7 @@ fn more_button(menu: &MessageMenu, cx: &App) -> AnyElement {
197 200 translate,
198 201 save,
199 202 toggle_pinned,
203 toggle_follow,
200 204 edit,
201 205 delete,
202 206 mark_unread,
@@ -211,6 +215,7 @@ fn more_button(menu: &MessageMenu, cx: &App) -> AnyElement {
211 215 menu.translate.clone(),
212 216 menu.save.clone(),
213 217 menu.toggle_pinned.clone(),
218 menu.toggle_follow.clone(),
214 219 menu.edit.clone(),
215 220 menu.delete.clone(),
216 221 menu.mark_unread.clone(),
@@ -218,7 +223,8 @@ fn more_button(menu: &MessageMenu, cx: &App) -> AnyElement {
218 223 menu.share_to_outlook.clone(),
219 224 menu.pin.clone(),
220 225 );
221 let (saved, pinned, translate_label) = (menu.saved, menu.pinned, menu.translate_label);
226 let (saved, pinned, followed, translate_label) =
227 (menu.saved, menu.pinned, menu.followed, menu.translate_label);
222 228 Button::new(element_id("message-more", &menu.key))
223 229 .child(icon(IconName::Ellipsis, BAR_ICON, theme::text_soft()))
224 230 .custom(bar_variant(cx))
@@ -291,6 +297,13 @@ fn more_button(menu: &MessageMenu, cx: &App) -> AnyElement {
291 297 item("Pin", IconName::Pin, toggle_pinned)
292 298 });
293 299 }
300 if let Some(toggle_follow) = toggle_follow.clone() {
301 popup = popup.item(if followed {
302 item(follow_label(true), IconName::BellOff, toggle_follow)
303 } else {
304 item(follow_label(false), IconName::Bell, toggle_follow)
305 });
306 }
294 307 if let Some(edit) = edit.clone() {
295 308 popup = popup.item(item("Edit", IconName::Pencil, edit));
296 309 }
@@ -15,6 +15,7 @@ use gpui_kit::*;
15use super::reaction_picker::{DoneHandler, PickHandler, ReactionPicker};
15use super::reaction_picker::{DoneHandler, PickHandler, ReactionPicker};
16use super::toolbar_placement::{HoverChange, TOOLBAR_HEIGHT, toolbar_slot};
16use super::toolbar_placement::{HoverChange, TOOLBAR_HEIGHT, toolbar_slot};
17use super::widgets::{icon, symbol};
17use super::widgets::{icon, symbol};
18use crate::post_follow::follow_label;
18use crate::forward_selection::{FORWARD_LABEL, MULTIPLE_MESSAGES_LABEL, THIS_MESSAGE_LABEL};
19use crate::forward_selection::{FORWARD_LABEL, MULTIPLE_MESSAGES_LABEL, THIS_MESSAGE_LABEL};
19use crate::rows::reaction_glyph;
20use crate::rows::reaction_glyph;
20use crate::share_outlook::SHARE_TO_OUTLOOK_LABEL;
21use crate::share_outlook::SHARE_TO_OUTLOOK_LABEL;
@@ -53,6 +54,8 @@ pub struct MessageMenu {
53 pub saved: bool,
54 pub saved: bool,
54 pub toggle_pinned: Option<Action>,
55 pub toggle_pinned: Option<Action>,
55 pub pinned: bool,
56 pub pinned: bool,
57 pub toggle_follow: Option<Action>,
58 pub followed: bool,
56 pub edit: Option<Action>,
59 pub edit: Option<Action>,
57 pub delete: Option<Action>,
60 pub delete: Option<Action>,
58 pub mark_unread: Option<Action>,
61 pub mark_unread: Option<Action>,
@@ -197,6 +200,7 @@ fn more_button(menu: &MessageMenu, cx: &App) -> AnyElement {
197 translate,
200 translate,
198 save,
201 save,
199 toggle_pinned,
202 toggle_pinned,
203 toggle_follow,
200 edit,
204 edit,
201 delete,
205 delete,
202 mark_unread,
206 mark_unread,
@@ -211,6 +215,7 @@ fn more_button(menu: &MessageMenu, cx: &App) -> AnyElement {
211 menu.translate.clone(),
215 menu.translate.clone(),
212 menu.save.clone(),
216 menu.save.clone(),
213 menu.toggle_pinned.clone(),
217 menu.toggle_pinned.clone(),
218 menu.toggle_follow.clone(),
214 menu.edit.clone(),
219 menu.edit.clone(),
215 menu.delete.clone(),
220 menu.delete.clone(),
216 menu.mark_unread.clone(),
221 menu.mark_unread.clone(),
@@ -218,7 +223,8 @@ fn more_button(menu: &MessageMenu, cx: &App) -> AnyElement {
218 menu.share_to_outlook.clone(),
223 menu.share_to_outlook.clone(),
219 menu.pin.clone(),
224 menu.pin.clone(),
220 );
225 );
221 let (saved, pinned, translate_label) = (menu.saved, menu.pinned, menu.translate_label);
226 let (saved, pinned, followed, translate_label) =
227 (menu.saved, menu.pinned, menu.followed, menu.translate_label);
222 Button::new(element_id("message-more", &menu.key))
228 Button::new(element_id("message-more", &menu.key))
223 .child(icon(IconName::Ellipsis, BAR_ICON, theme::text_soft()))
229 .child(icon(IconName::Ellipsis, BAR_ICON, theme::text_soft()))
224 .custom(bar_variant(cx))
230 .custom(bar_variant(cx))
@@ -291,6 +297,13 @@ fn more_button(menu: &MessageMenu, cx: &App) -> AnyElement {
291 item("Pin", IconName::Pin, toggle_pinned)
297 item("Pin", IconName::Pin, toggle_pinned)
292 });
298 });
293 }
299 }
300 if let Some(toggle_follow) = toggle_follow.clone() {
301 popup = popup.item(if followed {
302 item(follow_label(true), IconName::BellOff, toggle_follow)
303 } else {
304 item(follow_label(false), IconName::Bell, toggle_follow)
305 });
306 }
294 if let Some(edit) = edit.clone() {
307 if let Some(edit) = edit.clone() {
295 popup = popup.item(item("Edit", IconName::Pencil, edit));
308 popup = popup.item(item("Edit", IconName::Pencil, edit));
296 }
309 }
crates/chatsvc/src/lib.rs +2 −0
@@ -21,6 +21,7 @@ mod mask;
21 21 pub mod members;
22 22 pub mod messages;
23 23 pub mod pins;
24 pub mod post_follow;
24 25 pub mod presence;
25 26 pub mod reactions;
26 27 pub mod read_horizon;
@@ -77,6 +78,7 @@ pub use members::{
77 78 TopicProblem, topic_problem,
78 79 };
79 80 pub use messages::{ConversationRef, Messages};
81 pub use post_follow::{PostFollowState, parse_post_follow_states};
80 82 pub use pins::{
81 83 ChannelLayout, ChannelTab, Folder, FolderKind, Folders, PinnedChannels, PinnedChats,
82 84 PinnedMessage, Pins, TeamLayout,
@@ -21,6 +21,7 @@ mod mask;
21pub mod members;
21pub mod members;
22pub mod messages;
22pub mod messages;
23pub mod pins;
23pub mod pins;
24pub mod post_follow;
24pub mod presence;
25pub mod presence;
25pub mod reactions;
26pub mod reactions;
26pub mod read_horizon;
27pub mod read_horizon;
@@ -77,6 +78,7 @@ pub use members::{
77 TopicProblem, topic_problem,
78 TopicProblem, topic_problem,
78};
79};
79pub use messages::{ConversationRef, Messages};
80pub use messages::{ConversationRef, Messages};
81pub use post_follow::{PostFollowState, parse_post_follow_states};
80pub use pins::{
82pub use pins::{
81 ChannelLayout, ChannelTab, Folder, FolderKind, Folders, PinnedChannels, PinnedChats,
83 ChannelLayout, ChannelTab, Folder, FolderKind, Folders, PinnedChannels, PinnedChats,
82 PinnedMessage, Pins, TeamLayout,
84 PinnedMessage, Pins, TeamLayout,
crates/chatsvc/src/post_follow.rs added +265 −0
@@ -0,0 +1,265 @@
1 use std::collections::HashMap;
2
3 use serde_json::{Value, json};
4 use session::{Method, Request};
5
6 use crate::error::Result;
7 use crate::members::user_mri;
8 use crate::messages::{MessageTransport, Messages, encode, ensure_success};
9
10 const FOLLOW_EMOTION: &str = "follow";
11 const EXPLICIT_FOLLOW: u8 = 1;
12 const IMPLICIT_FOLLOW: u8 = 2;
13 const EXPLICIT_UNFOLLOW: u8 = 3;
14
15 /// Teams' reply chain follow state (`rcMetadata.f`).
16 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
17 pub enum PostFollowState {
18 ExplicitFollow,
19 ImplicitFollow,
20 ExplicitUnfollow,
21 }
22
23 impl PostFollowState {
24 fn from_code(code: u64) -> Option<Self> {
25 match u8::try_from(code).ok()? {
26 EXPLICIT_FOLLOW => Some(PostFollowState::ExplicitFollow),
27 IMPLICIT_FOLLOW => Some(PostFollowState::ImplicitFollow),
28 EXPLICIT_UNFOLLOW => Some(PostFollowState::ExplicitUnfollow),
29 _ => None,
30 }
31 }
32
33 pub fn followed(self) -> bool {
34 self != PostFollowState::ExplicitUnfollow
35 }
36 }
37
38 pub fn parse_post_follow_states(body: &Value) -> HashMap<String, PostFollowState> {
39 body.get("rcMetadataList")
40 .and_then(Value::as_array)
41 .into_iter()
42 .flatten()
43 .filter_map(|entry| {
44 let root_id = crate::json_id::id_text(entry.get("rootMessageId")?)?;
45 let state = PostFollowState::from_code(entry.pointer("/rcMetadata/f")?.as_u64()?)?;
46 Some((root_id, state))
47 })
48 .collect()
49 }
50
51 impl<T: MessageTransport> Messages<T> {
52 fn user_conversations_url(&self, user_id: &str) -> String {
53 self.base_url
54 .replace("/users/ME/", &format!("/users/{}/", user_mri(user_id)))
55 }
56
57 pub fn post_follow_request(
58 &self,
59 user_id: &str,
60 channel_id: &str,
61 root_id: &str,
62 followed: bool,
63 ) -> Request {
64 let code = if followed {
65 EXPLICIT_FOLLOW
66 } else {
67 EXPLICIT_UNFOLLOW
68 };
69 Request::with_body(
70 Method::Put,
71 format!(
72 "{}/{}/rcmetadata/{}",
73 self.user_conversations_url(user_id),
74 encode(channel_id),
75 encode(root_id)
76 ),
77 json!({"f": code}),
78 )
79 }
80
81 pub fn post_follow_annotation_request(
82 &self,
83 channel_id: &str,
84 root_id: &str,
85 followed: bool,
86 ) -> Request {
87 Request::with_body(
88 Method::Put,
89 format!(
90 "{}/{}/messages/{}/properties?name=emotions",
91 self.base_url,
92 encode(channel_id),
93 encode(root_id)
94 ),
95 json!({"emotions": {"key": FOLLOW_EMOTION, "value": u8::from(followed)}}),
96 )
97 }
98
99 pub fn post_follow_states_request(&self, channel_id: &str, root_ids: &[u64]) -> Request {
100 Request::with_body(
101 Method::Post,
102 format!("{}/{}/getrcmetadata", self.base_url, encode(channel_id)),
103 json!({"rootMessageIds": root_ids}),
104 )
105 }
106
107 /// Teams writes the reply chain metadata first and the `follow` annotation only after it succeeded.
108 pub async fn set_post_followed(
109 &self,
110 user_id: &str,
111 channel_id: &str,
112 root_id: &str,
113 followed: bool,
114 ) -> Result<()> {
115 let answer = self
116 .transport
117 .send(self.post_follow_request(user_id, channel_id, root_id, followed))
118 .await?;
119 ensure_success(&answer)?;
120 let answer = self
121 .transport
122 .send(self.post_follow_annotation_request(channel_id, root_id, followed))
123 .await?;
124 ensure_success(&answer)
125 }
126
127 pub async fn post_follow_states(
128 &self,
129 channel_id: &str,
130 root_ids: &[String],
131 ) -> Result<HashMap<String, PostFollowState>> {
132 let numeric: Vec<u64> = root_ids.iter().filter_map(|id| id.parse().ok()).collect();
133 if numeric.is_empty() {
134 return Ok(HashMap::new());
135 }
136 let answer = self
137 .transport
138 .send(self.post_follow_states_request(channel_id, &numeric))
139 .await?;
140 ensure_success(&answer)?;
141 Ok(parse_post_follow_states(&answer.body))
142 }
143 }
144
145 #[cfg(test)]
146 mod tests {
147 use std::sync::Mutex;
148
149 use session::ApiResponse;
150
151 use super::*;
152
153 struct Canned {
154 status: u16,
155 body: Value,
156 requests: Mutex<Vec<Request>>,
157 }
158
159 impl MessageTransport for Canned {
160 async fn send(&self, request: Request) -> Result<ApiResponse> {
161 self.requests.lock().unwrap().push(request);
162 Ok(ApiResponse {
163 status: self.status,
164 body: self.body.clone(),
165 retry_after: None,
166 })
167 }
168 }
169
170 fn canned(status: u16, body: Value) -> Messages<Canned> {
171 Messages::with_transport(
172 Canned {
173 status,
174 body,
175 requests: Mutex::new(Vec::new()),
176 },
177 "emea",
178 )
179 }
180
181 const BASE: &str = "https://teams.cloud.microsoft/api/chatsvc/emea/v1/users";
182
183 #[tokio::test]
184 async fn follow_writes_reply_chain_metadata_then_annotation() {
185 let messages = canned(200, json!({}));
186 messages
187 .set_post_followed("a1", "19:c@thread.tacv2", "1791368000000", true)
188 .await
189 .unwrap();
190 messages
191 .set_post_followed("a1", "19:c@thread.tacv2", "1791368000000", false)
192 .await
193 .unwrap();
194 let requests = messages.transport.requests.lock().unwrap();
195 assert_eq!(requests[0].method, Method::Put);
196 assert_eq!(
197 requests[0].url,
198 format!(
199 "{BASE}/8:orgid:a1/conversations/19%3Ac%40thread.tacv2/rcmetadata/1791368000000"
200 )
201 );
202 assert_eq!(requests[0].body, Some(json!({"f": 1})));
203 assert_eq!(
204 requests[1].url,
205 format!(
206 "{BASE}/ME/conversations/19%3Ac%40thread.tacv2/messages/1791368000000/properties?name=emotions"
207 )
208 );
209 assert_eq!(
210 requests[1].body,
211 Some(json!({"emotions": {"key": "follow", "value": 1}}))
212 );
213 assert_eq!(requests[2].body, Some(json!({"f": 3})));
214 assert_eq!(
215 requests[3].body,
216 Some(json!({"emotions": {"key": "follow", "value": 0}}))
217 );
218 }
219
220 #[tokio::test]
221 async fn failed_metadata_write_skips_the_annotation() {
222 let messages = canned(403, json!({}));
223 assert!(
224 messages
225 .set_post_followed("a1", "19:c", "1", true)
226 .await
227 .is_err()
228 );
229 assert_eq!(messages.transport.requests.lock().unwrap().len(), 1);
230 }
231
232 #[tokio::test]
233 async fn reads_follow_states_of_root_posts() {
234 let body = json!({"conversationId": "19:c", "rcMetadataList": [
235 {"statusCode": 200, "rootMessageId": 11, "rcMetadata": {"lu": 1, "f": 1}},
236 {"statusCode": 200, "rootMessageId": "12", "rcMetadata": {"lu": 1, "f": 3}},
237 {"statusCode": 200, "rootMessageId": 13, "rcMetadata": {"lu": 1, "f": 2}},
238 {"statusCode": 200, "rootMessageId": 14, "rcMetadata": {"lu": 1, "s": 1}},
239 {"statusCode": 404, "rootMessageId": 15},
240 ]});
241 let messages = canned(207, body);
242 let states = messages
243 .post_follow_states("19:c", &["11".into(), "12".into(), "x".into()])
244 .await
245 .unwrap();
246 assert_eq!(states.len(), 3);
247 assert!(states["11"].followed());
248 assert!(!states["12"].followed());
249 assert_eq!(states["13"], PostFollowState::ImplicitFollow);
250 let requests = messages.transport.requests.lock().unwrap();
251 assert_eq!(requests[0].method, Method::Post);
252 assert_eq!(
253 requests[0].url,
254 format!("{BASE}/ME/conversations/19%3Ac/getrcmetadata")
255 );
256 assert_eq!(requests[0].body, Some(json!({"rootMessageIds": [11, 12]})));
257 }
258
259 #[tokio::test]
260 async fn no_numeric_roots_sends_nothing() {
261 let messages = canned(200, json!({}));
262 assert!(messages.post_follow_states("19:c", &[]).await.unwrap().is_empty());
263 assert!(messages.transport.requests.lock().unwrap().is_empty());
264 }
265 }
@@ -0,0 +1,265 @@
1use std::collections::HashMap;
2
3use serde_json::{Value, json};
4use session::{Method, Request};
5
6use crate::error::Result;
7use crate::members::user_mri;
8use crate::messages::{MessageTransport, Messages, encode, ensure_success};
9
10const FOLLOW_EMOTION: &str = "follow";
11const EXPLICIT_FOLLOW: u8 = 1;
12const IMPLICIT_FOLLOW: u8 = 2;
13const EXPLICIT_UNFOLLOW: u8 = 3;
14
15/// Teams' reply chain follow state (`rcMetadata.f`).
16#[derive(Debug, Clone, Copy, PartialEq, Eq)]
17pub enum PostFollowState {
18 ExplicitFollow,
19 ImplicitFollow,
20 ExplicitUnfollow,
21}
22
23impl PostFollowState {
24 fn from_code(code: u64) -> Option<Self> {
25 match u8::try_from(code).ok()? {
26 EXPLICIT_FOLLOW => Some(PostFollowState::ExplicitFollow),
27 IMPLICIT_FOLLOW => Some(PostFollowState::ImplicitFollow),
28 EXPLICIT_UNFOLLOW => Some(PostFollowState::ExplicitUnfollow),
29 _ => None,
30 }
31 }
32
33 pub fn followed(self) -> bool {
34 self != PostFollowState::ExplicitUnfollow
35 }
36}
37
38pub fn parse_post_follow_states(body: &Value) -> HashMap<String, PostFollowState> {
39 body.get("rcMetadataList")
40 .and_then(Value::as_array)
41 .into_iter()
42 .flatten()
43 .filter_map(|entry| {
44 let root_id = crate::json_id::id_text(entry.get("rootMessageId")?)?;
45 let state = PostFollowState::from_code(entry.pointer("/rcMetadata/f")?.as_u64()?)?;
46 Some((root_id, state))
47 })
48 .collect()
49}
50
51impl<T: MessageTransport> Messages<T> {
52 fn user_conversations_url(&self, user_id: &str) -> String {
53 self.base_url
54 .replace("/users/ME/", &format!("/users/{}/", user_mri(user_id)))
55 }
56
57 pub fn post_follow_request(
58 &self,
59 user_id: &str,
60 channel_id: &str,
61 root_id: &str,
62 followed: bool,
63 ) -> Request {
64 let code = if followed {
65 EXPLICIT_FOLLOW
66 } else {
67 EXPLICIT_UNFOLLOW
68 };
69 Request::with_body(
70 Method::Put,
71 format!(
72 "{}/{}/rcmetadata/{}",
73 self.user_conversations_url(user_id),
74 encode(channel_id),
75 encode(root_id)
76 ),
77 json!({"f": code}),
78 )
79 }
80
81 pub fn post_follow_annotation_request(
82 &self,
83 channel_id: &str,
84 root_id: &str,
85 followed: bool,
86 ) -> Request {
87 Request::with_body(
88 Method::Put,
89 format!(
90 "{}/{}/messages/{}/properties?name=emotions",
91 self.base_url,
92 encode(channel_id),
93 encode(root_id)
94 ),
95 json!({"emotions": {"key": FOLLOW_EMOTION, "value": u8::from(followed)}}),
96 )
97 }
98
99 pub fn post_follow_states_request(&self, channel_id: &str, root_ids: &[u64]) -> Request {
100 Request::with_body(
101 Method::Post,
102 format!("{}/{}/getrcmetadata", self.base_url, encode(channel_id)),
103 json!({"rootMessageIds": root_ids}),
104 )
105 }
106
107 /// Teams writes the reply chain metadata first and the `follow` annotation only after it succeeded.
108 pub async fn set_post_followed(
109 &self,
110 user_id: &str,
111 channel_id: &str,
112 root_id: &str,
113 followed: bool,
114 ) -> Result<()> {
115 let answer = self
116 .transport
117 .send(self.post_follow_request(user_id, channel_id, root_id, followed))
118 .await?;
119 ensure_success(&answer)?;
120 let answer = self
121 .transport
122 .send(self.post_follow_annotation_request(channel_id, root_id, followed))
123 .await?;
124 ensure_success(&answer)
125 }
126
127 pub async fn post_follow_states(
128 &self,
129 channel_id: &str,
130 root_ids: &[String],
131 ) -> Result<HashMap<String, PostFollowState>> {
132 let numeric: Vec<u64> = root_ids.iter().filter_map(|id| id.parse().ok()).collect();
133 if numeric.is_empty() {
134 return Ok(HashMap::new());
135 }
136 let answer = self
137 .transport
138 .send(self.post_follow_states_request(channel_id, &numeric))
139 .await?;
140 ensure_success(&answer)?;
141 Ok(parse_post_follow_states(&answer.body))
142 }
143}
144
145#[cfg(test)]
146mod tests {
147 use std::sync::Mutex;
148
149 use session::ApiResponse;
150
151 use super::*;
152
153 struct Canned {
154 status: u16,
155 body: Value,
156 requests: Mutex<Vec<Request>>,
157 }
158
159 impl MessageTransport for Canned {
160 async fn send(&self, request: Request) -> Result<ApiResponse> {
161 self.requests.lock().unwrap().push(request);
162 Ok(ApiResponse {
163 status: self.status,
164 body: self.body.clone(),
165 retry_after: None,
166 })
167 }
168 }
169
170 fn canned(status: u16, body: Value) -> Messages<Canned> {
171 Messages::with_transport(
172 Canned {
173 status,
174 body,
175 requests: Mutex::new(Vec::new()),
176 },
177 "emea",
178 )
179 }
180
181 const BASE: &str = "https://teams.cloud.microsoft/api/chatsvc/emea/v1/users";
182
183 #[tokio::test]
184 async fn follow_writes_reply_chain_metadata_then_annotation() {
185 let messages = canned(200, json!({}));
186 messages
187 .set_post_followed("a1", "19:c@thread.tacv2", "1791368000000", true)
188 .await
189 .unwrap();
190 messages
191 .set_post_followed("a1", "19:c@thread.tacv2", "1791368000000", false)
192 .await
193 .unwrap();
194 let requests = messages.transport.requests.lock().unwrap();
195 assert_eq!(requests[0].method, Method::Put);
196 assert_eq!(
197 requests[0].url,
198 format!(
199 "{BASE}/8:orgid:a1/conversations/19%3Ac%40thread.tacv2/rcmetadata/1791368000000"
200 )
201 );
202 assert_eq!(requests[0].body, Some(json!({"f": 1})));
203 assert_eq!(
204 requests[1].url,
205 format!(
206 "{BASE}/ME/conversations/19%3Ac%40thread.tacv2/messages/1791368000000/properties?name=emotions"
207 )
208 );
209 assert_eq!(
210 requests[1].body,
211 Some(json!({"emotions": {"key": "follow", "value": 1}}))
212 );
213 assert_eq!(requests[2].body, Some(json!({"f": 3})));
214 assert_eq!(
215 requests[3].body,
216 Some(json!({"emotions": {"key": "follow", "value": 0}}))
217 );
218 }
219
220 #[tokio::test]
221 async fn failed_metadata_write_skips_the_annotation() {
222 let messages = canned(403, json!({}));
223 assert!(
224 messages
225 .set_post_followed("a1", "19:c", "1", true)
226 .await
227 .is_err()
228 );
229 assert_eq!(messages.transport.requests.lock().unwrap().len(), 1);
230 }
231
232 #[tokio::test]
233 async fn reads_follow_states_of_root_posts() {
234 let body = json!({"conversationId": "19:c", "rcMetadataList": [
235 {"statusCode": 200, "rootMessageId": 11, "rcMetadata": {"lu": 1, "f": 1}},
236 {"statusCode": 200, "rootMessageId": "12", "rcMetadata": {"lu": 1, "f": 3}},
237 {"statusCode": 200, "rootMessageId": 13, "rcMetadata": {"lu": 1, "f": 2}},
238 {"statusCode": 200, "rootMessageId": 14, "rcMetadata": {"lu": 1, "s": 1}},
239 {"statusCode": 404, "rootMessageId": 15},
240 ]});
241 let messages = canned(207, body);
242 let states = messages
243 .post_follow_states("19:c", &["11".into(), "12".into(), "x".into()])
244 .await
245 .unwrap();
246 assert_eq!(states.len(), 3);
247 assert!(states["11"].followed());
248 assert!(!states["12"].followed());
249 assert_eq!(states["13"], PostFollowState::ImplicitFollow);
250 let requests = messages.transport.requests.lock().unwrap();
251 assert_eq!(requests[0].method, Method::Post);
252 assert_eq!(
253 requests[0].url,
254 format!("{BASE}/ME/conversations/19%3Ac/getrcmetadata")
255 );
256 assert_eq!(requests[0].body, Some(json!({"rootMessageIds": [11, 12]})));
257 }
258
259 #[tokio::test]
260 async fn no_numeric_roots_sends_nothing() {
261 let messages = canned(200, json!({}));
262 assert!(messages.post_follow_states("19:c", &[]).await.unwrap().is_empty());
263 assert!(messages.transport.requests.lock().unwrap().is_empty());
264 }
265}
crates/core/src/lib.rs +1 −1
@@ -106,7 +106,7 @@ pub use card_width::{TargetWidth, WidthClass};
106 106 pub use chatsvc::substrate_search;
107 107 pub use chatsvc::{
108 108 CallDirection, CallLogEntry, CallOutcome, ChatApp, ForcedAvailability, ForcedKind,
109 ForwardResult, Gif, PinnedMessage, PresenceStatus, SavedMessage, ScheduledDraft, StatusNote,
109 ForwardResult, Gif, PinnedMessage, PostFollowState, PresenceStatus, SavedMessage, ScheduledDraft, StatusNote,
110 110 WindowDirection, WorkLocation, WorkLocationKind, WorkLocationSource,
111 111 };
112 112 pub use chat_settings_sync::{store_chat_settings, stored_chat_settings};
@@ -106,7 +106,7 @@ pub use card_width::{TargetWidth, WidthClass};
106pub use chatsvc::substrate_search;
106pub use chatsvc::substrate_search;
107pub use chatsvc::{
107pub use chatsvc::{
108 CallDirection, CallLogEntry, CallOutcome, ChatApp, ForcedAvailability, ForcedKind,
108 CallDirection, CallLogEntry, CallOutcome, ChatApp, ForcedAvailability, ForcedKind,
109 ForwardResult, Gif, PinnedMessage, PresenceStatus, SavedMessage, ScheduledDraft, StatusNote,
109 ForwardResult, Gif, PinnedMessage, PostFollowState, PresenceStatus, SavedMessage, ScheduledDraft, StatusNote,
110 WindowDirection, WorkLocation, WorkLocationKind, WorkLocationSource,
110 WindowDirection, WorkLocation, WorkLocationKind, WorkLocationSource,
111};
111};
112pub use chat_settings_sync::{store_chat_settings, stored_chat_settings};
112pub use chat_settings_sync::{store_chat_settings, stored_chat_settings};
crates/core/src/message_actions.rs +26 −1
@@ -1,4 +1,9 @@
1 use chatsvc::{CallLogEntry, EventKind, ForwardResult, MessageEvent, PinnedMessage, SavedMessage};
1 use std::collections::HashMap;
2
3 use chatsvc::{
4 CallLogEntry, EventKind, ForwardResult, MessageEvent, PinnedMessage, PostFollowState,
5 SavedMessage,
6 };
2 7
3 8 use crate::engine::{Conversation, SyncEngine};
4 9 use crate::error::{Error, Result};
@@ -60,6 +65,26 @@ impl<R: Remote> SyncEngine<R> {
60 65 .await
61 66 }
62 67
68 pub async fn set_post_followed(
69 &self,
70 channel_id: &str,
71 root_id: &str,
72 followed: bool,
73 ) -> Result<()> {
74 let my_user_id = self.my_user_id().await?;
75 self.remote
76 .set_post_followed(&my_user_id, channel_id, root_id, followed)
77 .await
78 }
79
80 pub async fn post_follow_states(
81 &self,
82 channel_id: &str,
83 root_ids: &[String],
84 ) -> Result<HashMap<String, PostFollowState>> {
85 self.remote.post_follow_states(channel_id, root_ids).await
86 }
87
63 88 pub async fn list_saved(&self) -> Result<Vec<SavedMessage>> {
64 89 self.remote.list_saved().await
65 90 }
@@ -1,4 +1,9 @@
1use chatsvc::{CallLogEntry, EventKind, ForwardResult, MessageEvent, PinnedMessage, SavedMessage};
1use std::collections::HashMap;
2
3use chatsvc::{
4 CallLogEntry, EventKind, ForwardResult, MessageEvent, PinnedMessage, PostFollowState,
5 SavedMessage,
6};
2
7
3use crate::engine::{Conversation, SyncEngine};
8use crate::engine::{Conversation, SyncEngine};
4use crate::error::{Error, Result};
9use crate::error::{Error, Result};
@@ -60,6 +65,26 @@ impl<R: Remote> SyncEngine<R> {
60 .await
65 .await
61 }
66 }
62
67
68 pub async fn set_post_followed(
69 &self,
70 channel_id: &str,
71 root_id: &str,
72 followed: bool,
73 ) -> Result<()> {
74 let my_user_id = self.my_user_id().await?;
75 self.remote
76 .set_post_followed(&my_user_id, channel_id, root_id, followed)
77 .await
78 }
79
80 pub async fn post_follow_states(
81 &self,
82 channel_id: &str,
83 root_ids: &[String],
84 ) -> Result<HashMap<String, PostFollowState>> {
85 self.remote.post_follow_states(channel_id, root_ids).await
86 }
87
63 pub async fn list_saved(&self) -> Result<Vec<SavedMessage>> {
88 pub async fn list_saved(&self) -> Result<Vec<SavedMessage>> {
64 self.remote.list_saved().await
89 self.remote.list_saved().await
65 }
90 }
crates/core/src/remote.rs +43 −1
@@ -1,3 +1,5 @@
1 use std::collections::HashMap;
2
1 3 use chatsvc::sound_settings::{SoundSettings, SoundSettingsClient};
2 4 use chatsvc::substrate_search::{
3 5 QueryRequest, QueryResults, SearchIdentity, SearchSession, SubstrateSearch, Suggestions,
@@ -12,7 +14,7 @@ use chatsvc::{
12 14 ConversationState, Conversations, ForcedAvailability, ForwardResult, Gif, Gifs, HistoryShare,
13 15 InvokeRequest, InvokeResponse, Language, LanguageSettings, LanguageSettingsClient, LinkInfo,
14 16 MemberHorizon, MessageEmotions, MessageLanguage, MessageLinks, MessageWindow, Messages,
15 PinnedMessage, Pins, PresenceLookup, PresenceService, PresenceStatus, Receipts,
17 PinnedMessage, Pins, PostFollowState, PresenceLookup, PresenceService, PresenceStatus, Receipts,
16 18 RecordingPolicy, SavedMessage, ScheduledDraft, ScheduledDrafts, StatusNote, ThreadMembers,
17 19 TranslateRequest, Translation, TranslationTrigger, Translator, WindowDirection,
18 20 WorkLocationKind,
@@ -343,6 +345,24 @@ pub trait Remote {
343 345 Err(Error::Unsupported("saved messages"))
344 346 }
345 347
348 async fn set_post_followed(
349 &self,
350 _user_id: &str,
351 _channel_id: &str,
352 _root_id: &str,
353 _followed: bool,
354 ) -> Result<()> {
355 Err(Error::Unsupported("following posts"))
356 }
357
358 async fn post_follow_states(
359 &self,
360 _channel_id: &str,
361 _root_ids: &[String],
362 ) -> Result<HashMap<String, PostFollowState>> {
363 Err(Error::Unsupported("post follow states"))
364 }
365
346 366 async fn list_call_logs(&self) -> Result<Vec<CallLogEntry>> {
347 367 Err(Error::Unsupported("call history"))
348 368 }
@@ -1144,6 +1164,28 @@ impl Remote for Graph {
1144 1164 Ok(Messages::new(self.session()).list_saved().await?)
1145 1165 }
1146 1166
1167 async fn set_post_followed(
1168 &self,
1169 user_id: &str,
1170 channel_id: &str,
1171 root_id: &str,
1172 followed: bool,
1173 ) -> Result<()> {
1174 Ok(Messages::new(self.session())
1175 .set_post_followed(user_id, channel_id, root_id, followed)
1176 .await?)
1177 }
1178
1179 async fn post_follow_states(
1180 &self,
1181 channel_id: &str,
1182 root_ids: &[String],
1183 ) -> Result<HashMap<String, PostFollowState>> {
1184 Ok(Messages::new(self.session())
1185 .post_follow_states(channel_id, root_ids)
1186 .await?)
1187 }
1188
1147 1189 async fn list_call_logs(&self) -> Result<Vec<CallLogEntry>> {
1148 1190 Ok(Messages::new(self.session()).list_call_logs().await?)
1149 1191 }
@@ -1,3 +1,5 @@
1use std::collections::HashMap;
2
1use chatsvc::sound_settings::{SoundSettings, SoundSettingsClient};
3use chatsvc::sound_settings::{SoundSettings, SoundSettingsClient};
2use chatsvc::substrate_search::{
4use chatsvc::substrate_search::{
3 QueryRequest, QueryResults, SearchIdentity, SearchSession, SubstrateSearch, Suggestions,
5 QueryRequest, QueryResults, SearchIdentity, SearchSession, SubstrateSearch, Suggestions,
@@ -12,7 +14,7 @@ use chatsvc::{
12 ConversationState, Conversations, ForcedAvailability, ForwardResult, Gif, Gifs, HistoryShare,
14 ConversationState, Conversations, ForcedAvailability, ForwardResult, Gif, Gifs, HistoryShare,
13 InvokeRequest, InvokeResponse, Language, LanguageSettings, LanguageSettingsClient, LinkInfo,
15 InvokeRequest, InvokeResponse, Language, LanguageSettings, LanguageSettingsClient, LinkInfo,
14 MemberHorizon, MessageEmotions, MessageLanguage, MessageLinks, MessageWindow, Messages,
16 MemberHorizon, MessageEmotions, MessageLanguage, MessageLinks, MessageWindow, Messages,
15 PinnedMessage, Pins, PresenceLookup, PresenceService, PresenceStatus, Receipts,
17 PinnedMessage, Pins, PostFollowState, PresenceLookup, PresenceService, PresenceStatus, Receipts,
16 RecordingPolicy, SavedMessage, ScheduledDraft, ScheduledDrafts, StatusNote, ThreadMembers,
18 RecordingPolicy, SavedMessage, ScheduledDraft, ScheduledDrafts, StatusNote, ThreadMembers,
17 TranslateRequest, Translation, TranslationTrigger, Translator, WindowDirection,
19 TranslateRequest, Translation, TranslationTrigger, Translator, WindowDirection,
18 WorkLocationKind,
20 WorkLocationKind,
@@ -343,6 +345,24 @@ pub trait Remote {
343 Err(Error::Unsupported("saved messages"))
345 Err(Error::Unsupported("saved messages"))
344 }
346 }
345
347
348 async fn set_post_followed(
349 &self,
350 _user_id: &str,
351 _channel_id: &str,
352 _root_id: &str,
353 _followed: bool,
354 ) -> Result<()> {
355 Err(Error::Unsupported("following posts"))
356 }
357
358 async fn post_follow_states(
359 &self,
360 _channel_id: &str,
361 _root_ids: &[String],
362 ) -> Result<HashMap<String, PostFollowState>> {
363 Err(Error::Unsupported("post follow states"))
364 }
365
346 async fn list_call_logs(&self) -> Result<Vec<CallLogEntry>> {
366 async fn list_call_logs(&self) -> Result<Vec<CallLogEntry>> {
347 Err(Error::Unsupported("call history"))
367 Err(Error::Unsupported("call history"))
348 }
368 }
@@ -1144,6 +1164,28 @@ impl Remote for Graph {
1144 Ok(Messages::new(self.session()).list_saved().await?)
1164 Ok(Messages::new(self.session()).list_saved().await?)
1145 }
1165 }
1146
1166
1167 async fn set_post_followed(
1168 &self,
1169 user_id: &str,
1170 channel_id: &str,
1171 root_id: &str,
1172 followed: bool,
1173 ) -> Result<()> {
1174 Ok(Messages::new(self.session())
1175 .set_post_followed(user_id, channel_id, root_id, followed)
1176 .await?)
1177 }
1178
1179 async fn post_follow_states(
1180 &self,
1181 channel_id: &str,
1182 root_ids: &[String],
1183 ) -> Result<HashMap<String, PostFollowState>> {
1184 Ok(Messages::new(self.session())
1185 .post_follow_states(channel_id, root_ids)
1186 .await?)
1187 }
1188
1147 async fn list_call_logs(&self) -> Result<Vec<CallLogEntry>> {
1189 async fn list_call_logs(&self) -> Result<Vec<CallLogEntry>> {
1148 Ok(Messages::new(self.session()).list_call_logs().await?)
1190 Ok(Messages::new(self.session()).list_call_logs().await?)
1149 }
1191 }
crates/core/tests/engine.rs +22 −0
@@ -904,6 +904,17 @@ impl Remote for Handle {
904 904 Ok(())
905 905 }
906 906
907 async fn set_post_followed(
908 &self,
909 user_id: &str,
910 channel_id: &str,
911 root_id: &str,
912 followed: bool,
913 ) -> Result<()> {
914 self.record(format!("follow {user_id} {channel_id} {root_id} {followed}"));
915 Ok(())
916 }
917
907 918 async fn pin_message(&self, chat_id: &str, message_id: &str) -> Result<()> {
908 919 self.record(format!("pin {chat_id} {message_id}"));
909 920 Ok(())
@@ -4946,6 +4957,17 @@ async fn save_uses_the_message_id_as_root_in_chats() {
4946 4957 );
4947 4958 }
4948 4959
4960 #[tokio::test]
4961 async fn post_follow_writes_as_the_signed_in_user() {
4962 let fake = Arc::new(Fake::default());
4963 let engine = channel_engine(&fake).await;
4964 engine.set_post_followed(CHANNEL, "3", false).await.unwrap();
4965 assert_eq!(
4966 fake.calls().last().unwrap(),
4967 &format!("follow {ME} {CHANNEL} 3 false")
4968 );
4969 }
4970
4949 4971 #[tokio::test]
4950 4972 async fn pinning_announces_in_chats() {
4951 4973 let fake = Arc::new(Fake::default());
@@ -904,6 +904,17 @@ impl Remote for Handle {
904 Ok(())
904 Ok(())
905 }
905 }
906
906
907 async fn set_post_followed(
908 &self,
909 user_id: &str,
910 channel_id: &str,
911 root_id: &str,
912 followed: bool,
913 ) -> Result<()> {
914 self.record(format!("follow {user_id} {channel_id} {root_id} {followed}"));
915 Ok(())
916 }
917
907 async fn pin_message(&self, chat_id: &str, message_id: &str) -> Result<()> {
918 async fn pin_message(&self, chat_id: &str, message_id: &str) -> Result<()> {
908 self.record(format!("pin {chat_id} {message_id}"));
919 self.record(format!("pin {chat_id} {message_id}"));
909 Ok(())
920 Ok(())
@@ -4946,6 +4957,17 @@ async fn save_uses_the_message_id_as_root_in_chats() {
4946 );
4957 );
4947}
4958}
4948
4959
4960#[tokio::test]
4961async fn post_follow_writes_as_the_signed_in_user() {
4962 let fake = Arc::new(Fake::default());
4963 let engine = channel_engine(&fake).await;
4964 engine.set_post_followed(CHANNEL, "3", false).await.unwrap();
4965 assert_eq!(
4966 fake.calls().last().unwrap(),
4967 &format!("follow {ME} {CHANNEL} 3 false")
4968 );
4969}
4970
4949#[tokio::test]
4971#[tokio::test]
4950async fn pinning_announces_in_chats() {
4972async fn pinning_announces_in_chats() {
4951 let fake = Arc::new(Fake::default());
4973 let fake = Arc::new(Fake::default());