BlueGit

ict rusty-teams

feat(teams): edit and delete channels from the channel menu

- "Edit channel" and "Delete channel" in the channel menu by team rights (standard: updateTopic/deleteTopic, private: team owners, never General or shared)
- Edit dialog with name and description (description prefilled from Graph), Teams strings
- Standard channels via Middle Tier PATCH/DELETE, private channels via the provisioning service (both proven live in a test team, channels deleted again)
- A deleted channel leaves the sidebar at once and is skipped in team refreshes for 60 min, since Graph and CSA keep listing it
- The sidebar refreshes after a failed create too (the server may have created it before a client timeout)

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

metis Daniel Däschle · pushed by metis

Authored 2026-11-08 · 3 weeks ago

Hash
2c1323ee351bb65e1db3ba3f79641aea79652a5f
Parent
a551cf5f
16 files changed +1058 −24
crates/app-state/src/channel_menu.rs +55 −4
@@ -4,6 +4,7 @@ use gpui_kit::*;
4 4
5 5 use crate::app_state::AppState;
6 6 use crate::sidebar_model::channel_shown;
7 use crate::team_admin::ChannelAdmin;
7 8
8 9 pub const COPIED_TO_CLIPBOARD: &str = "Copied to clipboard";
9 10 pub const PINNED_CHANNEL_CANNOT_HIDE: &str = "Pinned channels can't be hidden.";
@@ -15,8 +16,10 @@ pub enum ChannelMenuItem {
15 16 Unpin,
16 17 Show,
17 18 Hide,
19 EditChannel,
18 20 ManageChannel,
19 21 CopyLink,
22 DeleteChannel,
20 23 }
21 24
22 25 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
@@ -42,8 +45,10 @@ impl ChannelMenuItem {
42 45 ChannelMenuItem::Unpin => "Unpin",
43 46 ChannelMenuItem::Show => "Show",
44 47 ChannelMenuItem::Hide => "Hide",
48 ChannelMenuItem::EditChannel => "Edit channel",
45 49 ChannelMenuItem::ManageChannel => "Manage channel",
46 50 ChannelMenuItem::CopyLink => "Copy link",
51 ChannelMenuItem::DeleteChannel => "Delete channel",
47 52 }
48 53 }
49 54 }
@@ -75,10 +80,11 @@ impl LinkUse {
75 80 }
76 81 }
77 82
78 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
83 #[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
79 84 pub struct ChannelMenuState {
80 85 pub pinned: bool,
81 86 pub shown: bool,
87 pub admin: ChannelAdmin,
82 88 }
83 89
84 90 impl ChannelMenuState {
@@ -88,7 +94,7 @@ impl ChannelMenuState {
88 94 }
89 95
90 96 pub fn channel_menu_entries(state: ChannelMenuState) -> Vec<MenuEntry<ChannelMenuItem>> {
91 vec![
97 let mut entries = vec![
92 98 MenuEntry::Item(ChannelMenuItem::Notifications),
93 99 MenuEntry::Item(if state.pinned {
94 100 ChannelMenuItem::Unpin
@@ -101,9 +107,21 @@ pub fn channel_menu_entries(state: ChannelMenuState) -> Vec<MenuEntry<ChannelMen
101 107 ChannelMenuItem::Show
102 108 }),
103 109 MenuEntry::Separator,
110 ];
111 if state.admin.can_edit {
112 entries.push(MenuEntry::Item(ChannelMenuItem::EditChannel));
113 }
114 entries.extend([
104 115 MenuEntry::Item(ChannelMenuItem::ManageChannel),
105 116 MenuEntry::Item(ChannelMenuItem::CopyLink),
106 ]
117 ]);
118 if state.admin.can_delete {
119 entries.extend([
120 MenuEntry::Separator,
121 MenuEntry::Item(ChannelMenuItem::DeleteChannel),
122 ]);
123 }
124 entries
107 125 }
108 126
109 127 #[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
@@ -199,6 +217,7 @@ impl AppState {
199 217 .iter()
200 218 .find(|team| team.channels.iter().any(|channel| channel.id == channel_id))
201 219 .is_none_or(|team| channel_shown(team, channel_id)),
220 admin: self.channel_admin(channel_id),
202 221 }
203 222 }
204 223
@@ -344,7 +363,7 @@ impl AppState {
344 363 self.link_from(async move { engine.team_link(&owned_id).await }, link_use, cx);
345 364 }
346 365
347 fn channel_team_id(&self, channel_id: &str) -> Option<String> {
366 pub fn channel_team_id(&self, channel_id: &str) -> Option<String> {
348 367 self.sidebar.teams.iter().find_map(|team| {
349 368 team.channels
350 369 .iter()
@@ -421,6 +440,8 @@ impl AppState {
421 440
422 441 #[cfg(test)]
423 442 mod tests {
443 use crate::team_admin::ChannelAdmin;
444
424 445 use super::{
425 446 ChannelMenuItem, ChannelMenuState, MenuEntry, TeamMenuItem, TeamMenuState,
426 447 channel_menu_entries, channel_visibility_failure, pin_failure, post_pin_dialog,
@@ -445,6 +466,7 @@ mod tests {
445 466 let shown = channel_menu_entries(ChannelMenuState {
446 467 pinned: false,
447 468 shown: true,
469 ..ChannelMenuState::default()
448 470 });
449 471 assert_eq!(
450 472 labels(&shown, ChannelMenuItem::label),
@@ -453,6 +475,7 @@ mod tests {
453 475 let hidden_pinned = channel_menu_entries(ChannelMenuState {
454 476 pinned: true,
455 477 shown: false,
478 ..ChannelMenuState::default()
456 479 });
457 480 assert_eq!(
458 481 labels(&hidden_pinned, ChannelMenuItem::label),
@@ -465,16 +488,44 @@ mod tests {
465 488 let pinned = ChannelMenuState {
466 489 pinned: true,
467 490 shown: true,
491 ..ChannelMenuState::default()
468 492 };
469 493 assert!(pinned.disables(ChannelMenuItem::Hide));
470 494 assert!(!pinned.disables(ChannelMenuItem::Unpin));
471 495 let unpinned = ChannelMenuState {
472 496 pinned: false,
473 497 shown: true,
498 ..ChannelMenuState::default()
474 499 };
475 500 assert!(!unpinned.disables(ChannelMenuItem::Hide));
476 501 }
477 502
503 #[test]
504 fn edit_and_delete_appear_only_with_the_rights() {
505 let admin = ChannelMenuState {
506 pinned: false,
507 shown: true,
508 admin: ChannelAdmin {
509 can_edit: true,
510 can_delete: true,
511 },
512 };
513 assert_eq!(
514 labels(&channel_menu_entries(admin), ChannelMenuItem::label),
515 [
516 "Notifications",
517 "Pin",
518 "Hide",
519 "-",
520 "Edit channel",
521 "Manage channel",
522 "Copy link",
523 "-",
524 "Delete channel"
525 ]
526 );
527 }
528
478 529 #[test]
479 530 fn team_menu_switches_between_show_and_hide() {
480 531 let shown = TeamMenuState::default();
@@ -4,6 +4,7 @@ use gpui_kit::*;
4
4
5use crate::app_state::AppState;
5use crate::app_state::AppState;
6use crate::sidebar_model::channel_shown;
6use crate::sidebar_model::channel_shown;
7use crate::team_admin::ChannelAdmin;
7
8
8pub const COPIED_TO_CLIPBOARD: &str = "Copied to clipboard";
9pub const COPIED_TO_CLIPBOARD: &str = "Copied to clipboard";
9pub const PINNED_CHANNEL_CANNOT_HIDE: &str = "Pinned channels can't be hidden.";
10pub const PINNED_CHANNEL_CANNOT_HIDE: &str = "Pinned channels can't be hidden.";
@@ -15,8 +16,10 @@ pub enum ChannelMenuItem {
15 Unpin,
16 Unpin,
16 Show,
17 Show,
17 Hide,
18 Hide,
19 EditChannel,
18 ManageChannel,
20 ManageChannel,
19 CopyLink,
21 CopyLink,
22 DeleteChannel,
20}
23}
21
24
22#[derive(Debug, Clone, Copy, PartialEq, Eq)]
25#[derive(Debug, Clone, Copy, PartialEq, Eq)]
@@ -42,8 +45,10 @@ impl ChannelMenuItem {
42 ChannelMenuItem::Unpin => "Unpin",
45 ChannelMenuItem::Unpin => "Unpin",
43 ChannelMenuItem::Show => "Show",
46 ChannelMenuItem::Show => "Show",
44 ChannelMenuItem::Hide => "Hide",
47 ChannelMenuItem::Hide => "Hide",
48 ChannelMenuItem::EditChannel => "Edit channel",
45 ChannelMenuItem::ManageChannel => "Manage channel",
49 ChannelMenuItem::ManageChannel => "Manage channel",
46 ChannelMenuItem::CopyLink => "Copy link",
50 ChannelMenuItem::CopyLink => "Copy link",
51 ChannelMenuItem::DeleteChannel => "Delete channel",
47 }
52 }
48 }
53 }
49}
54}
@@ -75,10 +80,11 @@ impl LinkUse {
75 }
80 }
76}
81}
77
82
78#[derive(Debug, Clone, Copy, PartialEq, Eq)]
83#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
79pub struct ChannelMenuState {
84pub struct ChannelMenuState {
80 pub pinned: bool,
85 pub pinned: bool,
81 pub shown: bool,
86 pub shown: bool,
87 pub admin: ChannelAdmin,
82}
88}
83
89
84impl ChannelMenuState {
90impl ChannelMenuState {
@@ -88,7 +94,7 @@ impl ChannelMenuState {
88}
94}
89
95
90pub fn channel_menu_entries(state: ChannelMenuState) -> Vec<MenuEntry<ChannelMenuItem>> {
96pub fn channel_menu_entries(state: ChannelMenuState) -> Vec<MenuEntry<ChannelMenuItem>> {
91 vec![
97 let mut entries = vec![
92 MenuEntry::Item(ChannelMenuItem::Notifications),
98 MenuEntry::Item(ChannelMenuItem::Notifications),
93 MenuEntry::Item(if state.pinned {
99 MenuEntry::Item(if state.pinned {
94 ChannelMenuItem::Unpin
100 ChannelMenuItem::Unpin
@@ -101,9 +107,21 @@ pub fn channel_menu_entries(state: ChannelMenuState) -> Vec<MenuEntry<ChannelMen
101 ChannelMenuItem::Show
107 ChannelMenuItem::Show
102 }),
108 }),
103 MenuEntry::Separator,
109 MenuEntry::Separator,
110 ];
111 if state.admin.can_edit {
112 entries.push(MenuEntry::Item(ChannelMenuItem::EditChannel));
113 }
114 entries.extend([
104 MenuEntry::Item(ChannelMenuItem::ManageChannel),
115 MenuEntry::Item(ChannelMenuItem::ManageChannel),
105 MenuEntry::Item(ChannelMenuItem::CopyLink),
116 MenuEntry::Item(ChannelMenuItem::CopyLink),
106 ]
117 ]);
118 if state.admin.can_delete {
119 entries.extend([
120 MenuEntry::Separator,
121 MenuEntry::Item(ChannelMenuItem::DeleteChannel),
122 ]);
123 }
124 entries
107}
125}
108
126
109#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
127#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
@@ -199,6 +217,7 @@ impl AppState {
199 .iter()
217 .iter()
200 .find(|team| team.channels.iter().any(|channel| channel.id == channel_id))
218 .find(|team| team.channels.iter().any(|channel| channel.id == channel_id))
201 .is_none_or(|team| channel_shown(team, channel_id)),
219 .is_none_or(|team| channel_shown(team, channel_id)),
220 admin: self.channel_admin(channel_id),
202 }
221 }
203 }
222 }
204
223
@@ -344,7 +363,7 @@ impl AppState {
344 self.link_from(async move { engine.team_link(&owned_id).await }, link_use, cx);
363 self.link_from(async move { engine.team_link(&owned_id).await }, link_use, cx);
345 }
364 }
346
365
347 fn channel_team_id(&self, channel_id: &str) -> Option<String> {
366 pub fn channel_team_id(&self, channel_id: &str) -> Option<String> {
348 self.sidebar.teams.iter().find_map(|team| {
367 self.sidebar.teams.iter().find_map(|team| {
349 team.channels
368 team.channels
350 .iter()
369 .iter()
@@ -421,6 +440,8 @@ impl AppState {
421
440
422#[cfg(test)]
441#[cfg(test)]
423mod tests {
442mod tests {
443 use crate::team_admin::ChannelAdmin;
444
424 use super::{
445 use super::{
425 ChannelMenuItem, ChannelMenuState, MenuEntry, TeamMenuItem, TeamMenuState,
446 ChannelMenuItem, ChannelMenuState, MenuEntry, TeamMenuItem, TeamMenuState,
426 channel_menu_entries, channel_visibility_failure, pin_failure, post_pin_dialog,
447 channel_menu_entries, channel_visibility_failure, pin_failure, post_pin_dialog,
@@ -445,6 +466,7 @@ mod tests {
445 let shown = channel_menu_entries(ChannelMenuState {
466 let shown = channel_menu_entries(ChannelMenuState {
446 pinned: false,
467 pinned: false,
447 shown: true,
468 shown: true,
469 ..ChannelMenuState::default()
448 });
470 });
449 assert_eq!(
471 assert_eq!(
450 labels(&shown, ChannelMenuItem::label),
472 labels(&shown, ChannelMenuItem::label),
@@ -453,6 +475,7 @@ mod tests {
453 let hidden_pinned = channel_menu_entries(ChannelMenuState {
475 let hidden_pinned = channel_menu_entries(ChannelMenuState {
454 pinned: true,
476 pinned: true,
455 shown: false,
477 shown: false,
478 ..ChannelMenuState::default()
456 });
479 });
457 assert_eq!(
480 assert_eq!(
458 labels(&hidden_pinned, ChannelMenuItem::label),
481 labels(&hidden_pinned, ChannelMenuItem::label),
@@ -465,16 +488,44 @@ mod tests {
465 let pinned = ChannelMenuState {
488 let pinned = ChannelMenuState {
466 pinned: true,
489 pinned: true,
467 shown: true,
490 shown: true,
491 ..ChannelMenuState::default()
468 };
492 };
469 assert!(pinned.disables(ChannelMenuItem::Hide));
493 assert!(pinned.disables(ChannelMenuItem::Hide));
470 assert!(!pinned.disables(ChannelMenuItem::Unpin));
494 assert!(!pinned.disables(ChannelMenuItem::Unpin));
471 let unpinned = ChannelMenuState {
495 let unpinned = ChannelMenuState {
472 pinned: false,
496 pinned: false,
473 shown: true,
497 shown: true,
498 ..ChannelMenuState::default()
474 };
499 };
475 assert!(!unpinned.disables(ChannelMenuItem::Hide));
500 assert!(!unpinned.disables(ChannelMenuItem::Hide));
476 }
501 }
477
502
503 #[test]
504 fn edit_and_delete_appear_only_with_the_rights() {
505 let admin = ChannelMenuState {
506 pinned: false,
507 shown: true,
508 admin: ChannelAdmin {
509 can_edit: true,
510 can_delete: true,
511 },
512 };
513 assert_eq!(
514 labels(&channel_menu_entries(admin), ChannelMenuItem::label),
515 [
516 "Notifications",
517 "Pin",
518 "Hide",
519 "-",
520 "Edit channel",
521 "Manage channel",
522 "Copy link",
523 "-",
524 "Delete channel"
525 ]
526 );
527 }
528
478 #[test]
529 #[test]
479 fn team_menu_switches_between_show_and_hide() {
530 fn team_menu_switches_between_show_and_hide() {
480 let shown = TeamMenuState::default();
531 let shown = TeamMenuState::default();
crates/app-state/src/team_admin.rs +202 −3
@@ -2,9 +2,10 @@ use gpui_kit::*;
2 2 use store::TeamRights;
3 3 use teams_core::{ChannelPrivacy, MAX_CHANNEL_NAME_LENGTH};
4 4
5 use crate::app_state::AppState;
5 use crate::app_state::{AppState, Selection};
6 6
7 7 pub const CREATE_CHANNEL_FAILURE: &str = "We couldn't create the channel.";
8 pub const EDIT_CHANNEL_FAILURE: &str = "Channel wasn't renamed.";
8 9 pub const CHANNEL_NAME_CHARACTERS: &str =
9 10 "Channel names can't contain ~ # % & * { } + / \\ : < > ? | ' \" , or ..";
10 11 pub const CHANNEL_NAME_EDGES: &str = "Channel names can't start with _ or . and can't end with .";
@@ -32,6 +33,54 @@ pub fn can_create_channel(raw: &str) -> bool {
32 33 !raw.trim().is_empty() && channel_name_problem(raw).is_none()
33 34 }
34 35
36 pub fn delete_channel_failure(channel_name: &str) -> String {
37 format!("We couldn't delete the {channel_name} channel. Try deleting it again.")
38 }
39
40 pub fn channel_deleted_notice(channel_name: &str) -> String {
41 format!("{channel_name} has been deleted")
42 }
43
44 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
45 pub enum ChannelKind {
46 General,
47 Standard,
48 Private,
49 Shared,
50 }
51
52 impl ChannelKind {
53 pub fn of(general: bool, membership_type: Option<&str>) -> Self {
54 match membership_type.map(str::to_ascii_lowercase).as_deref() {
55 _ if general => ChannelKind::General,
56 Some("private") => ChannelKind::Private,
57 Some("shared") => ChannelKind::Shared,
58 _ => ChannelKind::Standard,
59 }
60 }
61 }
62
63 #[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
64 pub struct ChannelAdmin {
65 pub can_edit: bool,
66 pub can_delete: bool,
67 }
68
69 /// Private channels are managed by team owners here, the channel's own owner role is not loaded.
70 pub fn channel_admin(rights: TeamRights, kind: ChannelKind) -> ChannelAdmin {
71 match kind {
72 ChannelKind::General | ChannelKind::Shared => ChannelAdmin::default(),
73 ChannelKind::Private => ChannelAdmin {
74 can_edit: rights.owner,
75 can_delete: rights.owner,
76 },
77 ChannelKind::Standard => ChannelAdmin {
78 can_edit: rights.edit_channel,
79 can_delete: rights.delete_channel,
80 },
81 }
82 }
83
35 84 impl AppState {
36 85 pub fn team_rights(&self, team_id: &str) -> TeamRights {
37 86 self.sidebar
@@ -50,6 +99,108 @@ impl AppState {
50 99 .map(|team| team.team.name.clone())
51 100 }
52 101
102 pub fn channel_admin(&self, channel_id: &str) -> ChannelAdmin {
103 let Some((team, channel)) = self.sidebar.teams.iter().find_map(|team| {
104 team.channels
105 .iter()
106 .find(|channel| channel.id == channel_id)
107 .map(|channel| (team, channel))
108 }) else {
109 return ChannelAdmin::default();
110 };
111 let general = self
112 .store
113 .team_thread_id(&team.team.id)
114 .ok()
115 .flatten()
116 .is_some_and(|thread_id| thread_id == channel_id);
117 let kind = ChannelKind::of(general, channel.membership_type.as_deref());
118 channel_admin(team.rights, kind)
119 }
120
121 pub fn channel_is_private(&self, channel_id: &str) -> bool {
122 self.sidebar
123 .teams
124 .iter()
125 .flat_map(|team| &team.channels)
126 .find(|channel| channel.id == channel_id)
127 .is_some_and(|channel| {
128 ChannelKind::of(false, channel.membership_type.as_deref()) == ChannelKind::Private
129 })
130 }
131
132 pub fn load_channel_description(
133 &self,
134 channel_id: &str,
135 cx: &mut Context<Self>,
136 ) -> Task<Option<String>> {
137 let Some(engine) = self.engine.clone() else {
138 return Task::ready(None);
139 };
140 let channel_id = channel_id.to_owned();
141 let receiver =
142 crate::runtime::spawn(async move { engine.channel_description(&channel_id).await });
143 cx.background_spawn(async move { receiver.await.ok().and_then(Result::ok) })
144 }
145
146 pub fn edit_channel(
147 &mut self,
148 channel_id: &str,
149 name: &str,
150 description: Option<&str>,
151 cx: &mut Context<Self>,
152 ) {
153 let Some(Some(engine)) = self.chat_action_engine(cx) else {
154 return;
155 };
156 let (channel_id, name, description) = (
157 channel_id.to_owned(),
158 name.to_owned(),
159 description.map(str::to_owned),
160 );
161 self.run_channel_action(
162 EDIT_CHANNEL_FAILURE,
163 async move {
164 engine
165 .edit_channel(&channel_id, &name, description.as_deref())
166 .await
167 },
168 |_, _| {},
169 None,
170 cx,
171 );
172 }
173
174 pub fn delete_channel(&mut self, channel_id: &str, cx: &mut Context<Self>) {
175 let Some(Some(engine)) = self.chat_action_engine(cx) else {
176 return;
177 };
178 let channel_name = self.channel_name(channel_id).unwrap_or_default();
179 let general_id = self
180 .channel_team_id(channel_id)
181 .and_then(|team_id| self.store.team_thread_id(&team_id).ok().flatten());
182 let owned_id = channel_id.to_owned();
183 let receiver = crate::runtime::spawn(async move { engine.delete_channel(&owned_id).await });
184 let channel_id = channel_id.to_owned();
185 cx.spawn(async move |this, cx| {
186 let deleted = matches!(receiver.await, Ok(Ok(())));
187 this.update(cx, |state, cx| {
188 if !deleted {
189 state.raise_notice(delete_channel_failure(&channel_name), None, cx);
190 return;
191 }
192 if state.selection == Some(Selection::Channel(channel_id.clone()))
193 && let Some(general_id) = general_id
194 {
195 state.select(Selection::Channel(general_id), cx);
196 }
197 state.raise_notice(channel_deleted_notice(&channel_name), None, cx);
198 })
199 .ok();
200 })
201 .detach();
202 }
203
53 204 pub fn create_channel(
54 205 &mut self,
55 206 team_id: &str,
@@ -81,9 +232,11 @@ impl AppState {
81 232 mod tests {
82 233 use teams_core::MAX_CHANNEL_NAME_LENGTH;
83 234
235 use store::TeamRights;
236
84 237 use super::{
85 CHANNEL_NAME_CHARACTERS, CHANNEL_NAME_EDGES, CHANNEL_NAME_LENGTH, can_create_channel,
86 channel_name_problem,
238 CHANNEL_NAME_CHARACTERS, CHANNEL_NAME_EDGES, CHANNEL_NAME_LENGTH, ChannelAdmin,
239 ChannelKind, can_create_channel, channel_admin, channel_name_problem,
87 240 };
88 241
89 242 #[test]
@@ -103,4 +256,50 @@ mod tests {
103 256 assert_eq!(channel_name_problem("notes."), Some(CHANNEL_NAME_EDGES));
104 257 assert_eq!(channel_name_problem("Release notes"), None);
105 258 }
259
260 #[test]
261 fn channel_admin_follows_the_team_rights_and_channel_kind() {
262 let member = TeamRights {
263 edit_channel: true,
264 delete_channel: false,
265 ..TeamRights::default()
266 };
267 assert_eq!(
268 channel_admin(member, ChannelKind::Standard),
269 ChannelAdmin {
270 can_edit: true,
271 can_delete: false
272 }
273 );
274 assert_eq!(
275 channel_admin(member, ChannelKind::Private),
276 ChannelAdmin::default()
277 );
278 let owner = TeamRights {
279 owner: true,
280 edit_channel: true,
281 delete_channel: true,
282 ..TeamRights::default()
283 };
284 assert_eq!(
285 channel_admin(owner, ChannelKind::General),
286 ChannelAdmin::default()
287 );
288 assert_eq!(
289 channel_admin(owner, ChannelKind::Private),
290 ChannelAdmin {
291 can_edit: true,
292 can_delete: true
293 }
294 );
295 assert_eq!(
296 ChannelKind::of(false, Some("Private")),
297 ChannelKind::Private
298 );
299 assert_eq!(
300 ChannelKind::of(true, Some("standard")),
301 ChannelKind::General
302 );
303 assert_eq!(ChannelKind::of(false, None), ChannelKind::Standard);
304 }
106 305 }
@@ -2,9 +2,10 @@ use gpui_kit::*;
2use store::TeamRights;
2use store::TeamRights;
3use teams_core::{ChannelPrivacy, MAX_CHANNEL_NAME_LENGTH};
3use teams_core::{ChannelPrivacy, MAX_CHANNEL_NAME_LENGTH};
4
4
5use crate::app_state::AppState;
5use crate::app_state::{AppState, Selection};
6
6
7pub const CREATE_CHANNEL_FAILURE: &str = "We couldn't create the channel.";
7pub const CREATE_CHANNEL_FAILURE: &str = "We couldn't create the channel.";
8pub const EDIT_CHANNEL_FAILURE: &str = "Channel wasn't renamed.";
8pub const CHANNEL_NAME_CHARACTERS: &str =
9pub const CHANNEL_NAME_CHARACTERS: &str =
9 "Channel names can't contain ~ # % & * { } + / \\ : < > ? | ' \" , or ..";
10 "Channel names can't contain ~ # % & * { } + / \\ : < > ? | ' \" , or ..";
10pub const CHANNEL_NAME_EDGES: &str = "Channel names can't start with _ or . and can't end with .";
11pub const CHANNEL_NAME_EDGES: &str = "Channel names can't start with _ or . and can't end with .";
@@ -32,6 +33,54 @@ pub fn can_create_channel(raw: &str) -> bool {
32 !raw.trim().is_empty() && channel_name_problem(raw).is_none()
33 !raw.trim().is_empty() && channel_name_problem(raw).is_none()
33}
34}
34
35
36pub fn delete_channel_failure(channel_name: &str) -> String {
37 format!("We couldn't delete the {channel_name} channel. Try deleting it again.")
38}
39
40pub fn channel_deleted_notice(channel_name: &str) -> String {
41 format!("{channel_name} has been deleted")
42}
43
44#[derive(Debug, Clone, Copy, PartialEq, Eq)]
45pub enum ChannelKind {
46 General,
47 Standard,
48 Private,
49 Shared,
50}
51
52impl ChannelKind {
53 pub fn of(general: bool, membership_type: Option<&str>) -> Self {
54 match membership_type.map(str::to_ascii_lowercase).as_deref() {
55 _ if general => ChannelKind::General,
56 Some("private") => ChannelKind::Private,
57 Some("shared") => ChannelKind::Shared,
58 _ => ChannelKind::Standard,
59 }
60 }
61}
62
63#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
64pub struct ChannelAdmin {
65 pub can_edit: bool,
66 pub can_delete: bool,
67}
68
69/// Private channels are managed by team owners here, the channel's own owner role is not loaded.
70pub fn channel_admin(rights: TeamRights, kind: ChannelKind) -> ChannelAdmin {
71 match kind {
72 ChannelKind::General | ChannelKind::Shared => ChannelAdmin::default(),
73 ChannelKind::Private => ChannelAdmin {
74 can_edit: rights.owner,
75 can_delete: rights.owner,
76 },
77 ChannelKind::Standard => ChannelAdmin {
78 can_edit: rights.edit_channel,
79 can_delete: rights.delete_channel,
80 },
81 }
82}
83
35impl AppState {
84impl AppState {
36 pub fn team_rights(&self, team_id: &str) -> TeamRights {
85 pub fn team_rights(&self, team_id: &str) -> TeamRights {
37 self.sidebar
86 self.sidebar
@@ -50,6 +99,108 @@ impl AppState {
50 .map(|team| team.team.name.clone())
99 .map(|team| team.team.name.clone())
51 }
100 }
52
101
102 pub fn channel_admin(&self, channel_id: &str) -> ChannelAdmin {
103 let Some((team, channel)) = self.sidebar.teams.iter().find_map(|team| {
104 team.channels
105 .iter()
106 .find(|channel| channel.id == channel_id)
107 .map(|channel| (team, channel))
108 }) else {
109 return ChannelAdmin::default();
110 };
111 let general = self
112 .store
113 .team_thread_id(&team.team.id)
114 .ok()
115 .flatten()
116 .is_some_and(|thread_id| thread_id == channel_id);
117 let kind = ChannelKind::of(general, channel.membership_type.as_deref());
118 channel_admin(team.rights, kind)
119 }
120
121 pub fn channel_is_private(&self, channel_id: &str) -> bool {
122 self.sidebar
123 .teams
124 .iter()
125 .flat_map(|team| &team.channels)
126 .find(|channel| channel.id == channel_id)
127 .is_some_and(|channel| {
128 ChannelKind::of(false, channel.membership_type.as_deref()) == ChannelKind::Private
129 })
130 }
131
132 pub fn load_channel_description(
133 &self,
134 channel_id: &str,
135 cx: &mut Context<Self>,
136 ) -> Task<Option<String>> {
137 let Some(engine) = self.engine.clone() else {
138 return Task::ready(None);
139 };
140 let channel_id = channel_id.to_owned();
141 let receiver =
142 crate::runtime::spawn(async move { engine.channel_description(&channel_id).await });
143 cx.background_spawn(async move { receiver.await.ok().and_then(Result::ok) })
144 }
145
146 pub fn edit_channel(
147 &mut self,
148 channel_id: &str,
149 name: &str,
150 description: Option<&str>,
151 cx: &mut Context<Self>,
152 ) {
153 let Some(Some(engine)) = self.chat_action_engine(cx) else {
154 return;
155 };
156 let (channel_id, name, description) = (
157 channel_id.to_owned(),
158 name.to_owned(),
159 description.map(str::to_owned),
160 );
161 self.run_channel_action(
162 EDIT_CHANNEL_FAILURE,
163 async move {
164 engine
165 .edit_channel(&channel_id, &name, description.as_deref())
166 .await
167 },
168 |_, _| {},
169 None,
170 cx,
171 );
172 }
173
174 pub fn delete_channel(&mut self, channel_id: &str, cx: &mut Context<Self>) {
175 let Some(Some(engine)) = self.chat_action_engine(cx) else {
176 return;
177 };
178 let channel_name = self.channel_name(channel_id).unwrap_or_default();
179 let general_id = self
180 .channel_team_id(channel_id)
181 .and_then(|team_id| self.store.team_thread_id(&team_id).ok().flatten());
182 let owned_id = channel_id.to_owned();
183 let receiver = crate::runtime::spawn(async move { engine.delete_channel(&owned_id).await });
184 let channel_id = channel_id.to_owned();
185 cx.spawn(async move |this, cx| {
186 let deleted = matches!(receiver.await, Ok(Ok(())));
187 this.update(cx, |state, cx| {
188 if !deleted {
189 state.raise_notice(delete_channel_failure(&channel_name), None, cx);
190 return;
191 }
192 if state.selection == Some(Selection::Channel(channel_id.clone()))
193 && let Some(general_id) = general_id
194 {
195 state.select(Selection::Channel(general_id), cx);
196 }
197 state.raise_notice(channel_deleted_notice(&channel_name), None, cx);
198 })
199 .ok();
200 })
201 .detach();
202 }
203
53 pub fn create_channel(
204 pub fn create_channel(
54 &mut self,
205 &mut self,
55 team_id: &str,
206 team_id: &str,
@@ -81,9 +232,11 @@ impl AppState {
81mod tests {
232mod tests {
82 use teams_core::MAX_CHANNEL_NAME_LENGTH;
233 use teams_core::MAX_CHANNEL_NAME_LENGTH;
83
234
235 use store::TeamRights;
236
84 use super::{
237 use super::{
85 CHANNEL_NAME_CHARACTERS, CHANNEL_NAME_EDGES, CHANNEL_NAME_LENGTH, can_create_channel,
238 CHANNEL_NAME_CHARACTERS, CHANNEL_NAME_EDGES, CHANNEL_NAME_LENGTH, ChannelAdmin,
86 channel_name_problem,
239 ChannelKind, can_create_channel, channel_admin, channel_name_problem,
87 };
240 };
88
241
89 #[test]
242 #[test]
@@ -103,4 +256,50 @@ mod tests {
103 assert_eq!(channel_name_problem("notes."), Some(CHANNEL_NAME_EDGES));
256 assert_eq!(channel_name_problem("notes."), Some(CHANNEL_NAME_EDGES));
104 assert_eq!(channel_name_problem("Release notes"), None);
257 assert_eq!(channel_name_problem("Release notes"), None);
105 }
258 }
259
260 #[test]
261 fn channel_admin_follows_the_team_rights_and_channel_kind() {
262 let member = TeamRights {
263 edit_channel: true,
264 delete_channel: false,
265 ..TeamRights::default()
266 };
267 assert_eq!(
268 channel_admin(member, ChannelKind::Standard),
269 ChannelAdmin {
270 can_edit: true,
271 can_delete: false
272 }
273 );
274 assert_eq!(
275 channel_admin(member, ChannelKind::Private),
276 ChannelAdmin::default()
277 );
278 let owner = TeamRights {
279 owner: true,
280 edit_channel: true,
281 delete_channel: true,
282 ..TeamRights::default()
283 };
284 assert_eq!(
285 channel_admin(owner, ChannelKind::General),
286 ChannelAdmin::default()
287 );
288 assert_eq!(
289 channel_admin(owner, ChannelKind::Private),
290 ChannelAdmin {
291 can_edit: true,
292 can_delete: true
293 }
294 );
295 assert_eq!(
296 ChannelKind::of(false, Some("Private")),
297 ChannelKind::Private
298 );
299 assert_eq!(
300 ChannelKind::of(true, Some("standard")),
301 ChannelKind::General
302 );
303 assert_eq!(ChannelKind::of(false, None), ChannelKind::Standard);
304 }
106}
305}
crates/app/src/views/channel_admin_dialogs.rs added +225 −0
@@ -0,0 +1,225 @@
1 use gpui_kit::component::button::{Button, ButtonVariants as _};
2 use gpui_kit::component::dialog::{Dialog, DialogFooter};
3 use gpui_kit::component::input::{Input, InputEvent, InputState};
4 use gpui_kit::component::{Disableable as _, WindowExt as _, v_flex};
5 use gpui_kit::prelude::FluentBuilder as _;
6 use gpui_kit::*;
7
8 use super::new_meeting_dialog::labeled;
9 use crate::app_state::AppState;
10 use crate::team_admin::{can_create_channel, channel_name_problem};
11 use crate::theme;
12
13 const DIALOG_WIDTH: f32 = 480.;
14 const FIELD_GAP: f32 = 12.;
15 const ERROR_SIZE: f32 = 12.;
16
17 struct EditChannelForm {
18 state: Entity<AppState>,
19 channel_id: String,
20 name: Entity<InputState>,
21 description: Entity<InputState>,
22 description_loaded: bool,
23 _subscriptions: Vec<Subscription>,
24 }
25
26 impl EditChannelForm {
27 fn new(
28 state: Entity<AppState>,
29 channel_id: String,
30 current_name: &str,
31 window: &mut Window,
32 cx: &mut Context<Self>,
33 ) -> Self {
34 let name = cx.new(|cx| {
35 InputState::new(window, cx)
36 .placeholder("Letters, numbers, and spaces are allowed")
37 .default_value(current_name.to_owned())
38 });
39 let description = cx.new(|cx| {
40 InputState::new(window, cx)
41 .placeholder("Help others find the right channel by providing a description")
42 });
43 let subscriptions = vec![
44 cx.subscribe_in(&name, window, Self::on_input),
45 cx.subscribe_in(&description, window, Self::on_input),
46 ];
47 let loading = state.update(cx, |app, cx| app.load_channel_description(&channel_id, cx));
48 cx.spawn_in(window, async move |form, cx| {
49 let loaded = loading.await;
50 form.update_in(cx, |form, window, cx| {
51 form.fill_description(loaded, window, cx)
52 })
53 .ok();
54 })
55 .detach();
56 EditChannelForm {
57 state,
58 channel_id,
59 name,
60 description,
61 description_loaded: false,
62 _subscriptions: subscriptions,
63 }
64 }
65
66 fn fill_description(
67 &mut self,
68 loaded: Option<String>,
69 window: &mut Window,
70 cx: &mut Context<Self>,
71 ) {
72 let Some(text) = loaded else {
73 return;
74 };
75 self.description_loaded = true;
76 if self.description.read(cx).value().is_empty() {
77 self.description
78 .update(cx, |input, cx| input.set_value(text, window, cx));
79 }
80 cx.notify();
81 }
82
83 fn on_input(
84 &mut self,
85 _: &Entity<InputState>,
86 event: &InputEvent,
87 window: &mut Window,
88 cx: &mut Context<Self>,
89 ) {
90 if matches!(event, InputEvent::PressEnter { .. }) && self.submit(cx) {
91 window.close_dialog(cx);
92 }
93 cx.notify();
94 }
95
96 fn can_save(&self, cx: &App) -> bool {
97 can_create_channel(&self.name.read(cx).value())
98 }
99
100 fn submit(&mut self, cx: &mut Context<Self>) -> bool {
101 if !self.can_save(cx) {
102 return false;
103 }
104 let name = self.name.read(cx).value().to_string();
105 let typed = self.description.read(cx).value().to_string();
106 let description = (self.description_loaded || !typed.is_empty()).then_some(typed);
107 let channel_id = self.channel_id.clone();
108 self.state.update(cx, |state, cx| {
109 state.edit_channel(&channel_id, &name, description.as_deref(), cx)
110 });
111 true
112 }
113 }
114
115 impl Render for EditChannelForm {
116 fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
117 let problem = channel_name_problem(&self.name.read(cx).value());
118 v_flex()
119 .debug_selector(|| "edit-channel".into())
120 .gap(px(FIELD_GAP))
121 .child(labeled("Channel name", Input::new(&self.name)))
122 .when_some(problem, |form, problem| {
123 form.child(
124 div()
125 .text_size(px(ERROR_SIZE))
126 .text_color(theme::red_soft())
127 .child(problem),
128 )
129 })
130 .child(labeled("Description", Input::new(&self.description)))
131 }
132 }
133
134 pub fn open_edit_channel_dialog(
135 state: Entity<AppState>,
136 channel_id: &str,
137 window: &mut Window,
138 cx: &mut App,
139 ) {
140 let (channel_name, team_name) = {
141 let app = state.read(cx);
142 let channel_name = app.channel_name(channel_id).unwrap_or_default();
143 let team_name = app
144 .channel_team_id(channel_id)
145 .and_then(|team_id| app.team_name(&team_id))
146 .unwrap_or_default();
147 (channel_name, team_name)
148 };
149 let title = format!("Edit \"{channel_name}\" channel in \"{team_name}\" team");
150 let channel_id = channel_id.to_owned();
151 let form = cx.new(|cx| EditChannelForm::new(state, channel_id, &channel_name, window, cx));
152 let field = form.read(cx).name.clone();
153 window.open_dialog(cx, move |dialog: Dialog, _, cx| {
154 let submit_form = form.clone();
155 let can_save = form.read(cx).can_save(cx);
156 let footer = DialogFooter::new()
157 .child(
158 Button::new("edit-channel-cancel")
159 .label("Cancel")
160 .on_click(|_, window, cx| window.close_dialog(cx)),
161 )
162 .child(
163 Button::new("edit-channel-save")
164 .primary()
165 .label("Save")
166 .disabled(!can_save)
167 .on_click(move |_, window, cx| {
168 if submit_form.update(cx, |form, cx| form.submit(cx)) {
169 window.close_dialog(cx);
170 }
171 }),
172 );
173 dialog
174 .title(title.clone())
175 .w(px(DIALOG_WIDTH))
176 .child(form.clone())
177 .footer(footer)
178 });
179 window.defer(cx, move |window, cx| {
180 field.update(cx, |input, cx| input.focus(window, cx));
181 });
182 }
183
184 pub fn confirm_delete_channel(
185 state: Entity<AppState>,
186 channel_id: &str,
187 window: &mut Window,
188 cx: &mut App,
189 ) {
190 let (channel_name, private) = {
191 let app = state.read(cx);
192 (
193 app.channel_name(channel_id).unwrap_or_default(),
194 app.channel_is_private(channel_id),
195 )
196 };
197 let description = if private {
198 format!(
199 "Are you sure you want to delete the {channel_name} channel? All files and conversations will be deleted."
200 )
201 } else {
202 format!(
203 "Are you sure you want to delete the {channel_name} channel? All conversations will be deleted."
204 )
205 };
206 let channel_id = channel_id.to_owned();
207 window.open_alert_dialog(cx, move |alert, _, _| {
208 let (state, channel_id) = (state.clone(), channel_id.clone());
209 let cancel = Button::new("delete-channel-cancel")
210 .label("Cancel")
211 .on_click(|_, window, cx| window.close_dialog(cx));
212 let delete = Button::new("delete-channel-confirm")
213 .label("Delete")
214 .danger()
215 .on_click(move |_, window, cx| {
216 state.update(cx, |state, cx| state.delete_channel(&channel_id, cx));
217 window.close_dialog(cx);
218 });
219 alert
220 .title("Delete channel")
221 .description(description.clone())
222 .footer(DialogFooter::new().child(cancel).child(delete))
223 .on_ok(|_, _, _| false)
224 });
225 }
@@ -0,0 +1,225 @@
1use gpui_kit::component::button::{Button, ButtonVariants as _};
2use gpui_kit::component::dialog::{Dialog, DialogFooter};
3use gpui_kit::component::input::{Input, InputEvent, InputState};
4use gpui_kit::component::{Disableable as _, WindowExt as _, v_flex};
5use gpui_kit::prelude::FluentBuilder as _;
6use gpui_kit::*;
7
8use super::new_meeting_dialog::labeled;
9use crate::app_state::AppState;
10use crate::team_admin::{can_create_channel, channel_name_problem};
11use crate::theme;
12
13const DIALOG_WIDTH: f32 = 480.;
14const FIELD_GAP: f32 = 12.;
15const ERROR_SIZE: f32 = 12.;
16
17struct EditChannelForm {
18 state: Entity<AppState>,
19 channel_id: String,
20 name: Entity<InputState>,
21 description: Entity<InputState>,
22 description_loaded: bool,
23 _subscriptions: Vec<Subscription>,
24}
25
26impl EditChannelForm {
27 fn new(
28 state: Entity<AppState>,
29 channel_id: String,
30 current_name: &str,
31 window: &mut Window,
32 cx: &mut Context<Self>,
33 ) -> Self {
34 let name = cx.new(|cx| {
35 InputState::new(window, cx)
36 .placeholder("Letters, numbers, and spaces are allowed")
37 .default_value(current_name.to_owned())
38 });
39 let description = cx.new(|cx| {
40 InputState::new(window, cx)
41 .placeholder("Help others find the right channel by providing a description")
42 });
43 let subscriptions = vec![
44 cx.subscribe_in(&name, window, Self::on_input),
45 cx.subscribe_in(&description, window, Self::on_input),
46 ];
47 let loading = state.update(cx, |app, cx| app.load_channel_description(&channel_id, cx));
48 cx.spawn_in(window, async move |form, cx| {
49 let loaded = loading.await;
50 form.update_in(cx, |form, window, cx| {
51 form.fill_description(loaded, window, cx)
52 })
53 .ok();
54 })
55 .detach();
56 EditChannelForm {
57 state,
58 channel_id,
59 name,
60 description,
61 description_loaded: false,
62 _subscriptions: subscriptions,
63 }
64 }
65
66 fn fill_description(
67 &mut self,
68 loaded: Option<String>,
69 window: &mut Window,
70 cx: &mut Context<Self>,
71 ) {
72 let Some(text) = loaded else {
73 return;
74 };
75 self.description_loaded = true;
76 if self.description.read(cx).value().is_empty() {
77 self.description
78 .update(cx, |input, cx| input.set_value(text, window, cx));
79 }
80 cx.notify();
81 }
82
83 fn on_input(
84 &mut self,
85 _: &Entity<InputState>,
86 event: &InputEvent,
87 window: &mut Window,
88 cx: &mut Context<Self>,
89 ) {
90 if matches!(event, InputEvent::PressEnter { .. }) && self.submit(cx) {
91 window.close_dialog(cx);
92 }
93 cx.notify();
94 }
95
96 fn can_save(&self, cx: &App) -> bool {
97 can_create_channel(&self.name.read(cx).value())
98 }
99
100 fn submit(&mut self, cx: &mut Context<Self>) -> bool {
101 if !self.can_save(cx) {
102 return false;
103 }
104 let name = self.name.read(cx).value().to_string();
105 let typed = self.description.read(cx).value().to_string();
106 let description = (self.description_loaded || !typed.is_empty()).then_some(typed);
107 let channel_id = self.channel_id.clone();
108 self.state.update(cx, |state, cx| {
109 state.edit_channel(&channel_id, &name, description.as_deref(), cx)
110 });
111 true
112 }
113}
114
115impl Render for EditChannelForm {
116 fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
117 let problem = channel_name_problem(&self.name.read(cx).value());
118 v_flex()
119 .debug_selector(|| "edit-channel".into())
120 .gap(px(FIELD_GAP))
121 .child(labeled("Channel name", Input::new(&self.name)))
122 .when_some(problem, |form, problem| {
123 form.child(
124 div()
125 .text_size(px(ERROR_SIZE))
126 .text_color(theme::red_soft())
127 .child(problem),
128 )
129 })
130 .child(labeled("Description", Input::new(&self.description)))
131 }
132}
133
134pub fn open_edit_channel_dialog(
135 state: Entity<AppState>,
136 channel_id: &str,
137 window: &mut Window,
138 cx: &mut App,
139) {
140 let (channel_name, team_name) = {
141 let app = state.read(cx);
142 let channel_name = app.channel_name(channel_id).unwrap_or_default();
143 let team_name = app
144 .channel_team_id(channel_id)
145 .and_then(|team_id| app.team_name(&team_id))
146 .unwrap_or_default();
147 (channel_name, team_name)
148 };
149 let title = format!("Edit \"{channel_name}\" channel in \"{team_name}\" team");
150 let channel_id = channel_id.to_owned();
151 let form = cx.new(|cx| EditChannelForm::new(state, channel_id, &channel_name, window, cx));
152 let field = form.read(cx).name.clone();
153 window.open_dialog(cx, move |dialog: Dialog, _, cx| {
154 let submit_form = form.clone();
155 let can_save = form.read(cx).can_save(cx);
156 let footer = DialogFooter::new()
157 .child(
158 Button::new("edit-channel-cancel")
159 .label("Cancel")
160 .on_click(|_, window, cx| window.close_dialog(cx)),
161 )
162 .child(
163 Button::new("edit-channel-save")
164 .primary()
165 .label("Save")
166 .disabled(!can_save)
167 .on_click(move |_, window, cx| {
168 if submit_form.update(cx, |form, cx| form.submit(cx)) {
169 window.close_dialog(cx);
170 }
171 }),
172 );
173 dialog
174 .title(title.clone())
175 .w(px(DIALOG_WIDTH))
176 .child(form.clone())
177 .footer(footer)
178 });
179 window.defer(cx, move |window, cx| {
180 field.update(cx, |input, cx| input.focus(window, cx));
181 });
182}
183
184pub fn confirm_delete_channel(
185 state: Entity<AppState>,
186 channel_id: &str,
187 window: &mut Window,
188 cx: &mut App,
189) {
190 let (channel_name, private) = {
191 let app = state.read(cx);
192 (
193 app.channel_name(channel_id).unwrap_or_default(),
194 app.channel_is_private(channel_id),
195 )
196 };
197 let description = if private {
198 format!(
199 "Are you sure you want to delete the {channel_name} channel? All files and conversations will be deleted."
200 )
201 } else {
202 format!(
203 "Are you sure you want to delete the {channel_name} channel? All conversations will be deleted."
204 )
205 };
206 let channel_id = channel_id.to_owned();
207 window.open_alert_dialog(cx, move |alert, _, _| {
208 let (state, channel_id) = (state.clone(), channel_id.clone());
209 let cancel = Button::new("delete-channel-cancel")
210 .label("Cancel")
211 .on_click(|_, window, cx| window.close_dialog(cx));
212 let delete = Button::new("delete-channel-confirm")
213 .label("Delete")
214 .danger()
215 .on_click(move |_, window, cx| {
216 state.update(cx, |state, cx| state.delete_channel(&channel_id, cx));
217 window.close_dialog(cx);
218 });
219 alert
220 .title("Delete channel")
221 .description(description.clone())
222 .footer(DialogFooter::new().child(cancel).child(delete))
223 .on_ok(|_, _, _| false)
224 });
225}
crates/app/src/views/mod.rs +1 −0
@@ -40,6 +40,7 @@ pub mod chat_pop_out;
40 40 pub mod composer;
41 41 pub mod connection_banner;
42 42 pub mod conversation;
43 pub mod channel_admin_dialogs;
43 44 pub mod create_channel_dialog;
44 45 pub mod customize_reactions;
45 46 pub mod dialog_overlay;
@@ -40,6 +40,7 @@ pub mod chat_pop_out;
40pub mod composer;
40pub mod composer;
41pub mod connection_banner;
41pub mod connection_banner;
42pub mod conversation;
42pub mod conversation;
43pub mod channel_admin_dialogs;
43pub mod create_channel_dialog;
44pub mod create_channel_dialog;
44pub mod customize_reactions;
45pub mod customize_reactions;
45pub mod dialog_overlay;
46pub mod dialog_overlay;
crates/app/src/views/sidebar.rs +18 −2
@@ -23,6 +23,7 @@ use super::calls_tab::calls_body;
23 23 use super::chat_pop_out;
24 24 use super::saved_panel::SavedPanel;
25 25 use super::scroll_edge::{scroll_offset, with_top_edge};
26 use super::channel_admin_dialogs::{confirm_delete_channel, open_edit_channel_dialog};
26 27 use super::create_channel_dialog::open_create_channel_dialog;
27 28 use super::section_dialog::{SectionNameTarget, open_section_name_dialog};
28 29 use super::widgets::{count_badge, icon, menu_icon, page_header, symbol, unread_marker};
@@ -1999,7 +2000,18 @@ fn channel_menu(
1999 2000 PopupMenuItem::new(item.label())
2000 2001 .icon(menu_icon(channel_menu_icon(item)))
2001 2002 .disabled(menu_state.disables(item))
2002 .on_click(move |_, _, cx| {
2003 .on_click(move |_, window, cx| {
2004 match item {
2005 ChannelMenuItem::EditChannel => {
2006 open_edit_channel_dialog(action_state.clone(), &action_id, window, cx);
2007 return;
2008 }
2009 ChannelMenuItem::DeleteChannel => {
2010 confirm_delete_channel(action_state.clone(), &action_id, window, cx);
2011 return;
2012 }
2013 _ => {}
2014 }
2003 2015 action_state.update(cx, |state, cx| match item {
2004 2016 ChannelMenuItem::Pin => state.set_channel_pinned(&action_id, true, cx),
2005 2017 ChannelMenuItem::Unpin => state.set_channel_pinned(&action_id, false, cx),
@@ -2009,7 +2021,9 @@ fn channel_menu(
2009 2021 state.manage_channel_in_browser(&action_id, cx)
2010 2022 }
2011 2023 ChannelMenuItem::CopyLink => state.copy_channel_link(&action_id, cx),
2012 ChannelMenuItem::Notifications => {}
2024 ChannelMenuItem::Notifications
2025 | ChannelMenuItem::EditChannel
2026 | ChannelMenuItem::DeleteChannel => {}
2013 2027 });
2014 2028 }),
2015 2029 );
@@ -2024,8 +2038,10 @@ fn channel_menu_icon(item: ChannelMenuItem) -> IconName {
2024 2038 ChannelMenuItem::Unpin => IconName::PinOff,
2025 2039 ChannelMenuItem::Show => IconName::Eye,
2026 2040 ChannelMenuItem::Hide => IconName::EyeOff,
2041 ChannelMenuItem::EditChannel => IconName::Pencil,
2027 2042 ChannelMenuItem::ManageChannel => IconName::Settings,
2028 2043 ChannelMenuItem::CopyLink => IconName::Link,
2044 ChannelMenuItem::DeleteChannel => IconName::Trash,
2029 2045 }
2030 2046 }
2031 2047
@@ -23,6 +23,7 @@ use super::calls_tab::calls_body;
23use super::chat_pop_out;
23use super::chat_pop_out;
24use super::saved_panel::SavedPanel;
24use super::saved_panel::SavedPanel;
25use super::scroll_edge::{scroll_offset, with_top_edge};
25use super::scroll_edge::{scroll_offset, with_top_edge};
26use super::channel_admin_dialogs::{confirm_delete_channel, open_edit_channel_dialog};
26use super::create_channel_dialog::open_create_channel_dialog;
27use super::create_channel_dialog::open_create_channel_dialog;
27use super::section_dialog::{SectionNameTarget, open_section_name_dialog};
28use super::section_dialog::{SectionNameTarget, open_section_name_dialog};
28use super::widgets::{count_badge, icon, menu_icon, page_header, symbol, unread_marker};
29use super::widgets::{count_badge, icon, menu_icon, page_header, symbol, unread_marker};
@@ -1999,7 +2000,18 @@ fn channel_menu(
1999 PopupMenuItem::new(item.label())
2000 PopupMenuItem::new(item.label())
2000 .icon(menu_icon(channel_menu_icon(item)))
2001 .icon(menu_icon(channel_menu_icon(item)))
2001 .disabled(menu_state.disables(item))
2002 .disabled(menu_state.disables(item))
2002 .on_click(move |_, _, cx| {
2003 .on_click(move |_, window, cx| {
2004 match item {
2005 ChannelMenuItem::EditChannel => {
2006 open_edit_channel_dialog(action_state.clone(), &action_id, window, cx);
2007 return;
2008 }
2009 ChannelMenuItem::DeleteChannel => {
2010 confirm_delete_channel(action_state.clone(), &action_id, window, cx);
2011 return;
2012 }
2013 _ => {}
2014 }
2003 action_state.update(cx, |state, cx| match item {
2015 action_state.update(cx, |state, cx| match item {
2004 ChannelMenuItem::Pin => state.set_channel_pinned(&action_id, true, cx),
2016 ChannelMenuItem::Pin => state.set_channel_pinned(&action_id, true, cx),
2005 ChannelMenuItem::Unpin => state.set_channel_pinned(&action_id, false, cx),
2017 ChannelMenuItem::Unpin => state.set_channel_pinned(&action_id, false, cx),
@@ -2009,7 +2021,9 @@ fn channel_menu(
2009 state.manage_channel_in_browser(&action_id, cx)
2021 state.manage_channel_in_browser(&action_id, cx)
2010 }
2022 }
2011 ChannelMenuItem::CopyLink => state.copy_channel_link(&action_id, cx),
2023 ChannelMenuItem::CopyLink => state.copy_channel_link(&action_id, cx),
2012 ChannelMenuItem::Notifications => {}
2024 ChannelMenuItem::Notifications
2025 | ChannelMenuItem::EditChannel
2026 | ChannelMenuItem::DeleteChannel => {}
2013 });
2027 });
2014 }),
2028 }),
2015 );
2029 );
@@ -2024,8 +2038,10 @@ fn channel_menu_icon(item: ChannelMenuItem) -> IconName {
2024 ChannelMenuItem::Unpin => IconName::PinOff,
2038 ChannelMenuItem::Unpin => IconName::PinOff,
2025 ChannelMenuItem::Show => IconName::Eye,
2039 ChannelMenuItem::Show => IconName::Eye,
2026 ChannelMenuItem::Hide => IconName::EyeOff,
2040 ChannelMenuItem::Hide => IconName::EyeOff,
2041 ChannelMenuItem::EditChannel => IconName::Pencil,
2027 ChannelMenuItem::ManageChannel => IconName::Settings,
2042 ChannelMenuItem::ManageChannel => IconName::Settings,
2028 ChannelMenuItem::CopyLink => IconName::Link,
2043 ChannelMenuItem::CopyLink => IconName::Link,
2044 ChannelMenuItem::DeleteChannel => IconName::Trash,
2029 }
2045 }
2030}
2046}
2031
2047
crates/chatsvc/examples/team_admin_probe.rs +21 −0
@@ -34,6 +34,27 @@ async fn main() {
34 34 println!("{outcome:?}");
35 35 return;
36 36 }
37 let channel_arguments: Vec<&str> = arguments.iter().map(String::as_str).collect();
38 if let [action @ ("lib-edit" | "lib-delete"), team_thread_id, group_id, channel_id, substrate, name, object_id, tenant_id] =
39 channel_arguments.as_slice()
40 {
41 let channel = chatsvc::ExistingChannel {
42 team_thread_id,
43 group_id,
44 channel_id,
45 substrate_group_id: (*substrate != "-").then_some(*substrate),
46 };
47 let mailbox = chatsvc::Mailbox { object_id, tenant_id };
48 let admin = chatsvc::TeamAdmin::new(&session);
49 let outcome = if *action == "lib-edit" {
50 let edit = chatsvc::ChannelEdit { name, description: None };
51 admin.update_channel(channel, edit, mailbox).await
52 } else {
53 admin.delete_channel(channel, mailbox).await
54 };
55 println!("{outcome:?}");
56 return;
57 }
37 58 let (method, path, body) = match arguments.iter().map(String::as_str).collect::<Vec<_>>().as_slice() {
38 59 ["create-team", name] => (
39 60 Method::Post,
@@ -34,6 +34,27 @@ async fn main() {
34 println!("{outcome:?}");
34 println!("{outcome:?}");
35 return;
35 return;
36 }
36 }
37 let channel_arguments: Vec<&str> = arguments.iter().map(String::as_str).collect();
38 if let [action @ ("lib-edit" | "lib-delete"), team_thread_id, group_id, channel_id, substrate, name, object_id, tenant_id] =
39 channel_arguments.as_slice()
40 {
41 let channel = chatsvc::ExistingChannel {
42 team_thread_id,
43 group_id,
44 channel_id,
45 substrate_group_id: (*substrate != "-").then_some(*substrate),
46 };
47 let mailbox = chatsvc::Mailbox { object_id, tenant_id };
48 let admin = chatsvc::TeamAdmin::new(&session);
49 let outcome = if *action == "lib-edit" {
50 let edit = chatsvc::ChannelEdit { name, description: None };
51 admin.update_channel(channel, edit, mailbox).await
52 } else {
53 admin.delete_channel(channel, mailbox).await
54 };
55 println!("{outcome:?}");
56 return;
57 }
37 let (method, path, body) = match arguments.iter().map(String::as_str).collect::<Vec<_>>().as_slice() {
58 let (method, path, body) = match arguments.iter().map(String::as_str).collect::<Vec<_>>().as_slice() {
38 ["create-team", name] => (
59 ["create-team", name] => (
39 Method::Post,
60 Method::Post,
crates/chatsvc/src/lib.rs +1 −1
@@ -75,7 +75,7 @@ pub use language_settings::{
75 75 };
76 76 pub use links::{LinkImage, LinkInfo, MessageLinks, is_link_image_url};
77 77 pub use mask::mask_conversation_id;
78 pub use team_admin::{ChannelPrivacy, Mailbox, NewChannel, TeamAdmin};
78 pub use team_admin::{ChannelEdit, ChannelPrivacy, ExistingChannel, Mailbox, NewChannel, TeamAdmin};
79 79 pub use members::{
80 80 HistoryShare, INVALID_TOPIC_CHARACTER, MAX_HISTORY_DAYS, MAX_TOPIC_LENGTH, ThreadMembers,
81 81 TopicProblem, topic_problem,
@@ -75,7 +75,7 @@ pub use language_settings::{
75};
75};
76pub use links::{LinkImage, LinkInfo, MessageLinks, is_link_image_url};
76pub use links::{LinkImage, LinkInfo, MessageLinks, is_link_image_url};
77pub use mask::mask_conversation_id;
77pub use mask::mask_conversation_id;
78pub use team_admin::{ChannelPrivacy, Mailbox, NewChannel, TeamAdmin};
78pub use team_admin::{ChannelEdit, ChannelPrivacy, ExistingChannel, Mailbox, NewChannel, TeamAdmin};
79pub use members::{
79pub use members::{
80 HistoryShare, INVALID_TOPIC_CHARACTER, MAX_HISTORY_DAYS, MAX_TOPIC_LENGTH, ThreadMembers,
80 HistoryShare, INVALID_TOPIC_CHARACTER, MAX_HISTORY_DAYS, MAX_TOPIC_LENGTH, ThreadMembers,
81 TopicProblem, topic_problem,
81 TopicProblem, topic_problem,
crates/chatsvc/src/team_admin.rs +196 −8
@@ -26,6 +26,20 @@ pub struct NewChannel<'a> {
26 26 pub privacy: ChannelPrivacy,
27 27 }
28 28
29 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
30 pub struct ExistingChannel<'a> {
31 pub team_thread_id: &'a str,
32 pub group_id: &'a str,
33 pub channel_id: &'a str,
34 pub substrate_group_id: Option<&'a str>,
35 }
36
37 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
38 pub struct ChannelEdit<'a> {
39 pub name: &'a str,
40 pub description: Option<&'a str>,
41 }
42
29 43 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
30 44 pub struct Mailbox<'a> {
31 45 pub object_id: &'a str,
@@ -38,6 +52,22 @@ impl Mailbox<'_> {
38 52 }
39 53 }
40 54
55 pub fn channel_edit_body(edit: ChannelEdit<'_>) -> Value {
56 let mut body = json!({ "displayName": edit.name });
57 if let Some(description) = edit.description {
58 body["description"] = json!(description);
59 }
60 body
61 }
62
63 fn substrate_channel_id(substrate_group_id: &str, tenant_id: &str) -> String {
64 if substrate_group_id.starts_with("OID:") {
65 substrate_group_id.to_owned()
66 } else {
67 format!("OID:{substrate_group_id}@{tenant_id}")
68 }
69 }
70
41 71 pub fn standard_channel_body(channel: &NewChannel<'_>) -> Value {
42 72 json!({
43 73 "displayName": channel.name,
@@ -110,19 +140,105 @@ impl<T: CsaTransport> TeamAdmin<T> {
110 140 "https://teams.cloud.microsoft/fabric/{}/templates/api/teams/{}/channels?forceSync=false",
111 141 self.region, channel.group_id
112 142 );
113 let mut request = with_headers(Request::with_body(
114 Method::Post,
115 url,
116 private_channel_body(channel),
143 let request = Request::with_body(Method::Post, url, private_channel_body(channel));
144 self.provisioning
145 .send(with_anchor(request, mailbox))
146 .await?
147 }
148 };
149 ensure_success(&answer)
150 }
151
152 pub async fn update_channel(
153 &self,
154 channel: ExistingChannel<'_>,
155 edit: ChannelEdit<'_>,
156 mailbox: Mailbox<'_>,
157 ) -> Result<()> {
158 let body = channel_edit_body(edit);
159 let answer = match channel.substrate_group_id {
160 None => {
161 self.middle_tier
162 .send(with_headers(Request::with_body(
163 Method::Patch,
164 self.middle_tier_channel_url(channel),
165 body,
166 )))
167 .await?
168 }
169 Some(substrate_group_id) => {
170 let request = Request::with_body(
171 Method::Patch,
172 self.provisioning_channel_url(channel, substrate_group_id, mailbox),
173 body,
174 );
175 self.provisioning
176 .send(with_anchor(request, mailbox))
177 .await?
178 }
179 };
180 ensure_success(&answer)
181 }
182
183 pub async fn delete_channel(
184 &self,
185 channel: ExistingChannel<'_>,
186 mailbox: Mailbox<'_>,
187 ) -> Result<()> {
188 let answer = match channel.substrate_group_id {
189 None => {
190 self.middle_tier
191 .send(with_headers(Request::with_body(
192 Method::Delete,
193 self.middle_tier_channel_url(channel),
194 json!({}),
195 )))
196 .await?
197 }
198 Some(substrate_group_id) => {
199 let request = Request::delete(self.provisioning_channel_url(
200 channel,
201 substrate_group_id,
202 mailbox,
117 203 ));
118 request
119 .headers
120 .push((ANCHOR_HEADER.to_owned(), mailbox.anchor()));
121 self.provisioning.send(request).await?
204 self.provisioning
205 .send(with_anchor(request, mailbox))
206 .await?
122 207 }
123 208 };
124 209 ensure_success(&answer)
125 210 }
211
212 fn middle_tier_channel_url(&self, channel: ExistingChannel<'_>) -> String {
213 format!(
214 "https://teams.cloud.microsoft/api/mt/{}/beta/teams/{}/channels/{}",
215 self.region,
216 encode(channel.team_thread_id),
217 encode(channel.channel_id)
218 )
219 }
220
221 fn provisioning_channel_url(
222 &self,
223 channel: ExistingChannel<'_>,
224 substrate_group_id: &str,
225 mailbox: Mailbox<'_>,
226 ) -> String {
227 format!(
228 "https://teams.cloud.microsoft/fabric/{}/templates/api/teams/{}/channels/{}?forceSync=false",
229 self.region,
230 channel.group_id,
231 encode(&substrate_channel_id(substrate_group_id, mailbox.tenant_id))
232 )
233 }
234 }
235
236 fn with_anchor(request: Request, mailbox: Mailbox<'_>) -> Request {
237 let mut request = with_headers(request);
238 request
239 .headers
240 .push((ANCHOR_HEADER.to_owned(), mailbox.anchor()));
241 request
126 242 }
127 243
128 244 #[cfg(test)]
@@ -210,4 +326,76 @@ mod tests {
210 326 assert_eq!(body["channelType"], "Private");
211 327 assert!(middle_tier.requests.lock().unwrap().is_empty());
212 328 }
329
330 const STANDARD: ExistingChannel<'static> = ExistingChannel {
331 team_thread_id: "19:team@thread.skype",
332 group_id: "group-1",
333 channel_id: "19:channel@thread.skype",
334 substrate_group_id: None,
335 };
336
337 #[tokio::test]
338 async fn standard_channel_edits_and_deletes_go_to_the_middle_tier() {
339 let middle_tier = Recorder::default();
340 let provisioning = Recorder::default();
341 let admin = TeamAdmin::with_transports(&middle_tier, &provisioning, "emea");
342 let edit = ChannelEdit {
343 name: "Renamed",
344 description: None,
345 };
346 admin.update_channel(STANDARD, edit, MAILBOX).await.unwrap();
347 admin.delete_channel(STANDARD, MAILBOX).await.unwrap();
348 let requests = middle_tier.requests.lock().unwrap();
349 let url = "https://teams.cloud.microsoft/api/mt/emea/beta/teams/19%3Ateam%40thread.skype/channels/19%3Achannel%40thread.skype";
350 assert_eq!(
351 (requests[0].method, requests[0].url.as_str()),
352 (Method::Patch, url)
353 );
354 assert_eq!(
355 requests[0].body.as_ref().unwrap(),
356 &json!({"displayName": "Renamed"})
357 );
358 assert_eq!(
359 (requests[1].method, requests[1].url.as_str()),
360 (Method::Delete, url)
361 );
362 assert!(provisioning.requests.lock().unwrap().is_empty());
363 }
364
365 #[tokio::test]
366 async fn private_channel_edits_and_deletes_go_to_provisioning_by_substrate_id() {
367 let middle_tier = Recorder::default();
368 let provisioning = Recorder::default();
369 let admin = TeamAdmin::with_transports(&middle_tier, &provisioning, "emea");
370 let private = ExistingChannel {
371 substrate_group_id: Some("substrate-1"),
372 ..STANDARD
373 };
374 let edit = ChannelEdit {
375 name: "Renamed",
376 description: Some("About"),
377 };
378 admin.update_channel(private, edit, MAILBOX).await.unwrap();
379 admin.delete_channel(private, MAILBOX).await.unwrap();
380 let requests = provisioning.requests.lock().unwrap();
381 let url = "https://teams.cloud.microsoft/fabric/emea/templates/api/teams/group-1/channels/OID%3Asubstrate-1%40tenant?forceSync=false";
382 assert_eq!(
383 (requests[0].method, requests[0].url.as_str()),
384 (Method::Patch, url)
385 );
386 assert_eq!(
387 requests[0].body.as_ref().unwrap(),
388 &json!({"displayName": "Renamed", "description": "About"})
389 );
390 assert_eq!(
391 (requests[1].method, requests[1].url.as_str()),
392 (Method::Delete, url)
393 );
394 assert!(
395 requests[1]
396 .headers
397 .contains(&(ANCHOR_HEADER.to_owned(), "OID:me@tenant".to_owned()))
398 );
399 assert!(middle_tier.requests.lock().unwrap().is_empty());
400 }
213 401 }
@@ -26,6 +26,20 @@ pub struct NewChannel<'a> {
26 pub privacy: ChannelPrivacy,
26 pub privacy: ChannelPrivacy,
27}
27}
28
28
29#[derive(Debug, Clone, Copy, PartialEq, Eq)]
30pub struct ExistingChannel<'a> {
31 pub team_thread_id: &'a str,
32 pub group_id: &'a str,
33 pub channel_id: &'a str,
34 pub substrate_group_id: Option<&'a str>,
35}
36
37#[derive(Debug, Clone, Copy, PartialEq, Eq)]
38pub struct ChannelEdit<'a> {
39 pub name: &'a str,
40 pub description: Option<&'a str>,
41}
42
29#[derive(Debug, Clone, Copy, PartialEq, Eq)]
43#[derive(Debug, Clone, Copy, PartialEq, Eq)]
30pub struct Mailbox<'a> {
44pub struct Mailbox<'a> {
31 pub object_id: &'a str,
45 pub object_id: &'a str,
@@ -38,6 +52,22 @@ impl Mailbox<'_> {
38 }
52 }
39}
53}
40
54
55pub fn channel_edit_body(edit: ChannelEdit<'_>) -> Value {
56 let mut body = json!({ "displayName": edit.name });
57 if let Some(description) = edit.description {
58 body["description"] = json!(description);
59 }
60 body
61}
62
63fn substrate_channel_id(substrate_group_id: &str, tenant_id: &str) -> String {
64 if substrate_group_id.starts_with("OID:") {
65 substrate_group_id.to_owned()
66 } else {
67 format!("OID:{substrate_group_id}@{tenant_id}")
68 }
69}
70
41pub fn standard_channel_body(channel: &NewChannel<'_>) -> Value {
71pub fn standard_channel_body(channel: &NewChannel<'_>) -> Value {
42 json!({
72 json!({
43 "displayName": channel.name,
73 "displayName": channel.name,
@@ -110,19 +140,105 @@ impl<T: CsaTransport> TeamAdmin<T> {
110 "https://teams.cloud.microsoft/fabric/{}/templates/api/teams/{}/channels?forceSync=false",
140 "https://teams.cloud.microsoft/fabric/{}/templates/api/teams/{}/channels?forceSync=false",
111 self.region, channel.group_id
141 self.region, channel.group_id
112 );
142 );
113 let mut request = with_headers(Request::with_body(
143 let request = Request::with_body(Method::Post, url, private_channel_body(channel));
114 Method::Post,
144 self.provisioning
115 url,
145 .send(with_anchor(request, mailbox))
116 private_channel_body(channel),
146 .await?
147 }
148 };
149 ensure_success(&answer)
150 }
151
152 pub async fn update_channel(
153 &self,
154 channel: ExistingChannel<'_>,
155 edit: ChannelEdit<'_>,
156 mailbox: Mailbox<'_>,
157 ) -> Result<()> {
158 let body = channel_edit_body(edit);
159 let answer = match channel.substrate_group_id {
160 None => {
161 self.middle_tier
162 .send(with_headers(Request::with_body(
163 Method::Patch,
164 self.middle_tier_channel_url(channel),
165 body,
166 )))
167 .await?
168 }
169 Some(substrate_group_id) => {
170 let request = Request::with_body(
171 Method::Patch,
172 self.provisioning_channel_url(channel, substrate_group_id, mailbox),
173 body,
174 );
175 self.provisioning
176 .send(with_anchor(request, mailbox))
177 .await?
178 }
179 };
180 ensure_success(&answer)
181 }
182
183 pub async fn delete_channel(
184 &self,
185 channel: ExistingChannel<'_>,
186 mailbox: Mailbox<'_>,
187 ) -> Result<()> {
188 let answer = match channel.substrate_group_id {
189 None => {
190 self.middle_tier
191 .send(with_headers(Request::with_body(
192 Method::Delete,
193 self.middle_tier_channel_url(channel),
194 json!({}),
195 )))
196 .await?
197 }
198 Some(substrate_group_id) => {
199 let request = Request::delete(self.provisioning_channel_url(
200 channel,
201 substrate_group_id,
202 mailbox,
117 ));
203 ));
118 request
204 self.provisioning
119 .headers
205 .send(with_anchor(request, mailbox))
120 .push((ANCHOR_HEADER.to_owned(), mailbox.anchor()));
206 .await?
121 self.provisioning.send(request).await?
122 }
207 }
123 };
208 };
124 ensure_success(&answer)
209 ensure_success(&answer)
125 }
210 }
211
212 fn middle_tier_channel_url(&self, channel: ExistingChannel<'_>) -> String {
213 format!(
214 "https://teams.cloud.microsoft/api/mt/{}/beta/teams/{}/channels/{}",
215 self.region,
216 encode(channel.team_thread_id),
217 encode(channel.channel_id)
218 )
219 }
220
221 fn provisioning_channel_url(
222 &self,
223 channel: ExistingChannel<'_>,
224 substrate_group_id: &str,
225 mailbox: Mailbox<'_>,
226 ) -> String {
227 format!(
228 "https://teams.cloud.microsoft/fabric/{}/templates/api/teams/{}/channels/{}?forceSync=false",
229 self.region,
230 channel.group_id,
231 encode(&substrate_channel_id(substrate_group_id, mailbox.tenant_id))
232 )
233 }
234}
235
236fn with_anchor(request: Request, mailbox: Mailbox<'_>) -> Request {
237 let mut request = with_headers(request);
238 request
239 .headers
240 .push((ANCHOR_HEADER.to_owned(), mailbox.anchor()));
241 request
126}
242}
127
243
128#[cfg(test)]
244#[cfg(test)]
@@ -210,4 +326,76 @@ mod tests {
210 assert_eq!(body["channelType"], "Private");
326 assert_eq!(body["channelType"], "Private");
211 assert!(middle_tier.requests.lock().unwrap().is_empty());
327 assert!(middle_tier.requests.lock().unwrap().is_empty());
212 }
328 }
329
330 const STANDARD: ExistingChannel<'static> = ExistingChannel {
331 team_thread_id: "19:team@thread.skype",
332 group_id: "group-1",
333 channel_id: "19:channel@thread.skype",
334 substrate_group_id: None,
335 };
336
337 #[tokio::test]
338 async fn standard_channel_edits_and_deletes_go_to_the_middle_tier() {
339 let middle_tier = Recorder::default();
340 let provisioning = Recorder::default();
341 let admin = TeamAdmin::with_transports(&middle_tier, &provisioning, "emea");
342 let edit = ChannelEdit {
343 name: "Renamed",
344 description: None,
345 };
346 admin.update_channel(STANDARD, edit, MAILBOX).await.unwrap();
347 admin.delete_channel(STANDARD, MAILBOX).await.unwrap();
348 let requests = middle_tier.requests.lock().unwrap();
349 let url = "https://teams.cloud.microsoft/api/mt/emea/beta/teams/19%3Ateam%40thread.skype/channels/19%3Achannel%40thread.skype";
350 assert_eq!(
351 (requests[0].method, requests[0].url.as_str()),
352 (Method::Patch, url)
353 );
354 assert_eq!(
355 requests[0].body.as_ref().unwrap(),
356 &json!({"displayName": "Renamed"})
357 );
358 assert_eq!(
359 (requests[1].method, requests[1].url.as_str()),
360 (Method::Delete, url)
361 );
362 assert!(provisioning.requests.lock().unwrap().is_empty());
363 }
364
365 #[tokio::test]
366 async fn private_channel_edits_and_deletes_go_to_provisioning_by_substrate_id() {
367 let middle_tier = Recorder::default();
368 let provisioning = Recorder::default();
369 let admin = TeamAdmin::with_transports(&middle_tier, &provisioning, "emea");
370 let private = ExistingChannel {
371 substrate_group_id: Some("substrate-1"),
372 ..STANDARD
373 };
374 let edit = ChannelEdit {
375 name: "Renamed",
376 description: Some("About"),
377 };
378 admin.update_channel(private, edit, MAILBOX).await.unwrap();
379 admin.delete_channel(private, MAILBOX).await.unwrap();
380 let requests = provisioning.requests.lock().unwrap();
381 let url = "https://teams.cloud.microsoft/fabric/emea/templates/api/teams/group-1/channels/OID%3Asubstrate-1%40tenant?forceSync=false";
382 assert_eq!(
383 (requests[0].method, requests[0].url.as_str()),
384 (Method::Patch, url)
385 );
386 assert_eq!(
387 requests[0].body.as_ref().unwrap(),
388 &json!({"displayName": "Renamed", "description": "About"})
389 );
390 assert_eq!(
391 (requests[1].method, requests[1].url.as_str()),
392 (Method::Delete, url)
393 );
394 assert!(
395 requests[1]
396 .headers
397 .contains(&(ANCHOR_HEADER.to_owned(), "OID:me@tenant".to_owned()))
398 );
399 assert!(middle_tier.requests.lock().unwrap().is_empty());
400 }
213}
401}
crates/core/src/folders.rs +40 −3
@@ -7,9 +7,9 @@ use chatsvc::settings::{
7 7 parse_chat_sections, parse_default_reactions, parse_skin_tone, parse_teams_order,
8 8 };
9 9 use chatsvc::{
10 ChannelNotificationLevel, ChannelNotifications, ChannelSettings, ChannelTarget,
11 ChannelVisibility, ChatSection, ChatSectionSettings, Mailbox, NewChannel, Pins, TeamAdmin,
12 UserSettings,
10 ChannelEdit, ChannelNotificationLevel, ChannelNotifications, ChannelSettings, ChannelTarget,
11 ChannelVisibility, ChatSection, ChatSectionSettings, ExistingChannel, Mailbox, NewChannel,
12 Pins, TeamAdmin, UserSettings,
13 13 pins::SessionTransport,
14 14 };
15 15 use chrono::Utc;
@@ -132,6 +132,21 @@ pub trait FolderSource: Send + Sync {
132 132 ) -> BoxFuture<'a, Result<()>> {
133 133 Box::pin(async { Err(Error::Unsupported("channel creation without chatsvc")) })
134 134 }
135 fn update_channel<'a>(
136 &'a self,
137 _channel: ExistingChannel<'a>,
138 _edit: ChannelEdit<'a>,
139 _mailbox: Mailbox<'a>,
140 ) -> BoxFuture<'a, Result<()>> {
141 Box::pin(async { Err(Error::Unsupported("channel edits without chatsvc")) })
142 }
143 fn delete_channel<'a>(
144 &'a self,
145 _channel: ExistingChannel<'a>,
146 _mailbox: Mailbox<'a>,
147 ) -> BoxFuture<'a, Result<()>> {
148 Box::pin(async { Err(Error::Unsupported("channel deletion without chatsvc")) })
149 }
135 150 }
136 151
137 152 pub struct ChatsvcFolderSource {
@@ -222,6 +237,28 @@ impl FolderSource for ChatsvcFolderSource {
222 237 Box::pin(async move { Ok(self.team_admin.create_channel(&channel, mailbox).await?) })
223 238 }
224 239
240 fn update_channel<'a>(
241 &'a self,
242 channel: ExistingChannel<'a>,
243 edit: ChannelEdit<'a>,
244 mailbox: Mailbox<'a>,
245 ) -> BoxFuture<'a, Result<()>> {
246 Box::pin(async move {
247 Ok(self
248 .team_admin
249 .update_channel(channel, edit, mailbox)
250 .await?)
251 })
252 }
253
254 fn delete_channel<'a>(
255 &'a self,
256 channel: ExistingChannel<'a>,
257 mailbox: Mailbox<'a>,
258 ) -> BoxFuture<'a, Result<()>> {
259 Box::pin(async move { Ok(self.team_admin.delete_channel(channel, mailbox).await?) })
260 }
261
225 262 fn team_layout(&self) -> BoxFuture<'_, Result<Vec<TeamLayoutRecord>>> {
226 263 Box::pin(async {
227 264 let layout = self.pins.team_layout().await?;
@@ -7,9 +7,9 @@ use chatsvc::settings::{
7 parse_chat_sections, parse_default_reactions, parse_skin_tone, parse_teams_order,
7 parse_chat_sections, parse_default_reactions, parse_skin_tone, parse_teams_order,
8};
8};
9use chatsvc::{
9use chatsvc::{
10 ChannelNotificationLevel, ChannelNotifications, ChannelSettings, ChannelTarget,
10 ChannelEdit, ChannelNotificationLevel, ChannelNotifications, ChannelSettings, ChannelTarget,
11 ChannelVisibility, ChatSection, ChatSectionSettings, Mailbox, NewChannel, Pins, TeamAdmin,
11 ChannelVisibility, ChatSection, ChatSectionSettings, ExistingChannel, Mailbox, NewChannel,
12 UserSettings,
12 Pins, TeamAdmin, UserSettings,
13 pins::SessionTransport,
13 pins::SessionTransport,
14};
14};
15use chrono::Utc;
15use chrono::Utc;
@@ -132,6 +132,21 @@ pub trait FolderSource: Send + Sync {
132 ) -> BoxFuture<'a, Result<()>> {
132 ) -> BoxFuture<'a, Result<()>> {
133 Box::pin(async { Err(Error::Unsupported("channel creation without chatsvc")) })
133 Box::pin(async { Err(Error::Unsupported("channel creation without chatsvc")) })
134 }
134 }
135 fn update_channel<'a>(
136 &'a self,
137 _channel: ExistingChannel<'a>,
138 _edit: ChannelEdit<'a>,
139 _mailbox: Mailbox<'a>,
140 ) -> BoxFuture<'a, Result<()>> {
141 Box::pin(async { Err(Error::Unsupported("channel edits without chatsvc")) })
142 }
143 fn delete_channel<'a>(
144 &'a self,
145 _channel: ExistingChannel<'a>,
146 _mailbox: Mailbox<'a>,
147 ) -> BoxFuture<'a, Result<()>> {
148 Box::pin(async { Err(Error::Unsupported("channel deletion without chatsvc")) })
149 }
135}
150}
136
151
137pub struct ChatsvcFolderSource {
152pub struct ChatsvcFolderSource {
@@ -222,6 +237,28 @@ impl FolderSource for ChatsvcFolderSource {
222 Box::pin(async move { Ok(self.team_admin.create_channel(&channel, mailbox).await?) })
237 Box::pin(async move { Ok(self.team_admin.create_channel(&channel, mailbox).await?) })
223 }
238 }
224
239
240 fn update_channel<'a>(
241 &'a self,
242 channel: ExistingChannel<'a>,
243 edit: ChannelEdit<'a>,
244 mailbox: Mailbox<'a>,
245 ) -> BoxFuture<'a, Result<()>> {
246 Box::pin(async move {
247 Ok(self
248 .team_admin
249 .update_channel(channel, edit, mailbox)
250 .await?)
251 })
252 }
253
254 fn delete_channel<'a>(
255 &'a self,
256 channel: ExistingChannel<'a>,
257 mailbox: Mailbox<'a>,
258 ) -> BoxFuture<'a, Result<()>> {
259 Box::pin(async move { Ok(self.team_admin.delete_channel(channel, mailbox).await?) })
260 }
261
225 fn team_layout(&self) -> BoxFuture<'_, Result<Vec<TeamLayoutRecord>>> {
262 fn team_layout(&self) -> BoxFuture<'_, Result<Vec<TeamLayoutRecord>>> {
226 Box::pin(async {
263 Box::pin(async {
227 let layout = self.pins.team_layout().await?;
264 let layout = self.pins.team_layout().await?;
crates/core/src/remote.rs +8 −0
@@ -194,6 +194,10 @@ pub trait Remote {
194 194 Err(Error::Unsupported("team tags"))
195 195 }
196 196
197 async fn channel_description(&self, _team_id: &str, _channel_id: &str) -> Result<String> {
198 Err(Error::Unsupported("channel description"))
199 }
200
197 201 async fn reply_with_quote(
198 202 &self,
199 203 _chat_id: &str,
@@ -984,6 +988,10 @@ impl Remote for Graph {
984 988 Ok(Graph::team_tags(self, team_id).await?)
985 989 }
986 990
991 async fn channel_description(&self, team_id: &str, channel_id: &str) -> Result<String> {
992 Ok(Graph::channel_description(self, team_id, channel_id).await?)
993 }
994
987 995 async fn reply_with_quote(
988 996 &self,
989 997 chat_id: &str,
@@ -194,6 +194,10 @@ pub trait Remote {
194 Err(Error::Unsupported("team tags"))
194 Err(Error::Unsupported("team tags"))
195 }
195 }
196
196
197 async fn channel_description(&self, _team_id: &str, _channel_id: &str) -> Result<String> {
198 Err(Error::Unsupported("channel description"))
199 }
200
197 async fn reply_with_quote(
201 async fn reply_with_quote(
198 &self,
202 &self,
199 _chat_id: &str,
203 _chat_id: &str,
@@ -984,6 +988,10 @@ impl Remote for Graph {
984 Ok(Graph::team_tags(self, team_id).await?)
988 Ok(Graph::team_tags(self, team_id).await?)
985 }
989 }
986
990
991 async fn channel_description(&self, team_id: &str, channel_id: &str) -> Result<String> {
992 Ok(Graph::channel_description(self, team_id, channel_id).await?)
993 }
994
987 async fn reply_with_quote(
995 async fn reply_with_quote(
988 &self,
996 &self,
989 chat_id: &str,
997 chat_id: &str,
crates/core/src/sidebar_sync.rs +2 −0
@@ -389,11 +389,13 @@ impl<R: Remote> SyncEngine<R> {
389 389 self.store.remove_teams_except(&team_ids)?;
390 390 refresh.teams = records.len();
391 391 let listings = self.remote.channels_for_teams(&team_ids).await?;
392 let deleted = self.deleted_channel_ids();
392 393 for (team_id, listing) in team_ids.iter().zip(listings) {
393 394 match listing {
394 395 Ok(channels) => {
395 396 let channel_records: Vec<_> = channels
396 397 .iter()
398 .filter(|channel| !deleted.contains_key(&channel.id))
397 399 .map(|channel| channel_record(team_id, channel))
398 400 .collect();
399 401 self.store.upsert_channels(&channel_records)?;
@@ -389,11 +389,13 @@ impl<R: Remote> SyncEngine<R> {
389 self.store.remove_teams_except(&team_ids)?;
389 self.store.remove_teams_except(&team_ids)?;
390 refresh.teams = records.len();
390 refresh.teams = records.len();
391 let listings = self.remote.channels_for_teams(&team_ids).await?;
391 let listings = self.remote.channels_for_teams(&team_ids).await?;
392 let deleted = self.deleted_channel_ids();
392 for (team_id, listing) in team_ids.iter().zip(listings) {
393 for (team_id, listing) in team_ids.iter().zip(listings) {
393 match listing {
394 match listing {
394 Ok(channels) => {
395 Ok(channels) => {
395 let channel_records: Vec<_> = channels
396 let channel_records: Vec<_> = channels
396 .iter()
397 .iter()
398 .filter(|channel| !deleted.contains_key(&channel.id))
397 .map(|channel| channel_record(team_id, channel))
399 .map(|channel| channel_record(team_id, channel))
398 .collect();
400 .collect();
399 self.store.upsert_channels(&channel_records)?;
401 self.store.upsert_channels(&channel_records)?;
crates/core/src/team_admin.rs +162 −3
@@ -1,4 +1,7 @@
1 use chatsvc::{ChannelPrivacy, Mailbox, NewChannel};
1 use std::collections::HashMap;
2
3 use chatsvc::{ChannelEdit, ChannelPrivacy, ExistingChannel, Mailbox, NewChannel};
4 use chrono::{Duration, Utc};
2 5
3 6 use crate::engine::SyncEngine;
4 7 use crate::error::{Error, Result};
@@ -7,6 +10,24 @@ use crate::remote::Remote;
7 10
8 11 pub const MAX_CHANNEL_NAME_LENGTH: usize = 50;
9 12 pub const MAX_CHANNEL_DESCRIPTION_LENGTH: usize = 1024;
13 const META_DELETED_CHANNELS: &str = "deleted_channels";
14 const DELETED_CHANNEL_GRACE_MINUTES: i64 = 60;
15
16 /// Channel ids deleted here with their deletion time in ms; Graph and CSA keep listing them for minutes.
17 pub(crate) fn parse_deleted_channels(text: &str) -> HashMap<String, i64> {
18 serde_json::from_str(text).unwrap_or_default()
19 }
20
21 pub(crate) fn recent_deleted_channels(
22 deleted: HashMap<String, i64>,
23 now_ms: i64,
24 ) -> HashMap<String, i64> {
25 let grace_ms = Duration::minutes(DELETED_CHANNEL_GRACE_MINUTES).num_milliseconds();
26 deleted
27 .into_iter()
28 .filter(|(_, deleted_at)| now_ms - deleted_at < grace_ms)
29 .collect()
30 }
10 31
11 32 impl<R: Remote> SyncEngine<R> {
12 33 pub async fn create_channel(
@@ -27,7 +48,7 @@ impl<R: Remote> SyncEngine<R> {
27 48 let object_id = self.my_user_id().await?;
28 49 let tenant_id = self.my_tenant_id_from_any_chat().await?;
29 50 let source = self.folder_source()?;
30 source
51 let created = source
31 52 .create_channel(
32 53 NewChannel {
33 54 team_thread_id: &team_thread_id,
@@ -41,12 +62,150 @@ impl<R: Remote> SyncEngine<R> {
41 62 tenant_id: &tenant_id,
42 63 },
43 64 )
44 .await?;
65 .await;
45 66 self.refresh_teams(true).await;
46 67 if let Err(error) = self.refresh_team_layout(source, true).await {
47 68 self.report(format!("cannot refresh the team layout: {error}"));
48 69 }
49 70 let _ = self.events.send(CoreEvent::SidebarChanged);
71 created
72 }
73
74 pub async fn channel_description(&self, channel_id: &str) -> Result<String> {
75 let channel = self
76 .store
77 .channel(channel_id)?
78 .ok_or_else(|| Error::UnknownConversation(channel_id.to_owned()))?;
79 self.remote
80 .channel_description(&channel.team_id, channel_id)
81 .await
82 }
83
84 pub async fn edit_channel(
85 &self,
86 channel_id: &str,
87 name: &str,
88 description: Option<&str>,
89 ) -> Result<()> {
90 let name = name.trim();
91 if name.is_empty() {
92 return Err(Error::Unsupported("a channel needs a name"));
93 }
94 let address = self.existing_channel(channel_id)?;
95 let (object_id, tenant_id) = self.mailbox_ids().await?;
96 let source = self.folder_source()?;
97 source
98 .update_channel(
99 address.existing(),
100 ChannelEdit {
101 name,
102 description: description.map(str::trim),
103 },
104 Mailbox {
105 object_id: &object_id,
106 tenant_id: &tenant_id,
107 },
108 )
109 .await?;
110 self.store.rename_channel(channel_id, name)?;
111 let _ = self.events.send(CoreEvent::SidebarChanged);
112 Ok(())
113 }
114
115 pub async fn delete_channel(&self, channel_id: &str) -> Result<()> {
116 let address = self.existing_channel(channel_id)?;
117 let (object_id, tenant_id) = self.mailbox_ids().await?;
118 self.folder_source()?
119 .delete_channel(
120 address.existing(),
121 Mailbox {
122 object_id: &object_id,
123 tenant_id: &tenant_id,
124 },
125 )
126 .await?;
127 self.remember_deleted_channel(channel_id)?;
128 self.store.remove_channel(channel_id)?;
129 let _ = self.events.send(CoreEvent::SidebarChanged);
50 130 Ok(())
51 131 }
132
133 pub(crate) fn deleted_channel_ids(&self) -> HashMap<String, i64> {
134 let stored = self
135 .store
136 .meta(META_DELETED_CHANNELS)
137 .ok()
138 .flatten()
139 .map(|text| parse_deleted_channels(&text))
140 .unwrap_or_default();
141 recent_deleted_channels(stored, Utc::now().timestamp_millis())
142 }
143
144 fn remember_deleted_channel(&self, channel_id: &str) -> Result<()> {
145 let mut deleted = self.deleted_channel_ids();
146 deleted.insert(channel_id.to_owned(), Utc::now().timestamp_millis());
147 let text = serde_json::to_string(&deleted).unwrap_or_default();
148 Ok(self.store.set_meta(META_DELETED_CHANNELS, &text)?)
149 }
150
151 fn existing_channel(&self, channel_id: &str) -> Result<ChannelAddress> {
152 let channel = self
153 .store
154 .channel(channel_id)?
155 .ok_or_else(|| Error::UnknownConversation(channel_id.to_owned()))?;
156 let team_thread_id = self
157 .store
158 .team_thread_id(&channel.team_id)?
159 .ok_or_else(|| Error::UnknownConversation(channel.team_id.clone()))?;
160 Ok(ChannelAddress {
161 team_thread_id,
162 group_id: channel.team_id,
163 channel_id: channel.id,
164 substrate_group_id: self.store.channel_substrate_group_id(channel_id)?,
165 })
166 }
167
168 async fn mailbox_ids(&self) -> Result<(String, String)> {
169 Ok((
170 self.my_user_id().await?,
171 self.my_tenant_id_from_any_chat().await?,
172 ))
173 }
174 }
175
176 struct ChannelAddress {
177 team_thread_id: String,
178 group_id: String,
179 channel_id: String,
180 substrate_group_id: Option<String>,
181 }
182
183 impl ChannelAddress {
184 fn existing(&self) -> ExistingChannel<'_> {
185 ExistingChannel {
186 team_thread_id: &self.team_thread_id,
187 group_id: &self.group_id,
188 channel_id: &self.channel_id,
189 substrate_group_id: self.substrate_group_id.as_deref(),
190 }
191 }
192 }
193
194 #[cfg(test)]
195 mod tests {
196 use super::*;
197
198 #[test]
199 fn deleted_channels_are_kept_for_an_hour() {
200 let now_ms = 10 * 60 * 60 * 1000;
201 let deleted = parse_deleted_channels(&format!(
202 r#"{{"19:fresh":{},"19:old":{}}}"#,
203 now_ms - 1000,
204 now_ms - 61 * 60 * 1000
205 ));
206 let recent = recent_deleted_channels(deleted, now_ms);
207 assert!(recent.contains_key("19:fresh"));
208 assert!(!recent.contains_key("19:old"));
209 assert!(parse_deleted_channels("garbage").is_empty());
210 }
52 211 }
@@ -1,4 +1,7 @@
1use chatsvc::{ChannelPrivacy, Mailbox, NewChannel};
1use std::collections::HashMap;
2
3use chatsvc::{ChannelEdit, ChannelPrivacy, ExistingChannel, Mailbox, NewChannel};
4use chrono::{Duration, Utc};
2
5
3use crate::engine::SyncEngine;
6use crate::engine::SyncEngine;
4use crate::error::{Error, Result};
7use crate::error::{Error, Result};
@@ -7,6 +10,24 @@ use crate::remote::Remote;
7
10
8pub const MAX_CHANNEL_NAME_LENGTH: usize = 50;
11pub const MAX_CHANNEL_NAME_LENGTH: usize = 50;
9pub const MAX_CHANNEL_DESCRIPTION_LENGTH: usize = 1024;
12pub const MAX_CHANNEL_DESCRIPTION_LENGTH: usize = 1024;
13const META_DELETED_CHANNELS: &str = "deleted_channels";
14const DELETED_CHANNEL_GRACE_MINUTES: i64 = 60;
15
16/// Channel ids deleted here with their deletion time in ms; Graph and CSA keep listing them for minutes.
17pub(crate) fn parse_deleted_channels(text: &str) -> HashMap<String, i64> {
18 serde_json::from_str(text).unwrap_or_default()
19}
20
21pub(crate) fn recent_deleted_channels(
22 deleted: HashMap<String, i64>,
23 now_ms: i64,
24) -> HashMap<String, i64> {
25 let grace_ms = Duration::minutes(DELETED_CHANNEL_GRACE_MINUTES).num_milliseconds();
26 deleted
27 .into_iter()
28 .filter(|(_, deleted_at)| now_ms - deleted_at < grace_ms)
29 .collect()
30}
10
31
11impl<R: Remote> SyncEngine<R> {
32impl<R: Remote> SyncEngine<R> {
12 pub async fn create_channel(
33 pub async fn create_channel(
@@ -27,7 +48,7 @@ impl<R: Remote> SyncEngine<R> {
27 let object_id = self.my_user_id().await?;
48 let object_id = self.my_user_id().await?;
28 let tenant_id = self.my_tenant_id_from_any_chat().await?;
49 let tenant_id = self.my_tenant_id_from_any_chat().await?;
29 let source = self.folder_source()?;
50 let source = self.folder_source()?;
30 source
51 let created = source
31 .create_channel(
52 .create_channel(
32 NewChannel {
53 NewChannel {
33 team_thread_id: &team_thread_id,
54 team_thread_id: &team_thread_id,
@@ -41,12 +62,150 @@ impl<R: Remote> SyncEngine<R> {
41 tenant_id: &tenant_id,
62 tenant_id: &tenant_id,
42 },
63 },
43 )
64 )
44 .await?;
65 .await;
45 self.refresh_teams(true).await;
66 self.refresh_teams(true).await;
46 if let Err(error) = self.refresh_team_layout(source, true).await {
67 if let Err(error) = self.refresh_team_layout(source, true).await {
47 self.report(format!("cannot refresh the team layout: {error}"));
68 self.report(format!("cannot refresh the team layout: {error}"));
48 }
69 }
49 let _ = self.events.send(CoreEvent::SidebarChanged);
70 let _ = self.events.send(CoreEvent::SidebarChanged);
71 created
72 }
73
74 pub async fn channel_description(&self, channel_id: &str) -> Result<String> {
75 let channel = self
76 .store
77 .channel(channel_id)?
78 .ok_or_else(|| Error::UnknownConversation(channel_id.to_owned()))?;
79 self.remote
80 .channel_description(&channel.team_id, channel_id)
81 .await
82 }
83
84 pub async fn edit_channel(
85 &self,
86 channel_id: &str,
87 name: &str,
88 description: Option<&str>,
89 ) -> Result<()> {
90 let name = name.trim();
91 if name.is_empty() {
92 return Err(Error::Unsupported("a channel needs a name"));
93 }
94 let address = self.existing_channel(channel_id)?;
95 let (object_id, tenant_id) = self.mailbox_ids().await?;
96 let source = self.folder_source()?;
97 source
98 .update_channel(
99 address.existing(),
100 ChannelEdit {
101 name,
102 description: description.map(str::trim),
103 },
104 Mailbox {
105 object_id: &object_id,
106 tenant_id: &tenant_id,
107 },
108 )
109 .await?;
110 self.store.rename_channel(channel_id, name)?;
111 let _ = self.events.send(CoreEvent::SidebarChanged);
112 Ok(())
113 }
114
115 pub async fn delete_channel(&self, channel_id: &str) -> Result<()> {
116 let address = self.existing_channel(channel_id)?;
117 let (object_id, tenant_id) = self.mailbox_ids().await?;
118 self.folder_source()?
119 .delete_channel(
120 address.existing(),
121 Mailbox {
122 object_id: &object_id,
123 tenant_id: &tenant_id,
124 },
125 )
126 .await?;
127 self.remember_deleted_channel(channel_id)?;
128 self.store.remove_channel(channel_id)?;
129 let _ = self.events.send(CoreEvent::SidebarChanged);
50 Ok(())
130 Ok(())
51 }
131 }
132
133 pub(crate) fn deleted_channel_ids(&self) -> HashMap<String, i64> {
134 let stored = self
135 .store
136 .meta(META_DELETED_CHANNELS)
137 .ok()
138 .flatten()
139 .map(|text| parse_deleted_channels(&text))
140 .unwrap_or_default();
141 recent_deleted_channels(stored, Utc::now().timestamp_millis())
142 }
143
144 fn remember_deleted_channel(&self, channel_id: &str) -> Result<()> {
145 let mut deleted = self.deleted_channel_ids();
146 deleted.insert(channel_id.to_owned(), Utc::now().timestamp_millis());
147 let text = serde_json::to_string(&deleted).unwrap_or_default();
148 Ok(self.store.set_meta(META_DELETED_CHANNELS, &text)?)
149 }
150
151 fn existing_channel(&self, channel_id: &str) -> Result<ChannelAddress> {
152 let channel = self
153 .store
154 .channel(channel_id)?
155 .ok_or_else(|| Error::UnknownConversation(channel_id.to_owned()))?;
156 let team_thread_id = self
157 .store
158 .team_thread_id(&channel.team_id)?
159 .ok_or_else(|| Error::UnknownConversation(channel.team_id.clone()))?;
160 Ok(ChannelAddress {
161 team_thread_id,
162 group_id: channel.team_id,
163 channel_id: channel.id,
164 substrate_group_id: self.store.channel_substrate_group_id(channel_id)?,
165 })
166 }
167
168 async fn mailbox_ids(&self) -> Result<(String, String)> {
169 Ok((
170 self.my_user_id().await?,
171 self.my_tenant_id_from_any_chat().await?,
172 ))
173 }
174}
175
176struct ChannelAddress {
177 team_thread_id: String,
178 group_id: String,
179 channel_id: String,
180 substrate_group_id: Option<String>,
181}
182
183impl ChannelAddress {
184 fn existing(&self) -> ExistingChannel<'_> {
185 ExistingChannel {
186 team_thread_id: &self.team_thread_id,
187 group_id: &self.group_id,
188 channel_id: &self.channel_id,
189 substrate_group_id: self.substrate_group_id.as_deref(),
190 }
191 }
192}
193
194#[cfg(test)]
195mod tests {
196 use super::*;
197
198 #[test]
199 fn deleted_channels_are_kept_for_an_hour() {
200 let now_ms = 10 * 60 * 60 * 1000;
201 let deleted = parse_deleted_channels(&format!(
202 r#"{{"19:fresh":{},"19:old":{}}}"#,
203 now_ms - 1000,
204 now_ms - 61 * 60 * 1000
205 ));
206 let recent = recent_deleted_channels(deleted, now_ms);
207 assert!(recent.contains_key("19:fresh"));
208 assert!(!recent.contains_key("19:old"));
209 assert!(parse_deleted_channels("garbage").is_empty());
210 }
52}
211}
crates/core/tests/engine.rs +81 −0
@@ -3426,6 +3426,39 @@ impl FolderSource for FakeFolders {
3426 3426 Ok(())
3427 3427 })
3428 3428 }
3429
3430 fn update_channel<'a>(
3431 &'a self,
3432 channel: chatsvc::ExistingChannel<'a>,
3433 edit: chatsvc::ChannelEdit<'a>,
3434 _mailbox: chatsvc::Mailbox<'a>,
3435 ) -> BoxFuture<'a, Result<()>> {
3436 Box::pin(async move {
3437 self.calls.lock().unwrap().push(format!(
3438 "edit {} {} {:?} '{}' {:?}",
3439 channel.team_thread_id,
3440 channel.channel_id,
3441 channel.substrate_group_id,
3442 edit.name,
3443 edit.description
3444 ));
3445 Ok(())
3446 })
3447 }
3448
3449 fn delete_channel<'a>(
3450 &'a self,
3451 channel: chatsvc::ExistingChannel<'a>,
3452 _mailbox: chatsvc::Mailbox<'a>,
3453 ) -> BoxFuture<'a, Result<()>> {
3454 Box::pin(async move {
3455 self.calls.lock().unwrap().push(format!(
3456 "delete {} {}",
3457 channel.team_thread_id, channel.channel_id
3458 ));
3459 Ok(())
3460 })
3461 }
3429 3462 }
3430 3463
3431 3464 fn store_alpha_team(engine: &SyncEngine<Handle>) {
@@ -5895,3 +5928,51 @@ async fn create_channel_sends_the_team_thread_and_own_mailbox_then_refreshes() {
5895 5928 .is_err()
5896 5929 );
5897 5930 }
5931
5932 #[tokio::test]
5933 async fn edit_channel_sends_the_trimmed_name_and_keeps_an_unloaded_description() {
5934 let fake = Arc::new(Fake::default());
5935 let source = FakeFolders::new();
5936 let engine = engine_with(&fake, SyncConfig::default()).with_folder_source(source.clone());
5937 store_alpha_team(&engine);
5938 engine.store().set_meta("me_tenant_id", "tenant-1").unwrap();
5939
5940 engine
5941 .edit_channel("19:secret@thread.tacv2", " Renamed ", None)
5942 .await
5943 .unwrap();
5944 let calls = source.calls.lock().unwrap().clone();
5945 assert_eq!(
5946 calls[0],
5947 "edit 19:general@thread.tacv2 19:secret@thread.tacv2 None 'Renamed' None"
5948 );
5949 let renamed = engine.store().channel("19:secret@thread.tacv2").unwrap().unwrap();
5950 assert_eq!(renamed.name, "Renamed");
5951 assert!(
5952 engine
5953 .edit_channel("19:secret@thread.tacv2", " ", None)
5954 .await
5955 .is_err()
5956 );
5957 }
5958
5959 #[tokio::test]
5960 async fn a_deleted_channel_stays_gone_while_graph_still_lists_it() {
5961 let fake = Arc::new(Fake::default());
5962 *fake.teams.lock().unwrap() =
5963 vec![serde_json::from_value(json!({"id": "team-1", "displayName": "Squad"})).unwrap()];
5964 let source = FakeFolders::new();
5965 let engine = engine_with(&fake, SyncConfig::default()).with_folder_source(source.clone());
5966 engine.store().set_meta("me_tenant_id", "tenant-1").unwrap();
5967 engine.refresh_sidebar_full().await.unwrap();
5968 assert!(engine.store().channel(CHANNEL).unwrap().is_some());
5969
5970 engine.delete_channel(CHANNEL).await.unwrap();
5971 assert_eq!(
5972 source.calls.lock().unwrap().last().unwrap(),
5973 &format!("delete {CHANNEL} {CHANNEL}")
5974 );
5975 assert!(engine.store().channel(CHANNEL).unwrap().is_none());
5976 engine.refresh_sidebar_full().await.unwrap();
5977 assert!(engine.store().channel(CHANNEL).unwrap().is_none());
5978 }
@@ -3426,6 +3426,39 @@ impl FolderSource for FakeFolders {
3426 Ok(())
3426 Ok(())
3427 })
3427 })
3428 }
3428 }
3429
3430 fn update_channel<'a>(
3431 &'a self,
3432 channel: chatsvc::ExistingChannel<'a>,
3433 edit: chatsvc::ChannelEdit<'a>,
3434 _mailbox: chatsvc::Mailbox<'a>,
3435 ) -> BoxFuture<'a, Result<()>> {
3436 Box::pin(async move {
3437 self.calls.lock().unwrap().push(format!(
3438 "edit {} {} {:?} '{}' {:?}",
3439 channel.team_thread_id,
3440 channel.channel_id,
3441 channel.substrate_group_id,
3442 edit.name,
3443 edit.description
3444 ));
3445 Ok(())
3446 })
3447 }
3448
3449 fn delete_channel<'a>(
3450 &'a self,
3451 channel: chatsvc::ExistingChannel<'a>,
3452 _mailbox: chatsvc::Mailbox<'a>,
3453 ) -> BoxFuture<'a, Result<()>> {
3454 Box::pin(async move {
3455 self.calls.lock().unwrap().push(format!(
3456 "delete {} {}",
3457 channel.team_thread_id, channel.channel_id
3458 ));
3459 Ok(())
3460 })
3461 }
3429}
3462}
3430
3463
3431fn store_alpha_team(engine: &SyncEngine<Handle>) {
3464fn store_alpha_team(engine: &SyncEngine<Handle>) {
@@ -5895,3 +5928,51 @@ async fn create_channel_sends_the_team_thread_and_own_mailbox_then_refreshes() {
5895 .is_err()
5928 .is_err()
5896 );
5929 );
5897}
5930}
5931
5932#[tokio::test]
5933async fn edit_channel_sends_the_trimmed_name_and_keeps_an_unloaded_description() {
5934 let fake = Arc::new(Fake::default());
5935 let source = FakeFolders::new();
5936 let engine = engine_with(&fake, SyncConfig::default()).with_folder_source(source.clone());
5937 store_alpha_team(&engine);
5938 engine.store().set_meta("me_tenant_id", "tenant-1").unwrap();
5939
5940 engine
5941 .edit_channel("19:secret@thread.tacv2", " Renamed ", None)
5942 .await
5943 .unwrap();
5944 let calls = source.calls.lock().unwrap().clone();
5945 assert_eq!(
5946 calls[0],
5947 "edit 19:general@thread.tacv2 19:secret@thread.tacv2 None 'Renamed' None"
5948 );
5949 let renamed = engine.store().channel("19:secret@thread.tacv2").unwrap().unwrap();
5950 assert_eq!(renamed.name, "Renamed");
5951 assert!(
5952 engine
5953 .edit_channel("19:secret@thread.tacv2", " ", None)
5954 .await
5955 .is_err()
5956 );
5957}
5958
5959#[tokio::test]
5960async fn a_deleted_channel_stays_gone_while_graph_still_lists_it() {
5961 let fake = Arc::new(Fake::default());
5962 *fake.teams.lock().unwrap() =
5963 vec![serde_json::from_value(json!({"id": "team-1", "displayName": "Squad"})).unwrap()];
5964 let source = FakeFolders::new();
5965 let engine = engine_with(&fake, SyncConfig::default()).with_folder_source(source.clone());
5966 engine.store().set_meta("me_tenant_id", "tenant-1").unwrap();
5967 engine.refresh_sidebar_full().await.unwrap();
5968 assert!(engine.store().channel(CHANNEL).unwrap().is_some());
5969
5970 engine.delete_channel(CHANNEL).await.unwrap();
5971 assert_eq!(
5972 source.calls.lock().unwrap().last().unwrap(),
5973 &format!("delete {CHANNEL} {CHANNEL}")
5974 );
5975 assert!(engine.store().channel(CHANNEL).unwrap().is_none());
5976 engine.refresh_sidebar_full().await.unwrap();
5977 assert!(engine.store().channel(CHANNEL).unwrap().is_none());
5978}
crates/graph/src/client.rs +14 −0
@@ -128,6 +128,20 @@ impl Graph {
128 128 .await
129 129 }
130 130
131 pub async fn channel_description(&self, team_id: &str, channel_id: &str) -> Result<String> {
132 let body = self
133 .get(
134 &urls::channel_description(team_id, channel_id),
135 &Scope::graph("Channel.ReadBasic.All"),
136 )
137 .await?;
138 Ok(body
139 .get("description")
140 .and_then(Value::as_str)
141 .unwrap_or_default()
142 .to_owned())
143 }
144
131 145 pub async fn channels_for_teams(
132 146 &self,
133 147 team_ids: &[String],
@@ -128,6 +128,20 @@ impl Graph {
128 .await
128 .await
129 }
129 }
130
130
131 pub async fn channel_description(&self, team_id: &str, channel_id: &str) -> Result<String> {
132 let body = self
133 .get(
134 &urls::channel_description(team_id, channel_id),
135 &Scope::graph("Channel.ReadBasic.All"),
136 )
137 .await?;
138 Ok(body
139 .get("description")
140 .and_then(Value::as_str)
141 .unwrap_or_default()
142 .to_owned())
143 }
144
131 pub async fn channels_for_teams(
145 pub async fn channels_for_teams(
132 &self,
146 &self,
133 team_ids: &[String],
147 team_ids: &[String],
crates/graph/src/urls.rs +8 −0
@@ -291,6 +291,14 @@ pub fn channels(team_id: &str) -> String {
291 291 )
292 292 }
293 293
294 pub fn channel_description(team_id: &str, channel_id: &str) -> String {
295 format!(
296 "{GRAPH}/v1.0/teams/{}/channels/{}?$select=description",
297 segment(team_id),
298 segment(channel_id)
299 )
300 }
301
294 302 pub fn channel_messages(team_id: &str, channel_id: &str, top: usize) -> String {
295 303 format!(
296 304 "{GRAPH}/v1.0/teams/{}/channels/{}/messages?$top={top}&$expand=replies",
@@ -291,6 +291,14 @@ pub fn channels(team_id: &str) -> String {
291 )
291 )
292}
292}
293
293
294pub fn channel_description(team_id: &str, channel_id: &str) -> String {
295 format!(
296 "{GRAPH}/v1.0/teams/{}/channels/{}?$select=description",
297 segment(team_id),
298 segment(channel_id)
299 )
300}
301
294pub fn channel_messages(team_id: &str, channel_id: &str, top: usize) -> String {
302pub fn channel_messages(team_id: &str, channel_id: &str, top: usize) -> String {
295 format!(
303 format!(
296 "{GRAPH}/v1.0/teams/{}/channels/{}/messages?$top={top}&$expand=replies",
304 "{GRAPH}/v1.0/teams/{}/channels/{}/messages?$top={top}&$expand=replies",
crates/store/src/sidebar.rs +24 −0
@@ -222,6 +222,30 @@ impl Store {
222 222 Ok(())
223 223 }
224 224
225 pub fn channel_substrate_group_id(&self, channel_id: &str) -> Result<Option<String>> {
226 let connection = self.lock()?;
227 Ok(connection
228 .prepare_cached("SELECT substrate_group_id FROM channel_layout WHERE channel_id = ?1")?
229 .query_map([channel_id], |row| row.get::<_, Option<String>>(0))?
230 .next()
231 .transpose()?
232 .flatten())
233 }
234
235 pub fn rename_channel(&self, channel_id: &str, name: &str) -> Result<()> {
236 self.lock()?.execute(
237 "UPDATE channels SET name = ?2 WHERE id = ?1",
238 params![channel_id, name],
239 )?;
240 Ok(())
241 }
242
243 pub fn remove_channel(&self, channel_id: &str) -> Result<()> {
244 self.lock()?
245 .execute("DELETE FROM channels WHERE id = ?1", [channel_id])?;
246 Ok(())
247 }
248
225 249 /// The team's own thread id, which Teams' CSA routes take: the id of its General channel.
226 250 pub fn team_thread_id(&self, team_id: &str) -> Result<Option<String>> {
227 251 let connection = self.lock()?;
@@ -222,6 +222,30 @@ impl Store {
222 Ok(())
222 Ok(())
223 }
223 }
224
224
225 pub fn channel_substrate_group_id(&self, channel_id: &str) -> Result<Option<String>> {
226 let connection = self.lock()?;
227 Ok(connection
228 .prepare_cached("SELECT substrate_group_id FROM channel_layout WHERE channel_id = ?1")?
229 .query_map([channel_id], |row| row.get::<_, Option<String>>(0))?
230 .next()
231 .transpose()?
232 .flatten())
233 }
234
235 pub fn rename_channel(&self, channel_id: &str, name: &str) -> Result<()> {
236 self.lock()?.execute(
237 "UPDATE channels SET name = ?2 WHERE id = ?1",
238 params![channel_id, name],
239 )?;
240 Ok(())
241 }
242
243 pub fn remove_channel(&self, channel_id: &str) -> Result<()> {
244 self.lock()?
245 .execute("DELETE FROM channels WHERE id = ?1", [channel_id])?;
246 Ok(())
247 }
248
225 /// The team's own thread id, which Teams' CSA routes take: the id of its General channel.
249 /// The team's own thread id, which Teams' CSA routes take: the id of its General channel.
226 pub fn team_thread_id(&self, team_id: &str) -> Result<Option<String>> {
250 pub fn team_thread_id(&self, team_id: &str) -> Result<Option<String>> {
227 let connection = self.lock()?;
251 let connection = self.lock()?;