feat(teams): add channel from the team menu
- Team rights from the CSA team list (owner, add/edit/delete channel, private channels), stored in team_layout (migration 0027)
- "Add channel" leads the team menu when the team allows it; dialog with name, description, Standard or Private
- Standard channels via Middle Tier beta/teams/{thread}/channels, private channels via the provisioning service (proven live in a test team, channel deleted again)
- Sidebar refreshes teams and layout after creating
- Probe example team_admin_probe for the team and channel endpoints
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@@ -203,6 +203,7 @@ mod tests {
203
203
let mut state = state_with(&records);
204
204
state.sidebar.chats.clear();
205
205
state.sidebar.teams.push(store::SidebarTeam {
206
rights: Default::default(),
206
207
team: store::TeamRecord {
207
208
id: "team".to_owned(),
208
209
name: "Platform".to_owned(),
@@ -203,6 +203,7 @@ mod tests {203
let mut state = state_with(&records);203
let mut state = state_with(&records);204
state.sidebar.chats.clear();204
state.sidebar.chats.clear();205
state.sidebar.teams.push(store::SidebarTeam {205
state.sidebar.teams.push(store::SidebarTeam {206
rights: Default::default(),206
team: store::TeamRecord {207
team: store::TeamRecord {207
id: "team".to_owned(),208
id: "team".to_owned(),208
name: "Platform".to_owned(),209
name: "Platform".to_owned(),@@ -1185,6 +1185,7 @@ mod tests {
1185
1185
Sidebar {
1186
1186
chats: vec![chat("c1", "First", true), chat("c2", "", false)],
1187
1187
teams: vec![SidebarTeam {
1188
rights: Default::default(),
1188
1189
team: TeamRecord {
1189
1190
id: "t".into(),
1190
1191
name: "Team".into(),
@@ -1185,6 +1185,7 @@ mod tests {1185
Sidebar {1185
Sidebar {1186
chats: vec![chat("c1", "First", true), chat("c2", "", false)],1186
chats: vec![chat("c1", "First", true), chat("c2", "", false)],1187
teams: vec![SidebarTeam {1187
teams: vec![SidebarTeam {1188
rights: Default::default(),1188
team: TeamRecord {1189
team: TeamRecord {1189
id: "t".into(),1190
id: "t".into(),1190
name: "Team".into(),1191
name: "Team".into(),@@ -2046,12 +2046,18 @@ fn demo_team_layout(channels: &[ChannelRecord]) -> Vec<TeamLayoutRecord> {
2046
2046
DEMO_TEAM_ORDER
2047
2047
.iter()
2048
2048
.map(|team_id| TeamLayoutRecord {
2049
rights: store::TeamRights {
2050
add_channel: true,
2051
add_private_channel: true,
2052
..Default::default()
2053
},
2049
2054
team_id: (*team_id).to_owned(),
2050
2055
hidden: *team_id == DEMO_HIDDEN_TEAM,
2051
2056
channels: channels
2052
2057
.iter()
2053
2058
.filter(|channel| channel.team_id == *team_id)
2054
2059
.map(|channel| ChannelLayoutRecord {
2060
substrate_group_id: None,
2055
2061
channel_id: channel.id.clone(),
2056
2062
general: channel.name == "General",
2057
2063
hidden: channel.id == DEMO_HIDDEN_CHANNEL,
@@ -2046,12 +2046,18 @@ fn demo_team_layout(channels: &[ChannelRecord]) -> Vec<TeamLayoutRecord> {2046
DEMO_TEAM_ORDER2046
DEMO_TEAM_ORDER2047
.iter()2047
.iter()2048
.map(|team_id| TeamLayoutRecord {2048
.map(|team_id| TeamLayoutRecord {2049
rights: store::TeamRights {2050
add_channel: true,2051
add_private_channel: true,2052
..Default::default()2053
},2049
team_id: (*team_id).to_owned(),2054
team_id: (*team_id).to_owned(),2050
hidden: *team_id == DEMO_HIDDEN_TEAM,2055
hidden: *team_id == DEMO_HIDDEN_TEAM,2051
channels: channels2056
channels: channels2052
.iter()2057
.iter()2053
.filter(|channel| channel.team_id == *team_id)2058
.filter(|channel| channel.team_id == *team_id)2054
.map(|channel| ChannelLayoutRecord {2059
.map(|channel| ChannelLayoutRecord {2060
substrate_group_id: None,2055
channel_id: channel.id.clone(),2061
channel_id: channel.id.clone(),2056
general: channel.name == "General",2062
general: channel.name == "General",2057
hidden: channel.id == DEMO_HIDDEN_CHANNEL,2063
hidden: channel.id == DEMO_HIDDEN_CHANNEL,@@ -52,6 +52,7 @@ pub mod sidebar_model;
52
52
pub mod sound_actions;
53
53
pub mod stored_outgoing;
54
54
pub mod task_dialog;
55
pub mod team_admin;
55
56
pub mod translation_actions;
56
57
pub mod typing;
57
58
pub mod urgent_ack;
@@ -52,6 +52,7 @@ pub mod sidebar_model;52
pub mod sound_actions;52
pub mod sound_actions;53
pub mod stored_outgoing;53
pub mod stored_outgoing;54
pub mod task_dialog;54
pub mod task_dialog;55
pub mod team_admin;55
pub mod translation_actions;56
pub mod translation_actions;56
pub mod typing;57
pub mod typing;57
pub mod urgent_ack;58
pub mod urgent_ack;@@ -352,6 +352,7 @@ mod tests {
352
352
hidden_channel_ids: &[&str],
353
353
) -> SidebarTeam {
354
354
SidebarTeam {
355
rights: Default::default(),
355
356
team: TeamRecord {
356
357
id: team_id.into(),
357
358
name: "Team".into(),
@@ -352,6 +352,7 @@ mod tests {352
hidden_channel_ids: &[&str],352
hidden_channel_ids: &[&str],353
) -> SidebarTeam {353
) -> SidebarTeam {354
SidebarTeam {354
SidebarTeam {355
rights: Default::default(),355
team: TeamRecord {356
team: TeamRecord {356
id: team_id.into(),357
id: team_id.into(),357
name: "Team".into(),358
name: "Team".into(),@@ -55,6 +55,7 @@ mod tests {
55
55
chat("chat-read", false, false),
56
56
],
57
57
teams: vec![SidebarTeam {
58
rights: Default::default(),
58
59
team: TeamRecord {
59
60
id: "team".into(),
60
61
name: "Team".into(),
@@ -55,6 +55,7 @@ mod tests {55
chat("chat-read", false, false),55
chat("chat-read", false, false),56
],56
],57
teams: vec![SidebarTeam {57
teams: vec![SidebarTeam {58
rights: Default::default(),58
team: TeamRecord {59
team: TeamRecord {59
id: "team".into(),60
id: "team".into(),60
name: "Team".into(),61
name: "Team".into(),@@ -913,6 +913,7 @@ mod tests {
913
913
hidden_channel_ids: &[&str],
914
914
) -> SidebarTeam {
915
915
SidebarTeam {
916
rights: Default::default(),
916
917
team: store::TeamRecord {
917
918
id: id.into(),
918
919
name: id.into(),
@@ -913,6 +913,7 @@ mod tests {913
hidden_channel_ids: &[&str],913
hidden_channel_ids: &[&str],914
) -> SidebarTeam {914
) -> SidebarTeam {915
SidebarTeam {915
SidebarTeam {916
rights: Default::default(),916
team: store::TeamRecord {917
team: store::TeamRecord {917
id: id.into(),918
id: id.into(),918
name: id.into(),919
name: id.into(),@@ -0,0 +1,106 @@
1
use gpui_kit::*;
2
use store::TeamRights;
3
use teams_core::{ChannelPrivacy, MAX_CHANNEL_NAME_LENGTH};
4
5
use crate::app_state::AppState;
6
7
pub const CREATE_CHANNEL_FAILURE: &str = "We couldn't create the channel.";
8
pub const CHANNEL_NAME_CHARACTERS: &str =
9
"Channel names can't contain ~ # % & * { } + / \\ : < > ? | ' \" , or ..";
10
pub const CHANNEL_NAME_EDGES: &str = "Channel names can't start with _ or . and can't end with .";
11
pub const CHANNEL_NAME_LENGTH: &str = "Channel names can have up to 50 characters.";
12
const FORBIDDEN_CHARACTERS: &[char] = &[
13
'~', '#', '%', '&', '*', '{', '}', '+', '/', '\\', ':', '<', '>', '?', '|', '\'', '"', ',',
14
];
15
16
/// Why Teams would refuse this channel name, `None` when it may be created.
17
pub fn channel_name_problem(raw: &str) -> Option<&'static str> {
18
let name = raw.trim();
19
if name.chars().count() > MAX_CHANNEL_NAME_LENGTH {
20
return Some(CHANNEL_NAME_LENGTH);
21
}
22
if name.contains(FORBIDDEN_CHARACTERS) || name.contains("..") {
23
return Some(CHANNEL_NAME_CHARACTERS);
24
}
25
if name.starts_with(['_', '.']) || name.ends_with('.') {
26
return Some(CHANNEL_NAME_EDGES);
27
}
28
None
29
}
30
31
pub fn can_create_channel(raw: &str) -> bool {
32
!raw.trim().is_empty() && channel_name_problem(raw).is_none()
33
}
34
35
impl AppState {
36
pub fn team_rights(&self, team_id: &str) -> TeamRights {
37
self.sidebar
38
.teams
39
.iter()
40
.find(|team| team.team.id == team_id)
41
.map(|team| team.rights)
42
.unwrap_or_default()
43
}
44
45
pub fn team_name(&self, team_id: &str) -> Option<String> {
46
self.sidebar
47
.teams
48
.iter()
49
.find(|team| team.team.id == team_id)
50
.map(|team| team.team.name.clone())
51
}
52
53
pub fn create_channel(
54
&mut self,
55
team_id: &str,
56
name: &str,
57
description: &str,
58
privacy: ChannelPrivacy,
59
cx: &mut Context<Self>,
60
) {
61
let Some(Some(engine)) = self.chat_action_engine(cx) else {
62
return;
63
};
64
let (team_id, name, description) =
65
(team_id.to_owned(), name.to_owned(), description.to_owned());
66
self.run_channel_action(
67
CREATE_CHANNEL_FAILURE,
68
async move {
69
engine
70
.create_channel(&team_id, &name, &description, privacy)
71
.await
72
},
73
|_, _| {},
74
None,
75
cx,
76
);
77
}
78
}
79
80
#[cfg(test)]
81
mod tests {
82
use teams_core::MAX_CHANNEL_NAME_LENGTH;
83
84
use super::{
85
CHANNEL_NAME_CHARACTERS, CHANNEL_NAME_EDGES, CHANNEL_NAME_LENGTH, can_create_channel,
86
channel_name_problem,
87
};
88
89
#[test]
90
fn channel_names_follow_the_teams_rules() {
91
assert!(can_create_channel(" Planning 2027 "));
92
assert!(!can_create_channel(" "));
93
assert!(!can_create_channel(
94
&"a".repeat(MAX_CHANNEL_NAME_LENGTH + 1)
95
));
96
assert_eq!(
97
channel_name_problem(&"a".repeat(MAX_CHANNEL_NAME_LENGTH + 1)),
98
Some(CHANNEL_NAME_LENGTH)
99
);
100
assert_eq!(channel_name_problem("Q&A"), Some(CHANNEL_NAME_CHARACTERS));
101
assert_eq!(channel_name_problem("a..b"), Some(CHANNEL_NAME_CHARACTERS));
102
assert_eq!(channel_name_problem("_drafts"), Some(CHANNEL_NAME_EDGES));
103
assert_eq!(channel_name_problem("notes."), Some(CHANNEL_NAME_EDGES));
104
assert_eq!(channel_name_problem("Release notes"), None);
105
}
106
}
@@ -0,0 +1,106 @@1
use gpui_kit::*;2
use store::TeamRights;3
use teams_core::{ChannelPrivacy, MAX_CHANNEL_NAME_LENGTH};4
5
use crate::app_state::AppState;6
7
pub const CREATE_CHANNEL_FAILURE: &str = "We couldn't create the channel.";8
pub const CHANNEL_NAME_CHARACTERS: &str =9
"Channel names can't contain ~ # % & * { } + / \\ : < > ? | ' \" , or ..";10
pub const CHANNEL_NAME_EDGES: &str = "Channel names can't start with _ or . and can't end with .";11
pub const CHANNEL_NAME_LENGTH: &str = "Channel names can have up to 50 characters.";12
const FORBIDDEN_CHARACTERS: &[char] = &[13
'~', '#', '%', '&', '*', '{', '}', '+', '/', '\\', ':', '<', '>', '?', '|', '\'', '"', ',',14
];15
16
/// Why Teams would refuse this channel name, `None` when it may be created.17
pub fn channel_name_problem(raw: &str) -> Option<&'static str> {18
let name = raw.trim();19
if name.chars().count() > MAX_CHANNEL_NAME_LENGTH {20
return Some(CHANNEL_NAME_LENGTH);21
}22
if name.contains(FORBIDDEN_CHARACTERS) || name.contains("..") {23
return Some(CHANNEL_NAME_CHARACTERS);24
}25
if name.starts_with(['_', '.']) || name.ends_with('.') {26
return Some(CHANNEL_NAME_EDGES);27
}28
None29
}30
31
pub fn can_create_channel(raw: &str) -> bool {32
!raw.trim().is_empty() && channel_name_problem(raw).is_none()33
}34
35
impl AppState {36
pub fn team_rights(&self, team_id: &str) -> TeamRights {37
self.sidebar38
.teams39
.iter()40
.find(|team| team.team.id == team_id)41
.map(|team| team.rights)42
.unwrap_or_default()43
}44
45
pub fn team_name(&self, team_id: &str) -> Option<String> {46
self.sidebar47
.teams48
.iter()49
.find(|team| team.team.id == team_id)50
.map(|team| team.team.name.clone())51
}52
53
pub fn create_channel(54
&mut self,55
team_id: &str,56
name: &str,57
description: &str,58
privacy: ChannelPrivacy,59
cx: &mut Context<Self>,60
) {61
let Some(Some(engine)) = self.chat_action_engine(cx) else {62
return;63
};64
let (team_id, name, description) =65
(team_id.to_owned(), name.to_owned(), description.to_owned());66
self.run_channel_action(67
CREATE_CHANNEL_FAILURE,68
async move {69
engine70
.create_channel(&team_id, &name, &description, privacy)71
.await72
},73
|_, _| {},74
None,75
cx,76
);77
}78
}79
80
#[cfg(test)]81
mod tests {82
use teams_core::MAX_CHANNEL_NAME_LENGTH;83
84
use super::{85
CHANNEL_NAME_CHARACTERS, CHANNEL_NAME_EDGES, CHANNEL_NAME_LENGTH, can_create_channel,86
channel_name_problem,87
};88
89
#[test]90
fn channel_names_follow_the_teams_rules() {91
assert!(can_create_channel(" Planning 2027 "));92
assert!(!can_create_channel(" "));93
assert!(!can_create_channel(94
&"a".repeat(MAX_CHANNEL_NAME_LENGTH + 1)95
));96
assert_eq!(97
channel_name_problem(&"a".repeat(MAX_CHANNEL_NAME_LENGTH + 1)),98
Some(CHANNEL_NAME_LENGTH)99
);100
assert_eq!(channel_name_problem("Q&A"), Some(CHANNEL_NAME_CHARACTERS));101
assert_eq!(channel_name_problem("a..b"), Some(CHANNEL_NAME_CHARACTERS));102
assert_eq!(channel_name_problem("_drafts"), Some(CHANNEL_NAME_EDGES));103
assert_eq!(channel_name_problem("notes."), Some(CHANNEL_NAME_EDGES));104
assert_eq!(channel_name_problem("Release notes"), None);105
}106
}@@ -1632,6 +1632,7 @@ mod tests {
1632
1632
},
1633
1633
],
1634
1634
teams: vec![SidebarTeam {
1635
rights: Default::default(),
1635
1636
team: TeamRecord {
1636
1637
id: "t".into(),
1637
1638
name: "Team".into(),
@@ -1632,6 +1632,7 @@ mod tests {1632
},1632
},1633
],1633
],1634
teams: vec![SidebarTeam {1634
teams: vec![SidebarTeam {1635
rights: Default::default(),1635
team: TeamRecord {1636
team: TeamRecord {1636
id: "t".into(),1637
id: "t".into(),1637
name: "Team".into(),1638
name: "Team".into(),@@ -1037,6 +1037,7 @@ mod tests {
1037
1037
let sidebar = Sidebar {
1038
1038
chats: Vec::new(),
1039
1039
teams: vec![store::SidebarTeam {
1040
rights: Default::default(),
1040
1041
team: store::TeamRecord {
1041
1042
id: "team".into(),
1042
1043
name: "Platform".into(),
@@ -1037,6 +1037,7 @@ mod tests {1037
let sidebar = Sidebar {1037
let sidebar = Sidebar {1038
chats: Vec::new(),1038
chats: Vec::new(),1039
teams: vec![store::SidebarTeam {1039
teams: vec![store::SidebarTeam {1040
rights: Default::default(),1040
team: store::TeamRecord {1041
team: store::TeamRecord {1041
id: "team".into(),1042
id: "team".into(),1042
name: "Platform".into(),1043
name: "Platform".into(),@@ -0,0 +1,192 @@
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::radio::Radio;
5
use gpui_kit::component::{Disableable as _, WindowExt as _, v_flex};
6
use gpui_kit::prelude::FluentBuilder as _;
7
use gpui_kit::*;
8
use teams_core::ChannelPrivacy;
9
10
use super::new_meeting_dialog::labeled;
11
use crate::app_state::AppState;
12
use crate::team_admin::{can_create_channel, channel_name_problem};
13
use crate::theme;
14
15
const DIALOG_WIDTH: f32 = 480.;
16
const FIELD_GAP: f32 = 12.;
17
const OPTION_GAP: f32 = 8.;
18
const ERROR_SIZE: f32 = 12.;
19
20
struct CreateChannelForm {
21
state: Entity<AppState>,
22
team_id: String,
23
name: Entity<InputState>,
24
description: Entity<InputState>,
25
privacy: ChannelPrivacy,
26
private_allowed: bool,
27
_subscriptions: Vec<Subscription>,
28
}
29
30
impl CreateChannelForm {
31
fn new(
32
state: Entity<AppState>,
33
team_id: String,
34
private_allowed: bool,
35
window: &mut Window,
36
cx: &mut Context<Self>,
37
) -> Self {
38
let name = cx.new(|cx| {
39
InputState::new(window, cx).placeholder("Letters, numbers, and spaces are allowed")
40
});
41
let description = cx.new(|cx| {
42
InputState::new(window, cx)
43
.placeholder("Help others find the right channel by providing a description")
44
});
45
let subscriptions = vec![
46
cx.subscribe_in(&name, window, Self::on_input),
47
cx.subscribe_in(&description, window, Self::on_input),
48
];
49
CreateChannelForm {
50
state,
51
team_id,
52
name,
53
description,
54
privacy: ChannelPrivacy::Standard,
55
private_allowed,
56
_subscriptions: subscriptions,
57
}
58
}
59
60
fn on_input(
61
&mut self,
62
_: &Entity<InputState>,
63
event: &InputEvent,
64
window: &mut Window,
65
cx: &mut Context<Self>,
66
) {
67
if matches!(event, InputEvent::PressEnter { .. }) && self.submit(cx) {
68
window.close_dialog(cx);
69
}
70
cx.notify();
71
}
72
73
fn can_create(&self, cx: &App) -> bool {
74
can_create_channel(&self.name.read(cx).value())
75
}
76
77
fn submit(&mut self, cx: &mut Context<Self>) -> bool {
78
if !self.can_create(cx) {
79
return false;
80
}
81
let name = self.name.read(cx).value().to_string();
82
let description = self.description.read(cx).value().to_string();
83
let (team_id, privacy) = (self.team_id.clone(), self.privacy);
84
self.state.update(cx, |state, cx| {
85
state.create_channel(&team_id, &name, &description, privacy, cx)
86
});
87
true
88
}
89
90
fn choose(&mut self, privacy: ChannelPrivacy, cx: &mut Context<Self>) {
91
self.privacy = privacy;
92
cx.notify();
93
}
94
95
fn privacy_options(&self, cx: &mut Context<Self>) -> Div {
96
let form = cx.entity();
97
let option = |id: &'static str, label: &'static str, privacy: ChannelPrivacy| {
98
let form = form.clone();
99
Radio::new(id)
100
.label(label)
101
.checked(self.privacy == privacy)
102
.on_click(move |_, _, cx| form.update(cx, |form, cx| form.choose(privacy, cx)))
103
};
104
v_flex()
105
.debug_selector(|| "create-channel/type".into())
106
.gap(px(OPTION_GAP))
107
.child(option(
108
"create-channel-standard",
109
"Standard: Everyone on the team has access",
110
ChannelPrivacy::Standard,
111
))
112
.when(self.private_allowed, |options| {
113
options.child(option(
114
"create-channel-private",
115
"Private: Specific teammates have access",
116
ChannelPrivacy::Private,
117
))
118
})
119
}
120
}
121
122
impl Render for CreateChannelForm {
123
fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
124
let problem = channel_name_problem(&self.name.read(cx).value());
125
v_flex()
126
.debug_selector(|| "create-channel".into())
127
.gap(px(FIELD_GAP))
128
.child(labeled("Channel name", Input::new(&self.name)))
129
.when_some(problem, |form, problem| {
130
form.child(
131
div()
132
.text_size(px(ERROR_SIZE))
133
.text_color(theme::red_soft())
134
.child(problem),
135
)
136
})
137
.child(labeled(
138
"Description (optional)",
139
Input::new(&self.description),
140
))
141
.child(labeled("Choose a channel type", self.privacy_options(cx)))
142
}
143
}
144
145
pub fn open_create_channel_dialog(
146
state: Entity<AppState>,
147
team_id: &str,
148
window: &mut Window,
149
cx: &mut App,
150
) {
151
let (team_name, rights) = {
152
let app = state.read(cx);
153
(
154
app.team_name(team_id).unwrap_or_default(),
155
app.team_rights(team_id),
156
)
157
};
158
let title = format!("Create a channel for \"{team_name}\" team");
159
let team_id = team_id.to_owned();
160
let form =
161
cx.new(|cx| CreateChannelForm::new(state, team_id, rights.add_private_channel, window, cx));
162
let field = form.read(cx).name.clone();
163
window.open_dialog(cx, move |dialog: Dialog, _, cx| {
164
let submit_form = form.clone();
165
let can_create = form.read(cx).can_create(cx);
166
let footer = DialogFooter::new()
167
.child(
168
Button::new("create-channel-cancel")
169
.label("Cancel")
170
.on_click(|_, window, cx| window.close_dialog(cx)),
171
)
172
.child(
173
Button::new("create-channel-confirm")
174
.primary()
175
.label("Create")
176
.disabled(!can_create)
177
.on_click(move |_, window, cx| {
178
if submit_form.update(cx, |form, cx| form.submit(cx)) {
179
window.close_dialog(cx);
180
}
181
}),
182
);
183
dialog
184
.title(title.clone())
185
.w(px(DIALOG_WIDTH))
186
.child(form.clone())
187
.footer(footer)
188
});
189
window.defer(cx, move |window, cx| {
190
field.update(cx, |input, cx| input.focus(window, cx));
191
});
192
}
@@ -0,0 +1,192 @@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::radio::Radio;5
use gpui_kit::component::{Disableable as _, WindowExt as _, v_flex};6
use gpui_kit::prelude::FluentBuilder as _;7
use gpui_kit::*;8
use teams_core::ChannelPrivacy;9
10
use super::new_meeting_dialog::labeled;11
use crate::app_state::AppState;12
use crate::team_admin::{can_create_channel, channel_name_problem};13
use crate::theme;14
15
const DIALOG_WIDTH: f32 = 480.;16
const FIELD_GAP: f32 = 12.;17
const OPTION_GAP: f32 = 8.;18
const ERROR_SIZE: f32 = 12.;19
20
struct CreateChannelForm {21
state: Entity<AppState>,22
team_id: String,23
name: Entity<InputState>,24
description: Entity<InputState>,25
privacy: ChannelPrivacy,26
private_allowed: bool,27
_subscriptions: Vec<Subscription>,28
}29
30
impl CreateChannelForm {31
fn new(32
state: Entity<AppState>,33
team_id: String,34
private_allowed: bool,35
window: &mut Window,36
cx: &mut Context<Self>,37
) -> Self {38
let name = cx.new(|cx| {39
InputState::new(window, cx).placeholder("Letters, numbers, and spaces are allowed")40
});41
let description = cx.new(|cx| {42
InputState::new(window, cx)43
.placeholder("Help others find the right channel by providing a description")44
});45
let subscriptions = vec![46
cx.subscribe_in(&name, window, Self::on_input),47
cx.subscribe_in(&description, window, Self::on_input),48
];49
CreateChannelForm {50
state,51
team_id,52
name,53
description,54
privacy: ChannelPrivacy::Standard,55
private_allowed,56
_subscriptions: subscriptions,57
}58
}59
60
fn on_input(61
&mut self,62
_: &Entity<InputState>,63
event: &InputEvent,64
window: &mut Window,65
cx: &mut Context<Self>,66
) {67
if matches!(event, InputEvent::PressEnter { .. }) && self.submit(cx) {68
window.close_dialog(cx);69
}70
cx.notify();71
}72
73
fn can_create(&self, cx: &App) -> bool {74
can_create_channel(&self.name.read(cx).value())75
}76
77
fn submit(&mut self, cx: &mut Context<Self>) -> bool {78
if !self.can_create(cx) {79
return false;80
}81
let name = self.name.read(cx).value().to_string();82
let description = self.description.read(cx).value().to_string();83
let (team_id, privacy) = (self.team_id.clone(), self.privacy);84
self.state.update(cx, |state, cx| {85
state.create_channel(&team_id, &name, &description, privacy, cx)86
});87
true88
}89
90
fn choose(&mut self, privacy: ChannelPrivacy, cx: &mut Context<Self>) {91
self.privacy = privacy;92
cx.notify();93
}94
95
fn privacy_options(&self, cx: &mut Context<Self>) -> Div {96
let form = cx.entity();97
let option = |id: &'static str, label: &'static str, privacy: ChannelPrivacy| {98
let form = form.clone();99
Radio::new(id)100
.label(label)101
.checked(self.privacy == privacy)102
.on_click(move |_, _, cx| form.update(cx, |form, cx| form.choose(privacy, cx)))103
};104
v_flex()105
.debug_selector(|| "create-channel/type".into())106
.gap(px(OPTION_GAP))107
.child(option(108
"create-channel-standard",109
"Standard: Everyone on the team has access",110
ChannelPrivacy::Standard,111
))112
.when(self.private_allowed, |options| {113
options.child(option(114
"create-channel-private",115
"Private: Specific teammates have access",116
ChannelPrivacy::Private,117
))118
})119
}120
}121
122
impl Render for CreateChannelForm {123
fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {124
let problem = channel_name_problem(&self.name.read(cx).value());125
v_flex()126
.debug_selector(|| "create-channel".into())127
.gap(px(FIELD_GAP))128
.child(labeled("Channel name", Input::new(&self.name)))129
.when_some(problem, |form, problem| {130
form.child(131
div()132
.text_size(px(ERROR_SIZE))133
.text_color(theme::red_soft())134
.child(problem),135
)136
})137
.child(labeled(138
"Description (optional)",139
Input::new(&self.description),140
))141
.child(labeled("Choose a channel type", self.privacy_options(cx)))142
}143
}144
145
pub fn open_create_channel_dialog(146
state: Entity<AppState>,147
team_id: &str,148
window: &mut Window,149
cx: &mut App,150
) {151
let (team_name, rights) = {152
let app = state.read(cx);153
(154
app.team_name(team_id).unwrap_or_default(),155
app.team_rights(team_id),156
)157
};158
let title = format!("Create a channel for \"{team_name}\" team");159
let team_id = team_id.to_owned();160
let form =161
cx.new(|cx| CreateChannelForm::new(state, team_id, rights.add_private_channel, window, cx));162
let field = form.read(cx).name.clone();163
window.open_dialog(cx, move |dialog: Dialog, _, cx| {164
let submit_form = form.clone();165
let can_create = form.read(cx).can_create(cx);166
let footer = DialogFooter::new()167
.child(168
Button::new("create-channel-cancel")169
.label("Cancel")170
.on_click(|_, window, cx| window.close_dialog(cx)),171
)172
.child(173
Button::new("create-channel-confirm")174
.primary()175
.label("Create")176
.disabled(!can_create)177
.on_click(move |_, window, cx| {178
if submit_form.update(cx, |form, cx| form.submit(cx)) {179
window.close_dialog(cx);180
}181
}),182
);183
dialog184
.title(title.clone())185
.w(px(DIALOG_WIDTH))186
.child(form.clone())187
.footer(footer)188
});189
window.defer(cx, move |window, cx| {190
field.update(cx, |input, cx| input.focus(window, cx));191
});192
}@@ -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 create_channel_dialog;
43
44
pub mod customize_reactions;
44
45
pub mod dialog_overlay;
45
46
pub mod emoji_popup;
@@ -40,6 +40,7 @@ pub mod chat_pop_out;40
pub mod composer;40
pub mod composer;41
pub mod connection_banner;41
pub mod connection_banner;42
pub mod conversation;42
pub mod conversation;43
pub mod create_channel_dialog;43
pub mod customize_reactions;44
pub mod customize_reactions;44
pub mod dialog_overlay;45
pub mod dialog_overlay;45
pub mod emoji_popup;46
pub mod emoji_popup;@@ -144,7 +144,7 @@ impl MeetingForm {
144
144
}
145
145
}
146
146
147
fn labeled(label: &str, field: impl IntoElement) -> Div {
147
pub(super) fn labeled(label: &str, field: impl IntoElement) -> Div {
148
148
v_flex()
149
149
.gap(px(4.))
150
150
.child(
@@ -144,7 +144,7 @@ impl MeetingForm {144
}144
}145
}145
}146
146
147
fn labeled(label: &str, field: impl IntoElement) -> Div {147
pub(super) fn labeled(label: &str, field: impl IntoElement) -> Div {148
v_flex()148
v_flex()149
.gap(px(4.))149
.gap(px(4.))150
.child(150
.child(@@ -23,13 +23,15 @@ 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::create_channel_dialog::open_create_channel_dialog;
26
27
use super::section_dialog::{SectionNameTarget, open_section_name_dialog};
27
28
use super::widgets::{count_badge, icon, menu_icon, page_header, symbol, unread_marker};
28
29
use crate::agents::AgentsPanel;
29
30
use crate::app_state::{AppEvent, AppState, Selection};
30
31
use crate::presence_follow::{NOTIFY_WHEN_AVAILABLE, TURN_OFF_NOTIFICATIONS};
31
32
use crate::channel_menu::{
32
ChannelMenuItem, MenuEntry, TeamMenuItem, channel_menu_entries, team_menu_entries,
33
ChannelMenuItem, MenuEntry, TeamMenuItem, TeamMenuState, channel_menu_entries,
34
team_menu_entries,
33
35
};
34
36
use crate::chat_actions::TITLE_LIMIT;
35
37
use crate::chat_filter::{ChatFilter, filtered_sections, has_no_matches};
@@ -1589,8 +1591,11 @@ impl SidebarView {
1589
1591
let name_style = team_name_style(entry, expanded);
1590
1592
let badge = team_badge(entry, expanded);
1591
1593
let toggle_id = team_id.clone();
1592
let (team_menu_state, team_menu_id, team_hidden) =
1593
(self.state.clone(), team_id.clone(), entry.hidden);
1594
let (team_menu_state, team_menu_id) = (self.state.clone(), team_id.clone());
1595
let team_menu_flags = TeamMenuState {
1596
hidden: entry.hidden,
1597
can_add_channel: entry.rights.add_channel,
1598
};
1594
1599
list = list.child(
1595
1600
h_flex()
1596
1601
.id(SharedString::from(format!("team-{team_id}")))
@@ -1638,7 +1643,7 @@ impl SidebarView {
1638
1643
cx.notify();
1639
1644
}))
1640
1645
.context_menu(move |popup, _, _| {
1641
team_menu(popup, team_menu_state.clone(), &team_menu_id, team_hidden)
1646
team_menu(popup, team_menu_state.clone(), &team_menu_id, team_menu_flags)
1642
1647
}),
1643
1648
);
1644
1649
if !expanded {
@@ -2024,9 +2029,14 @@ fn channel_menu_icon(item: ChannelMenuItem) -> IconName {
2024
2029
}
2025
2030
}
2026
2031
2027
fn team_menu(popup: PopupMenu, state: Entity<AppState>, team_id: &str, hidden: bool) -> PopupMenu {
2032
fn team_menu(
2033
popup: PopupMenu,
2034
state: Entity<AppState>,
2035
team_id: &str,
2036
flags: TeamMenuState,
2037
) -> PopupMenu {
2028
2038
let mut popup = popup;
2029
for entry in team_menu_entries(hidden) {
2039
for entry in team_menu_entries(flags) {
2030
2040
let MenuEntry::Item(item) = entry else {
2031
2041
popup = popup.separator();
2032
2042
continue;
@@ -2035,13 +2045,19 @@ fn team_menu(popup: PopupMenu, state: Entity<AppState>, team_id: &str, hidden: b
2035
2045
popup = popup.item(
2036
2046
PopupMenuItem::new(item.label())
2037
2047
.icon(menu_icon(match item {
2048
TeamMenuItem::AddChannel => IconName::Plus,
2038
2049
TeamMenuItem::Show => IconName::Eye,
2039
2050
TeamMenuItem::Hide => IconName::EyeOff,
2040
2051
TeamMenuItem::ManageTeam => IconName::Settings,
2041
2052
TeamMenuItem::CopyLink => IconName::Link,
2042
2053
}))
2043
.on_click(move |_, _, cx| {
2054
.on_click(move |_, window, cx| {
2055
if item == TeamMenuItem::AddChannel {
2056
open_create_channel_dialog(action_state.clone(), &action_id, window, cx);
2057
return;
2058
}
2044
2059
action_state.update(cx, |state, cx| match item {
2060
TeamMenuItem::AddChannel => {}
2045
2061
TeamMenuItem::Show => state.set_team_shown(&action_id, true, cx),
2046
2062
TeamMenuItem::Hide => state.set_team_shown(&action_id, false, cx),
2047
2063
TeamMenuItem::ManageTeam => state.manage_team_in_browser(&action_id, cx),
@@ -23,13 +23,15 @@ use super::calls_tab::calls_body;23
use super::chat_pop_out;23
use super::chat_pop_out;24
use super::saved_panel::SavedPanel;24
use super::saved_panel::SavedPanel;25
use super::scroll_edge::{scroll_offset, with_top_edge};25
use super::scroll_edge::{scroll_offset, with_top_edge};26
use super::create_channel_dialog::open_create_channel_dialog;26
use super::section_dialog::{SectionNameTarget, open_section_name_dialog};27
use super::section_dialog::{SectionNameTarget, open_section_name_dialog};27
use super::widgets::{count_badge, icon, menu_icon, page_header, symbol, unread_marker};28
use super::widgets::{count_badge, icon, menu_icon, page_header, symbol, unread_marker};28
use crate::agents::AgentsPanel;29
use crate::agents::AgentsPanel;29
use crate::app_state::{AppEvent, AppState, Selection};30
use crate::app_state::{AppEvent, AppState, Selection};30
use crate::presence_follow::{NOTIFY_WHEN_AVAILABLE, TURN_OFF_NOTIFICATIONS};31
use crate::presence_follow::{NOTIFY_WHEN_AVAILABLE, TURN_OFF_NOTIFICATIONS};31
use crate::channel_menu::{32
use crate::channel_menu::{32
ChannelMenuItem, MenuEntry, TeamMenuItem, channel_menu_entries, team_menu_entries,33
ChannelMenuItem, MenuEntry, TeamMenuItem, TeamMenuState, channel_menu_entries,34
team_menu_entries,33
};35
};34
use crate::chat_actions::TITLE_LIMIT;36
use crate::chat_actions::TITLE_LIMIT;35
use crate::chat_filter::{ChatFilter, filtered_sections, has_no_matches};37
use crate::chat_filter::{ChatFilter, filtered_sections, has_no_matches};@@ -1589,8 +1591,11 @@ impl SidebarView {1589
let name_style = team_name_style(entry, expanded);1591
let name_style = team_name_style(entry, expanded);1590
let badge = team_badge(entry, expanded);1592
let badge = team_badge(entry, expanded);1591
let toggle_id = team_id.clone();1593
let toggle_id = team_id.clone();1592
let (team_menu_state, team_menu_id, team_hidden) =1594
let (team_menu_state, team_menu_id) = (self.state.clone(), team_id.clone());1593
(self.state.clone(), team_id.clone(), entry.hidden);1595
let team_menu_flags = TeamMenuState {1596
hidden: entry.hidden,1597
can_add_channel: entry.rights.add_channel,1598
};1594
list = list.child(1599
list = list.child(1595
h_flex()1600
h_flex()1596
.id(SharedString::from(format!("team-{team_id}")))1601
.id(SharedString::from(format!("team-{team_id}")))@@ -1638,7 +1643,7 @@ impl SidebarView {1638
cx.notify();1643
cx.notify();1639
}))1644
}))1640
.context_menu(move |popup, _, _| {1645
.context_menu(move |popup, _, _| {1641
team_menu(popup, team_menu_state.clone(), &team_menu_id, team_hidden)1646
team_menu(popup, team_menu_state.clone(), &team_menu_id, team_menu_flags)1642
}),1647
}),1643
);1648
);1644
if !expanded {1649
if !expanded {@@ -2024,9 +2029,14 @@ fn channel_menu_icon(item: ChannelMenuItem) -> IconName {2024
}2029
}2025
}2030
}2026
2031
2027
fn team_menu(popup: PopupMenu, state: Entity<AppState>, team_id: &str, hidden: bool) -> PopupMenu {2032
fn team_menu(2033
popup: PopupMenu,2034
state: Entity<AppState>,2035
team_id: &str,2036
flags: TeamMenuState,2037
) -> PopupMenu {2028
let mut popup = popup;2038
let mut popup = popup;2029
for entry in team_menu_entries(hidden) {2039
for entry in team_menu_entries(flags) {2030
let MenuEntry::Item(item) = entry else {2040
let MenuEntry::Item(item) = entry else {2031
popup = popup.separator();2041
popup = popup.separator();2032
continue;2042
continue;@@ -2035,13 +2045,19 @@ fn team_menu(popup: PopupMenu, state: Entity<AppState>, team_id: &str, hidden: b2035
popup = popup.item(2045
popup = popup.item(2036
PopupMenuItem::new(item.label())2046
PopupMenuItem::new(item.label())2037
.icon(menu_icon(match item {2047
.icon(menu_icon(match item {2048
TeamMenuItem::AddChannel => IconName::Plus,2038
TeamMenuItem::Show => IconName::Eye,2049
TeamMenuItem::Show => IconName::Eye,2039
TeamMenuItem::Hide => IconName::EyeOff,2050
TeamMenuItem::Hide => IconName::EyeOff,2040
TeamMenuItem::ManageTeam => IconName::Settings,2051
TeamMenuItem::ManageTeam => IconName::Settings,2041
TeamMenuItem::CopyLink => IconName::Link,2052
TeamMenuItem::CopyLink => IconName::Link,2042
}))2053
}))2043
.on_click(move |_, _, cx| {2054
.on_click(move |_, window, cx| {2055
if item == TeamMenuItem::AddChannel {2056
open_create_channel_dialog(action_state.clone(), &action_id, window, cx);2057
return;2058
}2044
action_state.update(cx, |state, cx| match item {2059
action_state.update(cx, |state, cx| match item {2060
TeamMenuItem::AddChannel => {}2045
TeamMenuItem::Show => state.set_team_shown(&action_id, true, cx),2061
TeamMenuItem::Show => state.set_team_shown(&action_id, true, cx),2046
TeamMenuItem::Hide => state.set_team_shown(&action_id, false, cx),2062
TeamMenuItem::Hide => state.set_team_shown(&action_id, false, cx),2047
TeamMenuItem::ManageTeam => state.manage_team_in_browser(&action_id, cx),2063
TeamMenuItem::ManageTeam => state.manage_team_in_browser(&action_id, cx),@@ -0,0 +1,82 @@
1
use serde_json::{Value, json};
2
use session::{DEFAULT_ENDPOINT, Method, Request, SPACES, Scope, Session};
3
4
const CSA_RESOURCE: &str = "https://chatsvcagg.teams.microsoft.com";
5
const MIDDLE_TIER: &str = "https://teams.cloud.microsoft/api/mt/emea/beta";
6
const CSA: &str = "https://teams.cloud.microsoft/api/csa/emea/api/v1";
7
const PROVISIONING: &str = "https://teams.cloud.microsoft/fabric/emea/templates/api";
8
const PROVISIONING_RESOURCE: &str = "https://templates.teams.microsoft.com";
9
const GRAPH: &str = "https://graph.microsoft.com";
10
11
#[tokio::main]
12
async fn main() {
13
let arguments: Vec<String> = std::env::args().skip(1).collect();
14
let endpoint = std::env::var("CDP_ENDPOINT").unwrap_or_else(|_| DEFAULT_ENDPOINT.to_owned());
15
let session = Session::connect(&endpoint).await.expect("browser");
16
let (method, path, body) = match arguments.iter().map(String::as_str).collect::<Vec<_>>().as_slice() {
17
["create-team", name] => (
18
Method::Post,
19
"teams/create".to_owned(),
20
Some(json!({"displayName": name, "description": "", "accessType": "Private"})),
21
),
22
["create-channel", team_thread_id, group_id, name, channel_type] => (
23
Method::Post,
24
format!("teams/{team_thread_id}/channels"),
25
Some(json!({"displayName": name, "description": "", "groupId": group_id, "channelType": channel_type})),
26
),
27
["delete-channel", team_thread_id, channel_id] => (
28
Method::Delete,
29
format!("teams/{team_thread_id}/channels/{channel_id}"),
30
Some(json!({})),
31
),
32
["delete-team", group_id] => (Method::Delete, format!("teams/{group_id}/delete"), None),
33
["get", path] => (Method::Get, (*path).to_owned(), None),
34
["csa-get", path] => (Method::Get, format!("csa:{path}"), None),
35
["graph-get", path] => (Method::Get, format!("graph:{path}"), None),
36
["create-private", group_id, team_thread_id, name] => (
37
Method::Post,
38
format!("provisioning:teams/{group_id}/channels?forceSync=false"),
39
Some(json!({"spaceThreadId": team_thread_id, "displayName": name, "description": "", "channelType": "Private", "sharedWithParentTeam": false})),
40
),
41
["send", method, path, body] => (
42
match *method {
43
"PATCH" => Method::Patch,
44
"DELETE" => Method::Delete,
45
"PUT" => Method::Put,
46
_ => Method::Post,
47
},
48
(*path).to_owned(),
49
Some(serde_json::from_str(body).expect("json body")),
50
),
51
["provisioning-get", path] => (Method::Get, format!("provisioning:{path}"), None),
52
_ => panic!("usage: create-team NAME | create-channel TEAM_THREAD GROUP NAME | delete-channel TEAM_THREAD CHANNEL | delete-team GROUP | get PATH"),
53
};
54
let (url, scope) = if let Some(path) = path.strip_prefix("csa:") {
55
(format!("{CSA}/{path}"), Scope::new(CSA_RESOURCE, "user_impersonation"))
56
} else if let Some(path) = path.strip_prefix("graph:") {
57
(format!("{GRAPH}/v1.0/{path}"), Scope::new(GRAPH, ".default"))
58
} else if let Some(path) = path.strip_prefix("provisioning:") {
59
(format!("{PROVISIONING}/{path}"), Scope::new(PROVISIONING_RESOURCE, ".default"))
60
} else {
61
(format!("{MIDDLE_TIER}/{path}"), Scope::new(SPACES, "user_impersonation"))
62
};
63
let mut request = match body {
64
Some(body) => Request::with_body(method, url, body),
65
None => Request { method, ..Request::get(url) },
66
};
67
request.headers = vec![
68
("x-ms-client-type".to_owned(), "TeamsV2Web".to_owned()),
69
("Accept".to_owned(), "application/json".to_owned()),
70
];
71
if let Ok(anchor) = std::env::var("ANCHOR_MAILBOX") {
72
request.headers.push(("X-AnchorMailbox".to_owned(), anchor));
73
}
74
let answers = session
75
.batch(&[request], &scope)
76
.await
77
.expect("request");
78
let answer = &answers[0];
79
println!("HTTP {}", answer.status);
80
let body: &Value = &answer.body;
81
println!("{}", serde_json::to_string_pretty(body).unwrap_or_default());
82
}
@@ -0,0 +1,82 @@1
use serde_json::{Value, json};2
use session::{DEFAULT_ENDPOINT, Method, Request, SPACES, Scope, Session};3
4
const CSA_RESOURCE: &str = "https://chatsvcagg.teams.microsoft.com";5
const MIDDLE_TIER: &str = "https://teams.cloud.microsoft/api/mt/emea/beta";6
const CSA: &str = "https://teams.cloud.microsoft/api/csa/emea/api/v1";7
const PROVISIONING: &str = "https://teams.cloud.microsoft/fabric/emea/templates/api";8
const PROVISIONING_RESOURCE: &str = "https://templates.teams.microsoft.com";9
const GRAPH: &str = "https://graph.microsoft.com";10
11
#[tokio::main]12
async fn main() {13
let arguments: Vec<String> = std::env::args().skip(1).collect();14
let endpoint = std::env::var("CDP_ENDPOINT").unwrap_or_else(|_| DEFAULT_ENDPOINT.to_owned());15
let session = Session::connect(&endpoint).await.expect("browser");16
let (method, path, body) = match arguments.iter().map(String::as_str).collect::<Vec<_>>().as_slice() {17
["create-team", name] => (18
Method::Post,19
"teams/create".to_owned(),20
Some(json!({"displayName": name, "description": "", "accessType": "Private"})),21
),22
["create-channel", team_thread_id, group_id, name, channel_type] => (23
Method::Post,24
format!("teams/{team_thread_id}/channels"),25
Some(json!({"displayName": name, "description": "", "groupId": group_id, "channelType": channel_type})),26
),27
["delete-channel", team_thread_id, channel_id] => (28
Method::Delete,29
format!("teams/{team_thread_id}/channels/{channel_id}"),30
Some(json!({})),31
),32
["delete-team", group_id] => (Method::Delete, format!("teams/{group_id}/delete"), None),33
["get", path] => (Method::Get, (*path).to_owned(), None),34
["csa-get", path] => (Method::Get, format!("csa:{path}"), None),35
["graph-get", path] => (Method::Get, format!("graph:{path}"), None),36
["create-private", group_id, team_thread_id, name] => (37
Method::Post,38
format!("provisioning:teams/{group_id}/channels?forceSync=false"),39
Some(json!({"spaceThreadId": team_thread_id, "displayName": name, "description": "", "channelType": "Private", "sharedWithParentTeam": false})),40
),41
["send", method, path, body] => (42
match *method {43
"PATCH" => Method::Patch,44
"DELETE" => Method::Delete,45
"PUT" => Method::Put,46
_ => Method::Post,47
},48
(*path).to_owned(),49
Some(serde_json::from_str(body).expect("json body")),50
),51
["provisioning-get", path] => (Method::Get, format!("provisioning:{path}"), None),52
_ => panic!("usage: create-team NAME | create-channel TEAM_THREAD GROUP NAME | delete-channel TEAM_THREAD CHANNEL | delete-team GROUP | get PATH"),53
};54
let (url, scope) = if let Some(path) = path.strip_prefix("csa:") {55
(format!("{CSA}/{path}"), Scope::new(CSA_RESOURCE, "user_impersonation"))56
} else if let Some(path) = path.strip_prefix("graph:") {57
(format!("{GRAPH}/v1.0/{path}"), Scope::new(GRAPH, ".default"))58
} else if let Some(path) = path.strip_prefix("provisioning:") {59
(format!("{PROVISIONING}/{path}"), Scope::new(PROVISIONING_RESOURCE, ".default"))60
} else {61
(format!("{MIDDLE_TIER}/{path}"), Scope::new(SPACES, "user_impersonation"))62
};63
let mut request = match body {64
Some(body) => Request::with_body(method, url, body),65
None => Request { method, ..Request::get(url) },66
};67
request.headers = vec![68
("x-ms-client-type".to_owned(), "TeamsV2Web".to_owned()),69
("Accept".to_owned(), "application/json".to_owned()),70
];71
if let Ok(anchor) = std::env::var("ANCHOR_MAILBOX") {72
request.headers.push(("X-AnchorMailbox".to_owned(), anchor));73
}74
let answers = session75
.batch(&[request], &scope)76
.await77
.expect("request");78
let answer = &answers[0];79
println!("HTTP {}", answer.status);80
let body: &Value = &answer.body;81
println!("{}", serde_json::to_string_pretty(body).unwrap_or_default());82
}@@ -36,6 +36,7 @@ pub mod settings;
36
36
pub mod sound_settings;
37
37
pub mod sounds;
38
38
pub mod substrate_search;
39
pub mod team_admin;
39
40
pub mod teams_cdn;
40
41
pub mod transcripts;
41
42
pub mod translate;
@@ -74,6 +75,7 @@ pub use language_settings::{
74
75
};
75
76
pub use links::{LinkImage, LinkInfo, MessageLinks, is_link_image_url};
76
77
pub use mask::mask_conversation_id;
78
pub use team_admin::{ChannelPrivacy, Mailbox, NewChannel, TeamAdmin};
77
79
pub use members::{
78
80
HistoryShare, INVALID_TOPIC_CHARACTER, MAX_HISTORY_DAYS, MAX_TOPIC_LENGTH, ThreadMembers,
79
81
TopicProblem, topic_problem,
@@ -82,7 +84,7 @@ pub use messages::{ConversationRef, Messages};
82
84
pub use post_follow::{PostFollowState, parse_post_follow_states};
83
85
pub use pins::{
84
86
ChannelLayout, ChannelTab, Folder, FolderKind, Folders, PinnedChannels, PinnedChats,
85
PinnedMessage, Pins, TeamLayout,
87
PinnedMessage, Pins, TeamLayout, TeamRights,
86
88
};
87
89
pub use presence::{
88
90
ActivityReporting, ForcedAvailability, ForcedKind, PresenceLookup, PresenceService,
@@ -36,6 +36,7 @@ pub mod settings;36
pub mod sound_settings;36
pub mod sound_settings;37
pub mod sounds;37
pub mod sounds;38
pub mod substrate_search;38
pub mod substrate_search;39
pub mod team_admin;39
pub mod teams_cdn;40
pub mod teams_cdn;40
pub mod transcripts;41
pub mod transcripts;41
pub mod translate;42
pub mod translate;@@ -74,6 +75,7 @@ pub use language_settings::{74
};75
};75
pub use links::{LinkImage, LinkInfo, MessageLinks, is_link_image_url};76
pub use links::{LinkImage, LinkInfo, MessageLinks, is_link_image_url};76
pub use mask::mask_conversation_id;77
pub use mask::mask_conversation_id;78
pub use team_admin::{ChannelPrivacy, Mailbox, NewChannel, TeamAdmin};77
pub use members::{79
pub use members::{78
HistoryShare, INVALID_TOPIC_CHARACTER, MAX_HISTORY_DAYS, MAX_TOPIC_LENGTH, ThreadMembers,80
HistoryShare, INVALID_TOPIC_CHARACTER, MAX_HISTORY_DAYS, MAX_TOPIC_LENGTH, ThreadMembers,79
TopicProblem, topic_problem,81
TopicProblem, topic_problem,@@ -82,7 +84,7 @@ pub use messages::{ConversationRef, Messages};82
pub use post_follow::{PostFollowState, parse_post_follow_states};84
pub use post_follow::{PostFollowState, parse_post_follow_states};83
pub use pins::{85
pub use pins::{84
ChannelLayout, ChannelTab, Folder, FolderKind, Folders, PinnedChannels, PinnedChats,86
ChannelLayout, ChannelTab, Folder, FolderKind, Folders, PinnedChannels, PinnedChats,85
PinnedMessage, Pins, TeamLayout,87
PinnedMessage, Pins, TeamLayout, TeamRights,86
};88
};87
pub use presence::{89
pub use presence::{88
ActivityReporting, ForcedAvailability, ForcedKind, PresenceLookup, PresenceService,90
ActivityReporting, ForcedAvailability, ForcedKind, PresenceLookup, PresenceService,@@ -13,7 +13,7 @@ pub use folders::{Folder, FolderKind, Folders};
13
13
pub use pinbar::PinnedMessage;
14
14
pub use posts::{PINNED_POSTS_PAGE_SIZE, PinnedPostsPage, parse_pinned_posts};
15
15
pub use state::{PinnedChannels, PinnedChats};
16
pub use teams::{ChannelLayout, ChannelTab, TeamLayout, parse_team_layout};
16
pub use teams::{ChannelLayout, ChannelTab, TeamLayout, TeamRights, parse_team_layout, parse_team_rights};
17
17
pub use transport::{CSA_RESOURCE, CSA_SCOPE, CsaTransport, SessionTransport, SkypeTokenTransport};
18
18
19
19
pub const DEFAULT_REGION: &str = "emea";
@@ -13,7 +13,7 @@ pub use folders::{Folder, FolderKind, Folders};13
pub use pinbar::PinnedMessage;13
pub use pinbar::PinnedMessage;14
pub use posts::{PINNED_POSTS_PAGE_SIZE, PinnedPostsPage, parse_pinned_posts};14
pub use posts::{PINNED_POSTS_PAGE_SIZE, PinnedPostsPage, parse_pinned_posts};15
pub use state::{PinnedChannels, PinnedChats};15
pub use state::{PinnedChannels, PinnedChats};16
pub use teams::{ChannelLayout, ChannelTab, TeamLayout, parse_team_layout};16
pub use teams::{ChannelLayout, ChannelTab, TeamLayout, TeamRights, parse_team_layout, parse_team_rights};17
pub use transport::{CSA_RESOURCE, CSA_SCOPE, CsaTransport, SessionTransport, SkypeTokenTransport};17
pub use transport::{CSA_RESOURCE, CSA_SCOPE, CsaTransport, SessionTransport, SkypeTokenTransport};18
18
19
pub const DEFAULT_REGION: &str = "emea";19
pub const DEFAULT_REGION: &str = "emea";@@ -11,6 +11,7 @@ use crate::error::{Error, Result};
11
11
const TEAMS_QUERY: &str = "isPrefetch=false&enableMembershipSummary=true";
12
12
const WIKI_DEFINITION_ID: &str = "com.microsoft.teamspace.tab.wiki";
13
13
const TAB_URL_KEYS: [&str; 3] = ["websiteUrl", "componentUrl", "url"];
14
const OWNER_ROLE: i64 = 2;
14
15
15
16
#[derive(Debug, Clone, PartialEq, Eq)]
16
17
pub struct ChannelTab {
@@ -28,6 +29,16 @@ pub struct ChannelLayout {
28
29
pub tabs: Vec<ChannelTab>,
29
30
pub notifications: Option<ChannelNotifications>,
30
31
pub followed: bool,
32
pub substrate_group_id: Option<String>,
33
}
34
35
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
36
pub struct TeamRights {
37
pub owner: bool,
38
pub add_channel: bool,
39
pub add_private_channel: bool,
40
pub edit_channel: bool,
41
pub delete_channel: bool,
31
42
}
32
43
33
44
#[derive(Debug, Clone, PartialEq, Eq)]
@@ -35,6 +46,7 @@ pub struct TeamLayout {
35
46
pub team_id: String,
36
47
pub group_id: Option<String>,
37
48
pub hidden: bool,
49
pub rights: TeamRights,
38
50
pub channels: Vec<ChannelLayout>,
39
51
}
40
52
@@ -107,6 +119,22 @@ pub fn parse_channel_tabs(channel: &Value) -> Vec<ChannelTab> {
107
119
tabs.into_iter().map(|(_, tab)| tab).collect()
108
120
}
109
121
122
pub fn parse_team_rights(team: &Value) -> TeamRights {
123
if flag(team, "channelOnlyMember") == Some(true) || flag(team, "isArchived") == Some(true) {
124
return TeamRights::default();
125
}
126
let owner = team.get("memberRole").and_then(Value::as_i64) == Some(OWNER_ROLE);
127
let settings = team.get("teamSettings").unwrap_or(&Value::Null);
128
let allowed = |key: &str| owner || flag(settings, key) == Some(true);
129
TeamRights {
130
owner,
131
add_channel: allowed("createTopic"),
132
add_private_channel: allowed("isPrivateChannelCreationEnabled"),
133
edit_channel: allowed("updateTopic"),
134
delete_channel: allowed("deleteTopic"),
135
}
136
}
137
110
138
fn parse_team(team: &Value) -> Option<TeamLayout> {
111
139
if flag(team, "isDeleted") == Some(true) {
112
140
return None;
@@ -136,6 +164,10 @@ fn parse_team(team: &Value) -> Option<TeamLayout> {
136
164
.and_then(Value::as_str)
137
165
.and_then(parse_property),
138
166
followed: flag(channel, "isFollowed").unwrap_or(false),
167
substrate_group_id: channel
168
.get("substrateGroupId")
169
.and_then(Value::as_str)
170
.map(str::to_owned),
139
171
})
140
172
})
141
173
.collect()
@@ -149,6 +181,7 @@ fn parse_team(team: &Value) -> Option<TeamLayout> {
149
181
.and_then(Value::as_str)
150
182
.map(str::to_owned),
151
183
hidden: flag(team, "isFavorite") == Some(false),
184
rights: parse_team_rights(team),
152
185
channels,
153
186
})
154
187
}
@@ -178,6 +211,30 @@ mod tests {
178
211
assert!(!layout[2].channels[0].hidden);
179
212
}
180
213
214
#[test]
215
fn members_get_the_rights_the_team_settings_grant() {
216
let settings = json!({"createTopic": true, "isPrivateChannelCreationEnabled": false,
217
"updateTopic": true, "deleteTopic": false});
218
let member = json!({"memberRole": 1, "teamSettings": settings});
219
assert_eq!(
220
parse_team_rights(&member),
221
TeamRights {
222
owner: false,
223
add_channel: true,
224
add_private_channel: false,
225
edit_channel: true,
226
delete_channel: false,
227
}
228
);
229
let owner = json!({"memberRole": 2, "teamSettings": {}});
230
let owner_rights = parse_team_rights(&owner);
231
assert!(owner_rights.owner && owner_rights.add_private_channel && owner_rights.delete_channel);
232
let archived = json!({"memberRole": 2, "isArchived": true});
233
assert_eq!(parse_team_rights(&archived), TeamRights::default());
234
let channel_only = json!({"memberRole": 1, "channelOnlyMember": true, "teamSettings": settings});
235
assert_eq!(parse_team_rights(&channel_only), TeamRights::default());
236
}
237
181
238
#[test]
182
239
fn reads_the_group_id_the_graph_team_id_uses() {
183
240
let body = json!({"teams": [
@@ -217,6 +274,7 @@ mod tests {
217
274
tabs: Vec::new(),
218
275
notifications: None,
219
276
followed: false,
277
substrate_group_id: None,
220
278
},
221
279
ChannelLayout {
222
280
channel_id: "19:b@thread.tacv2".into(),
@@ -225,6 +283,7 @@ mod tests {
225
283
tabs: Vec::new(),
226
284
notifications: None,
227
285
followed: false,
286
substrate_group_id: None,
228
287
},
229
288
]
230
289
);
@@ -11,6 +11,7 @@ use crate::error::{Error, Result};11
const TEAMS_QUERY: &str = "isPrefetch=false&enableMembershipSummary=true";11
const TEAMS_QUERY: &str = "isPrefetch=false&enableMembershipSummary=true";12
const WIKI_DEFINITION_ID: &str = "com.microsoft.teamspace.tab.wiki";12
const WIKI_DEFINITION_ID: &str = "com.microsoft.teamspace.tab.wiki";13
const TAB_URL_KEYS: [&str; 3] = ["websiteUrl", "componentUrl", "url"];13
const TAB_URL_KEYS: [&str; 3] = ["websiteUrl", "componentUrl", "url"];14
const OWNER_ROLE: i64 = 2;14
15
15
#[derive(Debug, Clone, PartialEq, Eq)]16
#[derive(Debug, Clone, PartialEq, Eq)]16
pub struct ChannelTab {17
pub struct ChannelTab {@@ -28,6 +29,16 @@ pub struct ChannelLayout {28
pub tabs: Vec<ChannelTab>,29
pub tabs: Vec<ChannelTab>,29
pub notifications: Option<ChannelNotifications>,30
pub notifications: Option<ChannelNotifications>,30
pub followed: bool,31
pub followed: bool,32
pub substrate_group_id: Option<String>,33
}34
35
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]36
pub struct TeamRights {37
pub owner: bool,38
pub add_channel: bool,39
pub add_private_channel: bool,40
pub edit_channel: bool,41
pub delete_channel: bool,31
}42
}32
43
33
#[derive(Debug, Clone, PartialEq, Eq)]44
#[derive(Debug, Clone, PartialEq, Eq)]@@ -35,6 +46,7 @@ pub struct TeamLayout {35
pub team_id: String,46
pub team_id: String,36
pub group_id: Option<String>,47
pub group_id: Option<String>,37
pub hidden: bool,48
pub hidden: bool,49
pub rights: TeamRights,38
pub channels: Vec<ChannelLayout>,50
pub channels: Vec<ChannelLayout>,39
}51
}40
52
@@ -107,6 +119,22 @@ pub fn parse_channel_tabs(channel: &Value) -> Vec<ChannelTab> {107
tabs.into_iter().map(|(_, tab)| tab).collect()119
tabs.into_iter().map(|(_, tab)| tab).collect()108
}120
}109
121
122
pub fn parse_team_rights(team: &Value) -> TeamRights {123
if flag(team, "channelOnlyMember") == Some(true) || flag(team, "isArchived") == Some(true) {124
return TeamRights::default();125
}126
let owner = team.get("memberRole").and_then(Value::as_i64) == Some(OWNER_ROLE);127
let settings = team.get("teamSettings").unwrap_or(&Value::Null);128
let allowed = |key: &str| owner || flag(settings, key) == Some(true);129
TeamRights {130
owner,131
add_channel: allowed("createTopic"),132
add_private_channel: allowed("isPrivateChannelCreationEnabled"),133
edit_channel: allowed("updateTopic"),134
delete_channel: allowed("deleteTopic"),135
}136
}137
110
fn parse_team(team: &Value) -> Option<TeamLayout> {138
fn parse_team(team: &Value) -> Option<TeamLayout> {111
if flag(team, "isDeleted") == Some(true) {139
if flag(team, "isDeleted") == Some(true) {112
return None;140
return None;@@ -136,6 +164,10 @@ fn parse_team(team: &Value) -> Option<TeamLayout> {136
.and_then(Value::as_str)164
.and_then(Value::as_str)137
.and_then(parse_property),165
.and_then(parse_property),138
followed: flag(channel, "isFollowed").unwrap_or(false),166
followed: flag(channel, "isFollowed").unwrap_or(false),167
substrate_group_id: channel168
.get("substrateGroupId")169
.and_then(Value::as_str)170
.map(str::to_owned),139
})171
})140
})172
})141
.collect()173
.collect()@@ -149,6 +181,7 @@ fn parse_team(team: &Value) -> Option<TeamLayout> {149
.and_then(Value::as_str)181
.and_then(Value::as_str)150
.map(str::to_owned),182
.map(str::to_owned),151
hidden: flag(team, "isFavorite") == Some(false),183
hidden: flag(team, "isFavorite") == Some(false),184
rights: parse_team_rights(team),152
channels,185
channels,153
})186
})154
}187
}@@ -178,6 +211,30 @@ mod tests {178
assert!(!layout[2].channels[0].hidden);211
assert!(!layout[2].channels[0].hidden);179
}212
}180
213
214
#[test]215
fn members_get_the_rights_the_team_settings_grant() {216
let settings = json!({"createTopic": true, "isPrivateChannelCreationEnabled": false,217
"updateTopic": true, "deleteTopic": false});218
let member = json!({"memberRole": 1, "teamSettings": settings});219
assert_eq!(220
parse_team_rights(&member),221
TeamRights {222
owner: false,223
add_channel: true,224
add_private_channel: false,225
edit_channel: true,226
delete_channel: false,227
}228
);229
let owner = json!({"memberRole": 2, "teamSettings": {}});230
let owner_rights = parse_team_rights(&owner);231
assert!(owner_rights.owner && owner_rights.add_private_channel && owner_rights.delete_channel);232
let archived = json!({"memberRole": 2, "isArchived": true});233
assert_eq!(parse_team_rights(&archived), TeamRights::default());234
let channel_only = json!({"memberRole": 1, "channelOnlyMember": true, "teamSettings": settings});235
assert_eq!(parse_team_rights(&channel_only), TeamRights::default());236
}237
181
#[test]238
#[test]182
fn reads_the_group_id_the_graph_team_id_uses() {239
fn reads_the_group_id_the_graph_team_id_uses() {183
let body = json!({"teams": [240
let body = json!({"teams": [@@ -217,6 +274,7 @@ mod tests {217
tabs: Vec::new(),274
tabs: Vec::new(),218
notifications: None,275
notifications: None,219
followed: false,276
followed: false,277
substrate_group_id: None,220
},278
},221
ChannelLayout {279
ChannelLayout {222
channel_id: "19:b@thread.tacv2".into(),280
channel_id: "19:b@thread.tacv2".into(),@@ -225,6 +283,7 @@ mod tests {225
tabs: Vec::new(),283
tabs: Vec::new(),226
notifications: None,284
notifications: None,227
followed: false,285
followed: false,286
substrate_group_id: None,228
},287
},229
]288
]230
);289
);@@ -0,0 +1,213 @@
1
use serde_json::{Value, json};
2
use session::{Method, Request, SPACES, Scope, Session};
3
4
use crate::error::Result;
5
use crate::language_settings::with_headers;
6
use crate::messages::{encode, ensure_success};
7
use crate::pins::{CsaTransport, DEFAULT_REGION, SessionTransport};
8
9
const MIDDLE_TIER_SCOPE: &str = "user_impersonation";
10
const PROVISIONING_RESOURCE: &str = "https://templates.teams.microsoft.com";
11
const PROVISIONING_SCOPE: &str = ".default";
12
const ANCHOR_HEADER: &str = "X-AnchorMailbox";
13
14
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
15
pub enum ChannelPrivacy {
16
Standard,
17
Private,
18
}
19
20
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
21
pub struct NewChannel<'a> {
22
pub team_thread_id: &'a str,
23
pub group_id: &'a str,
24
pub name: &'a str,
25
pub description: &'a str,
26
pub privacy: ChannelPrivacy,
27
}
28
29
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
30
pub struct Mailbox<'a> {
31
pub object_id: &'a str,
32
pub tenant_id: &'a str,
33
}
34
35
impl Mailbox<'_> {
36
fn anchor(&self) -> String {
37
format!("OID:{}@{}", self.object_id, self.tenant_id)
38
}
39
}
40
41
pub fn standard_channel_body(channel: &NewChannel<'_>) -> Value {
42
json!({
43
"displayName": channel.name,
44
"description": channel.description,
45
"groupId": channel.group_id,
46
"channelType": "Standard",
47
})
48
}
49
50
pub fn private_channel_body(channel: &NewChannel<'_>) -> Value {
51
json!({
52
"spaceThreadId": channel.team_thread_id,
53
"displayName": channel.name,
54
"description": channel.description,
55
"channelType": "Private",
56
"sharedWithParentTeam": false,
57
})
58
}
59
60
pub struct TeamAdmin<T: CsaTransport = SessionTransport> {
61
middle_tier: T,
62
provisioning: T,
63
region: String,
64
}
65
66
impl TeamAdmin<SessionTransport> {
67
pub fn new(session: &Session) -> Self {
68
TeamAdmin::with_transports(
69
SessionTransport::with_scope(session, Scope::new(SPACES, MIDDLE_TIER_SCOPE)),
70
SessionTransport::with_scope(
71
session,
72
Scope::new(PROVISIONING_RESOURCE, PROVISIONING_SCOPE),
73
),
74
DEFAULT_REGION,
75
)
76
}
77
}
78
79
impl<T: CsaTransport> TeamAdmin<T> {
80
pub fn with_transports(middle_tier: T, provisioning: T, region: &str) -> Self {
81
TeamAdmin {
82
middle_tier,
83
provisioning,
84
region: region.to_owned(),
85
}
86
}
87
88
pub async fn create_channel(
89
&self,
90
channel: &NewChannel<'_>,
91
mailbox: Mailbox<'_>,
92
) -> Result<()> {
93
let answer = match channel.privacy {
94
ChannelPrivacy::Standard => {
95
let url = format!(
96
"https://teams.cloud.microsoft/api/mt/{}/beta/teams/{}/channels",
97
self.region,
98
encode(channel.team_thread_id)
99
);
100
self.middle_tier
101
.send(with_headers(Request::with_body(
102
Method::Post,
103
url,
104
standard_channel_body(channel),
105
)))
106
.await?
107
}
108
ChannelPrivacy::Private => {
109
let url = format!(
110
"https://teams.cloud.microsoft/fabric/{}/templates/api/teams/{}/channels?forceSync=false",
111
self.region, channel.group_id
112
);
113
let mut request = with_headers(Request::with_body(
114
Method::Post,
115
url,
116
private_channel_body(channel),
117
));
118
request
119
.headers
120
.push((ANCHOR_HEADER.to_owned(), mailbox.anchor()));
121
self.provisioning.send(request).await?
122
}
123
};
124
ensure_success(&answer)
125
}
126
}
127
128
#[cfg(test)]
129
mod tests {
130
use std::sync::Mutex;
131
132
use session::ApiResponse;
133
134
use super::*;
135
136
#[derive(Default)]
137
struct Recorder {
138
requests: Mutex<Vec<Request>>,
139
}
140
141
impl CsaTransport for &Recorder {
142
async fn send(&self, request: Request) -> Result<ApiResponse> {
143
self.requests.lock().unwrap().push(request);
144
Ok(ApiResponse {
145
status: 200,
146
retry_after: None,
147
body: Value::Null,
148
})
149
}
150
}
151
152
fn channel(privacy: ChannelPrivacy) -> NewChannel<'static> {
153
NewChannel {
154
team_thread_id: "19:team@thread.skype",
155
group_id: "group-1",
156
name: "Planning",
157
description: "",
158
privacy,
159
}
160
}
161
162
const MAILBOX: Mailbox<'static> = Mailbox {
163
object_id: "me",
164
tenant_id: "tenant",
165
};
166
167
#[tokio::test]
168
async fn standard_channels_go_to_the_middle_tier() {
169
let middle_tier = Recorder::default();
170
let provisioning = Recorder::default();
171
let admin = TeamAdmin::with_transports(&middle_tier, &provisioning, "emea");
172
admin
173
.create_channel(&channel(ChannelPrivacy::Standard), MAILBOX)
174
.await
175
.unwrap();
176
let requests = middle_tier.requests.lock().unwrap();
177
assert_eq!(
178
requests[0].url,
179
"https://teams.cloud.microsoft/api/mt/emea/beta/teams/19%3Ateam%40thread.skype/channels"
180
);
181
assert_eq!(
182
requests[0].body.as_ref().unwrap()["channelType"],
183
"Standard"
184
);
185
assert_eq!(requests[0].body.as_ref().unwrap()["groupId"], "group-1");
186
assert!(provisioning.requests.lock().unwrap().is_empty());
187
}
188
189
#[tokio::test]
190
async fn private_channels_go_to_provisioning_with_the_mailbox_anchor() {
191
let middle_tier = Recorder::default();
192
let provisioning = Recorder::default();
193
let admin = TeamAdmin::with_transports(&middle_tier, &provisioning, "emea");
194
admin
195
.create_channel(&channel(ChannelPrivacy::Private), MAILBOX)
196
.await
197
.unwrap();
198
let requests = provisioning.requests.lock().unwrap();
199
assert_eq!(
200
requests[0].url,
201
"https://teams.cloud.microsoft/fabric/emea/templates/api/teams/group-1/channels?forceSync=false"
202
);
203
assert!(
204
requests[0]
205
.headers
206
.contains(&(ANCHOR_HEADER.to_owned(), "OID:me@tenant".to_owned()))
207
);
208
let body = requests[0].body.as_ref().unwrap();
209
assert_eq!(body["spaceThreadId"], "19:team@thread.skype");
210
assert_eq!(body["channelType"], "Private");
211
assert!(middle_tier.requests.lock().unwrap().is_empty());
212
}
213
}
@@ -0,0 +1,213 @@1
use serde_json::{Value, json};2
use session::{Method, Request, SPACES, Scope, Session};3
4
use crate::error::Result;5
use crate::language_settings::with_headers;6
use crate::messages::{encode, ensure_success};7
use crate::pins::{CsaTransport, DEFAULT_REGION, SessionTransport};8
9
const MIDDLE_TIER_SCOPE: &str = "user_impersonation";10
const PROVISIONING_RESOURCE: &str = "https://templates.teams.microsoft.com";11
const PROVISIONING_SCOPE: &str = ".default";12
const ANCHOR_HEADER: &str = "X-AnchorMailbox";13
14
#[derive(Debug, Clone, Copy, PartialEq, Eq)]15
pub enum ChannelPrivacy {16
Standard,17
Private,18
}19
20
#[derive(Debug, Clone, Copy, PartialEq, Eq)]21
pub struct NewChannel<'a> {22
pub team_thread_id: &'a str,23
pub group_id: &'a str,24
pub name: &'a str,25
pub description: &'a str,26
pub privacy: ChannelPrivacy,27
}28
29
#[derive(Debug, Clone, Copy, PartialEq, Eq)]30
pub struct Mailbox<'a> {31
pub object_id: &'a str,32
pub tenant_id: &'a str,33
}34
35
impl Mailbox<'_> {36
fn anchor(&self) -> String {37
format!("OID:{}@{}", self.object_id, self.tenant_id)38
}39
}40
41
pub fn standard_channel_body(channel: &NewChannel<'_>) -> Value {42
json!({43
"displayName": channel.name,44
"description": channel.description,45
"groupId": channel.group_id,46
"channelType": "Standard",47
})48
}49
50
pub fn private_channel_body(channel: &NewChannel<'_>) -> Value {51
json!({52
"spaceThreadId": channel.team_thread_id,53
"displayName": channel.name,54
"description": channel.description,55
"channelType": "Private",56
"sharedWithParentTeam": false,57
})58
}59
60
pub struct TeamAdmin<T: CsaTransport = SessionTransport> {61
middle_tier: T,62
provisioning: T,63
region: String,64
}65
66
impl TeamAdmin<SessionTransport> {67
pub fn new(session: &Session) -> Self {68
TeamAdmin::with_transports(69
SessionTransport::with_scope(session, Scope::new(SPACES, MIDDLE_TIER_SCOPE)),70
SessionTransport::with_scope(71
session,72
Scope::new(PROVISIONING_RESOURCE, PROVISIONING_SCOPE),73
),74
DEFAULT_REGION,75
)76
}77
}78
79
impl<T: CsaTransport> TeamAdmin<T> {80
pub fn with_transports(middle_tier: T, provisioning: T, region: &str) -> Self {81
TeamAdmin {82
middle_tier,83
provisioning,84
region: region.to_owned(),85
}86
}87
88
pub async fn create_channel(89
&self,90
channel: &NewChannel<'_>,91
mailbox: Mailbox<'_>,92
) -> Result<()> {93
let answer = match channel.privacy {94
ChannelPrivacy::Standard => {95
let url = format!(96
"https://teams.cloud.microsoft/api/mt/{}/beta/teams/{}/channels",97
self.region,98
encode(channel.team_thread_id)99
);100
self.middle_tier101
.send(with_headers(Request::with_body(102
Method::Post,103
url,104
standard_channel_body(channel),105
)))106
.await?107
}108
ChannelPrivacy::Private => {109
let url = format!(110
"https://teams.cloud.microsoft/fabric/{}/templates/api/teams/{}/channels?forceSync=false",111
self.region, channel.group_id112
);113
let mut request = with_headers(Request::with_body(114
Method::Post,115
url,116
private_channel_body(channel),117
));118
request119
.headers120
.push((ANCHOR_HEADER.to_owned(), mailbox.anchor()));121
self.provisioning.send(request).await?122
}123
};124
ensure_success(&answer)125
}126
}127
128
#[cfg(test)]129
mod tests {130
use std::sync::Mutex;131
132
use session::ApiResponse;133
134
use super::*;135
136
#[derive(Default)]137
struct Recorder {138
requests: Mutex<Vec<Request>>,139
}140
141
impl CsaTransport for &Recorder {142
async fn send(&self, request: Request) -> Result<ApiResponse> {143
self.requests.lock().unwrap().push(request);144
Ok(ApiResponse {145
status: 200,146
retry_after: None,147
body: Value::Null,148
})149
}150
}151
152
fn channel(privacy: ChannelPrivacy) -> NewChannel<'static> {153
NewChannel {154
team_thread_id: "19:team@thread.skype",155
group_id: "group-1",156
name: "Planning",157
description: "",158
privacy,159
}160
}161
162
const MAILBOX: Mailbox<'static> = Mailbox {163
object_id: "me",164
tenant_id: "tenant",165
};166
167
#[tokio::test]168
async fn standard_channels_go_to_the_middle_tier() {169
let middle_tier = Recorder::default();170
let provisioning = Recorder::default();171
let admin = TeamAdmin::with_transports(&middle_tier, &provisioning, "emea");172
admin173
.create_channel(&channel(ChannelPrivacy::Standard), MAILBOX)174
.await175
.unwrap();176
let requests = middle_tier.requests.lock().unwrap();177
assert_eq!(178
requests[0].url,179
"https://teams.cloud.microsoft/api/mt/emea/beta/teams/19%3Ateam%40thread.skype/channels"180
);181
assert_eq!(182
requests[0].body.as_ref().unwrap()["channelType"],183
"Standard"184
);185
assert_eq!(requests[0].body.as_ref().unwrap()["groupId"], "group-1");186
assert!(provisioning.requests.lock().unwrap().is_empty());187
}188
189
#[tokio::test]190
async fn private_channels_go_to_provisioning_with_the_mailbox_anchor() {191
let middle_tier = Recorder::default();192
let provisioning = Recorder::default();193
let admin = TeamAdmin::with_transports(&middle_tier, &provisioning, "emea");194
admin195
.create_channel(&channel(ChannelPrivacy::Private), MAILBOX)196
.await197
.unwrap();198
let requests = provisioning.requests.lock().unwrap();199
assert_eq!(200
requests[0].url,201
"https://teams.cloud.microsoft/fabric/emea/templates/api/teams/group-1/channels?forceSync=false"202
);203
assert!(204
requests[0]205
.headers206
.contains(&(ANCHOR_HEADER.to_owned(), "OID:me@tenant".to_owned()))207
);208
let body = requests[0].body.as_ref().unwrap();209
assert_eq!(body["spaceThreadId"], "19:team@thread.skype");210
assert_eq!(body["channelType"], "Private");211
assert!(middle_tier.requests.lock().unwrap().is_empty());212
}213
}@@ -8,7 +8,8 @@ use chatsvc::settings::{
8
8
};
9
9
use chatsvc::{
10
10
ChannelNotificationLevel, ChannelNotifications, ChannelSettings, ChannelTarget,
11
ChannelVisibility, ChatSection, ChatSectionSettings, Pins, UserSettings,
11
ChannelVisibility, ChatSection, ChatSectionSettings, Mailbox, NewChannel, Pins, TeamAdmin,
12
UserSettings,
12
13
pins::SessionTransport,
13
14
};
14
15
use chrono::Utc;
@@ -124,10 +125,18 @@ pub trait FolderSource: Send + Sync {
124
125
) -> BoxFuture<'a, Result<()>> {
125
126
Box::pin(async { Err(Error::Unsupported("team visibility without chatsvc")) })
126
127
}
128
fn create_channel<'a>(
129
&'a self,
130
_channel: NewChannel<'a>,
131
_mailbox: Mailbox<'a>,
132
) -> BoxFuture<'a, Result<()>> {
133
Box::pin(async { Err(Error::Unsupported("channel creation without chatsvc")) })
134
}
127
135
}
128
136
129
137
pub struct ChatsvcFolderSource {
130
138
pins: Pins<SessionTransport>,
139
team_admin: TeamAdmin,
131
140
visibility: ChannelVisibility,
132
141
settings: UserSettings,
133
142
channel_settings: ChannelSettings,
@@ -141,6 +150,7 @@ impl ChatsvcFolderSource {
141
150
pub fn new(session: &Session) -> Self {
142
151
ChatsvcFolderSource {
143
152
pins: Pins::new(session),
153
team_admin: TeamAdmin::new(session),
144
154
visibility: ChannelVisibility::new(session),
145
155
settings: UserSettings::new(session),
146
156
channel_settings: ChannelSettings::new(session),
@@ -204,6 +214,14 @@ impl FolderSource for ChatsvcFolderSource {
204
214
})
205
215
}
206
216
217
fn create_channel<'a>(
218
&'a self,
219
channel: NewChannel<'a>,
220
mailbox: Mailbox<'a>,
221
) -> BoxFuture<'a, Result<()>> {
222
Box::pin(async move { Ok(self.team_admin.create_channel(&channel, mailbox).await?) })
223
}
224
207
225
fn team_layout(&self) -> BoxFuture<'_, Result<Vec<TeamLayoutRecord>>> {
208
226
Box::pin(async {
209
227
let layout = self.pins.team_layout().await?;
@@ -448,6 +466,13 @@ fn layout_record(
448
466
TeamLayoutRecord {
449
467
team_id: team.group_id.unwrap_or(team.team_id),
450
468
hidden: team.hidden,
469
rights: store::TeamRights {
470
owner: team.rights.owner,
471
add_channel: team.rights.add_channel,
472
add_private_channel: team.rights.add_private_channel,
473
edit_channel: team.rights.edit_channel,
474
delete_channel: team.rights.delete_channel,
475
},
451
476
channels: team
452
477
.channels
453
478
.into_iter()
@@ -456,6 +481,7 @@ fn layout_record(
456
481
channel_id: channel.channel_id,
457
482
general: channel.general,
458
483
hidden: channel.hidden,
484
substrate_group_id: channel.substrate_group_id,
459
485
tabs: channel
460
486
.tabs
461
487
.into_iter()
@@ -562,7 +588,7 @@ impl<R: Remote> SyncEngine<R> {
562
588
Err(error) => Err(error),
563
589
};
564
590
self.refresh_section_settings(source).await;
565
let layout = self.refresh_team_layout(source).await;
591
let layout = self.refresh_team_layout(source, false).await;
566
592
match (folders, layout) {
567
593
(Err(folders_error), Err(layout_error)) => {
568
594
Err(Error::Folders(format!("{folders_error}; {layout_error}")))
@@ -625,9 +651,15 @@ impl<R: Remote> SyncEngine<R> {
625
651
.await
626
652
}
627
653
628
async fn refresh_team_layout(&self, source: &Arc<dyn FolderSource>) -> Result<()> {
654
pub(crate) async fn refresh_team_layout(
655
&self,
656
source: &Arc<dyn FolderSource>,
657
force: bool,
658
) -> Result<()> {
629
659
let last = self.store.meta_time(META_TEAM_LAYOUT_AT)?;
630
if last.is_some_and(|last| Utc::now() - last < self.config.team_layout_refresh_interval) {
660
let fresh =
661
last.is_some_and(|last| Utc::now() - last < self.config.team_layout_refresh_interval);
662
if !force && fresh {
631
663
return Ok(());
632
664
}
633
665
let mut layout = source.team_layout().await?;
@@ -704,6 +736,7 @@ mod tests {
704
736
followed: bool,
705
737
) -> chatsvc::ChannelLayout {
706
738
chatsvc::ChannelLayout {
739
substrate_group_id: None,
707
740
channel_id: "19:a".into(),
708
741
general: false,
709
742
hidden: false,
@@ -722,6 +755,7 @@ mod tests {
722
755
723
756
fn team(team_id: &str) -> TeamLayoutRecord {
724
757
TeamLayoutRecord {
758
rights: Default::default(),
725
759
team_id: team_id.into(),
726
760
hidden: false,
727
761
channels: Vec::new(),
@@ -8,7 +8,8 @@ use chatsvc::settings::{8
};8
};9
use chatsvc::{9
use chatsvc::{10
ChannelNotificationLevel, ChannelNotifications, ChannelSettings, ChannelTarget,10
ChannelNotificationLevel, ChannelNotifications, ChannelSettings, ChannelTarget,11
ChannelVisibility, ChatSection, ChatSectionSettings, Pins, UserSettings,11
ChannelVisibility, ChatSection, ChatSectionSettings, Mailbox, NewChannel, Pins, TeamAdmin,12
UserSettings,12
pins::SessionTransport,13
pins::SessionTransport,13
};14
};14
use chrono::Utc;15
use chrono::Utc;@@ -124,10 +125,18 @@ pub trait FolderSource: Send + Sync {124
) -> BoxFuture<'a, Result<()>> {125
) -> BoxFuture<'a, Result<()>> {125
Box::pin(async { Err(Error::Unsupported("team visibility without chatsvc")) })126
Box::pin(async { Err(Error::Unsupported("team visibility without chatsvc")) })126
}127
}128
fn create_channel<'a>(129
&'a self,130
_channel: NewChannel<'a>,131
_mailbox: Mailbox<'a>,132
) -> BoxFuture<'a, Result<()>> {133
Box::pin(async { Err(Error::Unsupported("channel creation without chatsvc")) })134
}127
}135
}128
136
129
pub struct ChatsvcFolderSource {137
pub struct ChatsvcFolderSource {130
pins: Pins<SessionTransport>,138
pins: Pins<SessionTransport>,139
team_admin: TeamAdmin,131
visibility: ChannelVisibility,140
visibility: ChannelVisibility,132
settings: UserSettings,141
settings: UserSettings,133
channel_settings: ChannelSettings,142
channel_settings: ChannelSettings,@@ -141,6 +150,7 @@ impl ChatsvcFolderSource {141
pub fn new(session: &Session) -> Self {150
pub fn new(session: &Session) -> Self {142
ChatsvcFolderSource {151
ChatsvcFolderSource {143
pins: Pins::new(session),152
pins: Pins::new(session),153
team_admin: TeamAdmin::new(session),144
visibility: ChannelVisibility::new(session),154
visibility: ChannelVisibility::new(session),145
settings: UserSettings::new(session),155
settings: UserSettings::new(session),146
channel_settings: ChannelSettings::new(session),156
channel_settings: ChannelSettings::new(session),@@ -204,6 +214,14 @@ impl FolderSource for ChatsvcFolderSource {204
})214
})205
}215
}206
216
217
fn create_channel<'a>(218
&'a self,219
channel: NewChannel<'a>,220
mailbox: Mailbox<'a>,221
) -> BoxFuture<'a, Result<()>> {222
Box::pin(async move { Ok(self.team_admin.create_channel(&channel, mailbox).await?) })223
}224
207
fn team_layout(&self) -> BoxFuture<'_, Result<Vec<TeamLayoutRecord>>> {225
fn team_layout(&self) -> BoxFuture<'_, Result<Vec<TeamLayoutRecord>>> {208
Box::pin(async {226
Box::pin(async {209
let layout = self.pins.team_layout().await?;227
let layout = self.pins.team_layout().await?;@@ -448,6 +466,13 @@ fn layout_record(448
TeamLayoutRecord {466
TeamLayoutRecord {449
team_id: team.group_id.unwrap_or(team.team_id),467
team_id: team.group_id.unwrap_or(team.team_id),450
hidden: team.hidden,468
hidden: team.hidden,469
rights: store::TeamRights {470
owner: team.rights.owner,471
add_channel: team.rights.add_channel,472
add_private_channel: team.rights.add_private_channel,473
edit_channel: team.rights.edit_channel,474
delete_channel: team.rights.delete_channel,475
},451
channels: team476
channels: team452
.channels477
.channels453
.into_iter()478
.into_iter()@@ -456,6 +481,7 @@ fn layout_record(456
channel_id: channel.channel_id,481
channel_id: channel.channel_id,457
general: channel.general,482
general: channel.general,458
hidden: channel.hidden,483
hidden: channel.hidden,484
substrate_group_id: channel.substrate_group_id,459
tabs: channel485
tabs: channel460
.tabs486
.tabs461
.into_iter()487
.into_iter()@@ -562,7 +588,7 @@ impl<R: Remote> SyncEngine<R> {562
Err(error) => Err(error),588
Err(error) => Err(error),563
};589
};564
self.refresh_section_settings(source).await;590
self.refresh_section_settings(source).await;565
let layout = self.refresh_team_layout(source).await;591
let layout = self.refresh_team_layout(source, false).await;566
match (folders, layout) {592
match (folders, layout) {567
(Err(folders_error), Err(layout_error)) => {593
(Err(folders_error), Err(layout_error)) => {568
Err(Error::Folders(format!("{folders_error}; {layout_error}")))594
Err(Error::Folders(format!("{folders_error}; {layout_error}")))@@ -625,9 +651,15 @@ impl<R: Remote> SyncEngine<R> {625
.await651
.await626
}652
}627
653
628
async fn refresh_team_layout(&self, source: &Arc<dyn FolderSource>) -> Result<()> {654
pub(crate) async fn refresh_team_layout(655
&self,656
source: &Arc<dyn FolderSource>,657
force: bool,658
) -> Result<()> {629
let last = self.store.meta_time(META_TEAM_LAYOUT_AT)?;659
let last = self.store.meta_time(META_TEAM_LAYOUT_AT)?;630
if last.is_some_and(|last| Utc::now() - last < self.config.team_layout_refresh_interval) {660
let fresh =661
last.is_some_and(|last| Utc::now() - last < self.config.team_layout_refresh_interval);662
if !force && fresh {631
return Ok(());663
return Ok(());632
}664
}633
let mut layout = source.team_layout().await?;665
let mut layout = source.team_layout().await?;@@ -704,6 +736,7 @@ mod tests {704
followed: bool,736
followed: bool,705
) -> chatsvc::ChannelLayout {737
) -> chatsvc::ChannelLayout {706
chatsvc::ChannelLayout {738
chatsvc::ChannelLayout {739
substrate_group_id: None,707
channel_id: "19:a".into(),740
channel_id: "19:a".into(),708
general: false,741
general: false,709
hidden: false,742
hidden: false,@@ -722,6 +755,7 @@ mod tests {722
755
723
fn team(team_id: &str) -> TeamLayoutRecord {756
fn team(team_id: &str) -> TeamLayoutRecord {724
TeamLayoutRecord {757
TeamLayoutRecord {758
rights: Default::default(),725
team_id: team_id.into(),759
team_id: team_id.into(),726
hidden: false,760
hidden: false,727
channels: Vec::new(),761
channels: Vec::new(),@@ -58,6 +58,7 @@ mod remote;
58
58
pub mod roster_event;
59
59
mod scheduled;
60
60
mod search;
61
mod team_admin;
61
62
mod server_search;
62
63
mod sidebar_sync;
63
64
mod skin_tone;
@@ -121,7 +122,8 @@ pub use chatsvc::{
121
122
ChatSettingsDocument, DesktopNotifications, EnterKeyBehavior, MeetingChatNotifications,
122
123
MessageDensity, NotificationAccountSettings, NotificationPreset, UpArrowBehavior,
123
124
};
124
pub use chatsvc::{ChatSection, ChatSectionSettings, RecordingPolicy};
125
pub use chatsvc::{ChannelPrivacy, ChatSection, ChatSectionSettings, RecordingPolicy};
126
pub use team_admin::{MAX_CHANNEL_DESCRIPTION_LENGTH, MAX_CHANNEL_NAME_LENGTH};
125
127
pub use chatsvc::{
126
128
Language, LanguageSettings, MessageLanguage, Translation, TranslationBehavior,
127
129
TranslationStatus, TranslationTrigger, authoring_patch, behavior_patch, language_code,
@@ -58,6 +58,7 @@ mod remote;58
pub mod roster_event;58
pub mod roster_event;59
mod scheduled;59
mod scheduled;60
mod search;60
mod search;61
mod team_admin;61
mod server_search;62
mod server_search;62
mod sidebar_sync;63
mod sidebar_sync;63
mod skin_tone;64
mod skin_tone;@@ -121,7 +122,8 @@ pub use chatsvc::{121
ChatSettingsDocument, DesktopNotifications, EnterKeyBehavior, MeetingChatNotifications,122
ChatSettingsDocument, DesktopNotifications, EnterKeyBehavior, MeetingChatNotifications,122
MessageDensity, NotificationAccountSettings, NotificationPreset, UpArrowBehavior,123
MessageDensity, NotificationAccountSettings, NotificationPreset, UpArrowBehavior,123
};124
};124
pub use chatsvc::{ChatSection, ChatSectionSettings, RecordingPolicy};125
pub use chatsvc::{ChannelPrivacy, ChatSection, ChatSectionSettings, RecordingPolicy};126
pub use team_admin::{MAX_CHANNEL_DESCRIPTION_LENGTH, MAX_CHANNEL_NAME_LENGTH};125
pub use chatsvc::{127
pub use chatsvc::{126
Language, LanguageSettings, MessageLanguage, Translation, TranslationBehavior,128
Language, LanguageSettings, MessageLanguage, Translation, TranslationBehavior,127
TranslationStatus, TranslationTrigger, authoring_patch, behavior_patch, language_code,129
TranslationStatus, TranslationTrigger, authoring_patch, behavior_patch, language_code,@@ -28,7 +28,7 @@ struct ChatRefresh {
28
28
}
29
29
30
30
#[derive(Default)]
31
struct TeamsRefresh {
31
pub(crate) struct TeamsRefresh {
32
32
refreshed: bool,
33
33
teams: usize,
34
34
channels: usize,
@@ -356,7 +356,7 @@ impl<R: Remote> SyncEngine<R> {
356
356
}))
357
357
}
358
358
359
async fn refresh_teams(&self, force: bool) -> TeamsRefresh {
359
pub(crate) async fn refresh_teams(&self, force: bool) -> TeamsRefresh {
360
360
let mut refresh = TeamsRefresh::default();
361
361
match self.store.meta_time(META_TEAMS_AT) {
362
362
Ok(last) if !force && !is_due(last, self.config.teams_refresh_interval) => {
@@ -28,7 +28,7 @@ struct ChatRefresh {28
}28
}29
29
30
#[derive(Default)]30
#[derive(Default)]31
struct TeamsRefresh {31
pub(crate) struct TeamsRefresh {32
refreshed: bool,32
refreshed: bool,33
teams: usize,33
teams: usize,34
channels: usize,34
channels: usize,@@ -356,7 +356,7 @@ impl<R: Remote> SyncEngine<R> {356
}))356
}))357
}357
}358
358
359
async fn refresh_teams(&self, force: bool) -> TeamsRefresh {359
pub(crate) async fn refresh_teams(&self, force: bool) -> TeamsRefresh {360
let mut refresh = TeamsRefresh::default();360
let mut refresh = TeamsRefresh::default();361
match self.store.meta_time(META_TEAMS_AT) {361
match self.store.meta_time(META_TEAMS_AT) {362
Ok(last) if !force && !is_due(last, self.config.teams_refresh_interval) => {362
Ok(last) if !force && !is_due(last, self.config.teams_refresh_interval) => {@@ -0,0 +1,52 @@
1
use chatsvc::{ChannelPrivacy, Mailbox, NewChannel};
2
3
use crate::engine::SyncEngine;
4
use crate::error::{Error, Result};
5
use crate::events::CoreEvent;
6
use crate::remote::Remote;
7
8
pub const MAX_CHANNEL_NAME_LENGTH: usize = 50;
9
pub const MAX_CHANNEL_DESCRIPTION_LENGTH: usize = 1024;
10
11
impl<R: Remote> SyncEngine<R> {
12
pub async fn create_channel(
13
&self,
14
team_id: &str,
15
name: &str,
16
description: &str,
17
privacy: ChannelPrivacy,
18
) -> Result<()> {
19
let name = name.trim();
20
if name.is_empty() {
21
return Err(Error::Unsupported("a channel needs a name"));
22
}
23
let team_thread_id = self
24
.store
25
.team_thread_id(team_id)?
26
.ok_or_else(|| Error::UnknownConversation(team_id.to_owned()))?;
27
let object_id = self.my_user_id().await?;
28
let tenant_id = self.my_tenant_id_from_any_chat().await?;
29
let source = self.folder_source()?;
30
source
31
.create_channel(
32
NewChannel {
33
team_thread_id: &team_thread_id,
34
group_id: team_id,
35
name,
36
description: description.trim(),
37
privacy,
38
},
39
Mailbox {
40
object_id: &object_id,
41
tenant_id: &tenant_id,
42
},
43
)
44
.await?;
45
self.refresh_teams(true).await;
46
if let Err(error) = self.refresh_team_layout(source, true).await {
47
self.report(format!("cannot refresh the team layout: {error}"));
48
}
49
let _ = self.events.send(CoreEvent::SidebarChanged);
50
Ok(())
51
}
52
}
@@ -0,0 +1,52 @@1
use chatsvc::{ChannelPrivacy, Mailbox, NewChannel};2
3
use crate::engine::SyncEngine;4
use crate::error::{Error, Result};5
use crate::events::CoreEvent;6
use crate::remote::Remote;7
8
pub const MAX_CHANNEL_NAME_LENGTH: usize = 50;9
pub const MAX_CHANNEL_DESCRIPTION_LENGTH: usize = 1024;10
11
impl<R: Remote> SyncEngine<R> {12
pub async fn create_channel(13
&self,14
team_id: &str,15
name: &str,16
description: &str,17
privacy: ChannelPrivacy,18
) -> Result<()> {19
let name = name.trim();20
if name.is_empty() {21
return Err(Error::Unsupported("a channel needs a name"));22
}23
let team_thread_id = self24
.store25
.team_thread_id(team_id)?26
.ok_or_else(|| Error::UnknownConversation(team_id.to_owned()))?;27
let object_id = self.my_user_id().await?;28
let tenant_id = self.my_tenant_id_from_any_chat().await?;29
let source = self.folder_source()?;30
source31
.create_channel(32
NewChannel {33
team_thread_id: &team_thread_id,34
group_id: team_id,35
name,36
description: description.trim(),37
privacy,38
},39
Mailbox {40
object_id: &object_id,41
tenant_id: &tenant_id,42
},43
)44
.await?;45
self.refresh_teams(true).await;46
if let Err(error) = self.refresh_team_layout(source, true).await {47
self.report(format!("cannot refresh the team layout: {error}"));48
}49
let _ = self.events.send(CoreEvent::SidebarChanged);50
Ok(())51
}52
}@@ -12,7 +12,7 @@ use store::{
12
12
ChannelLayoutRecord, ChannelRecord, ChannelTabRecord, Store, TeamLayoutRecord, TeamRecord,
13
13
};
14
14
use teams_core::{
15
Availability, BoxFuture, ChatFolder, ChatSection, ChatSectionSettings, ChatsPage, CoreEvent,
15
Availability, BoxFuture, ChannelPrivacy, ChatFolder, ChatSection, ChatSectionSettings, ChatsPage, CoreEvent,
16
16
DeltaPage, Error, FolderChange, FolderKind, FolderSource, MentionCandidate, MentionInput,
17
17
MentionTarget, NOTES_CHAT_ID, PersonSource, Remote, RemotePage, Result, SyncConfig, SyncEngine,
18
18
substrate_search,
@@ -3406,6 +3406,26 @@ impl FolderSource for FakeFolders {
3406
3406
Ok(())
3407
3407
})
3408
3408
}
3409
3410
fn create_channel<'a>(
3411
&'a self,
3412
channel: chatsvc::NewChannel<'a>,
3413
mailbox: chatsvc::Mailbox<'a>,
3414
) -> BoxFuture<'a, Result<()>> {
3415
Box::pin(async move {
3416
self.calls.lock().unwrap().push(format!(
3417
"create {} {} {} '{}' {:?} {}@{}",
3418
channel.team_thread_id,
3419
channel.group_id,
3420
channel.name,
3421
channel.description,
3422
channel.privacy,
3423
mailbox.object_id,
3424
mailbox.tenant_id
3425
));
3426
Ok(())
3427
})
3428
}
3409
3429
}
3410
3430
3411
3431
fn store_alpha_team(engine: &SyncEngine<Handle>) {
@@ -3620,9 +3640,11 @@ async fn a_failing_folder_list_still_stores_the_team_layout_and_tabs() {
3620
3640
let source_mut = Arc::get_mut(&mut source).unwrap();
3621
3641
source_mut.folders_fail = true;
3622
3642
source_mut.layout = vec![TeamLayoutRecord {
3643
rights: Default::default(),
3623
3644
team_id: "alpha".into(),
3624
3645
hidden: false,
3625
3646
channels: vec![ChannelLayoutRecord {
3647
substrate_group_id: None,
3626
3648
channel_id: "alpha-general".into(),
3627
3649
general: true,
3628
3650
hidden: false,
@@ -3672,6 +3694,7 @@ async fn team_order_follows_teams_order_and_survives_a_failing_order_lookup() {
3672
3694
let fake = Arc::new(Fake::default());
3673
3695
let mut source = FakeFolders::new();
3674
3696
let team = |id: &str| TeamLayoutRecord {
3697
rights: Default::default(),
3675
3698
team_id: id.into(),
3676
3699
hidden: false,
3677
3700
channels: Vec::new(),
@@ -3719,9 +3742,11 @@ async fn team_layout_from_teams_orders_and_hides_the_sidebar() {
3719
3742
let mut source = FakeFolders::new();
3720
3743
Arc::get_mut(&mut source).unwrap().layout = vec![
3721
3744
TeamLayoutRecord {
3745
rights: Default::default(),
3722
3746
team_id: "zeta".into(),
3723
3747
hidden: false,
3724
3748
channels: vec![ChannelLayoutRecord {
3749
substrate_group_id: None,
3725
3750
channel_id: "zeta-old".into(),
3726
3751
general: false,
3727
3752
hidden: true,
@@ -3730,6 +3755,7 @@ async fn team_layout_from_teams_orders_and_hides_the_sidebar() {
3730
3755
}],
3731
3756
},
3732
3757
TeamLayoutRecord {
3758
rights: Default::default(),
3733
3759
team_id: "alpha".into(),
3734
3760
hidden: true,
3735
3761
channels: Vec::new(),
@@ -5842,3 +5868,30 @@ async fn a_quoted_channel_reply_is_written_through_chatsvc_in_the_teams_quote_sh
5842
5868
assert_eq!(sent.reply_to_id.as_deref(), Some("m0030"));
5843
5869
assert!(sent.body_html.starts_with("e));
5844
5870
}
5871
5872
#[tokio::test]
5873
async fn create_channel_sends_the_team_thread_and_own_mailbox_then_refreshes() {
5874
let fake = Arc::new(Fake::default());
5875
let source = FakeFolders::new();
5876
let engine = engine_with(&fake, SyncConfig::default()).with_folder_source(source.clone());
5877
store_alpha_team(&engine);
5878
engine.store().set_meta("me_tenant_id", "tenant-1").unwrap();
5879
let mut events = engine.subscribe();
5880
5881
engine
5882
.create_channel("alpha", " Planning ", " Roadmap ", ChannelPrivacy::Private)
5883
.await
5884
.unwrap();
5885
let calls = source.calls.lock().unwrap().clone();
5886
assert_eq!(
5887
calls[0],
5888
format!("create 19:general@thread.tacv2 alpha Planning 'Roadmap' Private {ME}@tenant-1")
5889
);
5890
assert!(std::iter::from_fn(|| events.try_recv().ok()).any(|event| event == CoreEvent::SidebarChanged));
5891
assert!(
5892
engine
5893
.create_channel("alpha", " ", "", ChannelPrivacy::Standard)
5894
.await
5895
.is_err()
5896
);
5897
}
@@ -12,7 +12,7 @@ use store::{12
ChannelLayoutRecord, ChannelRecord, ChannelTabRecord, Store, TeamLayoutRecord, TeamRecord,12
ChannelLayoutRecord, ChannelRecord, ChannelTabRecord, Store, TeamLayoutRecord, TeamRecord,13
};13
};14
use teams_core::{14
use teams_core::{15
Availability, BoxFuture, ChatFolder, ChatSection, ChatSectionSettings, ChatsPage, CoreEvent,15
Availability, BoxFuture, ChannelPrivacy, ChatFolder, ChatSection, ChatSectionSettings, ChatsPage, CoreEvent,16
DeltaPage, Error, FolderChange, FolderKind, FolderSource, MentionCandidate, MentionInput,16
DeltaPage, Error, FolderChange, FolderKind, FolderSource, MentionCandidate, MentionInput,17
MentionTarget, NOTES_CHAT_ID, PersonSource, Remote, RemotePage, Result, SyncConfig, SyncEngine,17
MentionTarget, NOTES_CHAT_ID, PersonSource, Remote, RemotePage, Result, SyncConfig, SyncEngine,18
substrate_search,18
substrate_search,@@ -3406,6 +3406,26 @@ impl FolderSource for FakeFolders {3406
Ok(())3406
Ok(())3407
})3407
})3408
}3408
}3409
3410
fn create_channel<'a>(3411
&'a self,3412
channel: chatsvc::NewChannel<'a>,3413
mailbox: chatsvc::Mailbox<'a>,3414
) -> BoxFuture<'a, Result<()>> {3415
Box::pin(async move {3416
self.calls.lock().unwrap().push(format!(3417
"create {} {} {} '{}' {:?} {}@{}",3418
channel.team_thread_id,3419
channel.group_id,3420
channel.name,3421
channel.description,3422
channel.privacy,3423
mailbox.object_id,3424
mailbox.tenant_id3425
));3426
Ok(())3427
})3428
}3409
}3429
}3410
3430
3411
fn store_alpha_team(engine: &SyncEngine<Handle>) {3431
fn store_alpha_team(engine: &SyncEngine<Handle>) {@@ -3620,9 +3640,11 @@ async fn a_failing_folder_list_still_stores_the_team_layout_and_tabs() {3620
let source_mut = Arc::get_mut(&mut source).unwrap();3640
let source_mut = Arc::get_mut(&mut source).unwrap();3621
source_mut.folders_fail = true;3641
source_mut.folders_fail = true;3622
source_mut.layout = vec![TeamLayoutRecord {3642
source_mut.layout = vec![TeamLayoutRecord {3643
rights: Default::default(),3623
team_id: "alpha".into(),3644
team_id: "alpha".into(),3624
hidden: false,3645
hidden: false,3625
channels: vec![ChannelLayoutRecord {3646
channels: vec![ChannelLayoutRecord {3647
substrate_group_id: None,3626
channel_id: "alpha-general".into(),3648
channel_id: "alpha-general".into(),3627
general: true,3649
general: true,3628
hidden: false,3650
hidden: false,@@ -3672,6 +3694,7 @@ async fn team_order_follows_teams_order_and_survives_a_failing_order_lookup() {3672
let fake = Arc::new(Fake::default());3694
let fake = Arc::new(Fake::default());3673
let mut source = FakeFolders::new();3695
let mut source = FakeFolders::new();3674
let team = |id: &str| TeamLayoutRecord {3696
let team = |id: &str| TeamLayoutRecord {3697
rights: Default::default(),3675
team_id: id.into(),3698
team_id: id.into(),3676
hidden: false,3699
hidden: false,3677
channels: Vec::new(),3700
channels: Vec::new(),@@ -3719,9 +3742,11 @@ async fn team_layout_from_teams_orders_and_hides_the_sidebar() {3719
let mut source = FakeFolders::new();3742
let mut source = FakeFolders::new();3720
Arc::get_mut(&mut source).unwrap().layout = vec![3743
Arc::get_mut(&mut source).unwrap().layout = vec![3721
TeamLayoutRecord {3744
TeamLayoutRecord {3745
rights: Default::default(),3722
team_id: "zeta".into(),3746
team_id: "zeta".into(),3723
hidden: false,3747
hidden: false,3724
channels: vec![ChannelLayoutRecord {3748
channels: vec![ChannelLayoutRecord {3749
substrate_group_id: None,3725
channel_id: "zeta-old".into(),3750
channel_id: "zeta-old".into(),3726
general: false,3751
general: false,3727
hidden: true,3752
hidden: true,@@ -3730,6 +3755,7 @@ async fn team_layout_from_teams_orders_and_hides_the_sidebar() {3730
}],3755
}],3731
},3756
},3732
TeamLayoutRecord {3757
TeamLayoutRecord {3758
rights: Default::default(),3733
team_id: "alpha".into(),3759
team_id: "alpha".into(),3734
hidden: true,3760
hidden: true,3735
channels: Vec::new(),3761
channels: Vec::new(),@@ -5842,3 +5868,30 @@ async fn a_quoted_channel_reply_is_written_through_chatsvc_in_the_teams_quote_sh5842
assert_eq!(sent.reply_to_id.as_deref(), Some("m0030"));5868
assert_eq!(sent.reply_to_id.as_deref(), Some("m0030"));5843
assert!(sent.body_html.starts_with("e));5869
assert!(sent.body_html.starts_with("e));5844
}5870
}5871
5872
#[tokio::test]5873
async fn create_channel_sends_the_team_thread_and_own_mailbox_then_refreshes() {5874
let fake = Arc::new(Fake::default());5875
let source = FakeFolders::new();5876
let engine = engine_with(&fake, SyncConfig::default()).with_folder_source(source.clone());5877
store_alpha_team(&engine);5878
engine.store().set_meta("me_tenant_id", "tenant-1").unwrap();5879
let mut events = engine.subscribe();5880
5881
engine5882
.create_channel("alpha", " Planning ", " Roadmap ", ChannelPrivacy::Private)5883
.await5884
.unwrap();5885
let calls = source.calls.lock().unwrap().clone();5886
assert_eq!(5887
calls[0],5888
format!("create 19:general@thread.tacv2 alpha Planning 'Roadmap' Private {ME}@tenant-1")5889
);5890
assert!(std::iter::from_fn(|| events.try_recv().ok()).any(|event| event == CoreEvent::SidebarChanged));5891
assert!(5892
engine5893
.create_channel("alpha", " ", "", ChannelPrivacy::Standard)5894
.await5895
.is_err()5896
);5897
}@@ -31,7 +31,7 @@ pub use models::{
31
31
ChannelNotificationLevel, ChannelNotifications, ChannelReadState, ChannelRecord, ChannelTabRecord, ChatPreview,
32
32
ChatRecord, ConversationHit, DraftRecord, FolderRecord, ImageRecord, MemberRecord,
33
33
MessageImportance, MessageRecord, OutboxRecord, OutboxState, OutboxTarget, ReadHorizonRecord,
34
RecentScope, SearchHit, Sidebar, SidebarTeam, SyncState, TeamLayoutRecord, TeamRecord,
34
RecentScope, SearchHit, Sidebar, SidebarTeam, SyncState, TeamLayoutRecord, TeamRecord, TeamRights,
35
35
UNKNOWN_USER_NAME, is_bot_id,
36
36
};
37
37
pub use search::{HIGHLIGHT_END, HIGHLIGHT_START};
@@ -31,7 +31,7 @@ pub use models::{31
ChannelNotificationLevel, ChannelNotifications, ChannelReadState, ChannelRecord, ChannelTabRecord, ChatPreview,31
ChannelNotificationLevel, ChannelNotifications, ChannelReadState, ChannelRecord, ChannelTabRecord, ChatPreview,32
ChatRecord, ConversationHit, DraftRecord, FolderRecord, ImageRecord, MemberRecord,32
ChatRecord, ConversationHit, DraftRecord, FolderRecord, ImageRecord, MemberRecord,33
MessageImportance, MessageRecord, OutboxRecord, OutboxState, OutboxTarget, ReadHorizonRecord,33
MessageImportance, MessageRecord, OutboxRecord, OutboxState, OutboxTarget, ReadHorizonRecord,34
RecentScope, SearchHit, Sidebar, SidebarTeam, SyncState, TeamLayoutRecord, TeamRecord,34
RecentScope, SearchHit, Sidebar, SidebarTeam, SyncState, TeamLayoutRecord, TeamRecord, TeamRights,35
UNKNOWN_USER_NAME, is_bot_id,35
UNKNOWN_USER_NAME, is_bot_id,36
};36
};37
pub use search::{HIGHLIGHT_END, HIGHLIGHT_START};37
pub use search::{HIGHLIGHT_END, HIGHLIGHT_START};@@ -113,6 +113,10 @@ const MIGRATIONS: &[Migration] = &[
113
113
script: include_str!("migrations/0026_channel_read_until.sql"),
114
114
after: None,
115
115
},
116
Migration {
117
script: include_str!("migrations/0027_team_rights.sql"),
118
after: None,
119
},
116
120
];
117
121
118
122
pub fn latest_version() -> i64 {
@@ -113,6 +113,10 @@ const MIGRATIONS: &[Migration] = &[113
script: include_str!("migrations/0026_channel_read_until.sql"),113
script: include_str!("migrations/0026_channel_read_until.sql"),114
after: None,114
after: None,115
},115
},116
Migration {117
script: include_str!("migrations/0027_team_rights.sql"),118
after: None,119
},116
];120
];117
121
118
pub fn latest_version() -> i64 {122
pub fn latest_version() -> i64 {@@ -0,0 +1,7 @@
1
ALTER TABLE team_layout ADD COLUMN owner INTEGER NOT NULL DEFAULT 0;
2
ALTER TABLE team_layout ADD COLUMN add_channel INTEGER NOT NULL DEFAULT 0;
3
ALTER TABLE team_layout ADD COLUMN add_private_channel INTEGER NOT NULL DEFAULT 0;
4
ALTER TABLE team_layout ADD COLUMN edit_channel INTEGER NOT NULL DEFAULT 0;
5
ALTER TABLE team_layout ADD COLUMN delete_channel INTEGER NOT NULL DEFAULT 0;
6
ALTER TABLE channel_layout ADD COLUMN substrate_group_id TEXT;
7
DELETE FROM meta WHERE key = 'team_layout_refreshed_at';
@@ -0,0 +1,7 @@1
ALTER TABLE team_layout ADD COLUMN owner INTEGER NOT NULL DEFAULT 0;2
ALTER TABLE team_layout ADD COLUMN add_channel INTEGER NOT NULL DEFAULT 0;3
ALTER TABLE team_layout ADD COLUMN add_private_channel INTEGER NOT NULL DEFAULT 0;4
ALTER TABLE team_layout ADD COLUMN edit_channel INTEGER NOT NULL DEFAULT 0;5
ALTER TABLE team_layout ADD COLUMN delete_channel INTEGER NOT NULL DEFAULT 0;6
ALTER TABLE channel_layout ADD COLUMN substrate_group_id TEXT;7
DELETE FROM meta WHERE key = 'team_layout_refreshed_at';@@ -193,6 +193,7 @@ pub struct SidebarTeam {
193
193
pub team: TeamRecord,
194
194
pub channels: Vec<ChannelRecord>,
195
195
pub hidden: bool,
196
pub rights: TeamRights,
196
197
pub hidden_channel_ids: Vec<String>,
197
198
pub notifications: HashMap<String, ChannelNotifications>,
198
199
pub mentions: HashMap<String, ChannelMentions>,
@@ -272,12 +273,23 @@ pub struct ChannelLayoutRecord {
272
273
pub hidden: bool,
273
274
pub tabs: Vec<ChannelTabRecord>,
274
275
pub notifications: ChannelNotifications,
276
pub substrate_group_id: Option<String>,
277
}
278
279
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
280
pub struct TeamRights {
281
pub owner: bool,
282
pub add_channel: bool,
283
pub add_private_channel: bool,
284
pub edit_channel: bool,
285
pub delete_channel: bool,
275
286
}
276
287
277
288
#[derive(Debug, Clone, PartialEq, Eq)]
278
289
pub struct TeamLayoutRecord {
279
290
pub team_id: String,
280
291
pub hidden: bool,
292
pub rights: TeamRights,
281
293
pub channels: Vec<ChannelLayoutRecord>,
282
294
}
283
295
@@ -193,6 +193,7 @@ pub struct SidebarTeam {193
pub team: TeamRecord,193
pub team: TeamRecord,194
pub channels: Vec<ChannelRecord>,194
pub channels: Vec<ChannelRecord>,195
pub hidden: bool,195
pub hidden: bool,196
pub rights: TeamRights,196
pub hidden_channel_ids: Vec<String>,197
pub hidden_channel_ids: Vec<String>,197
pub notifications: HashMap<String, ChannelNotifications>,198
pub notifications: HashMap<String, ChannelNotifications>,198
pub mentions: HashMap<String, ChannelMentions>,199
pub mentions: HashMap<String, ChannelMentions>,@@ -272,12 +273,23 @@ pub struct ChannelLayoutRecord {272
pub hidden: bool,273
pub hidden: bool,273
pub tabs: Vec<ChannelTabRecord>,274
pub tabs: Vec<ChannelTabRecord>,274
pub notifications: ChannelNotifications,275
pub notifications: ChannelNotifications,276
pub substrate_group_id: Option<String>,277
}278
279
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]280
pub struct TeamRights {281
pub owner: bool,282
pub add_channel: bool,283
pub add_private_channel: bool,284
pub edit_channel: bool,285
pub delete_channel: bool,275
}286
}276
287
277
#[derive(Debug, Clone, PartialEq, Eq)]288
#[derive(Debug, Clone, PartialEq, Eq)]278
pub struct TeamLayoutRecord {289
pub struct TeamLayoutRecord {279
pub team_id: String,290
pub team_id: String,280
pub hidden: bool,291
pub hidden: bool,292
pub rights: TeamRights,281
pub channels: Vec<ChannelLayoutRecord>,293
pub channels: Vec<ChannelLayoutRecord>,282
}294
}283
295
@@ -6,7 +6,7 @@ use rusqlite::params;
6
6
use crate::error::Result;
7
7
use crate::models::{
8
8
ChannelMentions, ChannelNotificationLevel, ChannelNotifications, ChannelRecord,
9
ChannelTabRecord, Sidebar, SidebarTeam, TeamLayoutRecord, TeamRecord,
9
ChannelTabRecord, Sidebar, SidebarTeam, TeamLayoutRecord, TeamRecord, TeamRights,
10
10
};
11
11
use crate::store::Store;
12
12
use crate::teams::channel_from_row;
@@ -17,6 +17,7 @@ struct TeamRow {
17
17
team: TeamRecord,
18
18
position: Option<i64>,
19
19
hidden: bool,
20
rights: TeamRights,
20
21
}
21
22
22
23
struct ChannelRow {
@@ -32,7 +33,10 @@ impl Store {
32
33
let connection = self.lock()?;
33
34
let mut team_rows: Vec<TeamRow> = connection
34
35
.prepare_cached(
35
"SELECT teams.id, teams.name, team_layout.position, COALESCE(team_layout.hidden, 0)
36
"SELECT teams.id, teams.name, team_layout.position, COALESCE(team_layout.hidden, 0),
37
COALESCE(team_layout.owner, 0), COALESCE(team_layout.add_channel, 0),
38
COALESCE(team_layout.add_private_channel, 0),
39
COALESCE(team_layout.edit_channel, 0), COALESCE(team_layout.delete_channel, 0)
36
40
FROM teams LEFT JOIN team_layout ON team_layout.team_id = teams.id",
37
41
)?
38
42
.query_map([], |row| {
@@ -43,6 +47,13 @@ impl Store {
43
47
},
44
48
position: row.get(2)?,
45
49
hidden: row.get(3)?,
50
rights: TeamRights {
51
owner: row.get(4)?,
52
add_channel: row.get(5)?,
53
add_private_channel: row.get(6)?,
54
edit_channel: row.get(7)?,
55
delete_channel: row.get(8)?,
56
},
46
57
})
47
58
})?
48
59
.collect::<rusqlite::Result<_>>()?;
@@ -102,6 +113,7 @@ impl Store {
102
113
team: row.team,
103
114
channels: Vec::new(),
104
115
hidden: row.hidden,
116
rights: row.rights,
105
117
hidden_channel_ids: Vec::new(),
106
118
notifications: HashMap::new(),
107
119
mentions: HashMap::new(),
@@ -136,26 +148,38 @@ impl Store {
136
148
transaction.execute("DELETE FROM channel_tabs", [])?;
137
149
{
138
150
let mut team_insert = transaction.prepare_cached(
139
"INSERT OR REPLACE INTO team_layout (team_id, position, hidden) VALUES (?1, ?2, ?3)",
151
"INSERT OR REPLACE INTO team_layout
152
(team_id, position, hidden, owner, add_channel, add_private_channel, edit_channel, delete_channel)
153
VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8)",
140
154
)?;
141
155
let mut channel_insert = transaction.prepare_cached(
142
156
"INSERT OR REPLACE INTO channel_layout
143
(channel_id, general, hidden, notification_level, include_replies)
144
VALUES (?1, ?2, ?3, ?4, ?5)",
157
(channel_id, general, hidden, notification_level, include_replies, substrate_group_id)
158
VALUES (?1, ?2, ?3, ?4, ?5, ?6)",
145
159
)?;
146
160
let mut tab_insert = transaction.prepare_cached(
147
161
"INSERT OR REPLACE INTO channel_tabs (channel_id, position, tab_id, name, definition_id, open_url)
148
162
VALUES (?1, ?2, ?3, ?4, ?5, ?6)",
149
163
)?;
150
164
for (position, team) in layout.iter().enumerate() {
151
team_insert.execute(params![team.team_id, position as i64, team.hidden])?;
165
team_insert.execute(params![
166
team.team_id,
167
position as i64,
168
team.hidden,
169
team.rights.owner,
170
team.rights.add_channel,
171
team.rights.add_private_channel,
172
team.rights.edit_channel,
173
team.rights.delete_channel
174
])?;
152
175
for channel in &team.channels {
153
176
channel_insert.execute(params![
154
177
channel.channel_id,
155
178
channel.general,
156
179
channel.hidden,
157
180
channel.notifications.level.key(),
158
channel.notifications.include_replies
181
channel.notifications.include_replies,
182
channel.substrate_group_id
159
183
])?;
160
184
for (tab_position, tab) in channel.tabs.iter().enumerate() {
161
185
tab_insert.execute(params![
@@ -6,7 +6,7 @@ use rusqlite::params;6
use crate::error::Result;6
use crate::error::Result;7
use crate::models::{7
use crate::models::{8
ChannelMentions, ChannelNotificationLevel, ChannelNotifications, ChannelRecord,8
ChannelMentions, ChannelNotificationLevel, ChannelNotifications, ChannelRecord,9
ChannelTabRecord, Sidebar, SidebarTeam, TeamLayoutRecord, TeamRecord,9
ChannelTabRecord, Sidebar, SidebarTeam, TeamLayoutRecord, TeamRecord, TeamRights,10
};10
};11
use crate::store::Store;11
use crate::store::Store;12
use crate::teams::channel_from_row;12
use crate::teams::channel_from_row;@@ -17,6 +17,7 @@ struct TeamRow {17
team: TeamRecord,17
team: TeamRecord,18
position: Option<i64>,18
position: Option<i64>,19
hidden: bool,19
hidden: bool,20
rights: TeamRights,20
}21
}21
22
22
struct ChannelRow {23
struct ChannelRow {@@ -32,7 +33,10 @@ impl Store {32
let connection = self.lock()?;33
let connection = self.lock()?;33
let mut team_rows: Vec<TeamRow> = connection34
let mut team_rows: Vec<TeamRow> = connection34
.prepare_cached(35
.prepare_cached(35
"SELECT teams.id, teams.name, team_layout.position, COALESCE(team_layout.hidden, 0)36
"SELECT teams.id, teams.name, team_layout.position, COALESCE(team_layout.hidden, 0),37
COALESCE(team_layout.owner, 0), COALESCE(team_layout.add_channel, 0),38
COALESCE(team_layout.add_private_channel, 0),39
COALESCE(team_layout.edit_channel, 0), COALESCE(team_layout.delete_channel, 0)36
FROM teams LEFT JOIN team_layout ON team_layout.team_id = teams.id",40
FROM teams LEFT JOIN team_layout ON team_layout.team_id = teams.id",37
)?41
)?38
.query_map([], |row| {42
.query_map([], |row| {@@ -43,6 +47,13 @@ impl Store {43
},47
},44
position: row.get(2)?,48
position: row.get(2)?,45
hidden: row.get(3)?,49
hidden: row.get(3)?,50
rights: TeamRights {51
owner: row.get(4)?,52
add_channel: row.get(5)?,53
add_private_channel: row.get(6)?,54
edit_channel: row.get(7)?,55
delete_channel: row.get(8)?,56
},46
})57
})47
})?58
})?48
.collect::<rusqlite::Result<_>>()?;59
.collect::<rusqlite::Result<_>>()?;@@ -102,6 +113,7 @@ impl Store {102
team: row.team,113
team: row.team,103
channels: Vec::new(),114
channels: Vec::new(),104
hidden: row.hidden,115
hidden: row.hidden,116
rights: row.rights,105
hidden_channel_ids: Vec::new(),117
hidden_channel_ids: Vec::new(),106
notifications: HashMap::new(),118
notifications: HashMap::new(),107
mentions: HashMap::new(),119
mentions: HashMap::new(),@@ -136,26 +148,38 @@ impl Store {136
transaction.execute("DELETE FROM channel_tabs", [])?;148
transaction.execute("DELETE FROM channel_tabs", [])?;137
{149
{138
let mut team_insert = transaction.prepare_cached(150
let mut team_insert = transaction.prepare_cached(139
"INSERT OR REPLACE INTO team_layout (team_id, position, hidden) VALUES (?1, ?2, ?3)",151
"INSERT OR REPLACE INTO team_layout152
(team_id, position, hidden, owner, add_channel, add_private_channel, edit_channel, delete_channel)153
VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8)",140
)?;154
)?;141
let mut channel_insert = transaction.prepare_cached(155
let mut channel_insert = transaction.prepare_cached(142
"INSERT OR REPLACE INTO channel_layout156
"INSERT OR REPLACE INTO channel_layout143
(channel_id, general, hidden, notification_level, include_replies)157
(channel_id, general, hidden, notification_level, include_replies, substrate_group_id)144
VALUES (?1, ?2, ?3, ?4, ?5)",158
VALUES (?1, ?2, ?3, ?4, ?5, ?6)",145
)?;159
)?;146
let mut tab_insert = transaction.prepare_cached(160
let mut tab_insert = transaction.prepare_cached(147
"INSERT OR REPLACE INTO channel_tabs (channel_id, position, tab_id, name, definition_id, open_url)161
"INSERT OR REPLACE INTO channel_tabs (channel_id, position, tab_id, name, definition_id, open_url)148
VALUES (?1, ?2, ?3, ?4, ?5, ?6)",162
VALUES (?1, ?2, ?3, ?4, ?5, ?6)",149
)?;163
)?;150
for (position, team) in layout.iter().enumerate() {164
for (position, team) in layout.iter().enumerate() {151
team_insert.execute(params![team.team_id, position as i64, team.hidden])?;165
team_insert.execute(params![166
team.team_id,167
position as i64,168
team.hidden,169
team.rights.owner,170
team.rights.add_channel,171
team.rights.add_private_channel,172
team.rights.edit_channel,173
team.rights.delete_channel174
])?;152
for channel in &team.channels {175
for channel in &team.channels {153
channel_insert.execute(params![176
channel_insert.execute(params![154
channel.channel_id,177
channel.channel_id,155
channel.general,178
channel.general,156
channel.hidden,179
channel.hidden,157
channel.notifications.level.key(),180
channel.notifications.level.key(),158
channel.notifications.include_replies181
channel.notifications.include_replies,182
channel.substrate_group_id159
])?;183
])?;160
for (tab_position, tab) in channel.tabs.iter().enumerate() {184
for (tab_position, tab) in channel.tabs.iter().enumerate() {161
tab_insert.execute(params![185
tab_insert.execute(params![@@ -4,7 +4,7 @@ use store::{
4
4
AvatarRecord, ChannelLayoutRecord, ChannelMentions, ChannelNotificationLevel,
5
5
ChannelNotifications, ChannelReadState, ChannelRecord, ChannelTabRecord, ChatPreview, ChatRecord, FolderRecord,
6
6
MemberRecord, MessageImportance, MessageRecord, ReadHorizonRecord, RecentScope, Store,
7
SyncState, TeamLayoutRecord, TeamRecord, UNKNOWN_USER_NAME,
7
SyncState, TeamLayoutRecord, TeamRecord, TeamRights, UNKNOWN_USER_NAME,
8
8
};
9
9
10
10
#[test]
@@ -608,11 +608,11 @@ fn file_database_uses_wal_persists_and_migrates_once() {
608
608
let path = directory.path().join("nested").join("cache.sqlite3");
609
609
{
610
610
let store = Store::open(&path).unwrap();
611
assert_eq!(store.schema_version().unwrap(), 26);
611
assert_eq!(store.schema_version().unwrap(), 27);
612
612
store.upsert_messages(&[message("c", "m1", 1)]).unwrap();
613
613
}
614
614
let reopened = Store::open(&path).unwrap();
615
assert_eq!(reopened.schema_version().unwrap(), 26);
615
assert_eq!(reopened.schema_version().unwrap(), 27);
616
616
assert_eq!(reopened.message_count("c").unwrap(), 1);
617
617
drop(reopened);
618
618
let mode: String = rusqlite_open(&path)
@@ -628,7 +628,7 @@ fn newer_schema_is_refused() {
628
628
drop(Store::open(&path).unwrap());
629
629
let connection = rusqlite_open(&path);
630
630
connection
631
.execute_batch("PRAGMA user_version = 99")
631
.execute_batch("ALTER TABLE team_layout DROP COLUMN owner; ALTER TABLE team_layout DROP COLUMN add_channel; ALTER TABLE team_layout DROP COLUMN add_private_channel; ALTER TABLE team_layout DROP COLUMN edit_channel; ALTER TABLE team_layout DROP COLUMN delete_channel; ALTER TABLE channel_layout DROP COLUMN substrate_group_id; PRAGMA user_version = 99")
632
632
.unwrap();
633
633
drop(connection);
634
634
let error = Store::open(&path).err().expect("must refuse");
@@ -641,10 +641,10 @@ fn old_schema_is_upgraded_in_place() {
641
641
let path = directory.path().join("cache.sqlite3");
642
642
drop(Store::open(&path).unwrap());
643
643
let connection = rusqlite_open(&path);
644
connection.execute_batch("DROP TABLE messages; DROP TABLE sync_state; DROP TABLE chats; DROP TABLE chat_members; DROP TABLE channels; DROP TABLE teams; DROP TABLE meta; DROP TABLE avatars; DROP TABLE folder_items; DROP TABLE folders; DROP TABLE pinned_channels; DROP TABLE images; DROP TABLE search_keys; DROP TABLE message_search; DROP TABLE title_search; DROP TABLE team_layout; DROP TABLE channel_layout; DROP TABLE channel_tabs; DROP TABLE presence; DROP TABLE activity; DROP TABLE outbox; DROP TABLE drafts; DROP TABLE attachment_images; DROP TABLE agent_reaction_proposals; DROP TABLE agent_proposals; PRAGMA user_version = 0").unwrap();
644
connection.execute_batch("ALTER TABLE team_layout DROP COLUMN owner; ALTER TABLE team_layout DROP COLUMN add_channel; ALTER TABLE team_layout DROP COLUMN add_private_channel; ALTER TABLE team_layout DROP COLUMN edit_channel; ALTER TABLE team_layout DROP COLUMN delete_channel; ALTER TABLE channel_layout DROP COLUMN substrate_group_id; DROP TABLE messages; DROP TABLE sync_state; DROP TABLE chats; DROP TABLE chat_members; DROP TABLE channels; DROP TABLE teams; DROP TABLE meta; DROP TABLE avatars; DROP TABLE folder_items; DROP TABLE folders; DROP TABLE pinned_channels; DROP TABLE images; DROP TABLE search_keys; DROP TABLE message_search; DROP TABLE title_search; DROP TABLE team_layout; DROP TABLE channel_layout; DROP TABLE channel_tabs; DROP TABLE presence; DROP TABLE activity; DROP TABLE outbox; DROP TABLE drafts; DROP TABLE attachment_images; DROP TABLE agent_reaction_proposals; DROP TABLE agent_proposals; PRAGMA user_version = 0").unwrap();
645
645
drop(connection);
646
646
let store = Store::open(&path).unwrap();
647
assert_eq!(store.schema_version().unwrap(), 26);
647
assert_eq!(store.schema_version().unwrap(), 27);
648
648
store.upsert_messages(&[message("c", "m1", 1)]).unwrap();
649
649
}
650
650
@@ -710,7 +710,7 @@ fn migration_to_v2_keeps_existing_sync_state() {
710
710
let store = Store::open(&path).unwrap();
711
711
let state = store.sync_state("c").unwrap().unwrap();
712
712
assert_eq!(state.delta_link, None);
713
assert_eq!(store.schema_version().unwrap(), 26);
713
assert_eq!(store.schema_version().unwrap(), 27);
714
714
}
715
715
716
716
#[test]
@@ -723,7 +723,7 @@ fn migration_to_v13_clears_channel_delta_links_only() {
723
723
let connection = Connection::open(&path).unwrap();
724
724
connection
725
725
.execute_batch(
726
"INSERT INTO teams (id, name) VALUES ('t', 'T');
726
"ALTER TABLE team_layout DROP COLUMN owner; ALTER TABLE team_layout DROP COLUMN add_channel; ALTER TABLE team_layout DROP COLUMN add_private_channel; ALTER TABLE team_layout DROP COLUMN edit_channel; ALTER TABLE team_layout DROP COLUMN delete_channel; ALTER TABLE channel_layout DROP COLUMN substrate_group_id; INSERT INTO teams (id, name) VALUES ('t', 'T');
727
727
INSERT INTO channels (id, team_id, name) VALUES ('ch', 't', 'C');
728
728
INSERT INTO sync_state (conversation_id, delta_link) VALUES ('ch', 'link'), ('chat', 'link');
729
729
ALTER TABLE messages DROP COLUMN subject;
@@ -1019,7 +1019,7 @@ fn migration_indexes_rows_that_predate_search() {
1019
1019
let connection = Connection::open(&path).unwrap();
1020
1020
connection
1021
1021
.execute_batch(
1022
"DROP TRIGGER chats_title_insert; DROP TRIGGER chats_title_update; DROP TRIGGER chats_title_delete;
1022
"ALTER TABLE team_layout DROP COLUMN owner; ALTER TABLE team_layout DROP COLUMN add_channel; ALTER TABLE team_layout DROP COLUMN add_private_channel; ALTER TABLE team_layout DROP COLUMN edit_channel; ALTER TABLE team_layout DROP COLUMN delete_channel; ALTER TABLE channel_layout DROP COLUMN substrate_group_id; DROP TRIGGER chats_title_insert; DROP TRIGGER chats_title_update; DROP TRIGGER chats_title_delete;
1023
1023
DROP TRIGGER channels_title_insert; DROP TRIGGER channels_title_update; DROP TRIGGER channels_title_delete;
1024
1024
DROP TABLE images; DROP TABLE search_keys; DROP TABLE message_search; DROP TABLE title_search;
1025
1025
DROP TABLE team_layout; DROP TABLE channel_layout; DROP TABLE channel_tabs; DROP TABLE presence; DROP TABLE activity; DROP TABLE outbox; DROP TABLE drafts; DROP TABLE attachment_images; DROP TABLE agent_reaction_proposals; DROP TABLE agent_proposals;
@@ -1302,9 +1302,11 @@ fn channel_tabs_keep_their_saved_order_and_are_replaced_on_refresh() {
1302
1302
};
1303
1303
let layout = |tabs: Vec<ChannelTabRecord>| {
1304
1304
vec![TeamLayoutRecord {
1305
rights: Default::default(),
1305
1306
team_id: "team".to_owned(),
1306
1307
hidden: false,
1307
1308
channels: vec![ChannelLayoutRecord {
1309
substrate_group_id: None,
1308
1310
channel_id: "channel".to_owned(),
1309
1311
general: false,
1310
1312
hidden: false,
@@ -1369,9 +1371,11 @@ fn channel_notifications_default_to_feed_and_survive_layout_and_local_writes() {
1369
1371
};
1370
1372
store
1371
1373
.replace_team_layout(&[TeamLayoutRecord {
1374
rights: Default::default(),
1372
1375
team_id: "t1".to_owned(),
1373
1376
hidden: false,
1374
1377
channels: vec![ChannelLayoutRecord {
1378
substrate_group_id: None,
1375
1379
channel_id: "c2".to_owned(),
1376
1380
general: false,
1377
1381
hidden: false,
@@ -1453,9 +1457,11 @@ fn the_team_thread_id_is_the_general_channel_id() {
1453
1457
.unwrap();
1454
1458
store
1455
1459
.replace_team_layout(&[TeamLayoutRecord {
1460
rights: Default::default(),
1456
1461
team_id: "group-b".to_owned(),
1457
1462
hidden: false,
1458
1463
channels: vec![ChannelLayoutRecord {
1464
substrate_group_id: None,
1459
1465
channel_id: "19:b-renamed".to_owned(),
1460
1466
general: true,
1461
1467
hidden: false,
@@ -1595,12 +1601,12 @@ fn migration_to_v20_adds_the_call_event_column() {
1595
1601
Connection::open(&path)
1596
1602
.unwrap()
1597
1603
.execute_batch(
1598
"ALTER TABLE channels DROP COLUMN read_until; ALTER TABLE messages DROP COLUMN call_event_json; ALTER TABLE messages DROP COLUMN importance; PRAGMA user_version = 19",
1604
"ALTER TABLE team_layout DROP COLUMN owner; ALTER TABLE team_layout DROP COLUMN add_channel; ALTER TABLE team_layout DROP COLUMN add_private_channel; ALTER TABLE team_layout DROP COLUMN edit_channel; ALTER TABLE team_layout DROP COLUMN delete_channel; ALTER TABLE channel_layout DROP COLUMN substrate_group_id; ALTER TABLE channels DROP COLUMN read_until; ALTER TABLE messages DROP COLUMN call_event_json; ALTER TABLE messages DROP COLUMN importance; PRAGMA user_version = 19",
1599
1605
)
1600
1606
.unwrap();
1601
1607
}
1602
1608
let store = Store::open(&path).unwrap();
1603
assert_eq!(store.schema_version().unwrap(), 26);
1609
assert_eq!(store.schema_version().unwrap(), 27);
1604
1610
let old = store.messages("c", None, 10).unwrap();
1605
1611
assert_eq!(old[0].call_event_json, None);
1606
1612
assert!(store.sync_state("c").unwrap().is_none());
@@ -1646,11 +1652,11 @@ fn migration_to_v21_refetches_chats_and_channels_for_recordings() {
1646
1652
drop(store);
1647
1653
Connection::open(&path)
1648
1654
.unwrap()
1649
.execute_batch("ALTER TABLE channels DROP COLUMN read_until; ALTER TABLE messages DROP COLUMN importance; PRAGMA user_version = 20")
1655
.execute_batch("ALTER TABLE team_layout DROP COLUMN owner; ALTER TABLE team_layout DROP COLUMN add_channel; ALTER TABLE team_layout DROP COLUMN add_private_channel; ALTER TABLE team_layout DROP COLUMN edit_channel; ALTER TABLE team_layout DROP COLUMN delete_channel; ALTER TABLE channel_layout DROP COLUMN substrate_group_id; ALTER TABLE channels DROP COLUMN read_until; ALTER TABLE messages DROP COLUMN importance; PRAGMA user_version = 20")
1650
1656
.unwrap();
1651
1657
}
1652
1658
let store = Store::open(&path).unwrap();
1653
assert_eq!(store.schema_version().unwrap(), 26);
1659
assert_eq!(store.schema_version().unwrap(), 27);
1654
1660
assert!(store.sync_state("c").unwrap().is_none());
1655
1661
assert!(store.sync_state("channel").unwrap().is_none());
1656
1662
assert!(store.sync_state("other").unwrap().is_some());
@@ -1676,11 +1682,11 @@ fn migration_to_v22_adds_read_horizons_that_survive_a_reopen() {
1676
1682
drop(store);
1677
1683
Connection::open(&path)
1678
1684
.unwrap()
1679
.execute_batch("ALTER TABLE channels DROP COLUMN read_until; DROP TABLE read_horizons; ALTER TABLE messages DROP COLUMN importance; PRAGMA user_version = 21")
1685
.execute_batch("ALTER TABLE team_layout DROP COLUMN owner; ALTER TABLE team_layout DROP COLUMN add_channel; ALTER TABLE team_layout DROP COLUMN add_private_channel; ALTER TABLE team_layout DROP COLUMN edit_channel; ALTER TABLE team_layout DROP COLUMN delete_channel; ALTER TABLE channel_layout DROP COLUMN substrate_group_id; ALTER TABLE channels DROP COLUMN read_until; DROP TABLE read_horizons; ALTER TABLE messages DROP COLUMN importance; PRAGMA user_version = 21")
1680
1686
.unwrap();
1681
1687
}
1682
1688
let store = Store::open(&path).unwrap();
1683
assert_eq!(store.schema_version().unwrap(), 26);
1689
assert_eq!(store.schema_version().unwrap(), 27);
1684
1690
assert!(store.read_horizons("c").unwrap().is_empty());
1685
1691
let horizons = [
1686
1692
horizon("8:orgid:ada", 3, Some(4)),
@@ -1762,7 +1768,7 @@ fn migration_to_v25_drops_copies_stored_under_a_float_id() {
1762
1768
drop(store);
1763
1769
Connection::open(&path)
1764
1770
.unwrap()
1765
.execute_batch("ALTER TABLE channels DROP COLUMN read_until; PRAGMA user_version = 24")
1771
.execute_batch("ALTER TABLE team_layout DROP COLUMN owner; ALTER TABLE team_layout DROP COLUMN add_channel; ALTER TABLE team_layout DROP COLUMN add_private_channel; ALTER TABLE team_layout DROP COLUMN edit_channel; ALTER TABLE team_layout DROP COLUMN delete_channel; ALTER TABLE channel_layout DROP COLUMN substrate_group_id; ALTER TABLE channels DROP COLUMN read_until; PRAGMA user_version = 24")
1766
1772
.unwrap();
1767
1773
}
1768
1774
let store = Store::open(&path).unwrap();
@@ -1771,3 +1777,31 @@ fn migration_to_v25_drops_copies_stored_under_a_float_id() {
1771
1777
assert_eq!(found.len(), 1);
1772
1778
assert!(found.contains_key("1793871826192"));
1773
1779
}
1780
1781
#[test]
1782
fn team_rights_come_back_with_the_sidebar() {
1783
let store = Store::open_in_memory().unwrap();
1784
store
1785
.upsert_teams(&[TeamRecord {
1786
id: "team".to_owned(),
1787
name: "Team".to_owned(),
1788
}])
1789
.unwrap();
1790
assert_eq!(store.sidebar().unwrap().teams[0].rights, TeamRights::default());
1791
let rights = TeamRights {
1792
owner: false,
1793
add_channel: true,
1794
add_private_channel: true,
1795
edit_channel: false,
1796
delete_channel: true,
1797
};
1798
store
1799
.replace_team_layout(&[TeamLayoutRecord {
1800
team_id: "team".to_owned(),
1801
hidden: false,
1802
rights,
1803
channels: Vec::new(),
1804
}])
1805
.unwrap();
1806
assert_eq!(store.sidebar().unwrap().teams[0].rights, rights);
1807
}
@@ -4,7 +4,7 @@ use store::{4
AvatarRecord, ChannelLayoutRecord, ChannelMentions, ChannelNotificationLevel,4
AvatarRecord, ChannelLayoutRecord, ChannelMentions, ChannelNotificationLevel,5
ChannelNotifications, ChannelReadState, ChannelRecord, ChannelTabRecord, ChatPreview, ChatRecord, FolderRecord,5
ChannelNotifications, ChannelReadState, ChannelRecord, ChannelTabRecord, ChatPreview, ChatRecord, FolderRecord,6
MemberRecord, MessageImportance, MessageRecord, ReadHorizonRecord, RecentScope, Store,6
MemberRecord, MessageImportance, MessageRecord, ReadHorizonRecord, RecentScope, Store,7
SyncState, TeamLayoutRecord, TeamRecord, UNKNOWN_USER_NAME,7
SyncState, TeamLayoutRecord, TeamRecord, TeamRights, UNKNOWN_USER_NAME,8
};8
};9
9
10
#[test]10
#[test]@@ -608,11 +608,11 @@ fn file_database_uses_wal_persists_and_migrates_once() {608
let path = directory.path().join("nested").join("cache.sqlite3");608
let path = directory.path().join("nested").join("cache.sqlite3");609
{609
{610
let store = Store::open(&path).unwrap();610
let store = Store::open(&path).unwrap();611
assert_eq!(store.schema_version().unwrap(), 26);611
assert_eq!(store.schema_version().unwrap(), 27);612
store.upsert_messages(&[message("c", "m1", 1)]).unwrap();612
store.upsert_messages(&[message("c", "m1", 1)]).unwrap();613
}613
}614
let reopened = Store::open(&path).unwrap();614
let reopened = Store::open(&path).unwrap();615
assert_eq!(reopened.schema_version().unwrap(), 26);615
assert_eq!(reopened.schema_version().unwrap(), 27);616
assert_eq!(reopened.message_count("c").unwrap(), 1);616
assert_eq!(reopened.message_count("c").unwrap(), 1);617
drop(reopened);617
drop(reopened);618
let mode: String = rusqlite_open(&path)618
let mode: String = rusqlite_open(&path)@@ -628,7 +628,7 @@ fn newer_schema_is_refused() {628
drop(Store::open(&path).unwrap());628
drop(Store::open(&path).unwrap());629
let connection = rusqlite_open(&path);629
let connection = rusqlite_open(&path);630
connection630
connection631
.execute_batch("PRAGMA user_version = 99")631
.execute_batch("ALTER TABLE team_layout DROP COLUMN owner; ALTER TABLE team_layout DROP COLUMN add_channel; ALTER TABLE team_layout DROP COLUMN add_private_channel; ALTER TABLE team_layout DROP COLUMN edit_channel; ALTER TABLE team_layout DROP COLUMN delete_channel; ALTER TABLE channel_layout DROP COLUMN substrate_group_id; PRAGMA user_version = 99")632
.unwrap();632
.unwrap();633
drop(connection);633
drop(connection);634
let error = Store::open(&path).err().expect("must refuse");634
let error = Store::open(&path).err().expect("must refuse");@@ -641,10 +641,10 @@ fn old_schema_is_upgraded_in_place() {641
let path = directory.path().join("cache.sqlite3");641
let path = directory.path().join("cache.sqlite3");642
drop(Store::open(&path).unwrap());642
drop(Store::open(&path).unwrap());643
let connection = rusqlite_open(&path);643
let connection = rusqlite_open(&path);644
connection.execute_batch("DROP TABLE messages; DROP TABLE sync_state; DROP TABLE chats; DROP TABLE chat_members; DROP TABLE channels; DROP TABLE teams; DROP TABLE meta; DROP TABLE avatars; DROP TABLE folder_items; DROP TABLE folders; DROP TABLE pinned_channels; DROP TABLE images; DROP TABLE search_keys; DROP TABLE message_search; DROP TABLE title_search; DROP TABLE team_layout; DROP TABLE channel_layout; DROP TABLE channel_tabs; DROP TABLE presence; DROP TABLE activity; DROP TABLE outbox; DROP TABLE drafts; DROP TABLE attachment_images; DROP TABLE agent_reaction_proposals; DROP TABLE agent_proposals; PRAGMA user_version = 0").unwrap();644
connection.execute_batch("ALTER TABLE team_layout DROP COLUMN owner; ALTER TABLE team_layout DROP COLUMN add_channel; ALTER TABLE team_layout DROP COLUMN add_private_channel; ALTER TABLE team_layout DROP COLUMN edit_channel; ALTER TABLE team_layout DROP COLUMN delete_channel; ALTER TABLE channel_layout DROP COLUMN substrate_group_id; DROP TABLE messages; DROP TABLE sync_state; DROP TABLE chats; DROP TABLE chat_members; DROP TABLE channels; DROP TABLE teams; DROP TABLE meta; DROP TABLE avatars; DROP TABLE folder_items; DROP TABLE folders; DROP TABLE pinned_channels; DROP TABLE images; DROP TABLE search_keys; DROP TABLE message_search; DROP TABLE title_search; DROP TABLE team_layout; DROP TABLE channel_layout; DROP TABLE channel_tabs; DROP TABLE presence; DROP TABLE activity; DROP TABLE outbox; DROP TABLE drafts; DROP TABLE attachment_images; DROP TABLE agent_reaction_proposals; DROP TABLE agent_proposals; PRAGMA user_version = 0").unwrap();645
drop(connection);645
drop(connection);646
let store = Store::open(&path).unwrap();646
let store = Store::open(&path).unwrap();647
assert_eq!(store.schema_version().unwrap(), 26);647
assert_eq!(store.schema_version().unwrap(), 27);648
store.upsert_messages(&[message("c", "m1", 1)]).unwrap();648
store.upsert_messages(&[message("c", "m1", 1)]).unwrap();649
}649
}650
650
@@ -710,7 +710,7 @@ fn migration_to_v2_keeps_existing_sync_state() {710
let store = Store::open(&path).unwrap();710
let store = Store::open(&path).unwrap();711
let state = store.sync_state("c").unwrap().unwrap();711
let state = store.sync_state("c").unwrap().unwrap();712
assert_eq!(state.delta_link, None);712
assert_eq!(state.delta_link, None);713
assert_eq!(store.schema_version().unwrap(), 26);713
assert_eq!(store.schema_version().unwrap(), 27);714
}714
}715
715
716
#[test]716
#[test]@@ -723,7 +723,7 @@ fn migration_to_v13_clears_channel_delta_links_only() {723
let connection = Connection::open(&path).unwrap();723
let connection = Connection::open(&path).unwrap();724
connection724
connection725
.execute_batch(725
.execute_batch(726
"INSERT INTO teams (id, name) VALUES ('t', 'T');726
"ALTER TABLE team_layout DROP COLUMN owner; ALTER TABLE team_layout DROP COLUMN add_channel; ALTER TABLE team_layout DROP COLUMN add_private_channel; ALTER TABLE team_layout DROP COLUMN edit_channel; ALTER TABLE team_layout DROP COLUMN delete_channel; ALTER TABLE channel_layout DROP COLUMN substrate_group_id; INSERT INTO teams (id, name) VALUES ('t', 'T');727
INSERT INTO channels (id, team_id, name) VALUES ('ch', 't', 'C');727
INSERT INTO channels (id, team_id, name) VALUES ('ch', 't', 'C');728
INSERT INTO sync_state (conversation_id, delta_link) VALUES ('ch', 'link'), ('chat', 'link');728
INSERT INTO sync_state (conversation_id, delta_link) VALUES ('ch', 'link'), ('chat', 'link');729
ALTER TABLE messages DROP COLUMN subject;729
ALTER TABLE messages DROP COLUMN subject;@@ -1019,7 +1019,7 @@ fn migration_indexes_rows_that_predate_search() {1019
let connection = Connection::open(&path).unwrap();1019
let connection = Connection::open(&path).unwrap();1020
connection1020
connection1021
.execute_batch(1021
.execute_batch(1022
"DROP TRIGGER chats_title_insert; DROP TRIGGER chats_title_update; DROP TRIGGER chats_title_delete;1022
"ALTER TABLE team_layout DROP COLUMN owner; ALTER TABLE team_layout DROP COLUMN add_channel; ALTER TABLE team_layout DROP COLUMN add_private_channel; ALTER TABLE team_layout DROP COLUMN edit_channel; ALTER TABLE team_layout DROP COLUMN delete_channel; ALTER TABLE channel_layout DROP COLUMN substrate_group_id; DROP TRIGGER chats_title_insert; DROP TRIGGER chats_title_update; DROP TRIGGER chats_title_delete;1023
DROP TRIGGER channels_title_insert; DROP TRIGGER channels_title_update; DROP TRIGGER channels_title_delete;1023
DROP TRIGGER channels_title_insert; DROP TRIGGER channels_title_update; DROP TRIGGER channels_title_delete;1024
DROP TABLE images; DROP TABLE search_keys; DROP TABLE message_search; DROP TABLE title_search;1024
DROP TABLE images; DROP TABLE search_keys; DROP TABLE message_search; DROP TABLE title_search;1025
DROP TABLE team_layout; DROP TABLE channel_layout; DROP TABLE channel_tabs; DROP TABLE presence; DROP TABLE activity; DROP TABLE outbox; DROP TABLE drafts; DROP TABLE attachment_images; DROP TABLE agent_reaction_proposals; DROP TABLE agent_proposals;1025
DROP TABLE team_layout; DROP TABLE channel_layout; DROP TABLE channel_tabs; DROP TABLE presence; DROP TABLE activity; DROP TABLE outbox; DROP TABLE drafts; DROP TABLE attachment_images; DROP TABLE agent_reaction_proposals; DROP TABLE agent_proposals;@@ -1302,9 +1302,11 @@ fn channel_tabs_keep_their_saved_order_and_are_replaced_on_refresh() {1302
};1302
};1303
let layout = |tabs: Vec<ChannelTabRecord>| {1303
let layout = |tabs: Vec<ChannelTabRecord>| {1304
vec![TeamLayoutRecord {1304
vec![TeamLayoutRecord {1305
rights: Default::default(),1305
team_id: "team".to_owned(),1306
team_id: "team".to_owned(),1306
hidden: false,1307
hidden: false,1307
channels: vec![ChannelLayoutRecord {1308
channels: vec![ChannelLayoutRecord {1309
substrate_group_id: None,1308
channel_id: "channel".to_owned(),1310
channel_id: "channel".to_owned(),1309
general: false,1311
general: false,1310
hidden: false,1312
hidden: false,@@ -1369,9 +1371,11 @@ fn channel_notifications_default_to_feed_and_survive_layout_and_local_writes() {1369
};1371
};1370
store1372
store1371
.replace_team_layout(&[TeamLayoutRecord {1373
.replace_team_layout(&[TeamLayoutRecord {1374
rights: Default::default(),1372
team_id: "t1".to_owned(),1375
team_id: "t1".to_owned(),1373
hidden: false,1376
hidden: false,1374
channels: vec![ChannelLayoutRecord {1377
channels: vec![ChannelLayoutRecord {1378
substrate_group_id: None,1375
channel_id: "c2".to_owned(),1379
channel_id: "c2".to_owned(),1376
general: false,1380
general: false,1377
hidden: false,1381
hidden: false,@@ -1453,9 +1457,11 @@ fn the_team_thread_id_is_the_general_channel_id() {1453
.unwrap();1457
.unwrap();1454
store1458
store1455
.replace_team_layout(&[TeamLayoutRecord {1459
.replace_team_layout(&[TeamLayoutRecord {1460
rights: Default::default(),1456
team_id: "group-b".to_owned(),1461
team_id: "group-b".to_owned(),1457
hidden: false,1462
hidden: false,1458
channels: vec![ChannelLayoutRecord {1463
channels: vec![ChannelLayoutRecord {1464
substrate_group_id: None,1459
channel_id: "19:b-renamed".to_owned(),1465
channel_id: "19:b-renamed".to_owned(),1460
general: true,1466
general: true,1461
hidden: false,1467
hidden: false,@@ -1595,12 +1601,12 @@ fn migration_to_v20_adds_the_call_event_column() {1595
Connection::open(&path)1601
Connection::open(&path)1596
.unwrap()1602
.unwrap()1597
.execute_batch(1603
.execute_batch(1598
"ALTER TABLE channels DROP COLUMN read_until; ALTER TABLE messages DROP COLUMN call_event_json; ALTER TABLE messages DROP COLUMN importance; PRAGMA user_version = 19",1604
"ALTER TABLE team_layout DROP COLUMN owner; ALTER TABLE team_layout DROP COLUMN add_channel; ALTER TABLE team_layout DROP COLUMN add_private_channel; ALTER TABLE team_layout DROP COLUMN edit_channel; ALTER TABLE team_layout DROP COLUMN delete_channel; ALTER TABLE channel_layout DROP COLUMN substrate_group_id; ALTER TABLE channels DROP COLUMN read_until; ALTER TABLE messages DROP COLUMN call_event_json; ALTER TABLE messages DROP COLUMN importance; PRAGMA user_version = 19",1599
)1605
)1600
.unwrap();1606
.unwrap();1601
}1607
}1602
let store = Store::open(&path).unwrap();1608
let store = Store::open(&path).unwrap();1603
assert_eq!(store.schema_version().unwrap(), 26);1609
assert_eq!(store.schema_version().unwrap(), 27);1604
let old = store.messages("c", None, 10).unwrap();1610
let old = store.messages("c", None, 10).unwrap();1605
assert_eq!(old[0].call_event_json, None);1611
assert_eq!(old[0].call_event_json, None);1606
assert!(store.sync_state("c").unwrap().is_none());1612
assert!(store.sync_state("c").unwrap().is_none());@@ -1646,11 +1652,11 @@ fn migration_to_v21_refetches_chats_and_channels_for_recordings() {1646
drop(store);1652
drop(store);1647
Connection::open(&path)1653
Connection::open(&path)1648
.unwrap()1654
.unwrap()1649
.execute_batch("ALTER TABLE channels DROP COLUMN read_until; ALTER TABLE messages DROP COLUMN importance; PRAGMA user_version = 20")1655
.execute_batch("ALTER TABLE team_layout DROP COLUMN owner; ALTER TABLE team_layout DROP COLUMN add_channel; ALTER TABLE team_layout DROP COLUMN add_private_channel; ALTER TABLE team_layout DROP COLUMN edit_channel; ALTER TABLE team_layout DROP COLUMN delete_channel; ALTER TABLE channel_layout DROP COLUMN substrate_group_id; ALTER TABLE channels DROP COLUMN read_until; ALTER TABLE messages DROP COLUMN importance; PRAGMA user_version = 20")1650
.unwrap();1656
.unwrap();1651
}1657
}1652
let store = Store::open(&path).unwrap();1658
let store = Store::open(&path).unwrap();1653
assert_eq!(store.schema_version().unwrap(), 26);1659
assert_eq!(store.schema_version().unwrap(), 27);1654
assert!(store.sync_state("c").unwrap().is_none());1660
assert!(store.sync_state("c").unwrap().is_none());1655
assert!(store.sync_state("channel").unwrap().is_none());1661
assert!(store.sync_state("channel").unwrap().is_none());1656
assert!(store.sync_state("other").unwrap().is_some());1662
assert!(store.sync_state("other").unwrap().is_some());@@ -1676,11 +1682,11 @@ fn migration_to_v22_adds_read_horizons_that_survive_a_reopen() {1676
drop(store);1682
drop(store);1677
Connection::open(&path)1683
Connection::open(&path)1678
.unwrap()1684
.unwrap()1679
.execute_batch("ALTER TABLE channels DROP COLUMN read_until; DROP TABLE read_horizons; ALTER TABLE messages DROP COLUMN importance; PRAGMA user_version = 21")1685
.execute_batch("ALTER TABLE team_layout DROP COLUMN owner; ALTER TABLE team_layout DROP COLUMN add_channel; ALTER TABLE team_layout DROP COLUMN add_private_channel; ALTER TABLE team_layout DROP COLUMN edit_channel; ALTER TABLE team_layout DROP COLUMN delete_channel; ALTER TABLE channel_layout DROP COLUMN substrate_group_id; ALTER TABLE channels DROP COLUMN read_until; DROP TABLE read_horizons; ALTER TABLE messages DROP COLUMN importance; PRAGMA user_version = 21")1680
.unwrap();1686
.unwrap();1681
}1687
}1682
let store = Store::open(&path).unwrap();1688
let store = Store::open(&path).unwrap();1683
assert_eq!(store.schema_version().unwrap(), 26);1689
assert_eq!(store.schema_version().unwrap(), 27);1684
assert!(store.read_horizons("c").unwrap().is_empty());1690
assert!(store.read_horizons("c").unwrap().is_empty());1685
let horizons = [1691
let horizons = [1686
horizon("8:orgid:ada", 3, Some(4)),1692
horizon("8:orgid:ada", 3, Some(4)),@@ -1762,7 +1768,7 @@ fn migration_to_v25_drops_copies_stored_under_a_float_id() {1762
drop(store);1768
drop(store);1763
Connection::open(&path)1769
Connection::open(&path)1764
.unwrap()1770
.unwrap()1765
.execute_batch("ALTER TABLE channels DROP COLUMN read_until; PRAGMA user_version = 24")1771
.execute_batch("ALTER TABLE team_layout DROP COLUMN owner; ALTER TABLE team_layout DROP COLUMN add_channel; ALTER TABLE team_layout DROP COLUMN add_private_channel; ALTER TABLE team_layout DROP COLUMN edit_channel; ALTER TABLE team_layout DROP COLUMN delete_channel; ALTER TABLE channel_layout DROP COLUMN substrate_group_id; ALTER TABLE channels DROP COLUMN read_until; PRAGMA user_version = 24")1766
.unwrap();1772
.unwrap();1767
}1773
}1768
let store = Store::open(&path).unwrap();1774
let store = Store::open(&path).unwrap();@@ -1771,3 +1777,31 @@ fn migration_to_v25_drops_copies_stored_under_a_float_id() {1771
assert_eq!(found.len(), 1);1777
assert_eq!(found.len(), 1);1772
assert!(found.contains_key("1793871826192"));1778
assert!(found.contains_key("1793871826192"));1773
}1779
}1780
1781
#[test]1782
fn team_rights_come_back_with_the_sidebar() {1783
let store = Store::open_in_memory().unwrap();1784
store1785
.upsert_teams(&[TeamRecord {1786
id: "team".to_owned(),1787
name: "Team".to_owned(),1788
}])1789
.unwrap();1790
assert_eq!(store.sidebar().unwrap().teams[0].rights, TeamRights::default());1791
let rights = TeamRights {1792
owner: false,1793
add_channel: true,1794
add_private_channel: true,1795
edit_channel: false,1796
delete_channel: true,1797
};1798
store1799
.replace_team_layout(&[TeamLayoutRecord {1800
team_id: "team".to_owned(),1801
hidden: false,1802
rights,1803
channels: Vec::new(),1804
}])1805
.unwrap();1806
assert_eq!(store.sidebar().unwrap().teams[0].rights, rights);1807
}