feat(channels): per-channel notifications, tab bar with embedded websites, Shared tab
| Before | After | |---|---| | App-local "followed" channels decide alerts | Teams' per-channel setting: banner and activity, activity only, off, include thread replies (right-click > Notifications), synced; bell icons on rows | | No tabs | Tab bar: Posts, Shared, the channel's tabs in saved order, overflow menu | | - | Website tabs embedded on Windows (WebView2, "Open in browser"), browser on Linux; app tabs open their Teams web link (Graph tab webUrl) | | No files view | Shared tab like Teams: In library (breadcrumb, upload, drag and drop, new folder, open in SharePoint) and In messages (files and links from posts) | - Replies in threads you started or replied to still notify when a channel is Off, like Teams. - Fix: file resolve used $select with @microsoft.graph.downloadUrl, which Graph drops; chat file cards and library downloads now get the URL (library reuses the listing URL for 50 min). - Store migrations 0015 (channel tabs) and 0016 (channel notifications). - WebView2 embedding is not yet run on Windows; on any embed failure the tab opens in the browser. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@@ -35,6 +35,7 @@
35
35
**Chats and channels**
36
36
- Teams pin order, chat folders, hidden teams, Muted and Meeting chats sections
37
37
- Channel posts like Teams: one card per post, newest activity on top, last 3 replies, inline reply, new post with a subject, full conversation view
38
- Channel tabs and the Shared tab (library and files from posts), per-channel notifications
38
39
- Chat menu: pin, move to folder, mark as unread, mute, hide, leave
39
40
- Read receipts, typing indicator with faces, presence, unread jump
40
41
- Own status, status message and work location from the avatar menu; profile cards with org chart
@@ -35,6 +35,7 @@35
**Chats and channels**35
**Chats and channels**36
- Teams pin order, chat folders, hidden teams, Muted and Meeting chats sections36
- Teams pin order, chat folders, hidden teams, Muted and Meeting chats sections37
- Channel posts like Teams: one card per post, newest activity on top, last 3 replies, inline reply, new post with a subject, full conversation view37
- Channel posts like Teams: one card per post, newest activity on top, last 3 replies, inline reply, new post with a subject, full conversation view38
- Channel tabs and the Shared tab (library and files from posts), per-channel notifications38
- Chat menu: pin, move to folder, mark as unread, mute, hide, leave39
- Chat menu: pin, move to folder, mark as unread, mute, hide, leave39
- Read receipts, typing indicator with faces, presence, unread jump40
- Read receipts, typing indicator with faces, presence, unread jump40
- Own status, status message and work location from the avatar menu; profile cards with org chart41
- Own status, status message and work location from the avatar menu; profile cards with org chart@@ -2,7 +2,7 @@
2
2
3
3
Feature parity with the Microsoft Teams desktop client.
4
4
5
**Parity: 83 %** (72 done, 1 partial, 14 missing of 87). Partial counts half.
5
**Parity: 87 %** (75 done, 1 partial, 11 missing of 87). Partial counts half.
6
6
7
7
## By area
8
8
@@ -13,7 +13,7 @@ Feature parity with the Microsoft Teams desktop client.
13
13
| [Reading](#reading) | 89 % | 17 | 0 | 2 |
14
14
| [Writing](#writing) | 100 % | 14 | 0 | 0 |
15
15
| [Message actions](#message-actions) | 100 % | 5 | 0 | 0 |
16
| [Channels](#channels) | 57 % | 4 | 0 | 3 |
16
| [Channels](#channels) | 100 % | 7 | 0 | 0 |
17
17
| [Notifications](#notifications) | 88 % | 7 | 0 | 1 |
18
18
| [Search and navigation](#search-and-navigation) | 80 % | 4 | 0 | 1 |
19
19
| [Presence and people](#presence-and-people) | 100 % | 4 | 0 | 0 |
@@ -114,9 +114,9 @@ Feature parity with the Microsoft Teams desktop client.
114
114
| Posts feed, open a conversation, reply | Done | Newest activity on top, inline reply in the card |
115
115
| New post with subject | Done | Subject is stored with the message |
116
116
| Post cards like Teams | Done | One card per post: root and the last 3 replies |
117
| Follow a channel, per-channel notifications | Missing | |
118
| Channel tabs: tab bar, website and app tabs | Missing | Plan: each tab's Teams Web page in a WebView2 |
119
| Files tab | Missing | Plan: native, the channel's SharePoint folder via Graph |
117
| Follow a channel, per-channel notifications | Done | Right-click > Notifications: banner and activity, activity only, off, include thread replies; synced with Teams; bell icons in the sidebar |
118
| Channel tabs: tab bar, website and app tabs | Done | Posts, Shared, then the channel's tabs with overflow; website tabs embedded on Windows (WebView2), browser on Linux; app tabs open in Teams web |
119
| Files tab | Done | "Shared" like Teams: In library (folders, upload, drag and drop, new folder, open in SharePoint) and In messages (files and links from posts) |
120
120
121
121
## Notifications
122
122
@@ -2,7 +2,7 @@2
2
3
Feature parity with the Microsoft Teams desktop client.3
Feature parity with the Microsoft Teams desktop client.4
4
5
**Parity: 83 %** (72 done, 1 partial, 14 missing of 87). Partial counts half.5
**Parity: 87 %** (75 done, 1 partial, 11 missing of 87). Partial counts half.6
6
7
## By area7
## By area8
8
@@ -13,7 +13,7 @@ Feature parity with the Microsoft Teams desktop client.13
| [Reading](#reading) | 89 % | 17 | 0 | 2 |13
| [Reading](#reading) | 89 % | 17 | 0 | 2 |14
| [Writing](#writing) | 100 % | 14 | 0 | 0 |14
| [Writing](#writing) | 100 % | 14 | 0 | 0 |15
| [Message actions](#message-actions) | 100 % | 5 | 0 | 0 |15
| [Message actions](#message-actions) | 100 % | 5 | 0 | 0 |16
| [Channels](#channels) | 57 % | 4 | 0 | 3 |16
| [Channels](#channels) | 100 % | 7 | 0 | 0 |17
| [Notifications](#notifications) | 88 % | 7 | 0 | 1 |17
| [Notifications](#notifications) | 88 % | 7 | 0 | 1 |18
| [Search and navigation](#search-and-navigation) | 80 % | 4 | 0 | 1 |18
| [Search and navigation](#search-and-navigation) | 80 % | 4 | 0 | 1 |19
| [Presence and people](#presence-and-people) | 100 % | 4 | 0 | 0 |19
| [Presence and people](#presence-and-people) | 100 % | 4 | 0 | 0 |@@ -114,9 +114,9 @@ Feature parity with the Microsoft Teams desktop client.114
| Posts feed, open a conversation, reply | Done | Newest activity on top, inline reply in the card |114
| Posts feed, open a conversation, reply | Done | Newest activity on top, inline reply in the card |115
| New post with subject | Done | Subject is stored with the message |115
| New post with subject | Done | Subject is stored with the message |116
| Post cards like Teams | Done | One card per post: root and the last 3 replies |116
| Post cards like Teams | Done | One card per post: root and the last 3 replies |117
| Follow a channel, per-channel notifications | Missing | |117
| Follow a channel, per-channel notifications | Done | Right-click > Notifications: banner and activity, activity only, off, include thread replies; synced with Teams; bell icons in the sidebar |118
| Channel tabs: tab bar, website and app tabs | Missing | Plan: each tab's Teams Web page in a WebView2 |118
| Channel tabs: tab bar, website and app tabs | Done | Posts, Shared, then the channel's tabs with overflow; website tabs embedded on Windows (WebView2), browser on Linux; app tabs open in Teams web |119
| Files tab | Missing | Plan: native, the channel's SharePoint folder via Graph |119
| Files tab | Done | "Shared" like Teams: In library (folders, upload, drag and drop, new folder, open in SharePoint) and In messages (files and links from posts) |120
120
121
## Notifications121
## Notifications122
122
@@ -144,7 +144,6 @@ impl ActivityCenter {
144
144
let found = self.tracker.collect(
145
145
&state.store,
146
146
&state.sidebar,
147
&state.followed_channels,
148
147
my_user_id.as_deref(),
149
148
conversation_id,
150
149
);
@@ -144,7 +144,6 @@ impl ActivityCenter {144
let found = self.tracker.collect(144
let found = self.tracker.collect(145
&state.store,145
&state.store,146
&state.sidebar,146
&state.sidebar,147
&state.followed_channels,148
my_user_id.as_deref(),147
my_user_id.as_deref(),149
conversation_id,148
conversation_id,150
);149
);@@ -17,7 +17,6 @@ use crate::data::{self, Directory};
17
17
use crate::local_previews::{LocalPreview, load_local_previews};
18
18
use crate::message_actions::{ForwardSource, SavedSet};
19
19
use crate::notice::Notice;
20
use crate::notify;
21
20
use crate::profile_state::{ProfileCache, ProfileRequest};
22
21
use crate::typing::TypingState;
23
22
@@ -81,7 +80,6 @@ pub struct AppState {
81
80
pub directory: Directory,
82
81
pub collapsed: HashSet<String>,
83
82
pub expanded_lists: HashSet<String>,
84
pub followed_channels: HashSet<String>,
85
83
pub start_on_channels: bool,
86
84
pub pending_jump: Option<(String, String)>,
87
85
pub cards: CardState,
@@ -165,7 +163,6 @@ impl AppState {
165
163
directory: Directory::default(),
166
164
collapsed: HashSet::new(),
167
165
expanded_lists: HashSet::new(),
168
followed_channels: HashSet::new(),
169
166
start_on_channels: false,
170
167
pending_jump: None,
171
168
cards: CardState::default(),
@@ -192,7 +189,6 @@ impl AppState {
192
189
};
193
190
state.local_previews = load_local_previews(&state.store);
194
191
state.collapsed = state.load_collapsed();
195
state.followed_channels = notify::load_followed_channels(&state.store);
196
192
if !mode.demo {
197
193
state.directory.load_cached_presence(&state.store);
198
194
state.reload_directory();
@@ -215,14 +211,6 @@ impl AppState {
215
211
.unwrap_or_default()
216
212
}
217
213
218
pub fn toggle_followed_channel(&mut self, channel_id: &str, cx: &mut Context<Self>) {
219
if !self.followed_channels.remove(channel_id) {
220
self.followed_channels.insert(channel_id.to_owned());
221
}
222
notify::save_followed_channels(&self.store, &self.followed_channels);
223
cx.notify();
224
}
225
226
214
pub fn toggle_collapsed(&mut self, section_id: &str, cx: &mut Context<Self>) {
227
215
let now_collapsed = self.collapsed.insert(section_id.to_owned());
228
216
if !now_collapsed {
@@ -812,6 +800,7 @@ mod tests {
812
800
}],
813
801
hidden: false,
814
802
hidden_channel_ids: Vec::new(),
803
notifications: Default::default(),
815
804
}],
816
805
}
817
806
}
@@ -17,7 +17,6 @@ use crate::data::{self, Directory};17
use crate::local_previews::{LocalPreview, load_local_previews};17
use crate::local_previews::{LocalPreview, load_local_previews};18
use crate::message_actions::{ForwardSource, SavedSet};18
use crate::message_actions::{ForwardSource, SavedSet};19
use crate::notice::Notice;19
use crate::notice::Notice;20
use crate::notify;21
use crate::profile_state::{ProfileCache, ProfileRequest};20
use crate::profile_state::{ProfileCache, ProfileRequest};22
use crate::typing::TypingState;21
use crate::typing::TypingState;23
22
@@ -81,7 +80,6 @@ pub struct AppState {81
pub directory: Directory,80
pub directory: Directory,82
pub collapsed: HashSet<String>,81
pub collapsed: HashSet<String>,83
pub expanded_lists: HashSet<String>,82
pub expanded_lists: HashSet<String>,84
pub followed_channels: HashSet<String>,85
pub start_on_channels: bool,83
pub start_on_channels: bool,86
pub pending_jump: Option<(String, String)>,84
pub pending_jump: Option<(String, String)>,87
pub cards: CardState,85
pub cards: CardState,@@ -165,7 +163,6 @@ impl AppState {165
directory: Directory::default(),163
directory: Directory::default(),166
collapsed: HashSet::new(),164
collapsed: HashSet::new(),167
expanded_lists: HashSet::new(),165
expanded_lists: HashSet::new(),168
followed_channels: HashSet::new(),169
start_on_channels: false,166
start_on_channels: false,170
pending_jump: None,167
pending_jump: None,171
cards: CardState::default(),168
cards: CardState::default(),@@ -192,7 +189,6 @@ impl AppState {192
};189
};193
state.local_previews = load_local_previews(&state.store);190
state.local_previews = load_local_previews(&state.store);194
state.collapsed = state.load_collapsed();191
state.collapsed = state.load_collapsed();195
state.followed_channels = notify::load_followed_channels(&state.store);196
if !mode.demo {192
if !mode.demo {197
state.directory.load_cached_presence(&state.store);193
state.directory.load_cached_presence(&state.store);198
state.reload_directory();194
state.reload_directory();@@ -215,14 +211,6 @@ impl AppState {215
.unwrap_or_default()211
.unwrap_or_default()216
}212
}217
213
218
pub fn toggle_followed_channel(&mut self, channel_id: &str, cx: &mut Context<Self>) {219
if !self.followed_channels.remove(channel_id) {220
self.followed_channels.insert(channel_id.to_owned());221
}222
notify::save_followed_channels(&self.store, &self.followed_channels);223
cx.notify();224
}225
226
pub fn toggle_collapsed(&mut self, section_id: &str, cx: &mut Context<Self>) {214
pub fn toggle_collapsed(&mut self, section_id: &str, cx: &mut Context<Self>) {227
let now_collapsed = self.collapsed.insert(section_id.to_owned());215
let now_collapsed = self.collapsed.insert(section_id.to_owned());228
if !now_collapsed {216
if !now_collapsed {@@ -812,6 +800,7 @@ mod tests {812
}],800
}],813
hidden: false,801
hidden: false,814
hidden_channel_ids: Vec::new(),802
hidden_channel_ids: Vec::new(),803
notifications: Default::default(),815
}],804
}],816
}805
}817
}806
}@@ -0,0 +1,449 @@
1
use std::collections::HashMap;
2
use std::time::{Duration, Instant};
3
4
use chrono::{DateTime, FixedOffset, NaiveDate, Utc};
5
use store::MessageRecord;
6
use teams_core::{
7
DriveEntry, DriveFolder, FileCard, LibraryFile, files, preview_text, public_links,
8
};
9
10
use crate::format;
11
12
const WEEK_DAYS: i64 = 6;
13
const EXCERPT_WORDS: usize = 6;
14
const DOWNLOAD_URL_LIFETIME: Duration = Duration::from_secs(50 * 60);
15
16
#[derive(Debug, Clone, PartialEq, Eq)]
17
pub enum DownloadSource {
18
Share,
19
Library(LibraryFile),
20
}
21
22
pub fn library_file(entry: &DriveEntry, listed_at: Option<Instant>, now: Instant) -> LibraryFile {
23
let fresh = listed_at
24
.is_some_and(|listed_at| now.saturating_duration_since(listed_at) < DOWNLOAD_URL_LIFETIME);
25
LibraryFile {
26
drive_id: entry.drive_id.clone(),
27
item_id: entry.id.clone(),
28
name: entry.name.clone(),
29
size: entry.size,
30
cached_url: entry.download_url.clone().filter(|_| fresh),
31
}
32
}
33
34
#[derive(Debug, Clone, PartialEq, Eq)]
35
pub struct Crumb {
36
pub name: String,
37
pub folder: DriveFolder,
38
pub web_url: String,
39
}
40
41
#[derive(Debug, Clone, PartialEq, Eq)]
42
pub struct LibraryPath {
43
crumbs: Vec<Crumb>,
44
}
45
46
impl LibraryPath {
47
pub fn new(root: Crumb) -> Self {
48
LibraryPath { crumbs: vec![root] }
49
}
50
51
pub fn crumbs(&self) -> &[Crumb] {
52
&self.crumbs
53
}
54
55
pub fn current(&self) -> &DriveFolder {
56
&self.crumbs[self.crumbs.len() - 1].folder
57
}
58
59
pub fn current_web_url(&self) -> &str {
60
&self.crumbs[self.crumbs.len() - 1].web_url
61
}
62
63
pub fn enter(&mut self, entry: &DriveEntry) {
64
self.crumbs.push(Crumb {
65
name: entry.name.clone(),
66
folder: entry.folder(),
67
web_url: entry.web_url.clone(),
68
});
69
}
70
71
pub fn go_to(&mut self, index: usize) {
72
self.crumbs.truncate(index + 1);
73
}
74
}
75
76
pub fn count_label(child_count: u64) -> String {
77
match child_count {
78
1 => "1 item".to_owned(),
79
count => format!("{count} items"),
80
}
81
}
82
83
pub fn size_label(entry: &DriveEntry) -> String {
84
match entry.child_count {
85
Some(count) => count_label(count),
86
None => format::file_size_label(entry.size),
87
}
88
}
89
90
pub fn sorted_entries(mut entries: Vec<DriveEntry>) -> Vec<DriveEntry> {
91
entries.sort_by_cached_key(|entry| (!entry.is_folder(), entry.name.to_lowercase()));
92
entries
93
}
94
95
pub fn file_card(entry: &DriveEntry) -> FileCard {
96
FileCard {
97
kind: teams_core::FileKind::from_name(&entry.name),
98
name: entry.name.clone(),
99
content_type: None,
100
size: Some(entry.size),
101
open_url: entry.web_url.clone(),
102
}
103
}
104
105
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
106
pub enum MessageFilter {
107
All,
108
Files,
109
Links,
110
}
111
112
#[derive(Debug, Clone, PartialEq, Eq)]
113
pub enum SharedContent {
114
File(FileCard),
115
Link(String),
116
}
117
118
#[derive(Debug, Clone, PartialEq, Eq)]
119
pub struct SharedItem {
120
pub content: SharedContent,
121
pub author: String,
122
pub post_label: String,
123
pub message_id: String,
124
pub created_at: DateTime<Utc>,
125
}
126
127
impl SharedItem {
128
pub fn name(&self) -> &str {
129
match &self.content {
130
SharedContent::File(card) => &card.name,
131
SharedContent::Link(url) => url,
132
}
133
}
134
135
fn matches(&self, filter: MessageFilter) -> bool {
136
matches!(
137
(filter, &self.content),
138
(MessageFilter::All, _)
139
| (MessageFilter::Files, SharedContent::File(_))
140
| (MessageFilter::Links, SharedContent::Link(_))
141
)
142
}
143
}
144
145
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
146
pub enum SharedGroup {
147
ThisWeek,
148
Earlier,
149
}
150
151
impl SharedGroup {
152
pub fn label(self) -> &'static str {
153
match self {
154
SharedGroup::ThisWeek => "This week",
155
SharedGroup::Earlier => "Earlier",
156
}
157
}
158
}
159
160
fn post_label(root: Option<&MessageRecord>) -> String {
161
let Some(root) = root else {
162
return String::new();
163
};
164
if let Some(subject) = root
165
.subject
166
.as_deref()
167
.filter(|subject| !subject.is_empty())
168
{
169
return subject.to_owned();
170
}
171
let text = preview_text(&root.body_html).unwrap_or_default();
172
let words: Vec<&str> = text.split_whitespace().collect();
173
let shown = words[..words.len().min(EXCERPT_WORDS)].join(" ");
174
if words.len() > EXCERPT_WORDS {
175
format!("{shown} ...")
176
} else {
177
shown
178
}
179
}
180
181
pub fn shared_items(records: &[MessageRecord]) -> Vec<SharedItem> {
182
let roots: HashMap<&str, &MessageRecord> = records
183
.iter()
184
.filter(|record| record.reply_to_id.is_none())
185
.map(|record| (record.message_id.as_str(), record))
186
.collect();
187
let mut items = Vec::new();
188
for record in records.iter().filter(|record| !record.deleted) {
189
let root = match record.reply_to_id.as_deref() {
190
Some(root_id) => roots.get(root_id).copied(),
191
None => Some(record),
192
};
193
let label = post_label(root);
194
let author = record.sender_name.clone().unwrap_or_default();
195
let contents = files(record)
196
.into_iter()
197
.map(SharedContent::File)
198
.chain(public_links(record).into_iter().map(SharedContent::Link));
199
items.extend(contents.map(|content| SharedItem {
200
content,
201
author: author.clone(),
202
post_label: label.clone(),
203
message_id: record.message_id.clone(),
204
created_at: record.created_at,
205
}));
206
}
207
items.sort_by_key(|item| std::cmp::Reverse(item.created_at));
208
items
209
}
210
211
pub fn group_of(created_at: DateTime<Utc>, today: NaiveDate, offset: FixedOffset) -> SharedGroup {
212
let day = created_at.with_timezone(&offset).date_naive();
213
if (today - day).num_days() <= WEEK_DAYS {
214
SharedGroup::ThisWeek
215
} else {
216
SharedGroup::Earlier
217
}
218
}
219
220
pub fn grouped_items(
221
items: &[SharedItem],
222
filter: MessageFilter,
223
today: NaiveDate,
224
offset: FixedOffset,
225
) -> Vec<(SharedGroup, Vec<usize>)> {
226
let mut groups: Vec<(SharedGroup, Vec<usize>)> = Vec::new();
227
for (index, item) in items
228
.iter()
229
.enumerate()
230
.filter(|(_, item)| item.matches(filter))
231
{
232
let group = group_of(item.created_at, today, offset);
233
match groups.iter_mut().find(|(known, _)| *known == group) {
234
Some((_, members)) => members.push(index),
235
None => groups.push((group, vec![index])),
236
}
237
}
238
groups.sort_by_key(|(group, _)| *group as u8);
239
groups
240
}
241
242
#[cfg(test)]
243
mod tests {
244
use chrono::TimeZone;
245
246
use super::*;
247
248
fn folder(id: &str) -> DriveFolder {
249
DriveFolder {
250
drive_id: "drive".to_owned(),
251
item_id: id.to_owned(),
252
}
253
}
254
255
fn entry(name: &str, child_count: Option<u64>, size: u64) -> DriveEntry {
256
DriveEntry {
257
drive_id: "drive".to_owned(),
258
id: format!("id-{name}"),
259
name: name.to_owned(),
260
web_url: format!("https://x/{name}"),
261
size,
262
modified_at: None,
263
modified_by: None,
264
child_count,
265
download_url: None,
266
}
267
}
268
269
fn record(id: &str, reply_to: Option<&str>, days_ago: i64, html: &str) -> MessageRecord {
270
MessageRecord {
271
conversation_id: "channel".to_owned(),
272
message_id: id.to_owned(),
273
reply_to_id: reply_to.map(str::to_owned),
274
sender_id: None,
275
sender_name: Some("Mara".to_owned()),
276
created_at: Utc.with_ymd_and_hms(2026, 10, 9, 12, 0, 0).unwrap()
277
- chrono::Duration::days(days_ago),
278
edited_at: None,
279
deleted: false,
280
body_html: html.to_owned(),
281
attachments_json: "[]".to_owned(),
282
reactions_json: "[]".to_owned(),
283
mentions_json: "[]".to_owned(),
284
sender_application_id: None,
285
links_json: "[]".to_owned(),
286
subject: None,
287
}
288
}
289
290
fn with_file(mut record: MessageRecord, name: &str) -> MessageRecord {
291
record.attachments_json = format!(
292
r#"[{{"content_type":"reference","name":"{name}","url":"https://x/{name}","text":null,"size":10}}]"#
293
);
294
record
295
}
296
297
fn today() -> (NaiveDate, FixedOffset) {
298
let offset = FixedOffset::east_opt(0).unwrap();
299
(NaiveDate::from_ymd_opt(2026, 10, 9).unwrap(), offset)
300
}
301
302
#[test]
303
fn a_listed_download_url_is_used_until_it_is_about_to_expire() {
304
let mut listed = entry("a.pdf", None, 5);
305
listed.download_url = Some("https://dl.example/a".to_owned());
306
let start = Instant::now();
307
let url = |age_minutes: u64| {
308
library_file(
309
&listed,
310
Some(start),
311
start + Duration::from_secs(age_minutes * 60),
312
)
313
.cached_url
314
};
315
assert_eq!(url(10).as_deref(), Some("https://dl.example/a"));
316
assert_eq!(url(49).as_deref(), Some("https://dl.example/a"));
317
assert_eq!(url(51), None);
318
assert_eq!(library_file(&listed, None, start).cached_url, None);
319
let without = entry("b.pdf", None, 5);
320
assert_eq!(library_file(&without, Some(start), start).cached_url, None);
321
}
322
323
#[test]
324
fn breadcrumb_path_grows_and_shrinks() {
325
let mut path = LibraryPath::new(Crumb {
326
name: "Channel".to_owned(),
327
folder: folder("root"),
328
web_url: "https://x/root".to_owned(),
329
});
330
path.enter(&entry("Specs", Some(2), 0));
331
path.enter(&entry("2026", Some(0), 0));
332
let names: Vec<&str> = path
333
.crumbs()
334
.iter()
335
.map(|crumb| crumb.name.as_str())
336
.collect();
337
assert_eq!(names, ["Channel", "Specs", "2026"]);
338
assert_eq!(path.current().item_id, "id-2026");
339
path.go_to(1);
340
assert_eq!(path.current().item_id, "id-Specs");
341
path.go_to(0);
342
assert_eq!(path.current(), &folder("root"));
343
assert_eq!(path.current_web_url(), "https://x/root");
344
}
345
346
#[test]
347
fn sizes_and_item_counts_read_like_teams() {
348
assert_eq!(size_label(&entry("a", Some(0), 0)), "0 items");
349
assert_eq!(size_label(&entry("a", Some(1), 0)), "1 item");
350
assert_eq!(size_label(&entry("a", Some(12), 0)), "12 items");
351
assert_eq!(size_label(&entry("a.pdf", None, 48_213)), "47 KB");
352
}
353
354
#[test]
355
fn folders_sort_before_files_by_name() {
356
let sorted = sorted_entries(vec![
357
entry("b.pdf", None, 1),
358
entry("Zeta", Some(0), 0),
359
entry("a.pdf", None, 1),
360
entry("alpha", Some(0), 0),
361
]);
362
let names: Vec<&str> = sorted.iter().map(|entry| entry.name.as_str()).collect();
363
assert_eq!(names, ["alpha", "Zeta", "a.pdf", "b.pdf"]);
364
}
365
366
#[test]
367
fn messages_group_into_this_week_and_earlier() {
368
let records = vec![
369
with_file(record("old", None, 20, "<p>Old plan</p>"), "Old.pdf"),
370
with_file(record("new", None, 1, "<p>New plan</p>"), "New.xlsx"),
371
record(
372
"link",
373
None,
374
2,
375
"<p><a href=\"https://a.example/x\">x</a></p>",
376
),
377
];
378
let items = shared_items(&records);
379
let (day, offset) = today();
380
let groups = grouped_items(&items, MessageFilter::All, day, offset);
381
assert_eq!(groups.len(), 2);
382
assert_eq!(groups[0].0, SharedGroup::ThisWeek);
383
let week: Vec<&str> = groups[0]
384
.1
385
.iter()
386
.map(|index| items[*index].name())
387
.collect();
388
assert_eq!(week, ["New.xlsx", "https://a.example/x"]);
389
assert_eq!(groups[1].0, SharedGroup::Earlier);
390
assert_eq!(items[groups[1].1[0]].name(), "Old.pdf");
391
}
392
393
#[test]
394
fn filter_chips_split_files_from_links() {
395
let records = vec![
396
with_file(record("a", None, 1, "<p>Plan</p>"), "Plan.pdf"),
397
record("b", None, 1, "<p><a href=\"https://a.example\">a</a></p>"),
398
];
399
let items = shared_items(&records);
400
let (day, offset) = today();
401
let count = |filter| -> usize {
402
grouped_items(&items, filter, day, offset)
403
.iter()
404
.map(|(_, members)| members.len())
405
.sum()
406
};
407
assert_eq!(count(MessageFilter::All), 2);
408
assert_eq!(count(MessageFilter::Files), 1);
409
assert_eq!(count(MessageFilter::Links), 1);
410
}
411
412
#[test]
413
fn replies_name_their_post_by_subject_or_first_words() {
414
let mut root = record(
415
"root",
416
None,
417
1,
418
"<p>One two three four five six seven eight</p>",
419
);
420
let reply = with_file(record("reply", Some("root"), 1, "<p>See file</p>"), "A.pdf");
421
let subject_root = {
422
let mut other = record("other", None, 1, "<p>Body</p>");
423
other.subject = Some("Release 42".to_owned());
424
other
425
};
426
let other_reply = with_file(record("r2", Some("other"), 1, "<p>x</p>"), "B.pdf");
427
root.sender_name = Some("Tobias".to_owned());
428
let items = shared_items(&[root, reply, subject_root, other_reply]);
429
let label_of = |name: &str| {
430
items
431
.iter()
432
.find(|item| item.name() == name)
433
.map(|item| item.post_label.clone())
434
};
435
assert_eq!(
436
label_of("A.pdf").as_deref(),
437
Some("One two three four five six ...")
438
);
439
assert_eq!(label_of("B.pdf").as_deref(), Some("Release 42"));
440
assert_eq!(
441
items
442
.iter()
443
.find(|item| item.name() == "A.pdf")
444
.unwrap()
445
.message_id,
446
"reply"
447
);
448
}
449
}
@@ -0,0 +1,449 @@1
use std::collections::HashMap;2
use std::time::{Duration, Instant};3
4
use chrono::{DateTime, FixedOffset, NaiveDate, Utc};5
use store::MessageRecord;6
use teams_core::{7
DriveEntry, DriveFolder, FileCard, LibraryFile, files, preview_text, public_links,8
};9
10
use crate::format;11
12
const WEEK_DAYS: i64 = 6;13
const EXCERPT_WORDS: usize = 6;14
const DOWNLOAD_URL_LIFETIME: Duration = Duration::from_secs(50 * 60);15
16
#[derive(Debug, Clone, PartialEq, Eq)]17
pub enum DownloadSource {18
Share,19
Library(LibraryFile),20
}21
22
pub fn library_file(entry: &DriveEntry, listed_at: Option<Instant>, now: Instant) -> LibraryFile {23
let fresh = listed_at24
.is_some_and(|listed_at| now.saturating_duration_since(listed_at) < DOWNLOAD_URL_LIFETIME);25
LibraryFile {26
drive_id: entry.drive_id.clone(),27
item_id: entry.id.clone(),28
name: entry.name.clone(),29
size: entry.size,30
cached_url: entry.download_url.clone().filter(|_| fresh),31
}32
}33
34
#[derive(Debug, Clone, PartialEq, Eq)]35
pub struct Crumb {36
pub name: String,37
pub folder: DriveFolder,38
pub web_url: String,39
}40
41
#[derive(Debug, Clone, PartialEq, Eq)]42
pub struct LibraryPath {43
crumbs: Vec<Crumb>,44
}45
46
impl LibraryPath {47
pub fn new(root: Crumb) -> Self {48
LibraryPath { crumbs: vec![root] }49
}50
51
pub fn crumbs(&self) -> &[Crumb] {52
&self.crumbs53
}54
55
pub fn current(&self) -> &DriveFolder {56
&self.crumbs[self.crumbs.len() - 1].folder57
}58
59
pub fn current_web_url(&self) -> &str {60
&self.crumbs[self.crumbs.len() - 1].web_url61
}62
63
pub fn enter(&mut self, entry: &DriveEntry) {64
self.crumbs.push(Crumb {65
name: entry.name.clone(),66
folder: entry.folder(),67
web_url: entry.web_url.clone(),68
});69
}70
71
pub fn go_to(&mut self, index: usize) {72
self.crumbs.truncate(index + 1);73
}74
}75
76
pub fn count_label(child_count: u64) -> String {77
match child_count {78
1 => "1 item".to_owned(),79
count => format!("{count} items"),80
}81
}82
83
pub fn size_label(entry: &DriveEntry) -> String {84
match entry.child_count {85
Some(count) => count_label(count),86
None => format::file_size_label(entry.size),87
}88
}89
90
pub fn sorted_entries(mut entries: Vec<DriveEntry>) -> Vec<DriveEntry> {91
entries.sort_by_cached_key(|entry| (!entry.is_folder(), entry.name.to_lowercase()));92
entries93
}94
95
pub fn file_card(entry: &DriveEntry) -> FileCard {96
FileCard {97
kind: teams_core::FileKind::from_name(&entry.name),98
name: entry.name.clone(),99
content_type: None,100
size: Some(entry.size),101
open_url: entry.web_url.clone(),102
}103
}104
105
#[derive(Debug, Clone, Copy, PartialEq, Eq)]106
pub enum MessageFilter {107
All,108
Files,109
Links,110
}111
112
#[derive(Debug, Clone, PartialEq, Eq)]113
pub enum SharedContent {114
File(FileCard),115
Link(String),116
}117
118
#[derive(Debug, Clone, PartialEq, Eq)]119
pub struct SharedItem {120
pub content: SharedContent,121
pub author: String,122
pub post_label: String,123
pub message_id: String,124
pub created_at: DateTime<Utc>,125
}126
127
impl SharedItem {128
pub fn name(&self) -> &str {129
match &self.content {130
SharedContent::File(card) => &card.name,131
SharedContent::Link(url) => url,132
}133
}134
135
fn matches(&self, filter: MessageFilter) -> bool {136
matches!(137
(filter, &self.content),138
(MessageFilter::All, _)139
| (MessageFilter::Files, SharedContent::File(_))140
| (MessageFilter::Links, SharedContent::Link(_))141
)142
}143
}144
145
#[derive(Debug, Clone, Copy, PartialEq, Eq)]146
pub enum SharedGroup {147
ThisWeek,148
Earlier,149
}150
151
impl SharedGroup {152
pub fn label(self) -> &'static str {153
match self {154
SharedGroup::ThisWeek => "This week",155
SharedGroup::Earlier => "Earlier",156
}157
}158
}159
160
fn post_label(root: Option<&MessageRecord>) -> String {161
let Some(root) = root else {162
return String::new();163
};164
if let Some(subject) = root165
.subject166
.as_deref()167
.filter(|subject| !subject.is_empty())168
{169
return subject.to_owned();170
}171
let text = preview_text(&root.body_html).unwrap_or_default();172
let words: Vec<&str> = text.split_whitespace().collect();173
let shown = words[..words.len().min(EXCERPT_WORDS)].join(" ");174
if words.len() > EXCERPT_WORDS {175
format!("{shown} ...")176
} else {177
shown178
}179
}180
181
pub fn shared_items(records: &[MessageRecord]) -> Vec<SharedItem> {182
let roots: HashMap<&str, &MessageRecord> = records183
.iter()184
.filter(|record| record.reply_to_id.is_none())185
.map(|record| (record.message_id.as_str(), record))186
.collect();187
let mut items = Vec::new();188
for record in records.iter().filter(|record| !record.deleted) {189
let root = match record.reply_to_id.as_deref() {190
Some(root_id) => roots.get(root_id).copied(),191
None => Some(record),192
};193
let label = post_label(root);194
let author = record.sender_name.clone().unwrap_or_default();195
let contents = files(record)196
.into_iter()197
.map(SharedContent::File)198
.chain(public_links(record).into_iter().map(SharedContent::Link));199
items.extend(contents.map(|content| SharedItem {200
content,201
author: author.clone(),202
post_label: label.clone(),203
message_id: record.message_id.clone(),204
created_at: record.created_at,205
}));206
}207
items.sort_by_key(|item| std::cmp::Reverse(item.created_at));208
items209
}210
211
pub fn group_of(created_at: DateTime<Utc>, today: NaiveDate, offset: FixedOffset) -> SharedGroup {212
let day = created_at.with_timezone(&offset).date_naive();213
if (today - day).num_days() <= WEEK_DAYS {214
SharedGroup::ThisWeek215
} else {216
SharedGroup::Earlier217
}218
}219
220
pub fn grouped_items(221
items: &[SharedItem],222
filter: MessageFilter,223
today: NaiveDate,224
offset: FixedOffset,225
) -> Vec<(SharedGroup, Vec<usize>)> {226
let mut groups: Vec<(SharedGroup, Vec<usize>)> = Vec::new();227
for (index, item) in items228
.iter()229
.enumerate()230
.filter(|(_, item)| item.matches(filter))231
{232
let group = group_of(item.created_at, today, offset);233
match groups.iter_mut().find(|(known, _)| *known == group) {234
Some((_, members)) => members.push(index),235
None => groups.push((group, vec![index])),236
}237
}238
groups.sort_by_key(|(group, _)| *group as u8);239
groups240
}241
242
#[cfg(test)]243
mod tests {244
use chrono::TimeZone;245
246
use super::*;247
248
fn folder(id: &str) -> DriveFolder {249
DriveFolder {250
drive_id: "drive".to_owned(),251
item_id: id.to_owned(),252
}253
}254
255
fn entry(name: &str, child_count: Option<u64>, size: u64) -> DriveEntry {256
DriveEntry {257
drive_id: "drive".to_owned(),258
id: format!("id-{name}"),259
name: name.to_owned(),260
web_url: format!("https://x/{name}"),261
size,262
modified_at: None,263
modified_by: None,264
child_count,265
download_url: None,266
}267
}268
269
fn record(id: &str, reply_to: Option<&str>, days_ago: i64, html: &str) -> MessageRecord {270
MessageRecord {271
conversation_id: "channel".to_owned(),272
message_id: id.to_owned(),273
reply_to_id: reply_to.map(str::to_owned),274
sender_id: None,275
sender_name: Some("Mara".to_owned()),276
created_at: Utc.with_ymd_and_hms(2026, 10, 9, 12, 0, 0).unwrap()277
- chrono::Duration::days(days_ago),278
edited_at: None,279
deleted: false,280
body_html: html.to_owned(),281
attachments_json: "[]".to_owned(),282
reactions_json: "[]".to_owned(),283
mentions_json: "[]".to_owned(),284
sender_application_id: None,285
links_json: "[]".to_owned(),286
subject: None,287
}288
}289
290
fn with_file(mut record: MessageRecord, name: &str) -> MessageRecord {291
record.attachments_json = format!(292
r#"[{{"content_type":"reference","name":"{name}","url":"https://x/{name}","text":null,"size":10}}]"#293
);294
record295
}296
297
fn today() -> (NaiveDate, FixedOffset) {298
let offset = FixedOffset::east_opt(0).unwrap();299
(NaiveDate::from_ymd_opt(2026, 10, 9).unwrap(), offset)300
}301
302
#[test]303
fn a_listed_download_url_is_used_until_it_is_about_to_expire() {304
let mut listed = entry("a.pdf", None, 5);305
listed.download_url = Some("https://dl.example/a".to_owned());306
let start = Instant::now();307
let url = |age_minutes: u64| {308
library_file(309
&listed,310
Some(start),311
start + Duration::from_secs(age_minutes * 60),312
)313
.cached_url314
};315
assert_eq!(url(10).as_deref(), Some("https://dl.example/a"));316
assert_eq!(url(49).as_deref(), Some("https://dl.example/a"));317
assert_eq!(url(51), None);318
assert_eq!(library_file(&listed, None, start).cached_url, None);319
let without = entry("b.pdf", None, 5);320
assert_eq!(library_file(&without, Some(start), start).cached_url, None);321
}322
323
#[test]324
fn breadcrumb_path_grows_and_shrinks() {325
let mut path = LibraryPath::new(Crumb {326
name: "Channel".to_owned(),327
folder: folder("root"),328
web_url: "https://x/root".to_owned(),329
});330
path.enter(&entry("Specs", Some(2), 0));331
path.enter(&entry("2026", Some(0), 0));332
let names: Vec<&str> = path333
.crumbs()334
.iter()335
.map(|crumb| crumb.name.as_str())336
.collect();337
assert_eq!(names, ["Channel", "Specs", "2026"]);338
assert_eq!(path.current().item_id, "id-2026");339
path.go_to(1);340
assert_eq!(path.current().item_id, "id-Specs");341
path.go_to(0);342
assert_eq!(path.current(), &folder("root"));343
assert_eq!(path.current_web_url(), "https://x/root");344
}345
346
#[test]347
fn sizes_and_item_counts_read_like_teams() {348
assert_eq!(size_label(&entry("a", Some(0), 0)), "0 items");349
assert_eq!(size_label(&entry("a", Some(1), 0)), "1 item");350
assert_eq!(size_label(&entry("a", Some(12), 0)), "12 items");351
assert_eq!(size_label(&entry("a.pdf", None, 48_213)), "47 KB");352
}353
354
#[test]355
fn folders_sort_before_files_by_name() {356
let sorted = sorted_entries(vec![357
entry("b.pdf", None, 1),358
entry("Zeta", Some(0), 0),359
entry("a.pdf", None, 1),360
entry("alpha", Some(0), 0),361
]);362
let names: Vec<&str> = sorted.iter().map(|entry| entry.name.as_str()).collect();363
assert_eq!(names, ["alpha", "Zeta", "a.pdf", "b.pdf"]);364
}365
366
#[test]367
fn messages_group_into_this_week_and_earlier() {368
let records = vec![369
with_file(record("old", None, 20, "<p>Old plan</p>"), "Old.pdf"),370
with_file(record("new", None, 1, "<p>New plan</p>"), "New.xlsx"),371
record(372
"link",373
None,374
2,375
"<p><a href=\"https://a.example/x\">x</a></p>",376
),377
];378
let items = shared_items(&records);379
let (day, offset) = today();380
let groups = grouped_items(&items, MessageFilter::All, day, offset);381
assert_eq!(groups.len(), 2);382
assert_eq!(groups[0].0, SharedGroup::ThisWeek);383
let week: Vec<&str> = groups[0]384
.1385
.iter()386
.map(|index| items[*index].name())387
.collect();388
assert_eq!(week, ["New.xlsx", "https://a.example/x"]);389
assert_eq!(groups[1].0, SharedGroup::Earlier);390
assert_eq!(items[groups[1].1[0]].name(), "Old.pdf");391
}392
393
#[test]394
fn filter_chips_split_files_from_links() {395
let records = vec![396
with_file(record("a", None, 1, "<p>Plan</p>"), "Plan.pdf"),397
record("b", None, 1, "<p><a href=\"https://a.example\">a</a></p>"),398
];399
let items = shared_items(&records);400
let (day, offset) = today();401
let count = |filter| -> usize {402
grouped_items(&items, filter, day, offset)403
.iter()404
.map(|(_, members)| members.len())405
.sum()406
};407
assert_eq!(count(MessageFilter::All), 2);408
assert_eq!(count(MessageFilter::Files), 1);409
assert_eq!(count(MessageFilter::Links), 1);410
}411
412
#[test]413
fn replies_name_their_post_by_subject_or_first_words() {414
let mut root = record(415
"root",416
None,417
1,418
"<p>One two three four five six seven eight</p>",419
);420
let reply = with_file(record("reply", Some("root"), 1, "<p>See file</p>"), "A.pdf");421
let subject_root = {422
let mut other = record("other", None, 1, "<p>Body</p>");423
other.subject = Some("Release 42".to_owned());424
other425
};426
let other_reply = with_file(record("r2", Some("other"), 1, "<p>x</p>"), "B.pdf");427
root.sender_name = Some("Tobias".to_owned());428
let items = shared_items(&[root, reply, subject_root, other_reply]);429
let label_of = |name: &str| {430
items431
.iter()432
.find(|item| item.name() == name)433
.map(|item| item.post_label.clone())434
};435
assert_eq!(436
label_of("A.pdf").as_deref(),437
Some("One two three four five six ...")438
);439
assert_eq!(label_of("B.pdf").as_deref(), Some("Release 42"));440
assert_eq!(441
items442
.iter()443
.find(|item| item.name() == "A.pdf")444
.unwrap()445
.message_id,446
"reply"447
);448
}449
}@@ -2,7 +2,7 @@ use std::future::Future;
2
2
3
3
use chrono::{DateTime, Duration, Local, Offset, Utc};
4
4
use gpui_kit::*;
5
use store::ChatRecord;
5
use store::{ChannelNotifications, ChatRecord};
6
6
7
7
use crate::app_state::{AppState, Selection, chat_title};
8
8
use crate::notice::{NoticeAction, short_error, truncated};
@@ -93,6 +93,55 @@ impl AppState {
93
93
);
94
94
}
95
95
96
pub fn set_channel_notifications(
97
&mut self,
98
channel_id: &str,
99
notifications: ChannelNotifications,
100
cx: &mut Context<Self>,
101
) {
102
let Some(previous) = self.channel_notifications(channel_id) else {
103
return;
104
};
105
if previous == notifications {
106
return;
107
}
108
let Some(engine_or_demo) = self.chat_action_engine(cx) else {
109
return;
110
};
111
let _ = self
112
.store
113
.set_channel_notifications(channel_id, notifications);
114
self.reload_sidebar(cx);
115
let Some(engine) = engine_or_demo else {
116
return;
117
};
118
let owned_id = channel_id.to_owned();
119
let revert_id = owned_id.clone();
120
self.run_chat_action(
121
"Change notifications",
122
async move {
123
engine
124
.set_channel_notifications(&owned_id, notifications)
125
.await
126
},
127
move |state, cx| {
128
let _ = state.store.set_channel_notifications(&revert_id, previous);
129
state.reload_sidebar(cx);
130
},
131
|_, _| {},
132
cx,
133
);
134
}
135
136
pub fn channel_notifications(&self, channel_id: &str) -> Option<ChannelNotifications> {
137
self.sidebar.teams.iter().find_map(|team| {
138
team.channels
139
.iter()
140
.any(|channel| channel.id == channel_id)
141
.then(|| team.channel_notifications(channel_id))
142
})
143
}
144
96
145
pub fn hide_chat(&mut self, chat_id: &str, cx: &mut Context<Self>) {
97
146
let Some(chat) = self.chat_record(chat_id) else {
98
147
return;
@@ -2,7 +2,7 @@ use std::future::Future;2
2
3
use chrono::{DateTime, Duration, Local, Offset, Utc};3
use chrono::{DateTime, Duration, Local, Offset, Utc};4
use gpui_kit::*;4
use gpui_kit::*;5
use store::ChatRecord;5
use store::{ChannelNotifications, ChatRecord};6
6
7
use crate::app_state::{AppState, Selection, chat_title};7
use crate::app_state::{AppState, Selection, chat_title};8
use crate::notice::{NoticeAction, short_error, truncated};8
use crate::notice::{NoticeAction, short_error, truncated};@@ -93,6 +93,55 @@ impl AppState {93
);93
);94
}94
}95
95
96
pub fn set_channel_notifications(97
&mut self,98
channel_id: &str,99
notifications: ChannelNotifications,100
cx: &mut Context<Self>,101
) {102
let Some(previous) = self.channel_notifications(channel_id) else {103
return;104
};105
if previous == notifications {106
return;107
}108
let Some(engine_or_demo) = self.chat_action_engine(cx) else {109
return;110
};111
let _ = self112
.store113
.set_channel_notifications(channel_id, notifications);114
self.reload_sidebar(cx);115
let Some(engine) = engine_or_demo else {116
return;117
};118
let owned_id = channel_id.to_owned();119
let revert_id = owned_id.clone();120
self.run_chat_action(121
"Change notifications",122
async move {123
engine124
.set_channel_notifications(&owned_id, notifications)125
.await126
},127
move |state, cx| {128
let _ = state.store.set_channel_notifications(&revert_id, previous);129
state.reload_sidebar(cx);130
},131
|_, _| {},132
cx,133
);134
}135
136
pub fn channel_notifications(&self, channel_id: &str) -> Option<ChannelNotifications> {137
self.sidebar.teams.iter().find_map(|team| {138
team.channels139
.iter()140
.any(|channel| channel.id == channel_id)141
.then(|| team.channel_notifications(channel_id))142
})143
}144
96
pub fn hide_chat(&mut self, chat_id: &str, cx: &mut Context<Self>) {145
pub fn hide_chat(&mut self, chat_id: &str, cx: &mut Context<Self>) {97
let Some(chat) = self.chat_record(chat_id) else {146
let Some(chat) = self.chat_record(chat_id) else {98
return;147
return;@@ -5,8 +5,8 @@ use std::time::Instant;
5
5
use chrono::{DateTime, Duration, Local, TimeZone, Utc};
6
6
use gpui_kit::Image;
7
7
use store::{
8
ChannelLayoutRecord, ChannelRecord, ChatRecord, MemberRecord, MessageRecord, Store,
9
TeamLayoutRecord, TeamRecord,
8
ChannelLayoutRecord, ChannelNotificationLevel, ChannelNotifications, ChannelRecord,
9
ChannelTabRecord, ChatRecord, MemberRecord, MessageRecord, Store, TeamLayoutRecord, TeamRecord,
10
10
};
11
11
use teams_core::{
12
12
CardActionOutcome, ChatApp, ChatSection, Gif, LinkPreview, MentionCandidate, PersonCandidate,
@@ -127,6 +127,20 @@ const DEMO_TEAMS: [(&str, &str, [&str; 3]); 4] = [
127
127
const DEMO_TEAM_ORDER: [&str; 4] = ["demo-team-2", "demo-team-1", "demo-team-3", "demo-team-4"];
128
128
const DEMO_HIDDEN_TEAM: &str = "demo-team-4";
129
129
const DEMO_HIDDEN_CHANNEL: &str = "demo-channel-3-3";
130
const DEMO_CHANNEL_NOTIFICATIONS: [(&str, ChannelNotificationLevel, bool); 4] = [
131
(
132
"demo-channel-1-1",
133
ChannelNotificationLevel::BannerAndFeed,
134
false,
135
),
136
(
137
"demo-channel-1-2",
138
ChannelNotificationLevel::BannerAndFeed,
139
true,
140
),
141
("demo-channel-1-3", ChannelNotificationLevel::Off, false),
142
("demo-channel-2-2", ChannelNotificationLevel::Off, false),
143
];
130
144
131
145
const UNREAD_CHAT: &str = "demo-chat-atlas";
132
146
const RELEASE_CHAT: &str = "demo-chat-release";
@@ -1415,6 +1429,64 @@ fn unread_messages() -> Vec<MessageRecord> {
1415
1429
.collect()
1416
1430
}
1417
1431
1432
const DEMO_EXTRA_TABS_CHANNEL: &str = "demo-channel-1-2";
1433
const DEMO_EXTRA_TABS: [&str; 6] = [
1434
"Incident dashboard",
1435
"Postmortems",
1436
"Escalation policy",
1437
"Status page",
1438
"Vendor contacts",
1439
"On-call calendar",
1440
];
1441
1442
fn demo_tab(
1443
channel_id: &str,
1444
name: &str,
1445
definition_id: &str,
1446
open_url: Option<&str>,
1447
) -> ChannelTabRecord {
1448
ChannelTabRecord {
1449
tab_id: format!("{channel_id}-{}", name.to_lowercase().replace(' ', "-")),
1450
name: name.to_owned(),
1451
definition_id: definition_id.to_owned(),
1452
open_url: open_url.map(str::to_owned),
1453
}
1454
}
1455
1456
fn demo_channel_tabs(channel_id: &str) -> Vec<ChannelTabRecord> {
1457
let mut tabs = vec![
1458
demo_tab(
1459
channel_id,
1460
"Runbook",
1461
"com.microsoft.teamspace.tab.web",
1462
Some("https://wiki.example.com/display/TEAM/Runbook"),
1463
),
1464
demo_tab(
1465
channel_id,
1466
"Sprint board",
1467
"com.microsoft.teamspace.tab.planner",
1468
None,
1469
),
1470
demo_tab(
1471
channel_id,
1472
"Team notes",
1473
"0d820ecd-def2-4297-adad-78056cde7c78",
1474
Some("https://onenote.example.com/notes"),
1475
),
1476
];
1477
if channel_id == DEMO_EXTRA_TABS_CHANNEL {
1478
tabs.extend(DEMO_EXTRA_TABS.iter().map(|name| {
1479
demo_tab(
1480
channel_id,
1481
name,
1482
"com.microsoft.teamspace.tab.web",
1483
Some("https://wiki.example.com/display/TEAM/Page"),
1484
)
1485
}));
1486
}
1487
tabs
1488
}
1489
1418
1490
fn demo_team_layout(channels: &[ChannelRecord]) -> Vec<TeamLayoutRecord> {
1419
1491
DEMO_TEAM_ORDER
1420
1492
.iter()
@@ -1428,6 +1500,15 @@ fn demo_team_layout(channels: &[ChannelRecord]) -> Vec<TeamLayoutRecord> {
1428
1500
channel_id: channel.id.clone(),
1429
1501
general: channel.name == "General",
1430
1502
hidden: channel.id == DEMO_HIDDEN_CHANNEL,
1503
tabs: demo_channel_tabs(&channel.id),
1504
notifications: DEMO_CHANNEL_NOTIFICATIONS
1505
.iter()
1506
.find(|(id, _, _)| *id == channel.id)
1507
.map(|(_, level, include_replies)| ChannelNotifications {
1508
level: *level,
1509
include_replies: *include_replies,
1510
})
1511
.unwrap_or_default(),
1431
1512
})
1432
1513
.collect(),
1433
1514
})
@@ -1545,9 +1626,82 @@ fn channel_messages() -> Vec<MessageRecord> {
1545
1626
),
1546
1627
];
1547
1628
records.extend(rollout_replies);
1629
records.extend(shared_channel_messages(channel, mara, tobias));
1548
1630
records
1549
1631
}
1550
1632
1633
fn shared_channel_messages(
1634
channel: &str,
1635
mara: (&str, &str),
1636
tobias: (&str, &str),
1637
) -> Vec<MessageRecord> {
1638
let priya = (PRIYA_ID, "Priya Nair");
1639
let jonas = (JONAS_ID, "Jonas Ortega");
1640
let reference = |name: &str, size: u64| {
1641
format!(
1642
r#"{{"content_type":"reference","name":"{name}","url":"https://demo.sharepoint.example/sites/demo/{name}","text":null,"size":{size}}}"#
1643
)
1644
};
1645
vec![
1646
with_attachments(
1647
with_subject(
1648
message(
1649
channel,
1650
"t5",
1651
None,
1652
priya,
1653
at(1, 14, 5),
1654
"<p>Roadmap deck and checklist for Q4 are attached.</p>",
1655
"[]",
1656
false,
1657
),
1658
"Q4 planning files",
1659
),
1660
&format!(
1661
"[{},{}]",
1662
reference("Roadmap-Q4.pptx", 3_412_000),
1663
reference("Release-Checklist-Q4.xlsx", 48_213)
1664
),
1665
),
1666
message(
1667
channel,
1668
"t5r1",
1669
Some("t5"),
1670
jonas,
1671
at(1, 14, 30),
1672
"<p>Rollback steps are here: <a href=\"https://docs.example.org/runbooks/rollback\">https://docs.example.org/runbooks/rollback</a></p>",
1673
"[]",
1674
false,
1675
),
1676
with_attachments(
1677
message(
1678
channel,
1679
"t6",
1680
None,
1681
mara,
1682
at(12, 10, 0),
1683
"<p>Postmortem draft for the September outage. Status page: <a href=\"https://status.example.com/incidents/2026-09\">https://status.example.com/incidents/2026-09</a></p>",
1684
"[]",
1685
false,
1686
),
1687
&format!("[{}]", reference("Postmortem-Draft.docx", 91_400)),
1688
),
1689
with_attachments(
1690
message(
1691
channel,
1692
"t7",
1693
None,
1694
tobias,
1695
at(20, 9, 0),
1696
"<p>Rollout plan for the new export, please review.</p>",
1697
"[]",
1698
false,
1699
),
1700
&format!("[{}]", reference("Rollout-Plan.pdf", 2_306_867)),
1701
),
1702
]
1703
}
1704
1551
1705
fn crc32(bytes: &[u8]) -> u32 {
1552
1706
let mut crc = 0xffff_ffffu32;
1553
1707
for byte in bytes {
@@ -5,8 +5,8 @@ use std::time::Instant;5
use chrono::{DateTime, Duration, Local, TimeZone, Utc};5
use chrono::{DateTime, Duration, Local, TimeZone, Utc};6
use gpui_kit::Image;6
use gpui_kit::Image;7
use store::{7
use store::{8
ChannelLayoutRecord, ChannelRecord, ChatRecord, MemberRecord, MessageRecord, Store,8
ChannelLayoutRecord, ChannelNotificationLevel, ChannelNotifications, ChannelRecord,9
TeamLayoutRecord, TeamRecord,9
ChannelTabRecord, ChatRecord, MemberRecord, MessageRecord, Store, TeamLayoutRecord, TeamRecord,10
};10
};11
use teams_core::{11
use teams_core::{12
CardActionOutcome, ChatApp, ChatSection, Gif, LinkPreview, MentionCandidate, PersonCandidate,12
CardActionOutcome, ChatApp, ChatSection, Gif, LinkPreview, MentionCandidate, PersonCandidate,@@ -127,6 +127,20 @@ const DEMO_TEAMS: [(&str, &str, [&str; 3]); 4] = [127
const DEMO_TEAM_ORDER: [&str; 4] = ["demo-team-2", "demo-team-1", "demo-team-3", "demo-team-4"];127
const DEMO_TEAM_ORDER: [&str; 4] = ["demo-team-2", "demo-team-1", "demo-team-3", "demo-team-4"];128
const DEMO_HIDDEN_TEAM: &str = "demo-team-4";128
const DEMO_HIDDEN_TEAM: &str = "demo-team-4";129
const DEMO_HIDDEN_CHANNEL: &str = "demo-channel-3-3";129
const DEMO_HIDDEN_CHANNEL: &str = "demo-channel-3-3";130
const DEMO_CHANNEL_NOTIFICATIONS: [(&str, ChannelNotificationLevel, bool); 4] = [131
(132
"demo-channel-1-1",133
ChannelNotificationLevel::BannerAndFeed,134
false,135
),136
(137
"demo-channel-1-2",138
ChannelNotificationLevel::BannerAndFeed,139
true,140
),141
("demo-channel-1-3", ChannelNotificationLevel::Off, false),142
("demo-channel-2-2", ChannelNotificationLevel::Off, false),143
];130
144
131
const UNREAD_CHAT: &str = "demo-chat-atlas";145
const UNREAD_CHAT: &str = "demo-chat-atlas";132
const RELEASE_CHAT: &str = "demo-chat-release";146
const RELEASE_CHAT: &str = "demo-chat-release";@@ -1415,6 +1429,64 @@ fn unread_messages() -> Vec<MessageRecord> {1415
.collect()1429
.collect()1416
}1430
}1417
1431
1432
const DEMO_EXTRA_TABS_CHANNEL: &str = "demo-channel-1-2";1433
const DEMO_EXTRA_TABS: [&str; 6] = [1434
"Incident dashboard",1435
"Postmortems",1436
"Escalation policy",1437
"Status page",1438
"Vendor contacts",1439
"On-call calendar",1440
];1441
1442
fn demo_tab(1443
channel_id: &str,1444
name: &str,1445
definition_id: &str,1446
open_url: Option<&str>,1447
) -> ChannelTabRecord {1448
ChannelTabRecord {1449
tab_id: format!("{channel_id}-{}", name.to_lowercase().replace(' ', "-")),1450
name: name.to_owned(),1451
definition_id: definition_id.to_owned(),1452
open_url: open_url.map(str::to_owned),1453
}1454
}1455
1456
fn demo_channel_tabs(channel_id: &str) -> Vec<ChannelTabRecord> {1457
let mut tabs = vec![1458
demo_tab(1459
channel_id,1460
"Runbook",1461
"com.microsoft.teamspace.tab.web",1462
Some("https://wiki.example.com/display/TEAM/Runbook"),1463
),1464
demo_tab(1465
channel_id,1466
"Sprint board",1467
"com.microsoft.teamspace.tab.planner",1468
None,1469
),1470
demo_tab(1471
channel_id,1472
"Team notes",1473
"0d820ecd-def2-4297-adad-78056cde7c78",1474
Some("https://onenote.example.com/notes"),1475
),1476
];1477
if channel_id == DEMO_EXTRA_TABS_CHANNEL {1478
tabs.extend(DEMO_EXTRA_TABS.iter().map(|name| {1479
demo_tab(1480
channel_id,1481
name,1482
"com.microsoft.teamspace.tab.web",1483
Some("https://wiki.example.com/display/TEAM/Page"),1484
)1485
}));1486
}1487
tabs1488
}1489
1418
fn demo_team_layout(channels: &[ChannelRecord]) -> Vec<TeamLayoutRecord> {1490
fn demo_team_layout(channels: &[ChannelRecord]) -> Vec<TeamLayoutRecord> {1419
DEMO_TEAM_ORDER1491
DEMO_TEAM_ORDER1420
.iter()1492
.iter()@@ -1428,6 +1500,15 @@ fn demo_team_layout(channels: &[ChannelRecord]) -> Vec<TeamLayoutRecord> {1428
channel_id: channel.id.clone(),1500
channel_id: channel.id.clone(),1429
general: channel.name == "General",1501
general: channel.name == "General",1430
hidden: channel.id == DEMO_HIDDEN_CHANNEL,1502
hidden: channel.id == DEMO_HIDDEN_CHANNEL,1503
tabs: demo_channel_tabs(&channel.id),1504
notifications: DEMO_CHANNEL_NOTIFICATIONS1505
.iter()1506
.find(|(id, _, _)| *id == channel.id)1507
.map(|(_, level, include_replies)| ChannelNotifications {1508
level: *level,1509
include_replies: *include_replies,1510
})1511
.unwrap_or_default(),1431
})1512
})1432
.collect(),1513
.collect(),1433
})1514
})@@ -1545,9 +1626,82 @@ fn channel_messages() -> Vec<MessageRecord> {1545
),1626
),1546
];1627
];1547
records.extend(rollout_replies);1628
records.extend(rollout_replies);1629
records.extend(shared_channel_messages(channel, mara, tobias));1548
records1630
records1549
}1631
}1550
1632
1633
fn shared_channel_messages(1634
channel: &str,1635
mara: (&str, &str),1636
tobias: (&str, &str),1637
) -> Vec<MessageRecord> {1638
let priya = (PRIYA_ID, "Priya Nair");1639
let jonas = (JONAS_ID, "Jonas Ortega");1640
let reference = |name: &str, size: u64| {1641
format!(1642
r#"{{"content_type":"reference","name":"{name}","url":"https://demo.sharepoint.example/sites/demo/{name}","text":null,"size":{size}}}"#1643
)1644
};1645
vec![1646
with_attachments(1647
with_subject(1648
message(1649
channel,1650
"t5",1651
None,1652
priya,1653
at(1, 14, 5),1654
"<p>Roadmap deck and checklist for Q4 are attached.</p>",1655
"[]",1656
false,1657
),1658
"Q4 planning files",1659
),1660
&format!(1661
"[{},{}]",1662
reference("Roadmap-Q4.pptx", 3_412_000),1663
reference("Release-Checklist-Q4.xlsx", 48_213)1664
),1665
),1666
message(1667
channel,1668
"t5r1",1669
Some("t5"),1670
jonas,1671
at(1, 14, 30),1672
"<p>Rollback steps are here: <a href=\"https://docs.example.org/runbooks/rollback\">https://docs.example.org/runbooks/rollback</a></p>",1673
"[]",1674
false,1675
),1676
with_attachments(1677
message(1678
channel,1679
"t6",1680
None,1681
mara,1682
at(12, 10, 0),1683
"<p>Postmortem draft for the September outage. Status page: <a href=\"https://status.example.com/incidents/2026-09\">https://status.example.com/incidents/2026-09</a></p>",1684
"[]",1685
false,1686
),1687
&format!("[{}]", reference("Postmortem-Draft.docx", 91_400)),1688
),1689
with_attachments(1690
message(1691
channel,1692
"t7",1693
None,1694
tobias,1695
at(20, 9, 0),1696
"<p>Rollout plan for the new export, please review.</p>",1697
"[]",1698
false,1699
),1700
&format!("[{}]", reference("Rollout-Plan.pdf", 2_306_867)),1701
),1702
]1703
}1704
1551
fn crc32(bytes: &[u8]) -> u32 {1705
fn crc32(bytes: &[u8]) -> u32 {1552
let mut crc = 0xffff_ffffu32;1706
let mut crc = 0xffff_ffffu32;1553
for byte in bytes {1707
for byte in bytes {@@ -0,0 +1,173 @@
1
use std::collections::HashMap;
2
3
use chrono::{Duration, Utc};
4
use teams_core::DriveEntry;
5
6
const DEMO_SITE: &str = "https://demo.sharepoint.example/sites/demo";
7
const AUTHORS: [&str; 4] = [
8
"Mara Lindqvist",
9
"Jonas Ortega",
10
"Priya Nair",
11
"Tobias Klein",
12
];
13
const ROOT_FILES: [(&str, u64); 5] = [
14
("Roadmap-Q4.pptx", 3_412_000),
15
("Release-Checklist-Q4.xlsx", 48_213),
16
("Rollout-Plan.pdf", 2_306_867),
17
("Postmortem-Draft.docx", 91_400),
18
("Screenshots.zip", 12_880_000),
19
];
20
const SPEC_FILES: [(&str, u64); 2] = [("API-Design.pdf", 812_000), ("Data-model.xlsx", 64_300)];
21
const NOTE_FILES: [(&str, u64); 2] = [
22
("Weekly-sync-notes.docx", 38_900),
23
("Retro-2026-10.pdf", 205_000),
24
];
25
const YEAR_FILES: [(&str, u64); 1] = [("Settings-spec-v3.docx", 120_500)];
26
27
#[derive(Default)]
28
pub struct DemoLibrary {
29
children: HashMap<String, Vec<DriveEntry>>,
30
next_id: u64,
31
}
32
33
impl DemoLibrary {
34
pub fn root(&mut self, channel_id: &str, channel_name: &str) -> DriveEntry {
35
let root_id = format!("{channel_id}-root");
36
if !self.children.contains_key(&root_id) {
37
self.fill(&root_id);
38
}
39
self.entry(&root_id, channel_name, Some(0), 0)
40
}
41
42
pub fn children(&self, folder_id: &str) -> Vec<DriveEntry> {
43
self.children
44
.get(folder_id)
45
.map(|entries| {
46
entries
47
.iter()
48
.map(|entry| DriveEntry {
49
child_count: entry.child_count.map(|_| {
50
self.children
51
.get(&entry.id)
52
.map_or(0, |inner| inner.len() as u64)
53
}),
54
..entry.clone()
55
})
56
.collect()
57
})
58
.unwrap_or_default()
59
}
60
61
pub fn create_folder(&mut self, parent_id: &str, name: &str) -> DriveEntry {
62
let mut name = name.to_owned();
63
let taken = |library: &Self, name: &str| {
64
library.children.get(parent_id).is_some_and(|entries| {
65
entries
66
.iter()
67
.any(|entry| entry.name.eq_ignore_ascii_case(name))
68
})
69
};
70
let base = name.clone();
71
let mut number = 1;
72
while taken(self, &name) {
73
number += 1;
74
name = format!("{base} {number}");
75
}
76
let id = self.new_id(parent_id);
77
let entry = self.entry(&id, &name, Some(0), 0);
78
self.children
79
.entry(parent_id.to_owned())
80
.or_default()
81
.push(entry.clone());
82
self.children.insert(id, Vec::new());
83
entry
84
}
85
86
pub fn add_file(&mut self, parent_id: &str, name: &str, size: u64) -> DriveEntry {
87
let id = self.new_id(parent_id);
88
let entry = self.entry(&id, name, None, size);
89
self.children
90
.entry(parent_id.to_owned())
91
.or_default()
92
.push(entry.clone());
93
entry
94
}
95
96
fn new_id(&mut self, parent_id: &str) -> String {
97
self.next_id += 1;
98
format!("{parent_id}-{}", self.next_id)
99
}
100
101
fn entry(&self, id: &str, name: &str, child_count: Option<u64>, size: u64) -> DriveEntry {
102
let age = Duration::hours(3 + (id.len() as i64 * 37) % 400);
103
DriveEntry {
104
drive_id: "demo-drive".to_owned(),
105
id: id.to_owned(),
106
name: name.to_owned(),
107
web_url: format!("{DEMO_SITE}/{id}/{name}"),
108
size,
109
modified_at: Some(Utc::now() - age),
110
modified_by: Some(AUTHORS[id.len() % AUTHORS.len()].to_owned()),
111
child_count,
112
download_url: None,
113
}
114
}
115
116
fn fill(&mut self, root_id: &str) {
117
let specs = format!("{root_id}-specs");
118
let notes = format!("{root_id}-notes");
119
let year = format!("{specs}-2026");
120
let spec_folder = self.entry(&specs, "Specs", Some(0), 0);
121
let note_folder = self.entry(¬es, "Meeting notes", Some(0), 0);
122
let year_folder = self.entry(&year, "2026", Some(0), 0);
123
let files = |library: &Self, parent: &str, list: &[(&str, u64)]| -> Vec<DriveEntry> {
124
list.iter()
125
.map(|(name, size)| library.entry(&format!("{parent}-{name}"), name, None, *size))
126
.collect()
127
};
128
let mut root = vec![spec_folder, note_folder];
129
root.extend(files(self, root_id, &ROOT_FILES));
130
let mut spec_children = vec![year_folder];
131
spec_children.extend(files(self, &specs, &SPEC_FILES));
132
let note_children = files(self, ¬es, &NOTE_FILES);
133
let year_children = files(self, &year, &YEAR_FILES);
134
self.children.insert(root_id.to_owned(), root);
135
self.children.insert(specs, spec_children);
136
self.children.insert(notes, note_children);
137
self.children.insert(year, year_children);
138
}
139
}
140
141
#[cfg(test)]
142
mod tests {
143
use super::*;
144
145
#[test]
146
fn the_demo_library_has_folders_files_and_a_nested_folder() {
147
let mut library = DemoLibrary::default();
148
let root = library.root("demo-channel-1-1", "General");
149
let entries = library.children(&root.id);
150
assert_eq!(entries.iter().filter(|entry| entry.is_folder()).count(), 2);
151
assert_eq!(entries.iter().filter(|entry| !entry.is_folder()).count(), 5);
152
let specs = entries.iter().find(|entry| entry.name == "Specs").unwrap();
153
assert_eq!(specs.child_count, Some(3));
154
let inner = library.children(&specs.id);
155
assert!(
156
inner
157
.iter()
158
.any(|entry| entry.is_folder() && entry.child_count == Some(1))
159
);
160
}
161
162
#[test]
163
fn new_folders_get_a_free_name_and_uploads_show_up() {
164
let mut library = DemoLibrary::default();
165
let root = library.root("demo-channel-1-1", "General");
166
let first = library.create_folder(&root.id, "Specs");
167
assert_eq!(first.name, "Specs 2");
168
library.add_file(&first.id, "a.pdf", 10);
169
let listed = library.children(&root.id);
170
let created = listed.iter().find(|entry| entry.id == first.id).unwrap();
171
assert_eq!(created.child_count, Some(1));
172
}
173
}
@@ -0,0 +1,173 @@1
use std::collections::HashMap;2
3
use chrono::{Duration, Utc};4
use teams_core::DriveEntry;5
6
const DEMO_SITE: &str = "https://demo.sharepoint.example/sites/demo";7
const AUTHORS: [&str; 4] = [8
"Mara Lindqvist",9
"Jonas Ortega",10
"Priya Nair",11
"Tobias Klein",12
];13
const ROOT_FILES: [(&str, u64); 5] = [14
("Roadmap-Q4.pptx", 3_412_000),15
("Release-Checklist-Q4.xlsx", 48_213),16
("Rollout-Plan.pdf", 2_306_867),17
("Postmortem-Draft.docx", 91_400),18
("Screenshots.zip", 12_880_000),19
];20
const SPEC_FILES: [(&str, u64); 2] = [("API-Design.pdf", 812_000), ("Data-model.xlsx", 64_300)];21
const NOTE_FILES: [(&str, u64); 2] = [22
("Weekly-sync-notes.docx", 38_900),23
("Retro-2026-10.pdf", 205_000),24
];25
const YEAR_FILES: [(&str, u64); 1] = [("Settings-spec-v3.docx", 120_500)];26
27
#[derive(Default)]28
pub struct DemoLibrary {29
children: HashMap<String, Vec<DriveEntry>>,30
next_id: u64,31
}32
33
impl DemoLibrary {34
pub fn root(&mut self, channel_id: &str, channel_name: &str) -> DriveEntry {35
let root_id = format!("{channel_id}-root");36
if !self.children.contains_key(&root_id) {37
self.fill(&root_id);38
}39
self.entry(&root_id, channel_name, Some(0), 0)40
}41
42
pub fn children(&self, folder_id: &str) -> Vec<DriveEntry> {43
self.children44
.get(folder_id)45
.map(|entries| {46
entries47
.iter()48
.map(|entry| DriveEntry {49
child_count: entry.child_count.map(|_| {50
self.children51
.get(&entry.id)52
.map_or(0, |inner| inner.len() as u64)53
}),54
..entry.clone()55
})56
.collect()57
})58
.unwrap_or_default()59
}60
61
pub fn create_folder(&mut self, parent_id: &str, name: &str) -> DriveEntry {62
let mut name = name.to_owned();63
let taken = |library: &Self, name: &str| {64
library.children.get(parent_id).is_some_and(|entries| {65
entries66
.iter()67
.any(|entry| entry.name.eq_ignore_ascii_case(name))68
})69
};70
let base = name.clone();71
let mut number = 1;72
while taken(self, &name) {73
number += 1;74
name = format!("{base} {number}");75
}76
let id = self.new_id(parent_id);77
let entry = self.entry(&id, &name, Some(0), 0);78
self.children79
.entry(parent_id.to_owned())80
.or_default()81
.push(entry.clone());82
self.children.insert(id, Vec::new());83
entry84
}85
86
pub fn add_file(&mut self, parent_id: &str, name: &str, size: u64) -> DriveEntry {87
let id = self.new_id(parent_id);88
let entry = self.entry(&id, name, None, size);89
self.children90
.entry(parent_id.to_owned())91
.or_default()92
.push(entry.clone());93
entry94
}95
96
fn new_id(&mut self, parent_id: &str) -> String {97
self.next_id += 1;98
format!("{parent_id}-{}", self.next_id)99
}100
101
fn entry(&self, id: &str, name: &str, child_count: Option<u64>, size: u64) -> DriveEntry {102
let age = Duration::hours(3 + (id.len() as i64 * 37) % 400);103
DriveEntry {104
drive_id: "demo-drive".to_owned(),105
id: id.to_owned(),106
name: name.to_owned(),107
web_url: format!("{DEMO_SITE}/{id}/{name}"),108
size,109
modified_at: Some(Utc::now() - age),110
modified_by: Some(AUTHORS[id.len() % AUTHORS.len()].to_owned()),111
child_count,112
download_url: None,113
}114
}115
116
fn fill(&mut self, root_id: &str) {117
let specs = format!("{root_id}-specs");118
let notes = format!("{root_id}-notes");119
let year = format!("{specs}-2026");120
let spec_folder = self.entry(&specs, "Specs", Some(0), 0);121
let note_folder = self.entry(¬es, "Meeting notes", Some(0), 0);122
let year_folder = self.entry(&year, "2026", Some(0), 0);123
let files = |library: &Self, parent: &str, list: &[(&str, u64)]| -> Vec<DriveEntry> {124
list.iter()125
.map(|(name, size)| library.entry(&format!("{parent}-{name}"), name, None, *size))126
.collect()127
};128
let mut root = vec![spec_folder, note_folder];129
root.extend(files(self, root_id, &ROOT_FILES));130
let mut spec_children = vec![year_folder];131
spec_children.extend(files(self, &specs, &SPEC_FILES));132
let note_children = files(self, ¬es, &NOTE_FILES);133
let year_children = files(self, &year, &YEAR_FILES);134
self.children.insert(root_id.to_owned(), root);135
self.children.insert(specs, spec_children);136
self.children.insert(notes, note_children);137
self.children.insert(year, year_children);138
}139
}140
141
#[cfg(test)]142
mod tests {143
use super::*;144
145
#[test]146
fn the_demo_library_has_folders_files_and_a_nested_folder() {147
let mut library = DemoLibrary::default();148
let root = library.root("demo-channel-1-1", "General");149
let entries = library.children(&root.id);150
assert_eq!(entries.iter().filter(|entry| entry.is_folder()).count(), 2);151
assert_eq!(entries.iter().filter(|entry| !entry.is_folder()).count(), 5);152
let specs = entries.iter().find(|entry| entry.name == "Specs").unwrap();153
assert_eq!(specs.child_count, Some(3));154
let inner = library.children(&specs.id);155
assert!(156
inner157
.iter()158
.any(|entry| entry.is_folder() && entry.child_count == Some(1))159
);160
}161
162
#[test]163
fn new_folders_get_a_free_name_and_uploads_show_up() {164
let mut library = DemoLibrary::default();165
let root = library.root("demo-channel-1-1", "General");166
let first = library.create_folder(&root.id, "Specs");167
assert_eq!(first.name, "Specs 2");168
library.add_file(&first.id, "a.pdf", 10);169
let listed = library.children(&root.id);170
let created = listed.iter().find(|entry| entry.id == first.id).unwrap();171
assert_eq!(created.child_count, Some(1));172
}173
}@@ -0,0 +1,216 @@
1
use gpui_kit::component::{
2
button::{Button, ButtonVariants as _},
3
h_flex, v_flex,
4
};
5
use gpui_kit::*;
6
use tokio::sync::mpsc::UnboundedReceiver;
7
8
use crate::theme;
9
10
#[cfg(windows)]
11
mod native_windows;
12
#[cfg(windows)]
13
use native_windows as native;
14
#[cfg(not(windows))]
15
mod native_stub;
16
#[cfg(not(windows))]
17
use native_stub as native;
18
19
pub use native::{Native, NativeEvent, available};
20
21
const BAR_HEIGHT: f32 = 28.;
22
const BAR_TEXT_SIZE: f32 = 11.5;
23
const OPEN_LABEL: &str = "Open in browser \u{2197}";
24
25
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
26
pub struct Overlays {
27
pub panels: bool,
28
pub tab_menu: bool,
29
}
30
31
impl Global for Overlays {}
32
33
impl Overlays {
34
pub fn read(cx: &App) -> Self {
35
cx.try_global::<Overlays>().copied().unwrap_or_default()
36
}
37
38
pub fn update(cx: &mut App, change: impl FnOnce(&mut Overlays)) {
39
let mut next = Overlays::read(cx);
40
change(&mut next);
41
if next != Overlays::read(cx) {
42
cx.set_global(next);
43
}
44
}
45
46
pub fn any(self) -> bool {
47
self.panels || self.tab_menu
48
}
49
}
50
51
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
52
pub struct Visibility {
53
pub overlays: Overlays,
54
pub has_area: bool,
55
}
56
57
pub fn embed_visible(visibility: Visibility) -> bool {
58
visibility.has_area && !visibility.overlays.any()
59
}
60
61
pub fn url_bar_text(url: &str) -> String {
62
let shown = url.strip_prefix("https://").unwrap_or(url);
63
shown.strip_suffix('/').unwrap_or(shown).to_owned()
64
}
65
66
pub enum EmbeddedWebEvent {
67
Closed { start_url: String },
68
}
69
70
pub struct EmbeddedWeb {
71
tab_id: String,
72
start_url: String,
73
url: String,
74
native: Native,
75
_events: Task<()>,
76
}
77
78
impl EventEmitter<EmbeddedWebEvent> for EmbeddedWeb {}
79
80
impl EmbeddedWeb {
81
pub fn new(
82
tab_id: String,
83
start_url: String,
84
native: Native,
85
mut events: UnboundedReceiver<NativeEvent>,
86
cx: &mut Context<Self>,
87
) -> Self {
88
let task = cx.spawn(async move |this, cx| {
89
while let Some(event) = events.recv().await {
90
let handled = this.update(cx, |this, cx| this.on_event(event, cx));
91
if handled.is_err() {
92
break;
93
}
94
}
95
});
96
EmbeddedWeb {
97
tab_id,
98
url: start_url.clone(),
99
start_url,
100
native,
101
_events: task,
102
}
103
}
104
105
pub fn tab_id(&self) -> &str {
106
&self.tab_id
107
}
108
109
fn on_event(&mut self, event: NativeEvent, cx: &mut Context<Self>) {
110
match event {
111
NativeEvent::Navigated(url) => {
112
self.url = url;
113
cx.notify();
114
}
115
NativeEvent::NewWindow(url) => cx.open_url(&url),
116
NativeEvent::Closed => cx.emit(EmbeddedWebEvent::Closed {
117
start_url: self.start_url.clone(),
118
}),
119
}
120
}
121
}
122
123
impl Drop for EmbeddedWeb {
124
fn drop(&mut self) {
125
self.native.close();
126
}
127
}
128
129
impl Render for EmbeddedWeb {
130
fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
131
let native = self.native.clone();
132
let open_url = self.url.clone();
133
v_flex()
134
.size_full()
135
.child(
136
h_flex()
137
.h(px(BAR_HEIGHT))
138
.flex_none()
139
.w_full()
140
.px(px(12.))
141
.gap(px(8.))
142
.items_center()
143
.border_b_1()
144
.border_color(theme::border())
145
.child(
146
div()
147
.flex_1()
148
.min_w_0()
149
.overflow_hidden()
150
.text_ellipsis()
151
.whitespace_nowrap()
152
.text_size(px(BAR_TEXT_SIZE))
153
.text_color(theme::text_muted())
154
.child(url_bar_text(&self.url)),
155
)
156
.child(
157
Button::new("embedded-web-open")
158
.ghost()
159
.compact()
160
.label(OPEN_LABEL)
161
.on_click(move |_, _, cx| cx.open_url(&open_url)),
162
),
163
)
164
.child(
165
div()
166
.flex_1()
167
.min_h_0()
168
.w_full()
169
.bg(theme::background())
170
.child(
171
canvas(
172
move |bounds, window, cx| {
173
let visible = embed_visible(Visibility {
174
overlays: Overlays::read(cx),
175
has_area: bounds.size.width > px(0.)
176
&& bounds.size.height > px(0.),
177
});
178
native.place(bounds, window.scale_factor(), visible);
179
},
180
|_, _, _, _| {},
181
)
182
.size_full(),
183
),
184
)
185
}
186
}
187
188
#[cfg(test)]
189
mod tests {
190
use super::{Overlays, Visibility, embed_visible, url_bar_text};
191
192
fn visibility(panels: bool, tab_menu: bool, has_area: bool) -> Visibility {
193
Visibility {
194
overlays: Overlays { panels, tab_menu },
195
has_area,
196
}
197
}
198
199
#[test]
200
fn the_page_shows_only_without_overlays_and_with_room() {
201
assert!(embed_visible(visibility(false, false, true)));
202
assert!(!embed_visible(visibility(true, false, true)));
203
assert!(!embed_visible(visibility(false, true, true)));
204
assert!(!embed_visible(visibility(false, false, false)));
205
}
206
207
#[test]
208
fn the_url_bar_drops_the_scheme_and_a_trailing_slash() {
209
assert_eq!(url_bar_text("https://docs.example/"), "docs.example");
210
assert_eq!(
211
url_bar_text("https://docs.example/a/b?c=1"),
212
"docs.example/a/b?c=1"
213
);
214
assert_eq!(url_bar_text("http://plain.example"), "http://plain.example");
215
}
216
}
@@ -0,0 +1,216 @@1
use gpui_kit::component::{2
button::{Button, ButtonVariants as _},3
h_flex, v_flex,4
};5
use gpui_kit::*;6
use tokio::sync::mpsc::UnboundedReceiver;7
8
use crate::theme;9
10
#[cfg(windows)]11
mod native_windows;12
#[cfg(windows)]13
use native_windows as native;14
#[cfg(not(windows))]15
mod native_stub;16
#[cfg(not(windows))]17
use native_stub as native;18
19
pub use native::{Native, NativeEvent, available};20
21
const BAR_HEIGHT: f32 = 28.;22
const BAR_TEXT_SIZE: f32 = 11.5;23
const OPEN_LABEL: &str = "Open in browser \u{2197}";24
25
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]26
pub struct Overlays {27
pub panels: bool,28
pub tab_menu: bool,29
}30
31
impl Global for Overlays {}32
33
impl Overlays {34
pub fn read(cx: &App) -> Self {35
cx.try_global::<Overlays>().copied().unwrap_or_default()36
}37
38
pub fn update(cx: &mut App, change: impl FnOnce(&mut Overlays)) {39
let mut next = Overlays::read(cx);40
change(&mut next);41
if next != Overlays::read(cx) {42
cx.set_global(next);43
}44
}45
46
pub fn any(self) -> bool {47
self.panels || self.tab_menu48
}49
}50
51
#[derive(Debug, Clone, Copy, PartialEq, Eq)]52
pub struct Visibility {53
pub overlays: Overlays,54
pub has_area: bool,55
}56
57
pub fn embed_visible(visibility: Visibility) -> bool {58
visibility.has_area && !visibility.overlays.any()59
}60
61
pub fn url_bar_text(url: &str) -> String {62
let shown = url.strip_prefix("https://").unwrap_or(url);63
shown.strip_suffix('/').unwrap_or(shown).to_owned()64
}65
66
pub enum EmbeddedWebEvent {67
Closed { start_url: String },68
}69
70
pub struct EmbeddedWeb {71
tab_id: String,72
start_url: String,73
url: String,74
native: Native,75
_events: Task<()>,76
}77
78
impl EventEmitter<EmbeddedWebEvent> for EmbeddedWeb {}79
80
impl EmbeddedWeb {81
pub fn new(82
tab_id: String,83
start_url: String,84
native: Native,85
mut events: UnboundedReceiver<NativeEvent>,86
cx: &mut Context<Self>,87
) -> Self {88
let task = cx.spawn(async move |this, cx| {89
while let Some(event) = events.recv().await {90
let handled = this.update(cx, |this, cx| this.on_event(event, cx));91
if handled.is_err() {92
break;93
}94
}95
});96
EmbeddedWeb {97
tab_id,98
url: start_url.clone(),99
start_url,100
native,101
_events: task,102
}103
}104
105
pub fn tab_id(&self) -> &str {106
&self.tab_id107
}108
109
fn on_event(&mut self, event: NativeEvent, cx: &mut Context<Self>) {110
match event {111
NativeEvent::Navigated(url) => {112
self.url = url;113
cx.notify();114
}115
NativeEvent::NewWindow(url) => cx.open_url(&url),116
NativeEvent::Closed => cx.emit(EmbeddedWebEvent::Closed {117
start_url: self.start_url.clone(),118
}),119
}120
}121
}122
123
impl Drop for EmbeddedWeb {124
fn drop(&mut self) {125
self.native.close();126
}127
}128
129
impl Render for EmbeddedWeb {130
fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {131
let native = self.native.clone();132
let open_url = self.url.clone();133
v_flex()134
.size_full()135
.child(136
h_flex()137
.h(px(BAR_HEIGHT))138
.flex_none()139
.w_full()140
.px(px(12.))141
.gap(px(8.))142
.items_center()143
.border_b_1()144
.border_color(theme::border())145
.child(146
div()147
.flex_1()148
.min_w_0()149
.overflow_hidden()150
.text_ellipsis()151
.whitespace_nowrap()152
.text_size(px(BAR_TEXT_SIZE))153
.text_color(theme::text_muted())154
.child(url_bar_text(&self.url)),155
)156
.child(157
Button::new("embedded-web-open")158
.ghost()159
.compact()160
.label(OPEN_LABEL)161
.on_click(move |_, _, cx| cx.open_url(&open_url)),162
),163
)164
.child(165
div()166
.flex_1()167
.min_h_0()168
.w_full()169
.bg(theme::background())170
.child(171
canvas(172
move |bounds, window, cx| {173
let visible = embed_visible(Visibility {174
overlays: Overlays::read(cx),175
has_area: bounds.size.width > px(0.)176
&& bounds.size.height > px(0.),177
});178
native.place(bounds, window.scale_factor(), visible);179
},180
|_, _, _, _| {},181
)182
.size_full(),183
),184
)185
}186
}187
188
#[cfg(test)]189
mod tests {190
use super::{Overlays, Visibility, embed_visible, url_bar_text};191
192
fn visibility(panels: bool, tab_menu: bool, has_area: bool) -> Visibility {193
Visibility {194
overlays: Overlays { panels, tab_menu },195
has_area,196
}197
}198
199
#[test]200
fn the_page_shows_only_without_overlays_and_with_room() {201
assert!(embed_visible(visibility(false, false, true)));202
assert!(!embed_visible(visibility(true, false, true)));203
assert!(!embed_visible(visibility(false, true, true)));204
assert!(!embed_visible(visibility(false, false, false)));205
}206
207
#[test]208
fn the_url_bar_drops_the_scheme_and_a_trailing_slash() {209
assert_eq!(url_bar_text("https://docs.example/"), "docs.example");210
assert_eq!(211
url_bar_text("https://docs.example/a/b?c=1"),212
"docs.example/a/b?c=1"213
);214
assert_eq!(url_bar_text("http://plain.example"), "http://plain.example");215
}216
}@@ -0,0 +1,27 @@
1
#![allow(dead_code)]
2
3
use gpui_kit::*;
4
use tokio::sync::mpsc::UnboundedReceiver;
5
6
pub enum NativeEvent {
7
Navigated(String),
8
NewWindow(String),
9
Closed,
10
}
11
12
pub fn available() -> bool {
13
false
14
}
15
16
#[derive(Clone)]
17
pub struct Native;
18
19
impl Native {
20
pub fn open(_url: &str, _window: &Window) -> Option<(Native, UnboundedReceiver<NativeEvent>)> {
21
None
22
}
23
24
pub fn place(&self, _bounds: Bounds<Pixels>, _scale: f32, _visible: bool) {}
25
26
pub fn close(&self) {}
27
}
@@ -0,0 +1,27 @@1
#![allow(dead_code)]2
3
use gpui_kit::*;4
use tokio::sync::mpsc::UnboundedReceiver;5
6
pub enum NativeEvent {7
Navigated(String),8
NewWindow(String),9
Closed,10
}11
12
pub fn available() -> bool {13
false14
}15
16
#[derive(Clone)]17
pub struct Native;18
19
impl Native {20
pub fn open(_url: &str, _window: &Window) -> Option<(Native, UnboundedReceiver<NativeEvent>)> {21
None22
}23
24
pub fn place(&self, _bounds: Bounds<Pixels>, _scale: f32, _visible: bool) {}25
26
pub fn close(&self) {}27
}@@ -0,0 +1,60 @@
1
use std::cell::Cell;
2
use std::rc::Rc;
3
4
use gpui_kit::*;
5
use tokio::sync::mpsc::UnboundedReceiver;
6
use webview::{EmbedBounds, EmbedHandle, EmbedSpec};
7
8
use crate::{notify, task_dialog, theme};
9
10
pub use webview::EmbedEvent as NativeEvent;
11
12
pub fn available() -> bool {
13
task_dialog::host().is_some()
14
}
15
16
#[derive(Clone)]
17
pub struct Native {
18
handle: EmbedHandle,
19
placed: Rc<Cell<Option<(EmbedBounds, bool)>>>,
20
}
21
22
impl Native {
23
pub fn open(url: &str, window: &Window) -> Option<(Native, UnboundedReceiver<NativeEvent>)> {
24
let host = task_dialog::host()?;
25
let parent = notify::native_handle(window)?;
26
let (handle, events) = host.open_embed(EmbedSpec {
27
parent,
28
url: url.to_owned(),
29
background: theme::BACKGROUND,
30
});
31
let native = Native {
32
handle,
33
placed: Rc::new(Cell::new(None)),
34
};
35
Some((native, events))
36
}
37
38
pub fn place(&self, bounds: Bounds<Pixels>, scale: f32, visible: bool) {
39
let physical = |value: Pixels| (f32::from(value) * scale).round() as i32;
40
let placement = (
41
EmbedBounds {
42
x: physical(bounds.origin.x),
43
y: physical(bounds.origin.y),
44
width: physical(bounds.size.width),
45
height: physical(bounds.size.height),
46
},
47
visible,
48
);
49
if self.placed.get() == Some(placement) {
50
return;
51
}
52
self.placed.set(Some(placement));
53
self.handle.set_bounds(placement.0);
54
self.handle.set_visible(placement.1);
55
}
56
57
pub fn close(&self) {
58
self.handle.close();
59
}
60
}
@@ -0,0 +1,60 @@1
use std::cell::Cell;2
use std::rc::Rc;3
4
use gpui_kit::*;5
use tokio::sync::mpsc::UnboundedReceiver;6
use webview::{EmbedBounds, EmbedHandle, EmbedSpec};7
8
use crate::{notify, task_dialog, theme};9
10
pub use webview::EmbedEvent as NativeEvent;11
12
pub fn available() -> bool {13
task_dialog::host().is_some()14
}15
16
#[derive(Clone)]17
pub struct Native {18
handle: EmbedHandle,19
placed: Rc<Cell<Option<(EmbedBounds, bool)>>>,20
}21
22
impl Native {23
pub fn open(url: &str, window: &Window) -> Option<(Native, UnboundedReceiver<NativeEvent>)> {24
let host = task_dialog::host()?;25
let parent = notify::native_handle(window)?;26
let (handle, events) = host.open_embed(EmbedSpec {27
parent,28
url: url.to_owned(),29
background: theme::BACKGROUND,30
});31
let native = Native {32
handle,33
placed: Rc::new(Cell::new(None)),34
};35
Some((native, events))36
}37
38
pub fn place(&self, bounds: Bounds<Pixels>, scale: f32, visible: bool) {39
let physical = |value: Pixels| (f32::from(value) * scale).round() as i32;40
let placement = (41
EmbedBounds {42
x: physical(bounds.origin.x),43
y: physical(bounds.origin.y),44
width: physical(bounds.size.width),45
height: physical(bounds.size.height),46
},47
visible,48
);49
if self.placed.get() == Some(placement) {50
return;51
}52
self.placed.set(Some(placement));53
self.handle.set_bounds(placement.0);54
self.handle.set_visible(placement.1);55
}56
57
pub fn close(&self) {58
self.handle.close();59
}60
}@@ -14,14 +14,17 @@ mod chat_actions;
14
14
mod crash_log;
15
15
mod card_refresh;
16
16
mod card_state;
17
mod channel_files;
17
18
mod data;
18
19
mod demo;
19
20
mod demo_cards;
20
21
mod demo_chart_cards;
21
22
mod demo_gifs;
22
23
mod demo_input_cards;
24
mod demo_library;
23
25
mod demo_profiles;
24
26
mod downloads;
27
mod embedded_web;
25
28
mod emoji;
26
29
mod format;
27
30
mod frame_log;
@@ -14,14 +14,17 @@ mod chat_actions;14
mod crash_log;14
mod crash_log;15
mod card_refresh;15
mod card_refresh;16
mod card_state;16
mod card_state;17
mod channel_files;17
mod data;18
mod data;18
mod demo;19
mod demo;19
mod demo_cards;20
mod demo_cards;20
mod demo_chart_cards;21
mod demo_chart_cards;21
mod demo_gifs;22
mod demo_gifs;22
mod demo_input_cards;23
mod demo_input_cards;24
mod demo_library;23
mod demo_profiles;25
mod demo_profiles;24
mod downloads;26
mod downloads;27
mod embedded_web;25
mod emoji;28
mod emoji;26
mod format;29
mod format;27
mod frame_log;30
mod frame_log;@@ -199,7 +199,6 @@ impl NotificationCenter {
199
199
let found = self.tracker.collect(
200
200
&state.store,
201
201
&state.sidebar,
202
&state.followed_channels,
203
202
my_user_id.as_deref(),
204
203
conversation_id,
205
204
);
@@ -975,6 +974,7 @@ mod tests {
975
974
}],
976
975
hidden: false,
977
976
hidden_channel_ids: Vec::new(),
977
notifications: Default::default(),
978
978
}],
979
979
}
980
980
}
@@ -199,7 +199,6 @@ impl NotificationCenter {199
let found = self.tracker.collect(199
let found = self.tracker.collect(200
&state.store,200
&state.store,201
&state.sidebar,201
&state.sidebar,202
&state.followed_channels,203
my_user_id.as_deref(),202
my_user_id.as_deref(),204
conversation_id,203
conversation_id,205
);204
);@@ -975,6 +974,7 @@ mod tests {975
}],974
}],976
hidden: false,975
hidden: false,977
hidden_channel_ids: Vec::new(),976
hidden_channel_ids: Vec::new(),977
notifications: Default::default(),978
}],978
}],979
}979
}980
}980
}@@ -1,50 +0,0 @@
1
use std::collections::HashSet;
2
3
use store::Store;
4
5
const META_KEY: &str = "notifications.followed_channels";
6
7
pub fn load(store: &Store) -> HashSet<String> {
8
store
9
.meta(META_KEY)
10
.ok()
11
.flatten()
12
.map(|text| parse(&text))
13
.unwrap_or_default()
14
}
15
16
pub fn save(store: &Store, channel_ids: &HashSet<String>) {
17
let _ = store.set_meta(META_KEY, &serialize(channel_ids));
18
}
19
20
fn serialize(channel_ids: &HashSet<String>) -> String {
21
let mut ids: Vec<&str> = channel_ids.iter().map(String::as_str).collect();
22
ids.sort_unstable();
23
ids.join("\n")
24
}
25
26
fn parse(text: &str) -> HashSet<String> {
27
text.lines()
28
.filter(|id| !id.is_empty())
29
.map(str::to_owned)
30
.collect()
31
}
32
33
#[cfg(test)]
34
mod tests {
35
use super::*;
36
37
#[test]
38
fn persists_in_store() {
39
let store = Store::open_in_memory().unwrap();
40
assert!(load(&store).is_empty());
41
let followed: HashSet<String> = ["19:a@thread.tacv2", "19:b@thread.tacv2"]
42
.into_iter()
43
.map(str::to_owned)
44
.collect();
45
save(&store, &followed);
46
assert_eq!(load(&store), followed);
47
save(&store, &HashSet::new());
48
assert!(load(&store).is_empty());
49
}
50
}
@@ -1,50 +0,0 @@1
use std::collections::HashSet;2
3
use store::Store;4
5
const META_KEY: &str = "notifications.followed_channels";6
7
pub fn load(store: &Store) -> HashSet<String> {8
store9
.meta(META_KEY)10
.ok()11
.flatten()12
.map(|text| parse(&text))13
.unwrap_or_default()14
}15
16
pub fn save(store: &Store, channel_ids: &HashSet<String>) {17
let _ = store.set_meta(META_KEY, &serialize(channel_ids));18
}19
20
fn serialize(channel_ids: &HashSet<String>) -> String {21
let mut ids: Vec<&str> = channel_ids.iter().map(String::as_str).collect();22
ids.sort_unstable();23
ids.join("\n")24
}25
26
fn parse(text: &str) -> HashSet<String> {27
text.lines()28
.filter(|id| !id.is_empty())29
.map(str::to_owned)30
.collect()31
}32
33
#[cfg(test)]34
mod tests {35
use super::*;36
37
#[test]38
fn persists_in_store() {39
let store = Store::open_in_memory().unwrap();40
assert!(load(&store).is_empty());41
let followed: HashSet<String> = ["19:a@thread.tacv2", "19:b@thread.tacv2"]42
.into_iter()43
.map(str::to_owned)44
.collect();45
save(&store, &followed);46
assert_eq!(load(&store), followed);47
save(&store, &HashSet::new());48
assert!(load(&store).is_empty());49
}50
}@@ -1,7 +1,7 @@
1
use std::collections::{HashMap, HashSet};
1
use std::collections::HashMap;
2
2
3
3
use chrono::{DateTime, Utc};
4
use store::{MessageRecord, Sidebar, Store};
4
use store::{ChannelNotifications, MessageRecord, Sidebar, Store};
5
5
6
6
use super::rules::{ChannelSignals, ChatKind, Incoming, Preview};
7
7
use crate::app_state::chat_title;
@@ -26,14 +26,13 @@ impl IncomingTracker {
26
26
&mut self,
27
27
store: &Store,
28
28
sidebar: &Sidebar,
29
followed: &HashSet<String>,
30
29
my_user_id: Option<&str>,
31
30
conversation_id: &str,
32
31
) -> Vec<Incoming> {
33
32
let Ok(records) = store.messages(conversation_id, None, RECENT_WINDOW) else {
34
33
return Vec::new();
35
34
};
36
self.fresh(records, store, sidebar, followed, my_user_id)
35
self.fresh(records, store, sidebar, my_user_id)
37
36
}
38
37
39
38
fn fresh(
@@ -41,7 +40,6 @@ impl IncomingTracker {
41
40
records: Vec<MessageRecord>,
42
41
store: &Store,
43
42
sidebar: &Sidebar,
44
followed: &HashSet<String>,
45
43
my_user_id: Option<&str>,
46
44
) -> Vec<Incoming> {
47
45
let mut incoming = Vec::new();
@@ -60,7 +58,7 @@ impl IncomingTracker {
60
58
if record.deleted || is_own(&record, my_user_id) {
61
59
continue;
62
60
}
63
if let Some(entry) = build_incoming(&record, store, sidebar, followed, my_user_id) {
61
if let Some(entry) = build_incoming(&record, store, sidebar, my_user_id) {
64
62
incoming.push(entry);
65
63
}
66
64
}
@@ -76,12 +74,11 @@ pub fn build_incoming(
76
74
record: &MessageRecord,
77
75
store: &Store,
78
76
sidebar: &Sidebar,
79
followed: &HashSet<String>,
80
77
my_user_id: Option<&str>,
81
78
) -> Option<Incoming> {
82
79
let (kind, chat_name) = chat_context(sidebar, &record.conversation_id)?;
83
80
let signals = match kind {
84
ChatKind::Channel { .. } => channel_signals(record, store, sidebar, followed, my_user_id),
81
ChatKind::Channel { .. } => channel_signals(record, store, sidebar, my_user_id),
85
82
_ => ChannelSignals::default(),
86
83
};
87
84
Some(Incoming {
@@ -137,7 +134,6 @@ fn channel_signals(
137
134
record: &MessageRecord,
138
135
store: &Store,
139
136
sidebar: &Sidebar,
140
followed: &HashSet<String>,
141
137
my_user_id: Option<&str>,
142
138
) -> ChannelSignals {
143
139
let in_my_thread = match (record.reply_to_id.as_deref(), my_user_id) {
@@ -152,10 +148,24 @@ fn channel_signals(
152
148
.any(|mention| mention.group),
153
149
in_my_thread,
154
150
hidden: channel_hidden(sidebar, &record.conversation_id),
155
followed: followed.contains(&record.conversation_id),
151
is_reply: record.reply_to_id.is_some(),
152
notifications: channel_notifications(sidebar, &record.conversation_id),
156
153
}
157
154
}
158
155
156
fn channel_notifications(sidebar: &Sidebar, conversation_id: &str) -> ChannelNotifications {
157
sidebar
158
.teams
159
.iter()
160
.find(|team| {
161
team.channels
162
.iter()
163
.any(|channel| channel.id == conversation_id)
164
})
165
.map(|team| team.channel_notifications(conversation_id))
166
.unwrap_or_default()
167
}
168
159
169
fn channel_hidden(sidebar: &Sidebar, conversation_id: &str) -> bool {
160
170
sidebar.teams.iter().any(|team| {
161
171
team.channels
@@ -194,7 +204,9 @@ pub fn preview_of(record: &MessageRecord) -> Preview {
194
204
#[cfg(test)]
195
205
mod tests {
196
206
use chrono::Duration;
197
use store::{ChannelRecord, ChatRecord, MemberRecord, SidebarTeam, TeamRecord};
207
use store::{
208
ChannelNotificationLevel, ChannelRecord, ChatRecord, MemberRecord, SidebarTeam, TeamRecord,
209
};
198
210
199
211
use super::*;
200
212
@@ -255,12 +267,12 @@ mod tests {
255
267
.iter()
256
268
.map(|id| (*id).to_owned())
257
269
.collect(),
270
notifications: HashMap::new(),
258
271
}
259
272
}
260
273
261
fn collect_one(message: MessageRecord, store: &Store, followed: &[&str]) -> Incoming {
262
let followed: HashSet<String> = followed.iter().map(|id| (*id).to_owned()).collect();
263
build_incoming(&message, store, &sidebar(), &followed, Some("me")).unwrap()
274
fn collect_one(message: MessageRecord, store: &Store) -> Incoming {
275
build_incoming(&message, store, &sidebar(), Some("me")).unwrap()
264
276
}
265
277
266
278
fn record(conversation: &str, sender: &str, at: DateTime<Utc>, html: &str) -> MessageRecord {
@@ -289,9 +301,8 @@ mod tests {
289
301
quiet.chats[1].muted = true;
290
302
let message = record("group", "u1", Utc::now(), "hi");
291
303
let store = Store::open_in_memory().unwrap();
292
let build = |sidebar: &Sidebar| {
293
build_incoming(&message, &store, sidebar, &HashSet::new(), Some("me")).unwrap()
294
};
304
let build =
305
|sidebar: &Sidebar| build_incoming(&message, &store, sidebar, Some("me")).unwrap();
295
306
assert!(build(&quiet).muted);
296
307
assert!(!build(&sidebar()).muted);
297
308
}
@@ -306,7 +317,6 @@ mod tests {
306
317
vec![old, new],
307
318
&Store::open_in_memory().unwrap(),
308
319
&sidebar(),
309
&HashSet::new(),
310
320
Some("me"),
311
321
);
312
322
assert_eq!(found.len(), 1);
@@ -319,12 +329,12 @@ mod tests {
319
329
let mut tracker = IncomingTracker::new(start);
320
330
let message = record("direct", "u1", start + Duration::seconds(5), "neu");
321
331
let store = Store::open_in_memory().unwrap();
322
let (sidebar, followed) = (sidebar(), HashSet::new());
323
let first = tracker.fresh(vec![message.clone()], &store, &sidebar, &followed, None);
332
let sidebar = sidebar();
333
let first = tracker.fresh(vec![message.clone()], &store, &sidebar, None);
324
334
assert_eq!(first.len(), 1);
325
335
assert!(
326
336
tracker
327
.fresh(vec![message], &store, &sidebar, &followed, None)
337
.fresh(vec![message], &store, &sidebar, None)
328
338
.is_empty()
329
339
);
330
340
}
@@ -335,7 +345,7 @@ mod tests {
335
345
let mut tracker = IncomingTracker::new(start);
336
346
let own = record("direct", "me", start + Duration::seconds(5), "ich");
337
347
let store = Store::open_in_memory().unwrap();
338
let found = tracker.fresh(vec![own], &store, &sidebar(), &HashSet::new(), Some("me"));
348
let found = tracker.fresh(vec![own], &store, &sidebar(), Some("me"));
339
349
assert!(found.is_empty());
340
350
}
341
351
@@ -349,14 +359,13 @@ mod tests {
349
359
"<at>Me</at> hi",
350
360
);
351
361
message.mentions_json = r#"[{"user_id":"me","name":"Me"}]"#.into();
352
let found = collect_one(message.clone(), &Store::open_in_memory().unwrap(), &[]);
362
let found = collect_one(message.clone(), &Store::open_in_memory().unwrap());
353
363
assert!(found.mentions_me);
354
364
assert_eq!(found.kind, ChatKind::Group { member_count: 5 });
355
365
let other = build_incoming(
356
366
&message,
357
367
&Store::open_in_memory().unwrap(),
358
368
&sidebar(),
359
&HashSet::new(),
360
369
Some("other"),
361
370
);
362
371
assert!(!other.unwrap().mentions_me);
@@ -370,7 +379,6 @@ mod tests {
370
379
&message,
371
380
&Store::open_in_memory().unwrap(),
372
381
&sidebar(),
373
&HashSet::new(),
374
382
None
375
383
)
376
384
.is_none()
@@ -384,7 +392,6 @@ mod tests {
384
392
&message,
385
393
&Store::open_in_memory().unwrap(),
386
394
&sidebar(),
387
&HashSet::new(),
388
395
None,
389
396
)
390
397
.unwrap();
@@ -398,12 +405,12 @@ mod tests {
398
405
message.mentions_json =
399
406
r#"[{"user_id":null,"name":"channel","target_id":"channel-open","group":true}]"#.into();
400
407
assert!(
401
collect_one(message.clone(), &store, &[])
408
collect_one(message.clone(), &store)
402
409
.signals
403
410
.mentions_channel
404
411
);
405
412
message.mentions_json = r#"[{"user_id":null,"name":"bot","target_id":"bot-1"}]"#.into();
406
assert!(!collect_one(message, &store, &[]).signals.mentions_channel);
413
assert!(!collect_one(message, &store).signals.mentions_channel);
407
414
}
408
415
409
416
#[test]
@@ -415,32 +422,53 @@ mod tests {
415
422
store.upsert_messages(&[root]).unwrap();
416
423
let mut reply = record("channel-open", "u1", start + Duration::seconds(1), "reply");
417
424
reply.reply_to_id = Some("root".into());
418
assert!(collect_one(reply.clone(), &store, &[]).signals.in_my_thread);
425
assert!(collect_one(reply.clone(), &store).signals.in_my_thread);
419
426
reply.reply_to_id = Some("unknown-root".into());
420
assert!(!collect_one(reply, &store, &[]).signals.in_my_thread);
427
assert!(!collect_one(reply, &store).signals.in_my_thread);
421
428
let top_level = record("channel-open", "u1", start, "post");
422
assert!(!collect_one(top_level, &store, &[]).signals.in_my_thread);
429
assert!(!collect_one(top_level, &store).signals.in_my_thread);
423
430
}
424
431
425
432
#[test]
426
fn followed_and_hidden_channels_are_flagged() {
433
fn hidden_channels_are_flagged() {
427
434
let store = Store::open_in_memory().unwrap();
428
let now = Utc::now();
429
let signals = |channel: &str, followed: &[&str]| {
430
collect_one(record(channel, "u1", now, "x"), &store, followed).signals
435
let signals =
436
|channel: &str| collect_one(record(channel, "u1", Utc::now(), "x"), &store).signals;
437
assert!(!signals("channel-open").hidden);
438
assert!(signals("channel-in-hidden-team").hidden);
439
assert!(signals("channel-hidden").hidden);
440
assert!(!signals("channel-shown").hidden);
441
}
442
443
#[test]
444
fn channel_notifications_and_reply_flag_come_from_the_sidebar() {
445
let store = Store::open_in_memory().unwrap();
446
let banner = ChannelNotifications {
447
level: ChannelNotificationLevel::BannerAndFeed,
448
include_replies: true,
431
449
};
432
assert!(signals("channel-open", &["channel-open"]).followed);
433
assert!(!signals("channel-open", &[]).followed);
434
assert!(!signals("channel-open", &[]).hidden);
435
assert!(signals("channel-in-hidden-team", &[]).hidden);
436
assert!(signals("channel-hidden", &[]).hidden);
437
assert!(!signals("channel-shown", &[]).hidden);
450
let mut configured = sidebar();
451
configured.teams[0]
452
.notifications
453
.insert("channel-open".into(), banner);
454
let mut reply = record("channel-open", "u1", Utc::now(), "x");
455
let build = |message: &MessageRecord| {
456
build_incoming(message, &store, &configured, Some("me"))
457
.unwrap()
458
.signals
459
};
460
assert_eq!(build(&reply).notifications, banner);
461
assert!(!build(&reply).is_reply);
462
reply.reply_to_id = Some("root".into());
463
assert!(build(&reply).is_reply);
464
let other = record("channel-shown", "u1", Utc::now(), "x");
465
assert_eq!(build(&other).notifications, ChannelNotifications::default());
438
466
}
439
467
440
468
#[test]
441
469
fn chats_carry_no_channel_signals() {
442
470
let store = Store::open_in_memory().unwrap();
443
let found = collect_one(record("group", "u1", Utc::now(), "x"), &store, &["group"]);
471
let found = collect_one(record("group", "u1", Utc::now(), "x"), &store);
444
472
assert_eq!(found.signals, ChannelSignals::default());
445
473
}
446
474
}
@@ -1,7 +1,7 @@1
use std::collections::{HashMap, HashSet};1
use std::collections::HashMap;2
2
3
use chrono::{DateTime, Utc};3
use chrono::{DateTime, Utc};4
use store::{MessageRecord, Sidebar, Store};4
use store::{ChannelNotifications, MessageRecord, Sidebar, Store};5
5
6
use super::rules::{ChannelSignals, ChatKind, Incoming, Preview};6
use super::rules::{ChannelSignals, ChatKind, Incoming, Preview};7
use crate::app_state::chat_title;7
use crate::app_state::chat_title;@@ -26,14 +26,13 @@ impl IncomingTracker {26
&mut self,26
&mut self,27
store: &Store,27
store: &Store,28
sidebar: &Sidebar,28
sidebar: &Sidebar,29
followed: &HashSet<String>,30
my_user_id: Option<&str>,29
my_user_id: Option<&str>,31
conversation_id: &str,30
conversation_id: &str,32
) -> Vec<Incoming> {31
) -> Vec<Incoming> {33
let Ok(records) = store.messages(conversation_id, None, RECENT_WINDOW) else {32
let Ok(records) = store.messages(conversation_id, None, RECENT_WINDOW) else {34
return Vec::new();33
return Vec::new();35
};34
};36
self.fresh(records, store, sidebar, followed, my_user_id)35
self.fresh(records, store, sidebar, my_user_id)37
}36
}38
37
39
fn fresh(38
fn fresh(@@ -41,7 +40,6 @@ impl IncomingTracker {41
records: Vec<MessageRecord>,40
records: Vec<MessageRecord>,42
store: &Store,41
store: &Store,43
sidebar: &Sidebar,42
sidebar: &Sidebar,44
followed: &HashSet<String>,45
my_user_id: Option<&str>,43
my_user_id: Option<&str>,46
) -> Vec<Incoming> {44
) -> Vec<Incoming> {47
let mut incoming = Vec::new();45
let mut incoming = Vec::new();@@ -60,7 +58,7 @@ impl IncomingTracker {60
if record.deleted || is_own(&record, my_user_id) {58
if record.deleted || is_own(&record, my_user_id) {61
continue;59
continue;62
}60
}63
if let Some(entry) = build_incoming(&record, store, sidebar, followed, my_user_id) {61
if let Some(entry) = build_incoming(&record, store, sidebar, my_user_id) {64
incoming.push(entry);62
incoming.push(entry);65
}63
}66
}64
}@@ -76,12 +74,11 @@ pub fn build_incoming(76
record: &MessageRecord,74
record: &MessageRecord,77
store: &Store,75
store: &Store,78
sidebar: &Sidebar,76
sidebar: &Sidebar,79
followed: &HashSet<String>,80
my_user_id: Option<&str>,77
my_user_id: Option<&str>,81
) -> Option<Incoming> {78
) -> Option<Incoming> {82
let (kind, chat_name) = chat_context(sidebar, &record.conversation_id)?;79
let (kind, chat_name) = chat_context(sidebar, &record.conversation_id)?;83
let signals = match kind {80
let signals = match kind {84
ChatKind::Channel { .. } => channel_signals(record, store, sidebar, followed, my_user_id),81
ChatKind::Channel { .. } => channel_signals(record, store, sidebar, my_user_id),85
_ => ChannelSignals::default(),82
_ => ChannelSignals::default(),86
};83
};87
Some(Incoming {84
Some(Incoming {@@ -137,7 +134,6 @@ fn channel_signals(137
record: &MessageRecord,134
record: &MessageRecord,138
store: &Store,135
store: &Store,139
sidebar: &Sidebar,136
sidebar: &Sidebar,140
followed: &HashSet<String>,141
my_user_id: Option<&str>,137
my_user_id: Option<&str>,142
) -> ChannelSignals {138
) -> ChannelSignals {143
let in_my_thread = match (record.reply_to_id.as_deref(), my_user_id) {139
let in_my_thread = match (record.reply_to_id.as_deref(), my_user_id) {@@ -152,10 +148,24 @@ fn channel_signals(152
.any(|mention| mention.group),148
.any(|mention| mention.group),153
in_my_thread,149
in_my_thread,154
hidden: channel_hidden(sidebar, &record.conversation_id),150
hidden: channel_hidden(sidebar, &record.conversation_id),155
followed: followed.contains(&record.conversation_id),151
is_reply: record.reply_to_id.is_some(),152
notifications: channel_notifications(sidebar, &record.conversation_id),156
}153
}157
}154
}158
155
156
fn channel_notifications(sidebar: &Sidebar, conversation_id: &str) -> ChannelNotifications {157
sidebar158
.teams159
.iter()160
.find(|team| {161
team.channels162
.iter()163
.any(|channel| channel.id == conversation_id)164
})165
.map(|team| team.channel_notifications(conversation_id))166
.unwrap_or_default()167
}168
159
fn channel_hidden(sidebar: &Sidebar, conversation_id: &str) -> bool {169
fn channel_hidden(sidebar: &Sidebar, conversation_id: &str) -> bool {160
sidebar.teams.iter().any(|team| {170
sidebar.teams.iter().any(|team| {161
team.channels171
team.channels@@ -194,7 +204,9 @@ pub fn preview_of(record: &MessageRecord) -> Preview {194
#[cfg(test)]204
#[cfg(test)]195
mod tests {205
mod tests {196
use chrono::Duration;206
use chrono::Duration;197
use store::{ChannelRecord, ChatRecord, MemberRecord, SidebarTeam, TeamRecord};207
use store::{208
ChannelNotificationLevel, ChannelRecord, ChatRecord, MemberRecord, SidebarTeam, TeamRecord,209
};198
210
199
use super::*;211
use super::*;200
212
@@ -255,12 +267,12 @@ mod tests {255
.iter()267
.iter()256
.map(|id| (*id).to_owned())268
.map(|id| (*id).to_owned())257
.collect(),269
.collect(),270
notifications: HashMap::new(),258
}271
}259
}272
}260
273
261
fn collect_one(message: MessageRecord, store: &Store, followed: &[&str]) -> Incoming {274
fn collect_one(message: MessageRecord, store: &Store) -> Incoming {262
let followed: HashSet<String> = followed.iter().map(|id| (*id).to_owned()).collect();275
build_incoming(&message, store, &sidebar(), Some("me")).unwrap()263
build_incoming(&message, store, &sidebar(), &followed, Some("me")).unwrap()264
}276
}265
277
266
fn record(conversation: &str, sender: &str, at: DateTime<Utc>, html: &str) -> MessageRecord {278
fn record(conversation: &str, sender: &str, at: DateTime<Utc>, html: &str) -> MessageRecord {@@ -289,9 +301,8 @@ mod tests {289
quiet.chats[1].muted = true;301
quiet.chats[1].muted = true;290
let message = record("group", "u1", Utc::now(), "hi");302
let message = record("group", "u1", Utc::now(), "hi");291
let store = Store::open_in_memory().unwrap();303
let store = Store::open_in_memory().unwrap();292
let build = |sidebar: &Sidebar| {304
let build =293
build_incoming(&message, &store, sidebar, &HashSet::new(), Some("me")).unwrap()305
|sidebar: &Sidebar| build_incoming(&message, &store, sidebar, Some("me")).unwrap();294
};295
assert!(build(&quiet).muted);306
assert!(build(&quiet).muted);296
assert!(!build(&sidebar()).muted);307
assert!(!build(&sidebar()).muted);297
}308
}@@ -306,7 +317,6 @@ mod tests {306
vec![old, new],317
vec![old, new],307
&Store::open_in_memory().unwrap(),318
&Store::open_in_memory().unwrap(),308
&sidebar(),319
&sidebar(),309
&HashSet::new(),310
Some("me"),320
Some("me"),311
);321
);312
assert_eq!(found.len(), 1);322
assert_eq!(found.len(), 1);@@ -319,12 +329,12 @@ mod tests {319
let mut tracker = IncomingTracker::new(start);329
let mut tracker = IncomingTracker::new(start);320
let message = record("direct", "u1", start + Duration::seconds(5), "neu");330
let message = record("direct", "u1", start + Duration::seconds(5), "neu");321
let store = Store::open_in_memory().unwrap();331
let store = Store::open_in_memory().unwrap();322
let (sidebar, followed) = (sidebar(), HashSet::new());332
let sidebar = sidebar();323
let first = tracker.fresh(vec![message.clone()], &store, &sidebar, &followed, None);333
let first = tracker.fresh(vec![message.clone()], &store, &sidebar, None);324
assert_eq!(first.len(), 1);334
assert_eq!(first.len(), 1);325
assert!(335
assert!(326
tracker336
tracker327
.fresh(vec![message], &store, &sidebar, &followed, None)337
.fresh(vec![message], &store, &sidebar, None)328
.is_empty()338
.is_empty()329
);339
);330
}340
}@@ -335,7 +345,7 @@ mod tests {335
let mut tracker = IncomingTracker::new(start);345
let mut tracker = IncomingTracker::new(start);336
let own = record("direct", "me", start + Duration::seconds(5), "ich");346
let own = record("direct", "me", start + Duration::seconds(5), "ich");337
let store = Store::open_in_memory().unwrap();347
let store = Store::open_in_memory().unwrap();338
let found = tracker.fresh(vec![own], &store, &sidebar(), &HashSet::new(), Some("me"));348
let found = tracker.fresh(vec![own], &store, &sidebar(), Some("me"));339
assert!(found.is_empty());349
assert!(found.is_empty());340
}350
}341
351
@@ -349,14 +359,13 @@ mod tests {349
"<at>Me</at> hi",359
"<at>Me</at> hi",350
);360
);351
message.mentions_json = r#"[{"user_id":"me","name":"Me"}]"#.into();361
message.mentions_json = r#"[{"user_id":"me","name":"Me"}]"#.into();352
let found = collect_one(message.clone(), &Store::open_in_memory().unwrap(), &[]);362
let found = collect_one(message.clone(), &Store::open_in_memory().unwrap());353
assert!(found.mentions_me);363
assert!(found.mentions_me);354
assert_eq!(found.kind, ChatKind::Group { member_count: 5 });364
assert_eq!(found.kind, ChatKind::Group { member_count: 5 });355
let other = build_incoming(365
let other = build_incoming(356
&message,366
&message,357
&Store::open_in_memory().unwrap(),367
&Store::open_in_memory().unwrap(),358
&sidebar(),368
&sidebar(),359
&HashSet::new(),360
Some("other"),369
Some("other"),361
);370
);362
assert!(!other.unwrap().mentions_me);371
assert!(!other.unwrap().mentions_me);@@ -370,7 +379,6 @@ mod tests {370
&message,379
&message,371
&Store::open_in_memory().unwrap(),380
&Store::open_in_memory().unwrap(),372
&sidebar(),381
&sidebar(),373
&HashSet::new(),374
None382
None375
)383
)376
.is_none()384
.is_none()@@ -384,7 +392,6 @@ mod tests {384
&message,392
&message,385
&Store::open_in_memory().unwrap(),393
&Store::open_in_memory().unwrap(),386
&sidebar(),394
&sidebar(),387
&HashSet::new(),388
None,395
None,389
)396
)390
.unwrap();397
.unwrap();@@ -398,12 +405,12 @@ mod tests {398
message.mentions_json =405
message.mentions_json =399
r#"[{"user_id":null,"name":"channel","target_id":"channel-open","group":true}]"#.into();406
r#"[{"user_id":null,"name":"channel","target_id":"channel-open","group":true}]"#.into();400
assert!(407
assert!(401
collect_one(message.clone(), &store, &[])408
collect_one(message.clone(), &store)402
.signals409
.signals403
.mentions_channel410
.mentions_channel404
);411
);405
message.mentions_json = r#"[{"user_id":null,"name":"bot","target_id":"bot-1"}]"#.into();412
message.mentions_json = r#"[{"user_id":null,"name":"bot","target_id":"bot-1"}]"#.into();406
assert!(!collect_one(message, &store, &[]).signals.mentions_channel);413
assert!(!collect_one(message, &store).signals.mentions_channel);407
}414
}408
415
409
#[test]416
#[test]@@ -415,32 +422,53 @@ mod tests {415
store.upsert_messages(&[root]).unwrap();422
store.upsert_messages(&[root]).unwrap();416
let mut reply = record("channel-open", "u1", start + Duration::seconds(1), "reply");423
let mut reply = record("channel-open", "u1", start + Duration::seconds(1), "reply");417
reply.reply_to_id = Some("root".into());424
reply.reply_to_id = Some("root".into());418
assert!(collect_one(reply.clone(), &store, &[]).signals.in_my_thread);425
assert!(collect_one(reply.clone(), &store).signals.in_my_thread);419
reply.reply_to_id = Some("unknown-root".into());426
reply.reply_to_id = Some("unknown-root".into());420
assert!(!collect_one(reply, &store, &[]).signals.in_my_thread);427
assert!(!collect_one(reply, &store).signals.in_my_thread);421
let top_level = record("channel-open", "u1", start, "post");428
let top_level = record("channel-open", "u1", start, "post");422
assert!(!collect_one(top_level, &store, &[]).signals.in_my_thread);429
assert!(!collect_one(top_level, &store).signals.in_my_thread);423
}430
}424
431
425
#[test]432
#[test]426
fn followed_and_hidden_channels_are_flagged() {433
fn hidden_channels_are_flagged() {427
let store = Store::open_in_memory().unwrap();434
let store = Store::open_in_memory().unwrap();428
let now = Utc::now();435
let signals =429
let signals = |channel: &str, followed: &[&str]| {436
|channel: &str| collect_one(record(channel, "u1", Utc::now(), "x"), &store).signals;430
collect_one(record(channel, "u1", now, "x"), &store, followed).signals437
assert!(!signals("channel-open").hidden);438
assert!(signals("channel-in-hidden-team").hidden);439
assert!(signals("channel-hidden").hidden);440
assert!(!signals("channel-shown").hidden);441
}442
443
#[test]444
fn channel_notifications_and_reply_flag_come_from_the_sidebar() {445
let store = Store::open_in_memory().unwrap();446
let banner = ChannelNotifications {447
level: ChannelNotificationLevel::BannerAndFeed,448
include_replies: true,431
};449
};432
assert!(signals("channel-open", &["channel-open"]).followed);450
let mut configured = sidebar();433
assert!(!signals("channel-open", &[]).followed);451
configured.teams[0]434
assert!(!signals("channel-open", &[]).hidden);452
.notifications435
assert!(signals("channel-in-hidden-team", &[]).hidden);453
.insert("channel-open".into(), banner);436
assert!(signals("channel-hidden", &[]).hidden);454
let mut reply = record("channel-open", "u1", Utc::now(), "x");437
assert!(!signals("channel-shown", &[]).hidden);455
let build = |message: &MessageRecord| {456
build_incoming(message, &store, &configured, Some("me"))457
.unwrap()458
.signals459
};460
assert_eq!(build(&reply).notifications, banner);461
assert!(!build(&reply).is_reply);462
reply.reply_to_id = Some("root".into());463
assert!(build(&reply).is_reply);464
let other = record("channel-shown", "u1", Utc::now(), "x");465
assert_eq!(build(&other).notifications, ChannelNotifications::default());438
}466
}439
467
440
#[test]468
#[test]441
fn chats_carry_no_channel_signals() {469
fn chats_carry_no_channel_signals() {442
let store = Store::open_in_memory().unwrap();470
let store = Store::open_in_memory().unwrap();443
let found = collect_one(record("group", "u1", Utc::now(), "x"), &store, &["group"]);471
let found = collect_one(record("group", "u1", Utc::now(), "x"), &store);444
assert_eq!(found.signals, ChannelSignals::default());472
assert_eq!(found.signals, ChannelSignals::default());445
}473
}446
}474
}@@ -1,7 +1,6 @@
1
1
#[cfg_attr(not(windows), allow(dead_code))]
2
2
mod badge;
3
3
mod center;
4
mod followed;
5
4
mod incoming;
6
5
mod layout;
7
6
#[cfg_attr(not(windows), allow(dead_code))]
@@ -14,7 +13,6 @@ mod text;
14
13
mod toast;
15
14
16
15
pub use center::{NotificationCenter, selection_for};
17
pub use followed::{load as load_followed_channels, save as save_followed_channels};
18
16
pub use incoming::{IncomingTracker, preview_of};
19
17
pub use rules::{Incoming, Preview, channel_alerts};
20
18
#[cfg(test)]
@@ -1,7 +1,6 @@1
#[cfg_attr(not(windows), allow(dead_code))]1
#[cfg_attr(not(windows), allow(dead_code))]2
mod badge;2
mod badge;3
mod center;3
mod center;4
mod followed;5
mod incoming;4
mod incoming;6
mod layout;5
mod layout;7
#[cfg_attr(not(windows), allow(dead_code))]6
#[cfg_attr(not(windows), allow(dead_code))]@@ -14,7 +13,6 @@ mod text;14
mod toast;13
mod toast;15
14
16
pub use center::{NotificationCenter, selection_for};15
pub use center::{NotificationCenter, selection_for};17
pub use followed::{load as load_followed_channels, save as save_followed_channels};18
pub use incoming::{IncomingTracker, preview_of};16
pub use incoming::{IncomingTracker, preview_of};19
pub use rules::{Incoming, Preview, channel_alerts};17
pub use rules::{Incoming, Preview, channel_alerts};20
#[cfg(test)]18
#[cfg(test)]@@ -2,6 +2,7 @@ use std::collections::HashMap;
2
2
use std::time::{Duration, Instant};
3
3
4
4
use chrono::{DateTime, Utc};
5
use store::{ChannelNotificationLevel, ChannelNotifications};
5
6
6
7
pub const SOUND_THROTTLE: Duration = Duration::from_secs(10);
7
8
@@ -104,7 +105,8 @@ pub struct ChannelSignals {
104
105
pub mentions_channel: bool,
105
106
pub in_my_thread: bool,
106
107
pub hidden: bool,
107
pub followed: bool,
108
pub is_reply: bool,
109
pub notifications: ChannelNotifications,
108
110
}
109
111
110
112
#[derive(Debug, Clone, PartialEq, Eq)]
@@ -147,7 +149,25 @@ pub fn channel_alerts(incoming: &Incoming) -> bool {
147
149
return true;
148
150
}
149
151
let signals = incoming.signals;
150
!signals.hidden && (signals.mentions_channel || signals.in_my_thread || signals.followed)
152
if signals.hidden {
153
return false;
154
}
155
if signals.mentions_channel || signals.in_my_thread {
156
return true;
157
}
158
let notifications = signals.notifications;
159
notifications.level != ChannelNotificationLevel::Off
160
&& (!signals.is_reply || notifications.include_replies)
161
}
162
163
fn channel_toasts(incoming: &Incoming) -> bool {
164
if !matches!(incoming.kind, ChatKind::Channel { .. }) || incoming.mentions_me {
165
return true;
166
}
167
let signals = incoming.signals;
168
signals.mentions_channel
169
|| signals.in_my_thread
170
|| signals.notifications.level == ChannelNotificationLevel::BannerAndFeed
151
171
}
152
172
153
173
const SILENT: Decision = Decision {
@@ -157,6 +177,7 @@ const SILENT: Decision = Decision {
157
177
158
178
pub fn decide(settings: &Settings, incoming: &Incoming, environment: Environment) -> Decision {
159
179
let suppressed = !channel_alerts(incoming)
180
|| !channel_toasts(incoming)
160
181
|| environment.chat_in_foreground
161
182
|| environment.system_quiet
162
183
|| environment.own_do_not_disturb
@@ -302,43 +323,104 @@ mod tests {
302
323
..Default::default()
303
324
};
304
325
assert_eq!(decide(&settings, &group(), Environment::default()), SILENT);
305
assert!(decide(&settings, &incoming(ChatKind::Direct), Environment::default()).toast);
326
assert!(
327
decide(
328
&settings,
329
&incoming(ChatKind::Direct),
330
Environment::default()
331
)
332
.toast
333
);
306
334
let mut mention = group();
307
335
mention.mentions_me = true;
308
336
assert!(decide(&settings, &mention, Environment::default()).toast);
309
337
}
310
338
339
fn channel_with(level: ChannelNotificationLevel, include_replies: bool) -> Incoming {
340
let mut message = channel();
341
message.signals.notifications = ChannelNotifications {
342
level,
343
include_replies,
344
};
345
message
346
}
347
348
fn toast_of(incoming: &Incoming) -> bool {
349
decide(&Settings::default(), incoming, Environment::default()).toast
350
}
351
311
352
#[test]
312
fn plain_channel_post_is_silent() {
313
assert!(!channel_alerts(&channel()));
353
fn banner_and_activity_posts_toast_and_feed() {
354
let post = channel_with(ChannelNotificationLevel::BannerAndFeed, false);
355
assert!(channel_alerts(&post));
356
assert!(toast_of(&post));
357
}
358
359
#[test]
360
fn activity_only_posts_feed_without_a_toast() {
361
let post = channel_with(ChannelNotificationLevel::Feed, false);
362
assert!(channel_alerts(&post));
314
363
assert_eq!(
315
decide(&Settings::default(), &channel(), Environment::default()),
364
decide(&Settings::default(), &post, Environment::default()),
316
365
SILENT
317
366
);
367
assert!(channel_alerts(&channel()));
318
368
}
319
369
320
370
#[test]
321
fn channel_alerts_for_each_trigger() {
322
let triggers: [fn(&mut Incoming); 4] = [
371
fn off_channel_stays_silent_except_for_mentions_and_my_threads() {
372
let mut post = channel_with(ChannelNotificationLevel::Off, true);
373
assert!(!channel_alerts(&post));
374
assert_eq!(
375
decide(&Settings::default(), &post, Environment::default()),
376
SILENT
377
);
378
post.signals.is_reply = true;
379
assert!(!channel_alerts(&post));
380
let triggers: [fn(&mut Incoming); 3] = [
323
381
|incoming| incoming.mentions_me = true,
324
382
|incoming| incoming.signals.mentions_channel = true,
325
383
|incoming| incoming.signals.in_my_thread = true,
326
|incoming| incoming.signals.followed = true,
327
384
];
328
385
for trigger in triggers {
329
let mut message = channel();
330
trigger(&mut message);
331
assert!(channel_alerts(&message));
332
assert!(decide(&Settings::default(), &message, Environment::default()).toast);
386
let mut mention = channel_with(ChannelNotificationLevel::Off, false);
387
trigger(&mut mention);
388
assert!(channel_alerts(&mention));
389
assert!(toast_of(&mention));
333
390
}
334
391
}
335
392
393
#[test]
394
fn replies_need_include_replies_or_my_thread() {
395
for level in [
396
ChannelNotificationLevel::Feed,
397
ChannelNotificationLevel::BannerAndFeed,
398
] {
399
let mut reply = channel_with(level, false);
400
reply.signals.is_reply = true;
401
assert!(!channel_alerts(&reply));
402
reply.signals.in_my_thread = true;
403
assert!(channel_alerts(&reply));
404
let mut included = channel_with(level, true);
405
included.signals.is_reply = true;
406
assert!(channel_alerts(&included));
407
}
408
let mut banner_reply = channel_with(ChannelNotificationLevel::BannerAndFeed, true);
409
banner_reply.signals.is_reply = true;
410
assert!(toast_of(&banner_reply));
411
let mut feed_reply = channel_with(ChannelNotificationLevel::Feed, true);
412
feed_reply.signals.is_reply = true;
413
assert!(!toast_of(&feed_reply));
414
}
415
336
416
#[test]
337
417
fn hidden_channel_only_alerts_for_mentions_of_me() {
338
418
let triggers: [fn(&mut Incoming); 3] = [
339
419
|incoming| incoming.signals.mentions_channel = true,
340
420
|incoming| incoming.signals.in_my_thread = true,
341
|incoming| incoming.signals.followed = true,
421
|incoming| {
422
incoming.signals.notifications.level = ChannelNotificationLevel::BannerAndFeed
423
},
342
424
];
343
425
for trigger in triggers {
344
426
let mut message = channel();
@@ -2,6 +2,7 @@ use std::collections::HashMap;2
use std::time::{Duration, Instant};2
use std::time::{Duration, Instant};3
3
4
use chrono::{DateTime, Utc};4
use chrono::{DateTime, Utc};5
use store::{ChannelNotificationLevel, ChannelNotifications};5
6
6
pub const SOUND_THROTTLE: Duration = Duration::from_secs(10);7
pub const SOUND_THROTTLE: Duration = Duration::from_secs(10);7
8
@@ -104,7 +105,8 @@ pub struct ChannelSignals {104
pub mentions_channel: bool,105
pub mentions_channel: bool,105
pub in_my_thread: bool,106
pub in_my_thread: bool,106
pub hidden: bool,107
pub hidden: bool,107
pub followed: bool,108
pub is_reply: bool,109
pub notifications: ChannelNotifications,108
}110
}109
111
110
#[derive(Debug, Clone, PartialEq, Eq)]112
#[derive(Debug, Clone, PartialEq, Eq)]@@ -147,7 +149,25 @@ pub fn channel_alerts(incoming: &Incoming) -> bool {147
return true;149
return true;148
}150
}149
let signals = incoming.signals;151
let signals = incoming.signals;150
!signals.hidden && (signals.mentions_channel || signals.in_my_thread || signals.followed)152
if signals.hidden {153
return false;154
}155
if signals.mentions_channel || signals.in_my_thread {156
return true;157
}158
let notifications = signals.notifications;159
notifications.level != ChannelNotificationLevel::Off160
&& (!signals.is_reply || notifications.include_replies)161
}162
163
fn channel_toasts(incoming: &Incoming) -> bool {164
if !matches!(incoming.kind, ChatKind::Channel { .. }) || incoming.mentions_me {165
return true;166
}167
let signals = incoming.signals;168
signals.mentions_channel169
|| signals.in_my_thread170
|| signals.notifications.level == ChannelNotificationLevel::BannerAndFeed151
}171
}152
172
153
const SILENT: Decision = Decision {173
const SILENT: Decision = Decision {@@ -157,6 +177,7 @@ const SILENT: Decision = Decision {157
177
158
pub fn decide(settings: &Settings, incoming: &Incoming, environment: Environment) -> Decision {178
pub fn decide(settings: &Settings, incoming: &Incoming, environment: Environment) -> Decision {159
let suppressed = !channel_alerts(incoming)179
let suppressed = !channel_alerts(incoming)180
|| !channel_toasts(incoming)160
|| environment.chat_in_foreground181
|| environment.chat_in_foreground161
|| environment.system_quiet182
|| environment.system_quiet162
|| environment.own_do_not_disturb183
|| environment.own_do_not_disturb@@ -302,43 +323,104 @@ mod tests {302
..Default::default()323
..Default::default()303
};324
};304
assert_eq!(decide(&settings, &group(), Environment::default()), SILENT);325
assert_eq!(decide(&settings, &group(), Environment::default()), SILENT);305
assert!(decide(&settings, &incoming(ChatKind::Direct), Environment::default()).toast);326
assert!(327
decide(328
&settings,329
&incoming(ChatKind::Direct),330
Environment::default()331
)332
.toast333
);306
let mut mention = group();334
let mut mention = group();307
mention.mentions_me = true;335
mention.mentions_me = true;308
assert!(decide(&settings, &mention, Environment::default()).toast);336
assert!(decide(&settings, &mention, Environment::default()).toast);309
}337
}310
338
339
fn channel_with(level: ChannelNotificationLevel, include_replies: bool) -> Incoming {340
let mut message = channel();341
message.signals.notifications = ChannelNotifications {342
level,343
include_replies,344
};345
message346
}347
348
fn toast_of(incoming: &Incoming) -> bool {349
decide(&Settings::default(), incoming, Environment::default()).toast350
}351
311
#[test]352
#[test]312
fn plain_channel_post_is_silent() {353
fn banner_and_activity_posts_toast_and_feed() {313
assert!(!channel_alerts(&channel()));354
let post = channel_with(ChannelNotificationLevel::BannerAndFeed, false);355
assert!(channel_alerts(&post));356
assert!(toast_of(&post));357
}358
359
#[test]360
fn activity_only_posts_feed_without_a_toast() {361
let post = channel_with(ChannelNotificationLevel::Feed, false);362
assert!(channel_alerts(&post));314
assert_eq!(363
assert_eq!(315
decide(&Settings::default(), &channel(), Environment::default()),364
decide(&Settings::default(), &post, Environment::default()),316
SILENT365
SILENT317
);366
);367
assert!(channel_alerts(&channel()));318
}368
}319
369
320
#[test]370
#[test]321
fn channel_alerts_for_each_trigger() {371
fn off_channel_stays_silent_except_for_mentions_and_my_threads() {322
let triggers: [fn(&mut Incoming); 4] = [372
let mut post = channel_with(ChannelNotificationLevel::Off, true);373
assert!(!channel_alerts(&post));374
assert_eq!(375
decide(&Settings::default(), &post, Environment::default()),376
SILENT377
);378
post.signals.is_reply = true;379
assert!(!channel_alerts(&post));380
let triggers: [fn(&mut Incoming); 3] = [323
|incoming| incoming.mentions_me = true,381
|incoming| incoming.mentions_me = true,324
|incoming| incoming.signals.mentions_channel = true,382
|incoming| incoming.signals.mentions_channel = true,325
|incoming| incoming.signals.in_my_thread = true,383
|incoming| incoming.signals.in_my_thread = true,326
|incoming| incoming.signals.followed = true,327
];384
];328
for trigger in triggers {385
for trigger in triggers {329
let mut message = channel();386
let mut mention = channel_with(ChannelNotificationLevel::Off, false);330
trigger(&mut message);387
trigger(&mut mention);331
assert!(channel_alerts(&message));388
assert!(channel_alerts(&mention));332
assert!(decide(&Settings::default(), &message, Environment::default()).toast);389
assert!(toast_of(&mention));333
}390
}334
}391
}335
392
393
#[test]394
fn replies_need_include_replies_or_my_thread() {395
for level in [396
ChannelNotificationLevel::Feed,397
ChannelNotificationLevel::BannerAndFeed,398
] {399
let mut reply = channel_with(level, false);400
reply.signals.is_reply = true;401
assert!(!channel_alerts(&reply));402
reply.signals.in_my_thread = true;403
assert!(channel_alerts(&reply));404
let mut included = channel_with(level, true);405
included.signals.is_reply = true;406
assert!(channel_alerts(&included));407
}408
let mut banner_reply = channel_with(ChannelNotificationLevel::BannerAndFeed, true);409
banner_reply.signals.is_reply = true;410
assert!(toast_of(&banner_reply));411
let mut feed_reply = channel_with(ChannelNotificationLevel::Feed, true);412
feed_reply.signals.is_reply = true;413
assert!(!toast_of(&feed_reply));414
}415
336
#[test]416
#[test]337
fn hidden_channel_only_alerts_for_mentions_of_me() {417
fn hidden_channel_only_alerts_for_mentions_of_me() {338
let triggers: [fn(&mut Incoming); 3] = [418
let triggers: [fn(&mut Incoming); 3] = [339
|incoming| incoming.signals.mentions_channel = true,419
|incoming| incoming.signals.mentions_channel = true,340
|incoming| incoming.signals.in_my_thread = true,420
|incoming| incoming.signals.in_my_thread = true,341
|incoming| incoming.signals.followed = true,421
|incoming| {422
incoming.signals.notifications.level = ChannelNotificationLevel::BannerAndFeed423
},342
];424
];343
for trigger in triggers {425
for trigger in triggers {344
let mut message = channel();426
let mut message = channel();@@ -11,7 +11,7 @@ mod hosted;
11
11
mod sdk;
12
12
13
13
#[cfg(windows)]
14
pub use hosted::install_host;
14
pub use hosted::{host, install_host};
15
15
16
16
#[cfg_attr(not(windows), allow(dead_code))]
17
17
#[derive(Debug, Clone, PartialEq)]
@@ -11,7 +11,7 @@ mod hosted;11
mod sdk;11
mod sdk;12
12
13
#[cfg(windows)]13
#[cfg(windows)]14
pub use hosted::install_host;14
pub use hosted::{host, install_host};15
15
16
#[cfg_attr(not(windows), allow(dead_code))]16
#[cfg_attr(not(windows), allow(dead_code))]17
#[derive(Debug, Clone, PartialEq)]17
#[derive(Debug, Clone, PartialEq)]@@ -17,6 +17,10 @@ pub fn install_host(transport: Arc<WebViewTransport>) {
17
17
let _ = HOST.set(transport);
18
18
}
19
19
20
pub fn host() -> Option<Arc<WebViewTransport>> {
21
HOST.get().cloned()
22
}
23
20
24
pub fn open(dialog: UrlDialog, engine: Option<Arc<Engine>>, cx: &mut App) {
21
25
let Some(host) = HOST.get().cloned() else {
22
26
cx.open_url(&dialog.fallback_url);
@@ -17,6 +17,10 @@ pub fn install_host(transport: Arc<WebViewTransport>) {17
let _ = HOST.set(transport);17
let _ = HOST.set(transport);18
}18
}19
19
20
pub fn host() -> Option<Arc<WebViewTransport>> {21
HOST.get().cloned()22
}23
20
pub fn open(dialog: UrlDialog, engine: Option<Arc<Engine>>, cx: &mut App) {24
pub fn open(dialog: UrlDialog, engine: Option<Arc<Engine>>, cx: &mut App) {21
let Some(host) = HOST.get().cloned() else {25
let Some(host) = HOST.get().cloned() else {22
cx.open_url(&dialog.fallback_url);26
cx.open_url(&dialog.fallback_url);@@ -616,7 +616,7 @@ impl AttachmentTray {
616
616
}
617
617
}
618
618
619
fn display_name(path: &Path) -> String {
619
pub fn display_name(path: &Path) -> String {
620
620
path.file_name()
621
621
.map(|name| name.to_string_lossy().into_owned())
622
622
.unwrap_or_else(|| path.to_string_lossy().into_owned())
@@ -616,7 +616,7 @@ impl AttachmentTray {616
}616
}617
}617
}618
618
619
fn display_name(path: &Path) -> String {619
pub fn display_name(path: &Path) -> String {620
path.file_name()620
path.file_name()621
.map(|name| name.to_string_lossy().into_owned())621
.map(|name| name.to_string_lossy().into_owned())622
.unwrap_or_else(|| path.to_string_lossy().into_owned())622
.unwrap_or_else(|| path.to_string_lossy().into_owned())@@ -0,0 +1,299 @@
1
use std::rc::Rc;
2
3
use gpui_kit::component::{
4
button::{Button, ButtonVariants as _},
5
h_flex,
6
menu::{DropdownMenu as _, PopupMenuItem},
7
};
8
use gpui_kit::prelude::FluentBuilder as _;
9
use gpui_kit::*;
10
use store::ChannelTabRecord;
11
use teams_core::channel_tab_link;
12
13
use crate::theme;
14
15
const TAB_HEIGHT: f32 = 34.;
16
const TAB_GAP: f32 = 14.;
17
const TAB_TEXT_SIZE: f32 = 12.5;
18
const BAR_PADDING: f32 = 20.;
19
const CHAR_WIDTH: f32 = 6.5;
20
const ARROW_WIDTH: f32 = 14.;
21
const OVERFLOW_WIDTH: f32 = 44.;
22
const EXTERNAL_ARROW: &str = "\u{2197}";
23
24
pub const POSTS_LABEL: &str = "Posts";
25
pub const SHARED_LABEL: &str = "Shared";
26
27
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
28
pub enum ChannelPane {
29
Posts,
30
Shared,
31
Web,
32
}
33
34
pub type SelectPane = Rc<dyn Fn(ChannelPane, &mut App)>;
35
pub type OpenTab = Rc<dyn Fn(usize, &mut Window, &mut App)>;
36
pub type MenuToggled = Rc<dyn Fn(bool, &mut Window, &mut App)>;
37
38
#[derive(Clone)]
39
pub struct TabBarActions {
40
pub select: SelectPane,
41
pub open: OpenTab,
42
pub menu_toggled: MenuToggled,
43
}
44
45
#[derive(Debug, Clone, PartialEq, Eq)]
46
pub enum TabAction {
47
Embed(String),
48
Browser(String),
49
ResolveLink,
50
}
51
52
pub fn tab_action(
53
tab: &ChannelTabRecord,
54
embedding: bool,
55
resolved_link: Option<&str>,
56
) -> TabAction {
57
match (&tab.open_url, resolved_link) {
58
(Some(url), _) if embedding && tab.is_website() => TabAction::Embed(url.clone()),
59
(Some(url), _) => TabAction::Browser(url.clone()),
60
(None, Some(link)) => TabAction::Browser(link.to_owned()),
61
(None, None) => TabAction::ResolveLink,
62
}
63
}
64
65
pub fn fallback_tab_link(tab: &ChannelTabRecord, channel_id: &str) -> String {
66
channel_tab_link(channel_id, &tab.tab_id, &tab.name)
67
}
68
69
fn label_width(label: &str, external: bool) -> f32 {
70
label.chars().count() as f32 * CHAR_WIDTH + if external { ARROW_WIDTH } else { 0. }
71
}
72
73
pub fn visible_tab_count(tabs: &[ChannelTabRecord], available_width: f32) -> usize {
74
let fixed = label_width(POSTS_LABEL, false) + TAB_GAP + label_width(SHARED_LABEL, false);
75
let widths: Vec<f32> = tabs
76
.iter()
77
.map(|tab| TAB_GAP + label_width(&tab.name, true))
78
.collect();
79
if fixed + widths.iter().sum::<f32>() <= available_width {
80
return tabs.len();
81
}
82
let room = available_width - fixed - TAB_GAP - OVERFLOW_WIDTH;
83
let mut used = 0.;
84
widths
85
.iter()
86
.take_while(|width| {
87
used += **width;
88
used <= room
89
})
90
.count()
91
}
92
93
fn tab_label(
94
id: ElementId,
95
text: &str,
96
active: bool,
97
external: bool,
98
on_click: impl Fn(&mut Window, &mut App) + 'static,
99
) -> Stateful<Div> {
100
let color = if active {
101
theme::text()
102
} else {
103
theme::text_muted()
104
};
105
h_flex()
106
.id(id)
107
.h(px(TAB_HEIGHT))
108
.flex_none()
109
.items_center()
110
.gap(px(3.))
111
.cursor_pointer()
112
.border_b_2()
113
.border_color(if active {
114
theme::accent()
115
} else {
116
transparent_black()
117
})
118
.text_size(px(TAB_TEXT_SIZE))
119
.font_weight(if active {
120
FontWeight::SEMIBOLD
121
} else {
122
FontWeight::NORMAL
123
})
124
.text_color(color)
125
.hover(|tab| tab.text_color(theme::text()))
126
.on_click(move |_, window, cx| on_click(window, cx))
127
.child(text.to_owned())
128
.when(external, |tab| {
129
tab.child(div().text_color(theme::text_faint()).child(EXTERNAL_ARROW))
130
})
131
}
132
133
fn overflow_button(
134
hidden: &[(usize, String, bool)],
135
embedding: bool,
136
actions: &TabBarActions,
137
) -> impl IntoElement {
138
let entries = hidden.to_vec();
139
let open = actions.open.clone();
140
let menu_toggled = actions.menu_toggled.clone();
141
Button::new("channel-tab-overflow")
142
.ghost()
143
.compact()
144
.label(format!("+{}", hidden.len()))
145
.dropdown_menu(move |menu, _, _| {
146
entries.iter().fold(menu, |menu, (index, name, website)| {
147
let (open, index) = (open.clone(), *index);
148
let label = if embedding && *website {
149
name.clone()
150
} else {
151
format!("{name} {EXTERNAL_ARROW}")
152
};
153
menu.item(
154
PopupMenuItem::new(label)
155
.on_click(move |_, window, cx| open(index, window, cx)),
156
)
157
})
158
})
159
.on_open_change(move |open, window, cx| menu_toggled(*open, window, cx))
160
}
161
162
pub fn render_tab_bar(
163
tabs: &[ChannelTabRecord],
164
pane: ChannelPane,
165
active_tab_id: Option<&str>,
166
embedding: bool,
167
available_width: f32,
168
actions: &TabBarActions,
169
) -> AnyElement {
170
let visible = visible_tab_count(tabs, available_width - 2. * BAR_PADDING);
171
let select = actions.select.clone();
172
let posts = tab_label(
173
"channel-tab-posts".into(),
174
POSTS_LABEL,
175
pane == ChannelPane::Posts,
176
false,
177
{
178
let select = select.clone();
179
move |_, cx| select(ChannelPane::Posts, cx)
180
},
181
);
182
let shared = tab_label(
183
"channel-tab-shared".into(),
184
SHARED_LABEL,
185
pane == ChannelPane::Shared,
186
false,
187
move |_, cx| select(ChannelPane::Shared, cx),
188
);
189
let configured = tabs.iter().enumerate().take(visible).map(|(index, tab)| {
190
let open = actions.open.clone();
191
tab_label(
192
ElementId::NamedInteger("channel-tab".into(), index as u64),
193
&tab.name,
194
active_tab_id == Some(tab.tab_id.as_str()),
195
!(embedding && tab.is_website()),
196
move |window, cx| open(index, window, cx),
197
)
198
});
199
let hidden: Vec<(usize, String, bool)> = tabs
200
.iter()
201
.enumerate()
202
.skip(visible)
203
.map(|(index, tab)| (index, tab.name.clone(), tab.is_website()))
204
.collect();
205
h_flex()
206
.w_full()
207
.flex_none()
208
.px(px(BAR_PADDING))
209
.gap(px(TAB_GAP))
210
.items_center()
211
.border_b_1()
212
.border_color(theme::border())
213
.child(posts)
214
.child(shared)
215
.children(configured)
216
.when(!hidden.is_empty(), |bar| {
217
bar.child(overflow_button(&hidden, embedding, actions))
218
})
219
.into_any_element()
220
}
221
222
#[cfg(test)]
223
mod tests {
224
use store::ChannelTabRecord;
225
226
use super::{TabAction, fallback_tab_link, tab_action, visible_tab_count};
227
228
fn tab(name: &str, open_url: Option<&str>) -> ChannelTabRecord {
229
ChannelTabRecord {
230
tab_id: "tab-1".to_owned(),
231
name: name.to_owned(),
232
definition_id: "app".to_owned(),
233
open_url: open_url.map(str::to_owned),
234
}
235
}
236
237
fn website(url: &str) -> ChannelTabRecord {
238
ChannelTabRecord {
239
definition_id: "com.microsoft.teamspace.tab.web".to_owned(),
240
..tab("Docs", Some(url))
241
}
242
}
243
244
#[test]
245
fn website_tabs_embed_only_where_the_host_can() {
246
let docs = website("https://docs.example");
247
assert_eq!(
248
tab_action(&docs, true, None),
249
TabAction::Embed("https://docs.example".to_owned())
250
);
251
assert_eq!(
252
tab_action(&docs, false, None),
253
TabAction::Browser("https://docs.example".to_owned())
254
);
255
}
256
257
#[test]
258
fn other_tabs_with_a_page_open_it_in_the_browser() {
259
let notes = tab("Notes", Some("https://onenote.example/web"));
260
assert_eq!(
261
tab_action(¬es, true, None),
262
TabAction::Browser("https://onenote.example/web".to_owned())
263
);
264
}
265
266
#[test]
267
fn app_tabs_resolve_their_link_once_and_then_reuse_it() {
268
let board = tab("Board", None);
269
assert_eq!(tab_action(&board, true, None), TabAction::ResolveLink);
270
assert_eq!(
271
tab_action(&board, true, Some("https://teams.example/l/tab")),
272
TabAction::Browser("https://teams.example/l/tab".to_owned())
273
);
274
}
275
276
#[test]
277
fn the_fallback_link_is_the_hand_built_deep_link() {
278
assert_eq!(
279
fallback_tab_link(&tab("Board", None), "19:c@thread.tacv2"),
280
"https://teams.microsoft.com/l/channel/19:c@thread.tacv2/tab%3A%3Atab-1?label=Board"
281
);
282
}
283
284
#[test]
285
fn every_tab_stays_visible_while_it_fits() {
286
let tabs = [tab("Docs", None), tab("Planner", None)];
287
assert_eq!(visible_tab_count(&tabs, 600.), 2);
288
}
289
290
#[test]
291
fn tabs_that_do_not_fit_move_into_the_overflow() {
292
let tabs: Vec<ChannelTabRecord> = (0..8)
293
.map(|n| tab(&format!("Tab number {n}"), None))
294
.collect();
295
let visible = visible_tab_count(&tabs, 420.);
296
assert!(visible > 0 && visible < tabs.len());
297
assert_eq!(visible_tab_count(&tabs, 40.), 0);
298
}
299
}
@@ -0,0 +1,299 @@1
use std::rc::Rc;2
3
use gpui_kit::component::{4
button::{Button, ButtonVariants as _},5
h_flex,6
menu::{DropdownMenu as _, PopupMenuItem},7
};8
use gpui_kit::prelude::FluentBuilder as _;9
use gpui_kit::*;10
use store::ChannelTabRecord;11
use teams_core::channel_tab_link;12
13
use crate::theme;14
15
const TAB_HEIGHT: f32 = 34.;16
const TAB_GAP: f32 = 14.;17
const TAB_TEXT_SIZE: f32 = 12.5;18
const BAR_PADDING: f32 = 20.;19
const CHAR_WIDTH: f32 = 6.5;20
const ARROW_WIDTH: f32 = 14.;21
const OVERFLOW_WIDTH: f32 = 44.;22
const EXTERNAL_ARROW: &str = "\u{2197}";23
24
pub const POSTS_LABEL: &str = "Posts";25
pub const SHARED_LABEL: &str = "Shared";26
27
#[derive(Debug, Clone, Copy, PartialEq, Eq)]28
pub enum ChannelPane {29
Posts,30
Shared,31
Web,32
}33
34
pub type SelectPane = Rc<dyn Fn(ChannelPane, &mut App)>;35
pub type OpenTab = Rc<dyn Fn(usize, &mut Window, &mut App)>;36
pub type MenuToggled = Rc<dyn Fn(bool, &mut Window, &mut App)>;37
38
#[derive(Clone)]39
pub struct TabBarActions {40
pub select: SelectPane,41
pub open: OpenTab,42
pub menu_toggled: MenuToggled,43
}44
45
#[derive(Debug, Clone, PartialEq, Eq)]46
pub enum TabAction {47
Embed(String),48
Browser(String),49
ResolveLink,50
}51
52
pub fn tab_action(53
tab: &ChannelTabRecord,54
embedding: bool,55
resolved_link: Option<&str>,56
) -> TabAction {57
match (&tab.open_url, resolved_link) {58
(Some(url), _) if embedding && tab.is_website() => TabAction::Embed(url.clone()),59
(Some(url), _) => TabAction::Browser(url.clone()),60
(None, Some(link)) => TabAction::Browser(link.to_owned()),61
(None, None) => TabAction::ResolveLink,62
}63
}64
65
pub fn fallback_tab_link(tab: &ChannelTabRecord, channel_id: &str) -> String {66
channel_tab_link(channel_id, &tab.tab_id, &tab.name)67
}68
69
fn label_width(label: &str, external: bool) -> f32 {70
label.chars().count() as f32 * CHAR_WIDTH + if external { ARROW_WIDTH } else { 0. }71
}72
73
pub fn visible_tab_count(tabs: &[ChannelTabRecord], available_width: f32) -> usize {74
let fixed = label_width(POSTS_LABEL, false) + TAB_GAP + label_width(SHARED_LABEL, false);75
let widths: Vec<f32> = tabs76
.iter()77
.map(|tab| TAB_GAP + label_width(&tab.name, true))78
.collect();79
if fixed + widths.iter().sum::<f32>() <= available_width {80
return tabs.len();81
}82
let room = available_width - fixed - TAB_GAP - OVERFLOW_WIDTH;83
let mut used = 0.;84
widths85
.iter()86
.take_while(|width| {87
used += **width;88
used <= room89
})90
.count()91
}92
93
fn tab_label(94
id: ElementId,95
text: &str,96
active: bool,97
external: bool,98
on_click: impl Fn(&mut Window, &mut App) + 'static,99
) -> Stateful<Div> {100
let color = if active {101
theme::text()102
} else {103
theme::text_muted()104
};105
h_flex()106
.id(id)107
.h(px(TAB_HEIGHT))108
.flex_none()109
.items_center()110
.gap(px(3.))111
.cursor_pointer()112
.border_b_2()113
.border_color(if active {114
theme::accent()115
} else {116
transparent_black()117
})118
.text_size(px(TAB_TEXT_SIZE))119
.font_weight(if active {120
FontWeight::SEMIBOLD121
} else {122
FontWeight::NORMAL123
})124
.text_color(color)125
.hover(|tab| tab.text_color(theme::text()))126
.on_click(move |_, window, cx| on_click(window, cx))127
.child(text.to_owned())128
.when(external, |tab| {129
tab.child(div().text_color(theme::text_faint()).child(EXTERNAL_ARROW))130
})131
}132
133
fn overflow_button(134
hidden: &[(usize, String, bool)],135
embedding: bool,136
actions: &TabBarActions,137
) -> impl IntoElement {138
let entries = hidden.to_vec();139
let open = actions.open.clone();140
let menu_toggled = actions.menu_toggled.clone();141
Button::new("channel-tab-overflow")142
.ghost()143
.compact()144
.label(format!("+{}", hidden.len()))145
.dropdown_menu(move |menu, _, _| {146
entries.iter().fold(menu, |menu, (index, name, website)| {147
let (open, index) = (open.clone(), *index);148
let label = if embedding && *website {149
name.clone()150
} else {151
format!("{name} {EXTERNAL_ARROW}")152
};153
menu.item(154
PopupMenuItem::new(label)155
.on_click(move |_, window, cx| open(index, window, cx)),156
)157
})158
})159
.on_open_change(move |open, window, cx| menu_toggled(*open, window, cx))160
}161
162
pub fn render_tab_bar(163
tabs: &[ChannelTabRecord],164
pane: ChannelPane,165
active_tab_id: Option<&str>,166
embedding: bool,167
available_width: f32,168
actions: &TabBarActions,169
) -> AnyElement {170
let visible = visible_tab_count(tabs, available_width - 2. * BAR_PADDING);171
let select = actions.select.clone();172
let posts = tab_label(173
"channel-tab-posts".into(),174
POSTS_LABEL,175
pane == ChannelPane::Posts,176
false,177
{178
let select = select.clone();179
move |_, cx| select(ChannelPane::Posts, cx)180
},181
);182
let shared = tab_label(183
"channel-tab-shared".into(),184
SHARED_LABEL,185
pane == ChannelPane::Shared,186
false,187
move |_, cx| select(ChannelPane::Shared, cx),188
);189
let configured = tabs.iter().enumerate().take(visible).map(|(index, tab)| {190
let open = actions.open.clone();191
tab_label(192
ElementId::NamedInteger("channel-tab".into(), index as u64),193
&tab.name,194
active_tab_id == Some(tab.tab_id.as_str()),195
!(embedding && tab.is_website()),196
move |window, cx| open(index, window, cx),197
)198
});199
let hidden: Vec<(usize, String, bool)> = tabs200
.iter()201
.enumerate()202
.skip(visible)203
.map(|(index, tab)| (index, tab.name.clone(), tab.is_website()))204
.collect();205
h_flex()206
.w_full()207
.flex_none()208
.px(px(BAR_PADDING))209
.gap(px(TAB_GAP))210
.items_center()211
.border_b_1()212
.border_color(theme::border())213
.child(posts)214
.child(shared)215
.children(configured)216
.when(!hidden.is_empty(), |bar| {217
bar.child(overflow_button(&hidden, embedding, actions))218
})219
.into_any_element()220
}221
222
#[cfg(test)]223
mod tests {224
use store::ChannelTabRecord;225
226
use super::{TabAction, fallback_tab_link, tab_action, visible_tab_count};227
228
fn tab(name: &str, open_url: Option<&str>) -> ChannelTabRecord {229
ChannelTabRecord {230
tab_id: "tab-1".to_owned(),231
name: name.to_owned(),232
definition_id: "app".to_owned(),233
open_url: open_url.map(str::to_owned),234
}235
}236
237
fn website(url: &str) -> ChannelTabRecord {238
ChannelTabRecord {239
definition_id: "com.microsoft.teamspace.tab.web".to_owned(),240
..tab("Docs", Some(url))241
}242
}243
244
#[test]245
fn website_tabs_embed_only_where_the_host_can() {246
let docs = website("https://docs.example");247
assert_eq!(248
tab_action(&docs, true, None),249
TabAction::Embed("https://docs.example".to_owned())250
);251
assert_eq!(252
tab_action(&docs, false, None),253
TabAction::Browser("https://docs.example".to_owned())254
);255
}256
257
#[test]258
fn other_tabs_with_a_page_open_it_in_the_browser() {259
let notes = tab("Notes", Some("https://onenote.example/web"));260
assert_eq!(261
tab_action(¬es, true, None),262
TabAction::Browser("https://onenote.example/web".to_owned())263
);264
}265
266
#[test]267
fn app_tabs_resolve_their_link_once_and_then_reuse_it() {268
let board = tab("Board", None);269
assert_eq!(tab_action(&board, true, None), TabAction::ResolveLink);270
assert_eq!(271
tab_action(&board, true, Some("https://teams.example/l/tab")),272
TabAction::Browser("https://teams.example/l/tab".to_owned())273
);274
}275
276
#[test]277
fn the_fallback_link_is_the_hand_built_deep_link() {278
assert_eq!(279
fallback_tab_link(&tab("Board", None), "19:c@thread.tacv2"),280
"https://teams.microsoft.com/l/channel/19:c@thread.tacv2/tab%3A%3Atab-1?label=Board"281
);282
}283
284
#[test]285
fn every_tab_stays_visible_while_it_fits() {286
let tabs = [tab("Docs", None), tab("Planner", None)];287
assert_eq!(visible_tab_count(&tabs, 600.), 2);288
}289
290
#[test]291
fn tabs_that_do_not_fit_move_into_the_overflow() {292
let tabs: Vec<ChannelTabRecord> = (0..8)293
.map(|n| tab(&format!("Tab number {n}"), None))294
.collect();295
let visible = visible_tab_count(&tabs, 420.);296
assert!(visible > 0 && visible < tabs.len());297
assert_eq!(visible_tab_count(&tabs, 40.), 0);298
}299
}@@ -16,30 +16,35 @@ use gpui_kit::component::{
16
16
};
17
17
use gpui_kit::prelude::FluentBuilder as _;
18
18
use gpui_kit::*;
19
use store::{MessageRecord, OutboxState, OutboxTarget};
19
use store::{ChannelTabRecord, MessageRecord, OutboxState, OutboxTarget};
20
20
use teams_core::{ExecuteAction, FileCard, LinkPreview};
21
21
22
22
mod feed;
23
23
mod pins;
24
24
mod render_env;
25
25
mod scheduled;
26
mod shared;
26
27
27
28
use super::attachments::FileActions;
28
use super::profile_card::opens_profile;
29
29
use super::avatar::{member_stack, person_avatar, spec_avatar, square_avatar, with_presence};
30
use super::channel_tabs::ChannelPane;
30
31
use super::composer::{Composer, ComposerEvent, EditPreview, Outgoing, ReplyPreview};
31
32
use super::message_actions::{Action, MessageMenu, QUICK_REACTION_COUNT};
32
33
use super::message_row::{render_message_row, render_skeleton_row};
33
34
use super::new_chat::{NewChatDraft, NewChatEvent, composer_placeholder, existing_one_on_one};
34
35
use super::post_card::render_post;
36
use super::profile_card::opens_profile;
35
37
use super::reaction_picker::{PickHandler, ReactionPicker};
36
38
use super::reaction_pills::{ReactionControls, ReactionPopover};
37
39
use super::widgets::{icon, symbol};
38
40
use crate::app_state::{AppEvent, AppState, Selection, selection_title};
39
41
use crate::backend::Engine;
40
42
use crate::card_state::CardScope;
43
use crate::channel_files::DownloadSource;
41
44
use crate::data::{is_one_on_one, others};
45
use crate::demo_library::DemoLibrary;
42
46
use crate::downloads::{self, ClickAction, DownloadKey, Downloads, PartFile, RevealTarget};
47
use crate::embedded_web::EmbeddedWeb;
43
48
use crate::emoji;
44
49
use crate::notice::short_error;
45
50
use crate::outbox::{deliver, new_outbox_id, outbox_record, outgoing_of};
@@ -59,6 +64,7 @@ use crate::theme;
59
64
use crate::typing::typing_tooltip;
60
65
use feed::{FeedStash, subject_input};
61
66
use render_env::RenderEnv;
67
use shared::SharedState;
62
68
63
69
const CHAT_OPEN_LIMIT: usize = 60;
64
70
const CHANNEL_OPEN_LIMIT: usize = 300;
@@ -170,6 +176,14 @@ pub struct ConversationView {
170
176
drag_file_count: usize,
171
177
sync_generation: u64,
172
178
window_active: bool,
179
pane: ChannelPane,
180
channel_tabs: Vec<ChannelTabRecord>,
181
tab_links: HashMap<String, String>,
182
web: Option<Entity<EmbeddedWeb>>,
183
web_subscription: Option<Subscription>,
184
shared: SharedState,
185
demo_library: DemoLibrary,
186
new_folder_input: Option<Entity<InputState>>,
173
187
_subscriptions: Vec<Subscription>,
174
188
}
175
189
@@ -184,6 +198,7 @@ fn open_limit(selection: &Selection) -> usize {
184
198
enum DropTarget {
185
199
Chat,
186
200
Channel,
201
Library,
187
202
NewChat,
188
203
}
189
204
@@ -202,6 +217,10 @@ fn drop_overlay_text(title: &str, target: DropTarget, count: usize) -> (String,
202
217
format!("Drop to attach to {title}"),
203
218
format!("{files}. Images go into the message, other files to the channel's Files."),
204
219
),
220
DropTarget::Library => (
221
format!("Drop to upload to {title}"),
222
format!("{files}. Files go into the folder you have open."),
223
),
205
224
DropTarget::NewChat => (
206
225
"Drop to attach to the new chat".to_owned(),
207
226
format!(
@@ -230,20 +249,20 @@ enum DownloadEvent {
230
249
async fn save_file(
231
250
engine: &Engine,
232
251
card: &FileCard,
252
source: &DownloadSource,
233
253
events: &tokio::sync::mpsc::UnboundedSender<DownloadEvent>,
234
254
) -> Result<PathBuf, String> {
235
255
let mut part = PartFile::create(&downloads::downloads_directory(), &card.name)
236
256
.map_err(|error| short_error(&error))?;
237
engine
238
.download_file(
239
&card.open_url,
240
|bytes| part.write(bytes),
241
|percent| {
242
let _ = events.send(DownloadEvent::Progress(percent));
243
},
244
)
245
.await
246
.map_err(|error| short_error(&error))?;
257
let write = |bytes: &[u8]| part.write(bytes);
258
let progress = |percent| {
259
let _ = events.send(DownloadEvent::Progress(percent));
260
};
261
match source {
262
DownloadSource::Share => engine.download_file(&card.open_url, write, progress).await,
263
DownloadSource::Library(file) => engine.download_library_file(file, write, progress).await,
264
}
265
.map_err(|error| short_error(&error))?;
247
266
part.finish().map_err(|error| short_error(&error))
248
267
}
249
268
@@ -268,7 +287,7 @@ impl ConversationView {
268
287
let key = key.clone();
269
288
let conversation_id = conversation_id.clone();
270
289
view.update(cx, |this, cx| {
271
this.activate_file(&conversation_id, &key, card, cx)
290
this.activate_file(&conversation_id, &key, card, DownloadSource::Share, cx)
272
291
})
273
292
.ok();
274
293
}),
@@ -280,12 +299,13 @@ impl ConversationView {
280
299
conversation_id: &str,
281
300
message_key: &str,
282
301
card: FileCard,
302
source: DownloadSource,
283
303
cx: &mut Context<Self>,
284
304
) {
285
305
let key = DownloadKey::new(conversation_id, message_key, &card.open_url);
286
306
match downloads::click_action(self.downloads.state(&key)) {
287
307
ClickAction::Ignore => {}
288
ClickAction::Start => self.start_download(key, card, cx),
308
ClickAction::Start => self.start_download(key, card, source, cx),
289
309
ClickAction::Reveal(path) => {
290
310
let folder = path
291
311
.parent()
@@ -299,7 +319,13 @@ impl ConversationView {
299
319
}
300
320
}
301
321
302
fn start_download(&mut self, key: DownloadKey, card: FileCard, cx: &mut Context<Self>) {
322
fn start_download(
323
&mut self,
324
key: DownloadKey,
325
card: FileCard,
326
source: DownloadSource,
327
cx: &mut Context<Self>,
328
) {
303
329
if !self.downloads.begin(&key) {
304
330
return;
305
331
}
@@ -336,7 +362,7 @@ impl ConversationView {
336
362
return;
337
363
};
338
364
drop(runtime::spawn(async move {
339
let outcome = save_file(&engine, &card, &sender).await;
365
let outcome = save_file(&engine, &card, &source, &sender).await;
340
366
let _ = sender.send(DownloadEvent::Finished(outcome));
341
367
}));
342
368
cx.spawn(async move |this, cx| {
@@ -420,6 +446,14 @@ impl ConversationView {
420
446
drag_file_count: 0,
421
447
sync_generation: 0,
422
448
window_active: window.is_window_active(),
449
pane: ChannelPane::Posts,
450
channel_tabs: Vec::new(),
451
tab_links: HashMap::new(),
452
web: None,
453
web_subscription: None,
454
shared: SharedState::default(),
455
demo_library: DemoLibrary::default(),
456
new_folder_input: None,
423
457
_subscriptions: subscriptions,
424
458
};
425
459
if let Some(selection) = view.app.read(cx).selection.clone() {
@@ -488,6 +522,9 @@ impl ConversationView {
488
522
.as_ref()
489
523
.is_some_and(|current| current.selection.conversation_id() == conversation_id);
490
524
if is_current {
525
if self.shared_active() {
526
self.refresh_shared_items(cx);
527
}
491
528
self.rebuild(false, cx);
492
529
self.mark_read(ReadTrigger::Incoming, cx);
493
530
self.on_pins_changed(conversation_id, cx);
@@ -529,6 +566,7 @@ impl ConversationView {
529
566
}
530
567
}
531
568
AppEvent::Sidebar => {
569
self.reload_channel_tabs(cx);
532
570
self.mark_read(ReadTrigger::Incoming, cx);
533
571
self.refresh_reactor_names(cx);
534
572
if self.draft_active {
@@ -689,11 +727,11 @@ impl ConversationView {
689
727
sync: SyncProgress::default(),
690
728
});
691
729
self.sync_generation += 1;
730
self.reset_channel_tabs(cx);
692
731
self.reload_pending(cx);
693
732
self.notice = None;
694
733
self.scheduled_failure = None;
695
self.app
696
.update(cx, |state, cx| state.refresh_scheduled(cx));
734
self.app.update(cx, |state, cx| state.refresh_scheduled(cx));
697
735
self.rebuild(true, cx);
698
736
self.start_fetch(cx);
699
737
self.mark_read(ReadTrigger::Open, cx);
@@ -929,6 +967,8 @@ impl ConversationView {
929
967
current.first_unread = None;
930
968
let in_channel = matches!(current.selection, Selection::Channel(_));
931
969
if in_channel {
970
self.pane = ChannelPane::Posts;
971
self.close_web();
932
972
match record.reply_to_id.clone() {
933
973
Some(root_id) => {
934
974
self.enter_thread_mode(root_id.clone(), cx);
@@ -2683,6 +2723,7 @@ impl ConversationView {
2683
2723
fn render_drop_overlay(&self, cx: &mut Context<Self>) -> impl IntoElement {
2684
2724
let target = match self.current.as_ref().map(|current| ¤t.selection) {
2685
2725
Some(Selection::Chat(_)) => DropTarget::Chat,
2726
Some(Selection::Channel(_)) if self.shared_active() => DropTarget::Library,
2686
2727
Some(Selection::Channel(_)) => DropTarget::Channel,
2687
2728
None => DropTarget::NewChat,
2688
2729
};
@@ -2719,6 +2760,10 @@ impl ConversationView {
2719
2760
)
2720
2761
.on_drop(cx.listener(|this, dropped: &ExternalPaths, window, cx| {
2721
2762
let paths = dropped.paths().to_vec();
2763
if this.shared_active() {
2764
this.upload_paths(paths, cx);
2765
return;
2766
}
2722
2767
this.composer
2723
2768
.update(cx, |composer, cx| composer.add_paths(paths, window, cx));
2724
2769
}))
@@ -2931,6 +2976,9 @@ impl ConversationView {
2931
2976
2932
2977
impl Render for ConversationView {
2933
2978
fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
2979
if self.web.is_some() && !self.web_active() {
2980
self.close_web();
2981
}
2934
2982
let background = theme::background();
2935
2983
let mut root = v_flex().flex_1().min_w_0().h_full().bg(background);
2936
2984
let drafting = self.draft_active;
@@ -3031,6 +3079,7 @@ impl Render for ConversationView {
3031
3079
Some(current) => root.child(self.render_header(current, cx)),
3032
3080
None => root.child(self.draft.clone()),
3033
3081
};
3082
root = root.children(self.render_tab_bar(window, cx).filter(|_| !drafting));
3034
3083
root = root.children(self.render_pin_banner(cx).filter(|_| !drafting));
3035
3084
let sync_failed = self
3036
3085
.current
@@ -3064,6 +3113,10 @@ impl Render for ConversationView {
3064
3113
let draft = self.draft.read(cx);
3065
3114
let group_name = draft.group_name(cx);
3066
3115
draft.render_empty(&self.app.read(cx).directory, &group_name)
3116
} else if self.shared_active() {
3117
self.render_shared(cx)
3118
} else if let Some(web) = self.web.clone().filter(|_| self.web_active()) {
3119
web.into_any_element()
3067
3120
} else if empty_channel {
3068
3121
div()
3069
3122
.size_full()
@@ -16,30 +16,35 @@ use gpui_kit::component::{16
};16
};17
use gpui_kit::prelude::FluentBuilder as _;17
use gpui_kit::prelude::FluentBuilder as _;18
use gpui_kit::*;18
use gpui_kit::*;19
use store::{MessageRecord, OutboxState, OutboxTarget};19
use store::{ChannelTabRecord, MessageRecord, OutboxState, OutboxTarget};20
use teams_core::{ExecuteAction, FileCard, LinkPreview};20
use teams_core::{ExecuteAction, FileCard, LinkPreview};21
21
22
mod feed;22
mod feed;23
mod pins;23
mod pins;24
mod render_env;24
mod render_env;25
mod scheduled;25
mod scheduled;26
mod shared;26
27
27
use super::attachments::FileActions;28
use super::attachments::FileActions;28
use super::profile_card::opens_profile;29
use super::avatar::{member_stack, person_avatar, spec_avatar, square_avatar, with_presence};29
use super::avatar::{member_stack, person_avatar, spec_avatar, square_avatar, with_presence};30
use super::channel_tabs::ChannelPane;30
use super::composer::{Composer, ComposerEvent, EditPreview, Outgoing, ReplyPreview};31
use super::composer::{Composer, ComposerEvent, EditPreview, Outgoing, ReplyPreview};31
use super::message_actions::{Action, MessageMenu, QUICK_REACTION_COUNT};32
use super::message_actions::{Action, MessageMenu, QUICK_REACTION_COUNT};32
use super::message_row::{render_message_row, render_skeleton_row};33
use super::message_row::{render_message_row, render_skeleton_row};33
use super::new_chat::{NewChatDraft, NewChatEvent, composer_placeholder, existing_one_on_one};34
use super::new_chat::{NewChatDraft, NewChatEvent, composer_placeholder, existing_one_on_one};34
use super::post_card::render_post;35
use super::post_card::render_post;36
use super::profile_card::opens_profile;35
use super::reaction_picker::{PickHandler, ReactionPicker};37
use super::reaction_picker::{PickHandler, ReactionPicker};36
use super::reaction_pills::{ReactionControls, ReactionPopover};38
use super::reaction_pills::{ReactionControls, ReactionPopover};37
use super::widgets::{icon, symbol};39
use super::widgets::{icon, symbol};38
use crate::app_state::{AppEvent, AppState, Selection, selection_title};40
use crate::app_state::{AppEvent, AppState, Selection, selection_title};39
use crate::backend::Engine;41
use crate::backend::Engine;40
use crate::card_state::CardScope;42
use crate::card_state::CardScope;43
use crate::channel_files::DownloadSource;41
use crate::data::{is_one_on_one, others};44
use crate::data::{is_one_on_one, others};45
use crate::demo_library::DemoLibrary;42
use crate::downloads::{self, ClickAction, DownloadKey, Downloads, PartFile, RevealTarget};46
use crate::downloads::{self, ClickAction, DownloadKey, Downloads, PartFile, RevealTarget};47
use crate::embedded_web::EmbeddedWeb;43
use crate::emoji;48
use crate::emoji;44
use crate::notice::short_error;49
use crate::notice::short_error;45
use crate::outbox::{deliver, new_outbox_id, outbox_record, outgoing_of};50
use crate::outbox::{deliver, new_outbox_id, outbox_record, outgoing_of};@@ -59,6 +64,7 @@ use crate::theme;59
use crate::typing::typing_tooltip;64
use crate::typing::typing_tooltip;60
use feed::{FeedStash, subject_input};65
use feed::{FeedStash, subject_input};61
use render_env::RenderEnv;66
use render_env::RenderEnv;67
use shared::SharedState;62
68
63
const CHAT_OPEN_LIMIT: usize = 60;69
const CHAT_OPEN_LIMIT: usize = 60;64
const CHANNEL_OPEN_LIMIT: usize = 300;70
const CHANNEL_OPEN_LIMIT: usize = 300;@@ -170,6 +176,14 @@ pub struct ConversationView {170
drag_file_count: usize,176
drag_file_count: usize,171
sync_generation: u64,177
sync_generation: u64,172
window_active: bool,178
window_active: bool,179
pane: ChannelPane,180
channel_tabs: Vec<ChannelTabRecord>,181
tab_links: HashMap<String, String>,182
web: Option<Entity<EmbeddedWeb>>,183
web_subscription: Option<Subscription>,184
shared: SharedState,185
demo_library: DemoLibrary,186
new_folder_input: Option<Entity<InputState>>,173
_subscriptions: Vec<Subscription>,187
_subscriptions: Vec<Subscription>,174
}188
}175
189
@@ -184,6 +198,7 @@ fn open_limit(selection: &Selection) -> usize {184
enum DropTarget {198
enum DropTarget {185
Chat,199
Chat,186
Channel,200
Channel,201
Library,187
NewChat,202
NewChat,188
}203
}189
204
@@ -202,6 +217,10 @@ fn drop_overlay_text(title: &str, target: DropTarget, count: usize) -> (String,202
format!("Drop to attach to {title}"),217
format!("Drop to attach to {title}"),203
format!("{files}. Images go into the message, other files to the channel's Files."),218
format!("{files}. Images go into the message, other files to the channel's Files."),204
),219
),220
DropTarget::Library => (221
format!("Drop to upload to {title}"),222
format!("{files}. Files go into the folder you have open."),223
),205
DropTarget::NewChat => (224
DropTarget::NewChat => (206
"Drop to attach to the new chat".to_owned(),225
"Drop to attach to the new chat".to_owned(),207
format!(226
format!(@@ -230,20 +249,20 @@ enum DownloadEvent {230
async fn save_file(249
async fn save_file(231
engine: &Engine,250
engine: &Engine,232
card: &FileCard,251
card: &FileCard,252
source: &DownloadSource,233
events: &tokio::sync::mpsc::UnboundedSender<DownloadEvent>,253
events: &tokio::sync::mpsc::UnboundedSender<DownloadEvent>,234
) -> Result<PathBuf, String> {254
) -> Result<PathBuf, String> {235
let mut part = PartFile::create(&downloads::downloads_directory(), &card.name)255
let mut part = PartFile::create(&downloads::downloads_directory(), &card.name)236
.map_err(|error| short_error(&error))?;256
.map_err(|error| short_error(&error))?;237
engine257
let write = |bytes: &[u8]| part.write(bytes);238
.download_file(258
let progress = |percent| {239
&card.open_url,259
let _ = events.send(DownloadEvent::Progress(percent));240
|bytes| part.write(bytes),260
};241
|percent| {261
match source {242
let _ = events.send(DownloadEvent::Progress(percent));262
DownloadSource::Share => engine.download_file(&card.open_url, write, progress).await,243
},263
DownloadSource::Library(file) => engine.download_library_file(file, write, progress).await,244
)264
}245
.await265
.map_err(|error| short_error(&error))?;246
.map_err(|error| short_error(&error))?;247
part.finish().map_err(|error| short_error(&error))266
part.finish().map_err(|error| short_error(&error))248
}267
}249
268
@@ -268,7 +287,7 @@ impl ConversationView {268
let key = key.clone();287
let key = key.clone();269
let conversation_id = conversation_id.clone();288
let conversation_id = conversation_id.clone();270
view.update(cx, |this, cx| {289
view.update(cx, |this, cx| {271
this.activate_file(&conversation_id, &key, card, cx)290
this.activate_file(&conversation_id, &key, card, DownloadSource::Share, cx)272
})291
})273
.ok();292
.ok();274
}),293
}),@@ -280,12 +299,13 @@ impl ConversationView {280
conversation_id: &str,299
conversation_id: &str,281
message_key: &str,300
message_key: &str,282
card: FileCard,301
card: FileCard,302
source: DownloadSource,283
cx: &mut Context<Self>,303
cx: &mut Context<Self>,284
) {304
) {285
let key = DownloadKey::new(conversation_id, message_key, &card.open_url);305
let key = DownloadKey::new(conversation_id, message_key, &card.open_url);286
match downloads::click_action(self.downloads.state(&key)) {306
match downloads::click_action(self.downloads.state(&key)) {287
ClickAction::Ignore => {}307
ClickAction::Ignore => {}288
ClickAction::Start => self.start_download(key, card, cx),308
ClickAction::Start => self.start_download(key, card, source, cx),289
ClickAction::Reveal(path) => {309
ClickAction::Reveal(path) => {290
let folder = path310
let folder = path291
.parent()311
.parent()@@ -299,7 +319,13 @@ impl ConversationView {299
}319
}300
}320
}301
321
302
fn start_download(&mut self, key: DownloadKey, card: FileCard, cx: &mut Context<Self>) {322
fn start_download(323
&mut self,324
key: DownloadKey,325
card: FileCard,326
source: DownloadSource,327
cx: &mut Context<Self>,328
) {303
if !self.downloads.begin(&key) {329
if !self.downloads.begin(&key) {304
return;330
return;305
}331
}@@ -336,7 +362,7 @@ impl ConversationView {336
return;362
return;337
};363
};338
drop(runtime::spawn(async move {364
drop(runtime::spawn(async move {339
let outcome = save_file(&engine, &card, &sender).await;365
let outcome = save_file(&engine, &card, &source, &sender).await;340
let _ = sender.send(DownloadEvent::Finished(outcome));366
let _ = sender.send(DownloadEvent::Finished(outcome));341
}));367
}));342
cx.spawn(async move |this, cx| {368
cx.spawn(async move |this, cx| {@@ -420,6 +446,14 @@ impl ConversationView {420
drag_file_count: 0,446
drag_file_count: 0,421
sync_generation: 0,447
sync_generation: 0,422
window_active: window.is_window_active(),448
window_active: window.is_window_active(),449
pane: ChannelPane::Posts,450
channel_tabs: Vec::new(),451
tab_links: HashMap::new(),452
web: None,453
web_subscription: None,454
shared: SharedState::default(),455
demo_library: DemoLibrary::default(),456
new_folder_input: None,423
_subscriptions: subscriptions,457
_subscriptions: subscriptions,424
};458
};425
if let Some(selection) = view.app.read(cx).selection.clone() {459
if let Some(selection) = view.app.read(cx).selection.clone() {@@ -488,6 +522,9 @@ impl ConversationView {488
.as_ref()522
.as_ref()489
.is_some_and(|current| current.selection.conversation_id() == conversation_id);523
.is_some_and(|current| current.selection.conversation_id() == conversation_id);490
if is_current {524
if is_current {525
if self.shared_active() {526
self.refresh_shared_items(cx);527
}491
self.rebuild(false, cx);528
self.rebuild(false, cx);492
self.mark_read(ReadTrigger::Incoming, cx);529
self.mark_read(ReadTrigger::Incoming, cx);493
self.on_pins_changed(conversation_id, cx);530
self.on_pins_changed(conversation_id, cx);@@ -529,6 +566,7 @@ impl ConversationView {529
}566
}530
}567
}531
AppEvent::Sidebar => {568
AppEvent::Sidebar => {569
self.reload_channel_tabs(cx);532
self.mark_read(ReadTrigger::Incoming, cx);570
self.mark_read(ReadTrigger::Incoming, cx);533
self.refresh_reactor_names(cx);571
self.refresh_reactor_names(cx);534
if self.draft_active {572
if self.draft_active {@@ -689,11 +727,11 @@ impl ConversationView {689
sync: SyncProgress::default(),727
sync: SyncProgress::default(),690
});728
});691
self.sync_generation += 1;729
self.sync_generation += 1;730
self.reset_channel_tabs(cx);692
self.reload_pending(cx);731
self.reload_pending(cx);693
self.notice = None;732
self.notice = None;694
self.scheduled_failure = None;733
self.scheduled_failure = None;695
self.app734
self.app.update(cx, |state, cx| state.refresh_scheduled(cx));696
.update(cx, |state, cx| state.refresh_scheduled(cx));697
self.rebuild(true, cx);735
self.rebuild(true, cx);698
self.start_fetch(cx);736
self.start_fetch(cx);699
self.mark_read(ReadTrigger::Open, cx);737
self.mark_read(ReadTrigger::Open, cx);@@ -929,6 +967,8 @@ impl ConversationView {929
current.first_unread = None;967
current.first_unread = None;930
let in_channel = matches!(current.selection, Selection::Channel(_));968
let in_channel = matches!(current.selection, Selection::Channel(_));931
if in_channel {969
if in_channel {970
self.pane = ChannelPane::Posts;971
self.close_web();932
match record.reply_to_id.clone() {972
match record.reply_to_id.clone() {933
Some(root_id) => {973
Some(root_id) => {934
self.enter_thread_mode(root_id.clone(), cx);974
self.enter_thread_mode(root_id.clone(), cx);@@ -2683,6 +2723,7 @@ impl ConversationView {2683
fn render_drop_overlay(&self, cx: &mut Context<Self>) -> impl IntoElement {2723
fn render_drop_overlay(&self, cx: &mut Context<Self>) -> impl IntoElement {2684
let target = match self.current.as_ref().map(|current| ¤t.selection) {2724
let target = match self.current.as_ref().map(|current| ¤t.selection) {2685
Some(Selection::Chat(_)) => DropTarget::Chat,2725
Some(Selection::Chat(_)) => DropTarget::Chat,2726
Some(Selection::Channel(_)) if self.shared_active() => DropTarget::Library,2686
Some(Selection::Channel(_)) => DropTarget::Channel,2727
Some(Selection::Channel(_)) => DropTarget::Channel,2687
None => DropTarget::NewChat,2728
None => DropTarget::NewChat,2688
};2729
};@@ -2719,6 +2760,10 @@ impl ConversationView {2719
)2760
)2720
.on_drop(cx.listener(|this, dropped: &ExternalPaths, window, cx| {2761
.on_drop(cx.listener(|this, dropped: &ExternalPaths, window, cx| {2721
let paths = dropped.paths().to_vec();2762
let paths = dropped.paths().to_vec();2763
if this.shared_active() {2764
this.upload_paths(paths, cx);2765
return;2766
}2722
this.composer2767
this.composer2723
.update(cx, |composer, cx| composer.add_paths(paths, window, cx));2768
.update(cx, |composer, cx| composer.add_paths(paths, window, cx));2724
}))2769
}))@@ -2931,6 +2976,9 @@ impl ConversationView {2931
2976
2932
impl Render for ConversationView {2977
impl Render for ConversationView {2933
fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {2978
fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {2979
if self.web.is_some() && !self.web_active() {2980
self.close_web();2981
}2934
let background = theme::background();2982
let background = theme::background();2935
let mut root = v_flex().flex_1().min_w_0().h_full().bg(background);2983
let mut root = v_flex().flex_1().min_w_0().h_full().bg(background);2936
let drafting = self.draft_active;2984
let drafting = self.draft_active;@@ -3031,6 +3079,7 @@ impl Render for ConversationView {3031
Some(current) => root.child(self.render_header(current, cx)),3079
Some(current) => root.child(self.render_header(current, cx)),3032
None => root.child(self.draft.clone()),3080
None => root.child(self.draft.clone()),3033
};3081
};3082
root = root.children(self.render_tab_bar(window, cx).filter(|_| !drafting));3034
root = root.children(self.render_pin_banner(cx).filter(|_| !drafting));3083
root = root.children(self.render_pin_banner(cx).filter(|_| !drafting));3035
let sync_failed = self3084
let sync_failed = self3036
.current3085
.current@@ -3064,6 +3113,10 @@ impl Render for ConversationView {3064
let draft = self.draft.read(cx);3113
let draft = self.draft.read(cx);3065
let group_name = draft.group_name(cx);3114
let group_name = draft.group_name(cx);3066
draft.render_empty(&self.app.read(cx).directory, &group_name)3115
draft.render_empty(&self.app.read(cx).directory, &group_name)3116
} else if self.shared_active() {3117
self.render_shared(cx)3118
} else if let Some(web) = self.web.clone().filter(|_| self.web_active()) {3119
web.into_any_element()3067
} else if empty_channel {3120
} else if empty_channel {3068
div()3121
div()3069
.size_full()3122
.size_full()@@ -16,6 +16,7 @@ use crate::notice::short_error;
16
16
use crate::rows::Row;
17
17
use crate::runtime;
18
18
use crate::theme;
19
use crate::views::channel_tabs::ChannelPane;
19
20
use crate::views::composer::{Composer, ComposerEvent, ReplyPreview};
20
21
use crate::views::widgets::icon;
21
22
@@ -214,7 +215,7 @@ impl ConversationView {
214
215
window: &Window,
215
216
cx: &mut Context<Self>,
216
217
) -> Option<AnyElement> {
217
if !self.in_feed() {
218
if !self.in_feed() || self.pane != ChannelPane::Posts {
218
219
return None;
219
220
}
220
221
if !self.new_post_open {
@@ -314,6 +315,9 @@ impl ConversationView {
314
315
}
315
316
316
317
pub(super) fn on_escape(&mut self, window: &mut Window, cx: &mut Context<Self>) -> bool {
318
if self.close_new_folder(cx) {
319
return true;
320
}
317
321
if self.reply_root.is_some() {
318
322
self.close_reply_editor(cx);
319
323
return true;
@@ -16,6 +16,7 @@ use crate::notice::short_error;16
use crate::rows::Row;16
use crate::rows::Row;17
use crate::runtime;17
use crate::runtime;18
use crate::theme;18
use crate::theme;19
use crate::views::channel_tabs::ChannelPane;19
use crate::views::composer::{Composer, ComposerEvent, ReplyPreview};20
use crate::views::composer::{Composer, ComposerEvent, ReplyPreview};20
use crate::views::widgets::icon;21
use crate::views::widgets::icon;21
22
@@ -214,7 +215,7 @@ impl ConversationView {214
window: &Window,215
window: &Window,215
cx: &mut Context<Self>,216
cx: &mut Context<Self>,216
) -> Option<AnyElement> {217
) -> Option<AnyElement> {217
if !self.in_feed() {218
if !self.in_feed() || self.pane != ChannelPane::Posts {218
return None;219
return None;219
}220
}220
if !self.new_post_open {221
if !self.new_post_open {@@ -314,6 +315,9 @@ impl ConversationView {314
}315
}315
316
316
pub(super) fn on_escape(&mut self, window: &mut Window, cx: &mut Context<Self>) -> bool {317
pub(super) fn on_escape(&mut self, window: &mut Window, cx: &mut Context<Self>) -> bool {318
if self.close_new_folder(cx) {319
return true;320
}317
if self.reply_root.is_some() {321
if self.reply_root.is_some() {318
self.close_reply_editor(cx);322
self.close_reply_editor(cx);319
return true;323
return true;@@ -11,6 +11,7 @@ pub mod card_input;
11
11
pub mod card_media;
12
12
pub mod card_table;
13
13
pub mod card_widgets;
14
pub mod channel_tabs;
14
15
pub mod composer;
15
16
pub mod conversation;
16
17
pub mod dialog_overlay;
@@ -30,6 +31,7 @@ pub mod reaction_picker;
30
31
pub mod reaction_pills;
31
32
pub mod saved_panel;
32
33
pub mod scheduled_toolbar;
34
pub mod shared_tab;
33
35
pub mod shell;
34
36
pub mod sidebar;
35
37
pub mod status_bar;
@@ -11,6 +11,7 @@ pub mod card_input;11
pub mod card_media;11
pub mod card_media;12
pub mod card_table;12
pub mod card_table;13
pub mod card_widgets;13
pub mod card_widgets;14
pub mod channel_tabs;14
pub mod composer;15
pub mod composer;15
pub mod conversation;16
pub mod conversation;16
pub mod dialog_overlay;17
pub mod dialog_overlay;@@ -30,6 +31,7 @@ pub mod reaction_picker;30
pub mod reaction_pills;31
pub mod reaction_pills;31
pub mod saved_panel;32
pub mod saved_panel;32
pub mod scheduled_toolbar;33
pub mod scheduled_toolbar;34
pub mod shared_tab;33
pub mod shell;35
pub mod shell;34
pub mod sidebar;36
pub mod sidebar;35
pub mod status_bar;37
pub mod status_bar;@@ -15,6 +15,7 @@ use super::switcher::{Switcher, SwitcherEvent, candidates_from};
15
15
use super::title_bar::render_title_bar;
16
16
use crate::activity::ActivityCenter;
17
17
use crate::app_state::{AppEvent, AppState, Selection};
18
use crate::embedded_web::Overlays;
18
19
use crate::notice::NoticeAction;
19
20
use crate::notify::{NotificationCenter, selection_for};
20
21
use crate::theme;
@@ -384,12 +385,13 @@ impl AppShell {
384
385
return;
385
386
};
386
387
if let Some(card) = &self.profile_card {
387
card.update(cx, |card, cx| card.move_to(request.user_id, request.anchor, cx));
388
card.update(cx, |card, cx| {
389
card.move_to(request.user_id, request.anchor, cx)
390
});
388
391
return;
389
392
}
390
393
let app = self.state.clone();
391
let card =
392
cx.new(|cx| ProfileCard::new(app, request.user_id, request.anchor, window, cx));
394
let card = cx.new(|cx| ProfileCard::new(app, request.user_id, request.anchor, window, cx));
393
395
cx.subscribe_in(
394
396
&card,
395
397
window,
@@ -463,6 +465,17 @@ impl Render for AppShell {
463
465
});
464
466
});
465
467
}
468
let panels = self.switcher.is_some()
469
|| self.activity_panel.is_some()
470
|| self.saved_panel.is_some()
471
|| self.forward_dialog.is_some()
472
|| self.status_dialog.is_some()
473
|| self.profile_card.is_some()
474
|| {
475
let state = self.state.read(cx);
476
state.task_dialog.is_some() || state.status_menu_open
477
};
478
Overlays::update(cx, |overlays| overlays.panels = panels);
466
479
let state = self.state.read(cx);
467
480
let status = render_status_bar(
468
481
state,
@@ -15,6 +15,7 @@ use super::switcher::{Switcher, SwitcherEvent, candidates_from};15
use super::title_bar::render_title_bar;15
use super::title_bar::render_title_bar;16
use crate::activity::ActivityCenter;16
use crate::activity::ActivityCenter;17
use crate::app_state::{AppEvent, AppState, Selection};17
use crate::app_state::{AppEvent, AppState, Selection};18
use crate::embedded_web::Overlays;18
use crate::notice::NoticeAction;19
use crate::notice::NoticeAction;19
use crate::notify::{NotificationCenter, selection_for};20
use crate::notify::{NotificationCenter, selection_for};20
use crate::theme;21
use crate::theme;@@ -384,12 +385,13 @@ impl AppShell {384
return;385
return;385
};386
};386
if let Some(card) = &self.profile_card {387
if let Some(card) = &self.profile_card {387
card.update(cx, |card, cx| card.move_to(request.user_id, request.anchor, cx));388
card.update(cx, |card, cx| {389
card.move_to(request.user_id, request.anchor, cx)390
});388
return;391
return;389
}392
}390
let app = self.state.clone();393
let app = self.state.clone();391
let card =394
let card = cx.new(|cx| ProfileCard::new(app, request.user_id, request.anchor, window, cx));392
cx.new(|cx| ProfileCard::new(app, request.user_id, request.anchor, window, cx));393
cx.subscribe_in(395
cx.subscribe_in(394
&card,396
&card,395
window,397
window,@@ -463,6 +465,17 @@ impl Render for AppShell {463
});465
});464
});466
});465
}467
}468
let panels = self.switcher.is_some()469
|| self.activity_panel.is_some()470
|| self.saved_panel.is_some()471
|| self.forward_dialog.is_some()472
|| self.status_dialog.is_some()473
|| self.profile_card.is_some()474
|| {475
let state = self.state.read(cx);476
state.task_dialog.is_some() || state.status_menu_open477
};478
Overlays::update(cx, |overlays| overlays.panels = panels);466
let state = self.state.read(cx);479
let state = self.state.read(cx);467
let status = render_status_bar(480
let status = render_status_bar(468
state,481
state,@@ -8,10 +8,12 @@ use gpui_kit::component::menu::{ContextMenuExt as _, PopupMenu, PopupMenuItem};
8
8
use gpui_kit::component::{WindowExt as _, h_flex, tooltip::Tooltip, v_flex};
9
9
use gpui_kit::prelude::FluentBuilder as _;
10
10
use gpui_kit::*;
11
use store::{ChannelRecord, SidebarTeam, Store, TeamRecord};
11
use store::{
12
ChannelNotificationLevel, ChannelNotifications, ChannelRecord, SidebarTeam, Store, TeamRecord,
13
};
12
14
13
15
use super::avatar::{spec_avatar, square_avatar, with_presence};
14
use super::widgets::{count_badge, dot, icon, symbol, unread_marker};
16
use super::widgets::{count_badge, dot, icon, unread_marker};
15
17
use crate::app_state::{AppEvent, AppState, Selection};
16
18
use crate::chat_actions::TITLE_LIMIT;
17
19
use crate::data::{Directory, FolderKind};
@@ -43,6 +45,7 @@ const REVEAL_ROW_HEIGHT: f32 = 32.;
43
45
const NEW_CHAT_BUTTON_SIZE: f32 = 34.;
44
46
const MENU_ICON_SIZE: f32 = 15.;
45
47
const MUTED_ICON_SIZE: f32 = 13.;
48
const NOTIFICATION_ICON_SIZE: f32 = 13.;
46
49
47
50
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
48
51
enum SidebarTab {
@@ -883,7 +886,7 @@ impl SidebarView {
883
886
team: &TeamRecord,
884
887
channel: &ChannelRecord,
885
888
selected: bool,
886
followed: bool,
889
notifications: ChannelNotifications,
887
890
) -> AnyElement {
888
891
let unread = channel.unread;
889
892
let state = self.state.clone();
@@ -933,7 +936,7 @@ impl SidebarView {
933
936
.text_color(theme::text())
934
937
.child(format!("{} / {}", team.name, channel.name)),
935
938
)
936
.when(followed, |line| line.child(followed_bell()))
939
.children(notification_badge(notifications.level))
937
940
.child(
938
941
div()
939
942
.flex_none()
@@ -966,12 +969,15 @@ impl SidebarView {
966
969
let selection = selection.clone();
967
970
state.update(cx, |state, cx| state.select(selection, cx));
968
971
})
969
.context_menu(move |popup, _, _| {
970
popup.item(follow_item(
972
.context_menu(move |popup, window, cx| {
973
channel_menu(
974
popup,
975
window,
976
cx,
971
977
menu_state.clone(),
972
menu_channel_id.clone(),
973
followed,
974
))
978
&menu_channel_id,
979
notifications,
980
)
975
981
})
976
982
.into_any_element()
977
983
}
@@ -996,7 +1002,6 @@ impl SidebarView {
996
1002
selected: Option<&Selection>,
997
1003
cx: &mut Context<Self>,
998
1004
) -> Div {
999
let followed = self.state.read(cx).followed_channels.clone();
1000
1005
let team_id = entry.team.id.clone();
1001
1006
let expanded = team_expanded(&team_id, &self.collapsed_teams);
1002
1007
let unread = entry.channels.iter().any(|channel| channel.unread);
@@ -1059,7 +1064,7 @@ impl SidebarView {
1059
1064
list = list.child(self.team_channel_row(
1060
1065
channel,
1061
1066
is_selected(channel),
1062
followed.contains(&channel.id),
1067
entry.channel_notifications(&channel.id),
1063
1068
));
1064
1069
}
1065
1070
let hidden: Vec<&ChannelRecord> = entry
@@ -1089,7 +1094,7 @@ impl SidebarView {
1089
1094
list = list.child(self.team_channel_row(
1090
1095
channel,
1091
1096
false,
1092
followed.contains(&channel.id),
1097
entry.channel_notifications(&channel.id),
1093
1098
));
1094
1099
}
1095
1100
}
@@ -1137,7 +1142,7 @@ impl SidebarView {
1137
1142
&self,
1138
1143
channel: &ChannelRecord,
1139
1144
is_selected: bool,
1140
followed: bool,
1145
notifications: ChannelNotifications,
1141
1146
) -> impl IntoElement {
1142
1147
let state = self.state.clone();
1143
1148
let menu_state = self.state.clone();
@@ -1180,33 +1185,35 @@ impl SidebarView {
1180
1185
.text_color(theme::text())
1181
1186
.child(channel.name.clone()),
1182
1187
)
1183
.when(followed, |row| row.child(followed_bell()))
1188
.children(notification_badge(notifications.level))
1184
1189
.when(channel.unread, |row| row.child(dot(7.)))
1185
1190
.on_click(move |_, _, cx| {
1186
1191
let selection = selection.clone();
1187
1192
state.update(cx, |state, cx| state.select(selection, cx));
1188
1193
})
1189
.context_menu(move |popup, _, _| {
1190
popup.item(follow_item(
1194
.context_menu(move |popup, window, cx| {
1195
channel_menu(
1196
popup,
1197
window,
1198
cx,
1191
1199
menu_state.clone(),
1192
menu_channel_id.clone(),
1193
followed,
1194
))
1200
&menu_channel_id,
1201
notifications,
1202
)
1195
1203
})
1196
1204
}
1197
1205
1198
1206
fn channels_body(&self, cx: &mut Context<Self>) -> AnyElement {
1199
let (sidebar, pinned_ids, followed, selected) = {
1207
let (sidebar, pinned_ids, selected) = {
1200
1208
let state = self.state.read(cx);
1201
1209
(
1202
1210
state.sidebar.clone(),
1203
1211
state.directory.pinned_channels.clone(),
1204
state.followed_channels.clone(),
1205
1212
state.selection.clone().filter(|_| !state.new_chat),
1206
1213
)
1207
1214
};
1208
1215
let mut list = v_flex().w_full().pb(px(12.));
1209
let pinned: Vec<(&TeamRecord, &ChannelRecord)> = pinned_ids
1216
let pinned: Vec<(&SidebarTeam, &ChannelRecord)> = pinned_ids
1210
1217
.iter()
1211
1218
.filter_map(|id| {
1212
1219
sidebar.teams.iter().find_map(|entry| {
@@ -1214,20 +1221,20 @@ impl SidebarView {
1214
1221
.channels
1215
1222
.iter()
1216
1223
.find(|channel| &channel.id == id)
1217
.map(|channel| (&entry.team, channel))
1224
.map(|channel| (entry, channel))
1218
1225
})
1219
1226
})
1220
1227
.collect();
1221
1228
if !pinned.is_empty() {
1222
1229
list = list.child(self.plain_header(PINNED_LABEL));
1223
for (team, channel) in pinned {
1230
for (entry, channel) in pinned {
1224
1231
let is_selected = selected == Some(Selection::Channel(channel.id.clone()));
1225
1232
list = list.child(self.channel_row(
1226
1233
&channel.id,
1227
team,
1234
&entry.team,
1228
1235
channel,
1229
1236
is_selected,
1230
followed.contains(&channel.id),
1237
entry.channel_notifications(&channel.id),
1231
1238
));
1232
1239
}
1233
1240
}
@@ -1269,18 +1276,70 @@ impl SidebarView {
1269
1276
}
1270
1277
}
1271
1278
1272
fn followed_bell() -> impl IntoElement {
1273
symbol("notifications", 12., theme::text_muted())
1279
fn notification_badge(level: ChannelNotificationLevel) -> Option<impl IntoElement> {
1280
let name = match level {
1281
ChannelNotificationLevel::BannerAndFeed => IconName::Bell,
1282
ChannelNotificationLevel::Off => IconName::BellOff,
1283
ChannelNotificationLevel::Feed => return None,
1284
};
1285
Some(icon(name, NOTIFICATION_ICON_SIZE, theme::text_muted()))
1274
1286
}
1275
1287
1276
fn follow_item(state: Entity<AppState>, channel_id: String, followed: bool) -> PopupMenuItem {
1277
PopupMenuItem::new("Notify on all posts")
1278
.checked(followed)
1279
.on_click(move |_, _, cx| {
1280
state.update(cx, |state, cx| {
1281
state.toggle_followed_channel(&channel_id, cx)
1282
});
1283
})
1288
fn channel_menu(
1289
popup: PopupMenu,
1290
window: &mut Window,
1291
cx: &mut Context<PopupMenu>,
1292
state: Entity<AppState>,
1293
channel_id: &str,
1294
notifications: ChannelNotifications,
1295
) -> PopupMenu {
1296
let channel_id = channel_id.to_owned();
1297
popup.submenu_with_icon(
1298
Some(menu_icon(IconName::Bell)),
1299
"Notifications",
1300
window,
1301
cx,
1302
move |submenu, _, _| {
1303
let level_item = |label: &'static str, level: ChannelNotificationLevel| {
1304
let (state, channel_id) = (state.clone(), channel_id.clone());
1305
PopupMenuItem::new(label)
1306
.checked(notifications.level == level)
1307
.on_click(move |_, _, cx| {
1308
let changed = ChannelNotifications {
1309
level,
1310
include_replies: notifications.include_replies
1311
&& level != ChannelNotificationLevel::Off,
1312
};
1313
state.update(cx, |state, cx| {
1314
state.set_channel_notifications(&channel_id, changed, cx)
1315
});
1316
})
1317
};
1318
let (replies_state, replies_id) = (state.clone(), channel_id.clone());
1319
submenu
1320
.item(level_item(
1321
"Banner and activity",
1322
ChannelNotificationLevel::BannerAndFeed,
1323
))
1324
.item(level_item("Activity only", ChannelNotificationLevel::Feed))
1325
.item(level_item("Off", ChannelNotificationLevel::Off))
1326
.separator()
1327
.item(
1328
PopupMenuItem::new("Include thread replies")
1329
.checked(notifications.include_replies)
1330
.disabled(notifications.level == ChannelNotificationLevel::Off)
1331
.on_click(move |_, _, cx| {
1332
let changed = ChannelNotifications {
1333
level: notifications.level,
1334
include_replies: !notifications.include_replies,
1335
};
1336
replies_state.update(cx, |state, cx| {
1337
state.set_channel_notifications(&replies_id, changed, cx)
1338
});
1339
}),
1340
)
1341
},
1342
)
1284
1343
}
1285
1344
1286
1345
fn team_expanded(team_id: &str, collapsed_teams: &HashSet<String>) -> bool {
@@ -8,10 +8,12 @@ use gpui_kit::component::menu::{ContextMenuExt as _, PopupMenu, PopupMenuItem};8
use gpui_kit::component::{WindowExt as _, h_flex, tooltip::Tooltip, v_flex};8
use gpui_kit::component::{WindowExt as _, h_flex, tooltip::Tooltip, v_flex};9
use gpui_kit::prelude::FluentBuilder as _;9
use gpui_kit::prelude::FluentBuilder as _;10
use gpui_kit::*;10
use gpui_kit::*;11
use store::{ChannelRecord, SidebarTeam, Store, TeamRecord};11
use store::{12
ChannelNotificationLevel, ChannelNotifications, ChannelRecord, SidebarTeam, Store, TeamRecord,13
};12
14
13
use super::avatar::{spec_avatar, square_avatar, with_presence};15
use super::avatar::{spec_avatar, square_avatar, with_presence};14
use super::widgets::{count_badge, dot, icon, symbol, unread_marker};16
use super::widgets::{count_badge, dot, icon, unread_marker};15
use crate::app_state::{AppEvent, AppState, Selection};17
use crate::app_state::{AppEvent, AppState, Selection};16
use crate::chat_actions::TITLE_LIMIT;18
use crate::chat_actions::TITLE_LIMIT;17
use crate::data::{Directory, FolderKind};19
use crate::data::{Directory, FolderKind};@@ -43,6 +45,7 @@ const REVEAL_ROW_HEIGHT: f32 = 32.;43
const NEW_CHAT_BUTTON_SIZE: f32 = 34.;45
const NEW_CHAT_BUTTON_SIZE: f32 = 34.;44
const MENU_ICON_SIZE: f32 = 15.;46
const MENU_ICON_SIZE: f32 = 15.;45
const MUTED_ICON_SIZE: f32 = 13.;47
const MUTED_ICON_SIZE: f32 = 13.;48
const NOTIFICATION_ICON_SIZE: f32 = 13.;46
49
47
#[derive(Debug, Clone, Copy, PartialEq, Eq)]50
#[derive(Debug, Clone, Copy, PartialEq, Eq)]48
enum SidebarTab {51
enum SidebarTab {@@ -883,7 +886,7 @@ impl SidebarView {883
team: &TeamRecord,886
team: &TeamRecord,884
channel: &ChannelRecord,887
channel: &ChannelRecord,885
selected: bool,888
selected: bool,886
followed: bool,889
notifications: ChannelNotifications,887
) -> AnyElement {890
) -> AnyElement {888
let unread = channel.unread;891
let unread = channel.unread;889
let state = self.state.clone();892
let state = self.state.clone();@@ -933,7 +936,7 @@ impl SidebarView {933
.text_color(theme::text())936
.text_color(theme::text())934
.child(format!("{} / {}", team.name, channel.name)),937
.child(format!("{} / {}", team.name, channel.name)),935
)938
)936
.when(followed, |line| line.child(followed_bell()))939
.children(notification_badge(notifications.level))937
.child(940
.child(938
div()941
div()939
.flex_none()942
.flex_none()@@ -966,12 +969,15 @@ impl SidebarView {966
let selection = selection.clone();969
let selection = selection.clone();967
state.update(cx, |state, cx| state.select(selection, cx));970
state.update(cx, |state, cx| state.select(selection, cx));968
})971
})969
.context_menu(move |popup, _, _| {972
.context_menu(move |popup, window, cx| {970
popup.item(follow_item(973
channel_menu(974
popup,975
window,976
cx,971
menu_state.clone(),977
menu_state.clone(),972
menu_channel_id.clone(),978
&menu_channel_id,973
followed,979
notifications,974
))980
)975
})981
})976
.into_any_element()982
.into_any_element()977
}983
}@@ -996,7 +1002,6 @@ impl SidebarView {996
selected: Option<&Selection>,1002
selected: Option<&Selection>,997
cx: &mut Context<Self>,1003
cx: &mut Context<Self>,998
) -> Div {1004
) -> Div {999
let followed = self.state.read(cx).followed_channels.clone();1000
let team_id = entry.team.id.clone();1005
let team_id = entry.team.id.clone();1001
let expanded = team_expanded(&team_id, &self.collapsed_teams);1006
let expanded = team_expanded(&team_id, &self.collapsed_teams);1002
let unread = entry.channels.iter().any(|channel| channel.unread);1007
let unread = entry.channels.iter().any(|channel| channel.unread);@@ -1059,7 +1064,7 @@ impl SidebarView {1059
list = list.child(self.team_channel_row(1064
list = list.child(self.team_channel_row(1060
channel,1065
channel,1061
is_selected(channel),1066
is_selected(channel),1062
followed.contains(&channel.id),1067
entry.channel_notifications(&channel.id),1063
));1068
));1064
}1069
}1065
let hidden: Vec<&ChannelRecord> = entry1070
let hidden: Vec<&ChannelRecord> = entry@@ -1089,7 +1094,7 @@ impl SidebarView {1089
list = list.child(self.team_channel_row(1094
list = list.child(self.team_channel_row(1090
channel,1095
channel,1091
false,1096
false,1092
followed.contains(&channel.id),1097
entry.channel_notifications(&channel.id),1093
));1098
));1094
}1099
}1095
}1100
}@@ -1137,7 +1142,7 @@ impl SidebarView {1137
&self,1142
&self,1138
channel: &ChannelRecord,1143
channel: &ChannelRecord,1139
is_selected: bool,1144
is_selected: bool,1140
followed: bool,1145
notifications: ChannelNotifications,1141
) -> impl IntoElement {1146
) -> impl IntoElement {1142
let state = self.state.clone();1147
let state = self.state.clone();1143
let menu_state = self.state.clone();1148
let menu_state = self.state.clone();@@ -1180,33 +1185,35 @@ impl SidebarView {1180
.text_color(theme::text())1185
.text_color(theme::text())1181
.child(channel.name.clone()),1186
.child(channel.name.clone()),1182
)1187
)1183
.when(followed, |row| row.child(followed_bell()))1188
.children(notification_badge(notifications.level))1184
.when(channel.unread, |row| row.child(dot(7.)))1189
.when(channel.unread, |row| row.child(dot(7.)))1185
.on_click(move |_, _, cx| {1190
.on_click(move |_, _, cx| {1186
let selection = selection.clone();1191
let selection = selection.clone();1187
state.update(cx, |state, cx| state.select(selection, cx));1192
state.update(cx, |state, cx| state.select(selection, cx));1188
})1193
})1189
.context_menu(move |popup, _, _| {1194
.context_menu(move |popup, window, cx| {1190
popup.item(follow_item(1195
channel_menu(1196
popup,1197
window,1198
cx,1191
menu_state.clone(),1199
menu_state.clone(),1192
menu_channel_id.clone(),1200
&menu_channel_id,1193
followed,1201
notifications,1194
))1202
)1195
})1203
})1196
}1204
}1197
1205
1198
fn channels_body(&self, cx: &mut Context<Self>) -> AnyElement {1206
fn channels_body(&self, cx: &mut Context<Self>) -> AnyElement {1199
let (sidebar, pinned_ids, followed, selected) = {1207
let (sidebar, pinned_ids, selected) = {1200
let state = self.state.read(cx);1208
let state = self.state.read(cx);1201
(1209
(1202
state.sidebar.clone(),1210
state.sidebar.clone(),1203
state.directory.pinned_channels.clone(),1211
state.directory.pinned_channels.clone(),1204
state.followed_channels.clone(),1205
state.selection.clone().filter(|_| !state.new_chat),1212
state.selection.clone().filter(|_| !state.new_chat),1206
)1213
)1207
};1214
};1208
let mut list = v_flex().w_full().pb(px(12.));1215
let mut list = v_flex().w_full().pb(px(12.));1209
let pinned: Vec<(&TeamRecord, &ChannelRecord)> = pinned_ids1216
let pinned: Vec<(&SidebarTeam, &ChannelRecord)> = pinned_ids1210
.iter()1217
.iter()1211
.filter_map(|id| {1218
.filter_map(|id| {1212
sidebar.teams.iter().find_map(|entry| {1219
sidebar.teams.iter().find_map(|entry| {@@ -1214,20 +1221,20 @@ impl SidebarView {1214
.channels1221
.channels1215
.iter()1222
.iter()1216
.find(|channel| &channel.id == id)1223
.find(|channel| &channel.id == id)1217
.map(|channel| (&entry.team, channel))1224
.map(|channel| (entry, channel))1218
})1225
})1219
})1226
})1220
.collect();1227
.collect();1221
if !pinned.is_empty() {1228
if !pinned.is_empty() {1222
list = list.child(self.plain_header(PINNED_LABEL));1229
list = list.child(self.plain_header(PINNED_LABEL));1223
for (team, channel) in pinned {1230
for (entry, channel) in pinned {1224
let is_selected = selected == Some(Selection::Channel(channel.id.clone()));1231
let is_selected = selected == Some(Selection::Channel(channel.id.clone()));1225
list = list.child(self.channel_row(1232
list = list.child(self.channel_row(1226
&channel.id,1233
&channel.id,1227
team,1234
&entry.team,1228
channel,1235
channel,1229
is_selected,1236
is_selected,1230
followed.contains(&channel.id),1237
entry.channel_notifications(&channel.id),1231
));1238
));1232
}1239
}1233
}1240
}@@ -1269,18 +1276,70 @@ impl SidebarView {1269
}1276
}1270
}1277
}1271
1278
1272
fn followed_bell() -> impl IntoElement {1279
fn notification_badge(level: ChannelNotificationLevel) -> Option<impl IntoElement> {1273
symbol("notifications", 12., theme::text_muted())1280
let name = match level {1281
ChannelNotificationLevel::BannerAndFeed => IconName::Bell,1282
ChannelNotificationLevel::Off => IconName::BellOff,1283
ChannelNotificationLevel::Feed => return None,1284
};1285
Some(icon(name, NOTIFICATION_ICON_SIZE, theme::text_muted()))1274
}1286
}1275
1287
1276
fn follow_item(state: Entity<AppState>, channel_id: String, followed: bool) -> PopupMenuItem {1288
fn channel_menu(1277
PopupMenuItem::new("Notify on all posts")1289
popup: PopupMenu,1278
.checked(followed)1290
window: &mut Window,1279
.on_click(move |_, _, cx| {1291
cx: &mut Context<PopupMenu>,1280
state.update(cx, |state, cx| {1292
state: Entity<AppState>,1281
state.toggle_followed_channel(&channel_id, cx)1293
channel_id: &str,1282
});1294
notifications: ChannelNotifications,1283
})1295
) -> PopupMenu {1296
let channel_id = channel_id.to_owned();1297
popup.submenu_with_icon(1298
Some(menu_icon(IconName::Bell)),1299
"Notifications",1300
window,1301
cx,1302
move |submenu, _, _| {1303
let level_item = |label: &'static str, level: ChannelNotificationLevel| {1304
let (state, channel_id) = (state.clone(), channel_id.clone());1305
PopupMenuItem::new(label)1306
.checked(notifications.level == level)1307
.on_click(move |_, _, cx| {1308
let changed = ChannelNotifications {1309
level,1310
include_replies: notifications.include_replies1311
&& level != ChannelNotificationLevel::Off,1312
};1313
state.update(cx, |state, cx| {1314
state.set_channel_notifications(&channel_id, changed, cx)1315
});1316
})1317
};1318
let (replies_state, replies_id) = (state.clone(), channel_id.clone());1319
submenu1320
.item(level_item(1321
"Banner and activity",1322
ChannelNotificationLevel::BannerAndFeed,1323
))1324
.item(level_item("Activity only", ChannelNotificationLevel::Feed))1325
.item(level_item("Off", ChannelNotificationLevel::Off))1326
.separator()1327
.item(1328
PopupMenuItem::new("Include thread replies")1329
.checked(notifications.include_replies)1330
.disabled(notifications.level == ChannelNotificationLevel::Off)1331
.on_click(move |_, _, cx| {1332
let changed = ChannelNotifications {1333
level: notifications.level,1334
include_replies: !notifications.include_replies,1335
};1336
replies_state.update(cx, |state, cx| {1337
state.set_channel_notifications(&replies_id, changed, cx)1338
});1339
}),1340
)1341
},1342
)1284
}1343
}1285
1344
1286
fn team_expanded(team_id: &str, collapsed_teams: &HashSet<String>) -> bool {1345
fn team_expanded(team_id: &str, collapsed_teams: &HashSet<String>) -> bool {@@ -0,0 +1,324 @@
1
use std::collections::HashMap;
2
3
use serde_json::{Value, json};
4
use session::{Method, Request, Scope, Session};
5
6
use crate::error::{Error, Result};
7
use crate::pins::{CsaTransport, DEFAULT_REGION, SessionTransport};
8
9
pub const NSS_RESOURCE: &str = "https://uis.teams.microsoft.com";
10
const NSS_SCOPE: &str = "user_impersonation";
11
pub(crate) const PROPERTY_NAME: &str = "channelNotificationSettings";
12
const NSS_BATCH_LIMIT: usize = 100;
13
14
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
15
pub enum ChannelNotificationLevel {
16
BannerAndFeed,
17
#[default]
18
Feed,
19
Off,
20
}
21
22
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
23
pub struct ChannelNotifications {
24
pub level: ChannelNotificationLevel,
25
pub include_replies: bool,
26
}
27
28
impl ChannelNotifications {
29
pub fn from_followed(followed: bool) -> Self {
30
if followed {
31
ChannelNotifications {
32
level: ChannelNotificationLevel::BannerAndFeed,
33
include_replies: true,
34
}
35
} else {
36
ChannelNotifications::default()
37
}
38
}
39
40
pub fn property_value(self) -> String {
41
let mut settings = match self.level {
42
ChannelNotificationLevel::BannerAndFeed => {
43
json!({"allNewPosts": "On", "dskNotif": "On"})
44
}
45
ChannelNotificationLevel::Feed => json!({"allNewPosts": "On"}),
46
ChannelNotificationLevel::Off => json!({"allNewPosts": "Off"}),
47
};
48
settings["includeReplies"] =
49
json!(self.include_replies && self.level != ChannelNotificationLevel::Off);
50
settings.to_string()
51
}
52
}
53
54
pub fn parse_property(raw: &str) -> Option<ChannelNotifications> {
55
let settings: Value = serde_json::from_str(raw).ok()?;
56
let level = match (
57
settings.get("allNewPosts").and_then(Value::as_str)?,
58
settings.get("dskNotif").and_then(Value::as_str),
59
) {
60
("On", Some("On")) => ChannelNotificationLevel::BannerAndFeed,
61
("On", _) => ChannelNotificationLevel::Feed,
62
_ => ChannelNotificationLevel::Off,
63
};
64
Some(ChannelNotifications {
65
level,
66
include_replies: settings
67
.get("includeReplies")
68
.and_then(Value::as_bool)
69
.unwrap_or(false),
70
})
71
}
72
73
pub fn parse_nss_batch(body: &Value) -> HashMap<String, ChannelNotifications> {
74
body.get("results")
75
.and_then(Value::as_array)
76
.into_iter()
77
.flatten()
78
.filter_map(|result| {
79
let settings = result
80
.get("settings")
81
.filter(|settings| settings.is_object())?;
82
let level = match settings.get("allNewPosts").and_then(Value::as_str)? {
83
"BannerAndFeed" => ChannelNotificationLevel::BannerAndFeed,
84
"Feed" => ChannelNotificationLevel::Feed,
85
_ => ChannelNotificationLevel::Off,
86
};
87
Some((
88
result.get("channelId")?.as_str()?.to_owned(),
89
ChannelNotifications {
90
level,
91
include_replies: settings
92
.get("includeReplies")
93
.and_then(Value::as_bool)
94
.unwrap_or(false),
95
},
96
))
97
})
98
.collect()
99
}
100
101
pub struct ChannelSettings<T: CsaTransport = SessionTransport> {
102
transport: T,
103
url: String,
104
}
105
106
impl ChannelSettings<SessionTransport> {
107
pub fn new(session: &Session) -> Self {
108
ChannelSettings::with_transport(
109
SessionTransport::with_scope(session, Scope::new(NSS_RESOURCE, NSS_SCOPE)),
110
DEFAULT_REGION,
111
)
112
}
113
}
114
115
impl<T: CsaTransport> ChannelSettings<T> {
116
pub fn with_transport(transport: T, region: &str) -> Self {
117
ChannelSettings {
118
transport,
119
url: format!(
120
"https://teams.cloud.microsoft/api/nss/{region}/v1/me/notificationSettings/channels/batch"
121
),
122
}
123
}
124
125
pub async fn fetch(
126
&self,
127
channel_ids: &[String],
128
) -> Result<HashMap<String, ChannelNotifications>> {
129
let mut settings = HashMap::new();
130
for batch in channel_ids.chunks(NSS_BATCH_LIMIT) {
131
let answer = self
132
.transport
133
.send(Request::with_body(
134
Method::Post,
135
&self.url,
136
json!({"channelIds": batch}),
137
))
138
.await?;
139
if !answer.is_success() {
140
return Err(Error::UnexpectedAnswer(format!(
141
"channel settings answered {}",
142
answer.status
143
)));
144
}
145
settings.extend(parse_nss_batch(&answer.body));
146
}
147
Ok(settings)
148
}
149
}
150
151
#[cfg(test)]
152
mod tests {
153
use std::collections::VecDeque;
154
use std::sync::Mutex;
155
156
use session::ApiResponse;
157
158
use super::*;
159
use crate::conversations::Conversations;
160
use crate::messages::MessageTransport;
161
162
struct Canned {
163
answers: Mutex<VecDeque<(u16, Value)>>,
164
requests: Mutex<Vec<Request>>,
165
}
166
167
impl CsaTransport for &Canned {
168
async fn send(&self, request: Request) -> Result<ApiResponse> {
169
self.requests.lock().unwrap().push(request);
170
let (status, body) = self.answers.lock().unwrap().pop_front().expect("exhausted");
171
Ok(ApiResponse {
172
status,
173
body,
174
retry_after: None,
175
})
176
}
177
}
178
179
impl MessageTransport for &Canned {
180
async fn send(&self, request: Request) -> Result<ApiResponse> {
181
CsaTransport::send(self, request).await
182
}
183
}
184
185
fn canned(answers: Vec<(u16, Value)>) -> Canned {
186
Canned {
187
answers: Mutex::new(answers.into()),
188
requests: Mutex::new(Vec::new()),
189
}
190
}
191
192
#[test]
193
fn property_maps_the_three_levels() {
194
let banner =
195
parse_property(r#"{"allNewPosts":"On","dskNotif":"On","includeReplies":true}"#);
196
assert_eq!(
197
banner,
198
Some(ChannelNotifications {
199
level: ChannelNotificationLevel::BannerAndFeed,
200
include_replies: true
201
})
202
);
203
let feed = parse_property(r#"{"allNewPosts":"On","latestCnsVersion":1}"#).unwrap();
204
assert_eq!(feed.level, ChannelNotificationLevel::Feed);
205
assert!(!feed.include_replies);
206
let off = parse_property(r#"{"allNewPosts":"Off","includeReplies":false}"#).unwrap();
207
assert_eq!(off.level, ChannelNotificationLevel::Off);
208
}
209
210
#[test]
211
fn unreadable_property_is_missing() {
212
assert_eq!(parse_property("not json"), None);
213
assert_eq!(parse_property(r#"{"includeReplies":true}"#), None);
214
}
215
216
#[test]
217
fn followed_without_a_value_means_banner_with_replies() {
218
assert_eq!(
219
ChannelNotifications::from_followed(true),
220
ChannelNotifications {
221
level: ChannelNotificationLevel::BannerAndFeed,
222
include_replies: true
223
}
224
);
225
assert_eq!(
226
ChannelNotifications::from_followed(false).level,
227
ChannelNotificationLevel::Feed
228
);
229
}
230
231
#[test]
232
fn nss_batch_skips_channels_without_settings() {
233
let body = json!({"results": [
234
{"channelId": "19:a", "success": true, "settings": {"allNewPosts": "BannerAndFeed", "includeReplies": true}},
235
{"channelId": "19:b", "success": true, "settings": {"allNewPosts": "Feed"}},
236
{"channelId": "19:c", "success": true, "settings": {"allNewPosts": "Off"}},
237
{"channelId": "19:d", "success": true, "settings": null},
238
{"channelId": "19:e", "success": false, "settings": null, "errorMessage": "x"},
239
]});
240
let parsed = parse_nss_batch(&body);
241
assert_eq!(parsed.len(), 3);
242
assert_eq!(
243
parsed["19:a"].level,
244
ChannelNotificationLevel::BannerAndFeed
245
);
246
assert!(parsed["19:a"].include_replies);
247
assert_eq!(parsed["19:b"].level, ChannelNotificationLevel::Feed);
248
assert_eq!(parsed["19:c"].level, ChannelNotificationLevel::Off);
249
}
250
251
#[tokio::test]
252
async fn fetch_splits_into_batches_of_one_hundred() {
253
let transport = canned(vec![
254
(200, json!({"results": []})),
255
(200, json!({"results": []})),
256
]);
257
let ids: Vec<String> = (0..101).map(|index| format!("19:{index}")).collect();
258
ChannelSettings::with_transport(&transport, "emea")
259
.fetch(&ids)
260
.await
261
.unwrap();
262
let requests = transport.requests.lock().unwrap();
263
let sizes: Vec<usize> = requests
264
.iter()
265
.map(|request| {
266
request.body.as_ref().unwrap()["channelIds"]
267
.as_array()
268
.unwrap()
269
.len()
270
})
271
.collect();
272
assert_eq!(sizes, [100, 1]);
273
}
274
275
#[tokio::test]
276
async fn write_puts_the_settings_as_a_json_string() {
277
let transport = canned(vec![
278
(200, Value::Null),
279
(200, Value::Null),
280
(200, Value::Null),
281
]);
282
let conversations = Conversations::with_transport(&transport, "emea");
283
for (level, include_replies) in [
284
(ChannelNotificationLevel::BannerAndFeed, false),
285
(ChannelNotificationLevel::Feed, true),
286
(ChannelNotificationLevel::Off, true),
287
] {
288
conversations
289
.set_channel_notifications(
290
"19:a@thread.tacv2",
291
ChannelNotifications {
292
level,
293
include_replies,
294
},
295
)
296
.await
297
.unwrap();
298
}
299
let requests = transport.requests.lock().unwrap();
300
assert_eq!(requests[0].method, Method::Put);
301
assert_eq!(
302
requests[0].url,
303
"https://teams.cloud.microsoft/api/chatsvc/emea/v1/users/ME/conversations/19%3Aa%40thread.tacv2/properties?name=channelNotificationSettings"
304
);
305
assert_eq!(
306
requests[0].body,
307
Some(
308
json!({"channelNotificationSettings": "{\"allNewPosts\":\"On\",\"dskNotif\":\"On\",\"includeReplies\":false}"})
309
)
310
);
311
assert_eq!(
312
requests[1].body,
313
Some(
314
json!({"channelNotificationSettings": "{\"allNewPosts\":\"On\",\"includeReplies\":true}"})
315
)
316
);
317
assert_eq!(
318
requests[2].body,
319
Some(
320
json!({"channelNotificationSettings": "{\"allNewPosts\":\"Off\",\"includeReplies\":false}"})
321
)
322
);
323
}
324
}
@@ -0,0 +1,324 @@1
use std::collections::HashMap;2
3
use serde_json::{Value, json};4
use session::{Method, Request, Scope, Session};5
6
use crate::error::{Error, Result};7
use crate::pins::{CsaTransport, DEFAULT_REGION, SessionTransport};8
9
pub const NSS_RESOURCE: &str = "https://uis.teams.microsoft.com";10
const NSS_SCOPE: &str = "user_impersonation";11
pub(crate) const PROPERTY_NAME: &str = "channelNotificationSettings";12
const NSS_BATCH_LIMIT: usize = 100;13
14
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]15
pub enum ChannelNotificationLevel {16
BannerAndFeed,17
#[default]18
Feed,19
Off,20
}21
22
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]23
pub struct ChannelNotifications {24
pub level: ChannelNotificationLevel,25
pub include_replies: bool,26
}27
28
impl ChannelNotifications {29
pub fn from_followed(followed: bool) -> Self {30
if followed {31
ChannelNotifications {32
level: ChannelNotificationLevel::BannerAndFeed,33
include_replies: true,34
}35
} else {36
ChannelNotifications::default()37
}38
}39
40
pub fn property_value(self) -> String {41
let mut settings = match self.level {42
ChannelNotificationLevel::BannerAndFeed => {43
json!({"allNewPosts": "On", "dskNotif": "On"})44
}45
ChannelNotificationLevel::Feed => json!({"allNewPosts": "On"}),46
ChannelNotificationLevel::Off => json!({"allNewPosts": "Off"}),47
};48
settings["includeReplies"] =49
json!(self.include_replies && self.level != ChannelNotificationLevel::Off);50
settings.to_string()51
}52
}53
54
pub fn parse_property(raw: &str) -> Option<ChannelNotifications> {55
let settings: Value = serde_json::from_str(raw).ok()?;56
let level = match (57
settings.get("allNewPosts").and_then(Value::as_str)?,58
settings.get("dskNotif").and_then(Value::as_str),59
) {60
("On", Some("On")) => ChannelNotificationLevel::BannerAndFeed,61
("On", _) => ChannelNotificationLevel::Feed,62
_ => ChannelNotificationLevel::Off,63
};64
Some(ChannelNotifications {65
level,66
include_replies: settings67
.get("includeReplies")68
.and_then(Value::as_bool)69
.unwrap_or(false),70
})71
}72
73
pub fn parse_nss_batch(body: &Value) -> HashMap<String, ChannelNotifications> {74
body.get("results")75
.and_then(Value::as_array)76
.into_iter()77
.flatten()78
.filter_map(|result| {79
let settings = result80
.get("settings")81
.filter(|settings| settings.is_object())?;82
let level = match settings.get("allNewPosts").and_then(Value::as_str)? {83
"BannerAndFeed" => ChannelNotificationLevel::BannerAndFeed,84
"Feed" => ChannelNotificationLevel::Feed,85
_ => ChannelNotificationLevel::Off,86
};87
Some((88
result.get("channelId")?.as_str()?.to_owned(),89
ChannelNotifications {90
level,91
include_replies: settings92
.get("includeReplies")93
.and_then(Value::as_bool)94
.unwrap_or(false),95
},96
))97
})98
.collect()99
}100
101
pub struct ChannelSettings<T: CsaTransport = SessionTransport> {102
transport: T,103
url: String,104
}105
106
impl ChannelSettings<SessionTransport> {107
pub fn new(session: &Session) -> Self {108
ChannelSettings::with_transport(109
SessionTransport::with_scope(session, Scope::new(NSS_RESOURCE, NSS_SCOPE)),110
DEFAULT_REGION,111
)112
}113
}114
115
impl<T: CsaTransport> ChannelSettings<T> {116
pub fn with_transport(transport: T, region: &str) -> Self {117
ChannelSettings {118
transport,119
url: format!(120
"https://teams.cloud.microsoft/api/nss/{region}/v1/me/notificationSettings/channels/batch"121
),122
}123
}124
125
pub async fn fetch(126
&self,127
channel_ids: &[String],128
) -> Result<HashMap<String, ChannelNotifications>> {129
let mut settings = HashMap::new();130
for batch in channel_ids.chunks(NSS_BATCH_LIMIT) {131
let answer = self132
.transport133
.send(Request::with_body(134
Method::Post,135
&self.url,136
json!({"channelIds": batch}),137
))138
.await?;139
if !answer.is_success() {140
return Err(Error::UnexpectedAnswer(format!(141
"channel settings answered {}",142
answer.status143
)));144
}145
settings.extend(parse_nss_batch(&answer.body));146
}147
Ok(settings)148
}149
}150
151
#[cfg(test)]152
mod tests {153
use std::collections::VecDeque;154
use std::sync::Mutex;155
156
use session::ApiResponse;157
158
use super::*;159
use crate::conversations::Conversations;160
use crate::messages::MessageTransport;161
162
struct Canned {163
answers: Mutex<VecDeque<(u16, Value)>>,164
requests: Mutex<Vec<Request>>,165
}166
167
impl CsaTransport for &Canned {168
async fn send(&self, request: Request) -> Result<ApiResponse> {169
self.requests.lock().unwrap().push(request);170
let (status, body) = self.answers.lock().unwrap().pop_front().expect("exhausted");171
Ok(ApiResponse {172
status,173
body,174
retry_after: None,175
})176
}177
}178
179
impl MessageTransport for &Canned {180
async fn send(&self, request: Request) -> Result<ApiResponse> {181
CsaTransport::send(self, request).await182
}183
}184
185
fn canned(answers: Vec<(u16, Value)>) -> Canned {186
Canned {187
answers: Mutex::new(answers.into()),188
requests: Mutex::new(Vec::new()),189
}190
}191
192
#[test]193
fn property_maps_the_three_levels() {194
let banner =195
parse_property(r#"{"allNewPosts":"On","dskNotif":"On","includeReplies":true}"#);196
assert_eq!(197
banner,198
Some(ChannelNotifications {199
level: ChannelNotificationLevel::BannerAndFeed,200
include_replies: true201
})202
);203
let feed = parse_property(r#"{"allNewPosts":"On","latestCnsVersion":1}"#).unwrap();204
assert_eq!(feed.level, ChannelNotificationLevel::Feed);205
assert!(!feed.include_replies);206
let off = parse_property(r#"{"allNewPosts":"Off","includeReplies":false}"#).unwrap();207
assert_eq!(off.level, ChannelNotificationLevel::Off);208
}209
210
#[test]211
fn unreadable_property_is_missing() {212
assert_eq!(parse_property("not json"), None);213
assert_eq!(parse_property(r#"{"includeReplies":true}"#), None);214
}215
216
#[test]217
fn followed_without_a_value_means_banner_with_replies() {218
assert_eq!(219
ChannelNotifications::from_followed(true),220
ChannelNotifications {221
level: ChannelNotificationLevel::BannerAndFeed,222
include_replies: true223
}224
);225
assert_eq!(226
ChannelNotifications::from_followed(false).level,227
ChannelNotificationLevel::Feed228
);229
}230
231
#[test]232
fn nss_batch_skips_channels_without_settings() {233
let body = json!({"results": [234
{"channelId": "19:a", "success": true, "settings": {"allNewPosts": "BannerAndFeed", "includeReplies": true}},235
{"channelId": "19:b", "success": true, "settings": {"allNewPosts": "Feed"}},236
{"channelId": "19:c", "success": true, "settings": {"allNewPosts": "Off"}},237
{"channelId": "19:d", "success": true, "settings": null},238
{"channelId": "19:e", "success": false, "settings": null, "errorMessage": "x"},239
]});240
let parsed = parse_nss_batch(&body);241
assert_eq!(parsed.len(), 3);242
assert_eq!(243
parsed["19:a"].level,244
ChannelNotificationLevel::BannerAndFeed245
);246
assert!(parsed["19:a"].include_replies);247
assert_eq!(parsed["19:b"].level, ChannelNotificationLevel::Feed);248
assert_eq!(parsed["19:c"].level, ChannelNotificationLevel::Off);249
}250
251
#[tokio::test]252
async fn fetch_splits_into_batches_of_one_hundred() {253
let transport = canned(vec![254
(200, json!({"results": []})),255
(200, json!({"results": []})),256
]);257
let ids: Vec<String> = (0..101).map(|index| format!("19:{index}")).collect();258
ChannelSettings::with_transport(&transport, "emea")259
.fetch(&ids)260
.await261
.unwrap();262
let requests = transport.requests.lock().unwrap();263
let sizes: Vec<usize> = requests264
.iter()265
.map(|request| {266
request.body.as_ref().unwrap()["channelIds"]267
.as_array()268
.unwrap()269
.len()270
})271
.collect();272
assert_eq!(sizes, [100, 1]);273
}274
275
#[tokio::test]276
async fn write_puts_the_settings_as_a_json_string() {277
let transport = canned(vec![278
(200, Value::Null),279
(200, Value::Null),280
(200, Value::Null),281
]);282
let conversations = Conversations::with_transport(&transport, "emea");283
for (level, include_replies) in [284
(ChannelNotificationLevel::BannerAndFeed, false),285
(ChannelNotificationLevel::Feed, true),286
(ChannelNotificationLevel::Off, true),287
] {288
conversations289
.set_channel_notifications(290
"19:a@thread.tacv2",291
ChannelNotifications {292
level,293
include_replies,294
},295
)296
.await297
.unwrap();298
}299
let requests = transport.requests.lock().unwrap();300
assert_eq!(requests[0].method, Method::Put);301
assert_eq!(302
requests[0].url,303
"https://teams.cloud.microsoft/api/chatsvc/emea/v1/users/ME/conversations/19%3Aa%40thread.tacv2/properties?name=channelNotificationSettings"304
);305
assert_eq!(306
requests[0].body,307
Some(308
json!({"channelNotificationSettings": "{\"allNewPosts\":\"On\",\"dskNotif\":\"On\",\"includeReplies\":false}"})309
)310
);311
assert_eq!(312
requests[1].body,313
Some(314
json!({"channelNotificationSettings": "{\"allNewPosts\":\"On\",\"includeReplies\":true}"})315
)316
);317
assert_eq!(318
requests[2].body,319
Some(320
json!({"channelNotificationSettings": "{\"allNewPosts\":\"Off\",\"includeReplies\":false}"})321
)322
);323
}324
}@@ -1,6 +1,7 @@
1
1
use serde_json::{Value, json};
2
2
use session::{Method, Request, Session};
3
3
4
use crate::channel_notifications::{ChannelNotifications, PROPERTY_NAME};
4
5
use crate::error::{Error, Result};
5
6
use crate::messages::{MessageTransport, SessionMessageTransport, encode, ensure_success};
6
7
use crate::pins::DEFAULT_REGION;
@@ -73,6 +74,24 @@ impl<T: MessageTransport> Conversations<T> {
73
74
.await?;
74
75
ensure_success(&answer)
75
76
}
77
78
pub async fn set_channel_notifications(
79
&self,
80
channel_id: &str,
81
notifications: ChannelNotifications,
82
) -> Result<()> {
83
let url = format!(
84
"{}/{}/properties?name={PROPERTY_NAME}",
85
self.base_url,
86
encode(channel_id)
87
);
88
let body = json!({ PROPERTY_NAME: notifications.property_value() });
89
let answer = self
90
.transport
91
.send(Request::with_body(Method::Put, url, body))
92
.await?;
93
ensure_success(&answer)
94
}
76
95
}
77
96
78
97
fn backward_link(body: &Value) -> Option<String> {
@@ -1,6 +1,7 @@1
use serde_json::{Value, json};1
use serde_json::{Value, json};2
use session::{Method, Request, Session};2
use session::{Method, Request, Session};3
3
4
use crate::channel_notifications::{ChannelNotifications, PROPERTY_NAME};4
use crate::error::{Error, Result};5
use crate::error::{Error, Result};5
use crate::messages::{MessageTransport, SessionMessageTransport, encode, ensure_success};6
use crate::messages::{MessageTransport, SessionMessageTransport, encode, ensure_success};6
use crate::pins::DEFAULT_REGION;7
use crate::pins::DEFAULT_REGION;@@ -73,6 +74,24 @@ impl<T: MessageTransport> Conversations<T> {73
.await?;74
.await?;74
ensure_success(&answer)75
ensure_success(&answer)75
}76
}77
78
pub async fn set_channel_notifications(79
&self,80
channel_id: &str,81
notifications: ChannelNotifications,82
) -> Result<()> {83
let url = format!(84
"{}/{}/properties?name={PROPERTY_NAME}",85
self.base_url,86
encode(channel_id)87
);88
let body = json!({ PROPERTY_NAME: notifications.property_value() });89
let answer = self90
.transport91
.send(Request::with_body(Method::Put, url, body))92
.await?;93
ensure_success(&answer)94
}76
}95
}77
96
78
fn backward_link(body: &Value) -> Option<String> {97
fn backward_link(body: &Value) -> Option<String> {@@ -1,4 +1,5 @@
1
1
pub mod cards;
2
pub mod channel_notifications;
2
3
pub mod conversations;
3
4
pub mod drafts;
4
5
mod error;
@@ -18,6 +19,7 @@ pub mod settings;
18
19
pub use cards::{
19
20
CardActions, ChatApp, InvokeRequest, InvokeResponse, TaskContent, TaskContinue, TaskResponse,
20
21
};
22
pub use channel_notifications::{ChannelNotificationLevel, ChannelNotifications, ChannelSettings};
21
23
pub use conversations::Conversations;
22
24
pub use drafts::{ScheduledDraft, ScheduledDrafts};
23
25
pub use error::{Error, Result};
@@ -27,8 +29,8 @@ pub use links::{LinkImage, LinkInfo, MessageLinks, is_link_image_url};
27
29
pub use mask::mask_conversation_id;
28
30
pub use messages::{ConversationRef, Messages};
29
31
pub use pins::{
30
ChannelLayout, Folder, FolderKind, Folders, PinnedChannels, PinnedChats, PinnedMessage, Pins,
31
TeamLayout,
32
ChannelLayout, ChannelTab, Folder, FolderKind, Folders, PinnedChannels, PinnedChats,
33
PinnedMessage, Pins, TeamLayout,
32
34
};
33
35
pub use presence::{
34
36
ForcedAvailability, ForcedKind, PresenceService, PresenceStatus, StatusNote, WorkLocation,
@@ -1,4 +1,5 @@1
pub mod cards;1
pub mod cards;2
pub mod channel_notifications;2
pub mod conversations;3
pub mod conversations;3
pub mod drafts;4
pub mod drafts;4
mod error;5
mod error;@@ -18,6 +19,7 @@ pub mod settings;18
pub use cards::{19
pub use cards::{19
CardActions, ChatApp, InvokeRequest, InvokeResponse, TaskContent, TaskContinue, TaskResponse,20
CardActions, ChatApp, InvokeRequest, InvokeResponse, TaskContent, TaskContinue, TaskResponse,20
};21
};22
pub use channel_notifications::{ChannelNotificationLevel, ChannelNotifications, ChannelSettings};21
pub use conversations::Conversations;23
pub use conversations::Conversations;22
pub use drafts::{ScheduledDraft, ScheduledDrafts};24
pub use drafts::{ScheduledDraft, ScheduledDrafts};23
pub use error::{Error, Result};25
pub use error::{Error, Result};@@ -27,8 +29,8 @@ pub use links::{LinkImage, LinkInfo, MessageLinks, is_link_image_url};27
pub use mask::mask_conversation_id;29
pub use mask::mask_conversation_id;28
pub use messages::{ConversationRef, Messages};30
pub use messages::{ConversationRef, Messages};29
pub use pins::{31
pub use pins::{30
ChannelLayout, Folder, FolderKind, Folders, PinnedChannels, PinnedChats, PinnedMessage, Pins,32
ChannelLayout, ChannelTab, Folder, FolderKind, Folders, PinnedChannels, PinnedChats,31
TeamLayout,33
PinnedMessage, Pins, TeamLayout,32
};34
};33
pub use presence::{35
pub use presence::{34
ForcedAvailability, ForcedKind, PresenceService, PresenceStatus, StatusNote, WorkLocation,36
ForcedAvailability, ForcedKind, PresenceService, PresenceStatus, StatusNote, WorkLocation,@@ -11,7 +11,7 @@ use session::Session;
11
11
pub use folders::{Folder, FolderKind, Folders};
12
12
pub use pinbar::PinnedMessage;
13
13
pub use state::{PinnedChannels, PinnedChats};
14
pub use teams::{ChannelLayout, TeamLayout};
14
pub use teams::{ChannelLayout, ChannelTab, TeamLayout};
15
15
pub use transport::{CSA_RESOURCE, CSA_SCOPE, CsaTransport, SessionTransport};
16
16
17
17
pub const DEFAULT_REGION: &str = "emea";
@@ -11,7 +11,7 @@ use session::Session;11
pub use folders::{Folder, FolderKind, Folders};11
pub use folders::{Folder, FolderKind, Folders};12
pub use pinbar::PinnedMessage;12
pub use pinbar::PinnedMessage;13
pub use state::{PinnedChannels, PinnedChats};13
pub use state::{PinnedChannels, PinnedChats};14
pub use teams::{ChannelLayout, TeamLayout};14
pub use teams::{ChannelLayout, ChannelTab, TeamLayout};15
pub use transport::{CSA_RESOURCE, CSA_SCOPE, CsaTransport, SessionTransport};15
pub use transport::{CSA_RESOURCE, CSA_SCOPE, CsaTransport, SessionTransport};16
16
17
pub const DEFAULT_REGION: &str = "emea";17
pub const DEFAULT_REGION: &str = "emea";@@ -4,15 +4,29 @@ use session::Request;
4
4
use super::Pins;
5
5
use super::chats::ensure_success;
6
6
use super::transport::CsaTransport;
7
use crate::channel_notifications::{ChannelNotifications, parse_property};
7
8
use crate::error::{Error, Result};
8
9
9
10
const TEAMS_QUERY: &str = "isPrefetch=false&enableMembershipSummary=true";
11
const WIKI_DEFINITION_ID: &str = "com.microsoft.teamspace.tab.wiki";
12
const TAB_URL_KEYS: [&str; 3] = ["websiteUrl", "componentUrl", "url"];
13
14
#[derive(Debug, Clone, PartialEq, Eq)]
15
pub struct ChannelTab {
16
pub id: String,
17
pub name: String,
18
pub definition_id: String,
19
pub open_url: Option<String>,
20
}
10
21
11
22
#[derive(Debug, Clone, PartialEq, Eq)]
12
23
pub struct ChannelLayout {
13
24
pub channel_id: String,
14
25
pub general: bool,
15
26
pub hidden: bool,
27
pub tabs: Vec<ChannelTab>,
28
pub notifications: Option<ChannelNotifications>,
29
pub followed: bool,
16
30
}
17
31
18
32
#[derive(Debug, Clone, PartialEq, Eq)]
@@ -45,6 +59,46 @@ fn flag(value: &Value, key: &str) -> Option<bool> {
45
59
value.get(key).and_then(Value::as_bool)
46
60
}
47
61
62
fn tab_open_url(settings: &Value) -> Option<String> {
63
TAB_URL_KEYS
64
.iter()
65
.filter_map(|key| settings.get(key).and_then(Value::as_str))
66
.map(str::trim)
67
.find(|url| url.starts_with("http") && !url.contains('{'))
68
.map(str::to_owned)
69
}
70
71
fn parse_tab(tab: &Value) -> Option<(i64, ChannelTab)> {
72
let definition_id = tab.get("definitionId")?.as_str()?;
73
if definition_id == WIKI_DEFINITION_ID {
74
return None;
75
}
76
let order = tab
77
.get("order")
78
.and_then(|order| order.as_i64().or_else(|| order.as_str()?.parse().ok()))
79
.unwrap_or(i64::MAX);
80
let settings = tab.get("settings").unwrap_or(&Value::Null);
81
Some((
82
order,
83
ChannelTab {
84
id: tab.get("id")?.as_str()?.to_owned(),
85
name: tab.get("name")?.as_str()?.to_owned(),
86
definition_id: definition_id.to_owned(),
87
open_url: tab_open_url(settings),
88
},
89
))
90
}
91
92
pub fn parse_channel_tabs(channel: &Value) -> Vec<ChannelTab> {
93
let mut tabs: Vec<(i64, ChannelTab)> = channel
94
.get("tabs")
95
.and_then(Value::as_array)
96
.map(|tabs| tabs.iter().filter_map(parse_tab).collect())
97
.unwrap_or_default();
98
tabs.sort_by_key(|(order, _)| *order);
99
tabs.into_iter().map(|(_, tab)| tab).collect()
100
}
101
48
102
fn parse_team(team: &Value) -> Option<TeamLayout> {
49
103
if flag(team, "isDeleted") == Some(true) {
50
104
return None;
@@ -68,6 +122,12 @@ fn parse_team(team: &Value) -> Option<TeamLayout> {
68
122
channel_id: channel.get("id")?.as_str()?.to_owned(),
69
123
general,
70
124
hidden: !shown,
125
tabs: parse_channel_tabs(channel),
126
notifications: channel
127
.get("channelNotificationSettings")
128
.and_then(Value::as_str)
129
.and_then(parse_property),
130
followed: flag(channel, "isFollowed").unwrap_or(false),
71
131
})
72
132
})
73
133
.collect()
@@ -129,12 +189,18 @@ mod tests {
129
189
ChannelLayout {
130
190
channel_id: "19:b2@thread.tacv2".into(),
131
191
general: false,
132
hidden: true
192
hidden: true,
193
tabs: Vec::new(),
194
notifications: None,
195
followed: false,
133
196
},
134
197
ChannelLayout {
135
198
channel_id: "19:b@thread.tacv2".into(),
136
199
general: true,
137
hidden: false
200
hidden: false,
201
tabs: Vec::new(),
202
notifications: None,
203
followed: false,
138
204
},
139
205
]
140
206
);
@@ -142,6 +208,62 @@ mod tests {
142
208
assert!(!layout[1].channels[1].hidden);
143
209
}
144
210
211
#[test]
212
fn tabs_follow_the_order_field_and_hide_wiki() {
213
let channel = json!({"id": "19:a@thread.tacv2", "tabs": [
214
{"id": "t3", "name": "Notes", "definitionId": "0d820ecd-def2-4297-adad-78056cde7c78",
215
"order": 30, "settings": {
216
"url": "https://onenote.example/{tid}/content",
217
"websiteUrl": "https://onenote.example/web"}},
218
{"id": "t0", "name": "Wiki", "definitionId": "com.microsoft.teamspace.tab.wiki", "order": 5},
219
{"id": "t1", "name": "Docs", "definitionId": "com.microsoft.teamspace.tab.web",
220
"order": 10, "settings": {"url": "https://docs.example", "websiteUrl": "https://docs.example"}},
221
{"id": "t2", "name": "Plan", "definitionId": "com.microsoft.teamspace.tab.planner",
222
"order": "20", "settings": {"url": "https://tasks.example/{locale}"}}
223
]});
224
let tabs = parse_channel_tabs(&channel);
225
let names: Vec<&str> = tabs.iter().map(|tab| tab.name.as_str()).collect();
226
assert_eq!(names, ["Docs", "Plan", "Notes"]);
227
assert_eq!(tabs[0].open_url.as_deref(), Some("https://docs.example"));
228
assert_eq!(tabs[1].open_url, None);
229
assert_eq!(
230
tabs[2].open_url.as_deref(),
231
Some("https://onenote.example/web")
232
);
233
}
234
235
#[test]
236
fn reads_the_notification_string_and_the_followed_flag() {
237
let body = json!({"teams": [
238
{"id": "19:a@thread.tacv2", "channels": [
239
{"id": "19:a1", "channelNotificationSettings": "{\"allNewPosts\":\"On\",\"dskNotif\":\"On\",\"includeReplies\":true}", "isFollowed": true},
240
{"id": "19:a2", "channelNotificationSettings": null, "isFollowed": true},
241
{"id": "19:a3"}
242
]}
243
]});
244
let channels = &parse_team_layout(&body).unwrap()[0].channels;
245
assert_eq!(
246
channels[0].notifications,
247
Some(ChannelNotifications {
248
level: crate::ChannelNotificationLevel::BannerAndFeed,
249
include_replies: true
250
})
251
);
252
assert_eq!(
253
(channels[1].notifications, channels[1].followed),
254
(None, true)
255
);
256
assert_eq!(
257
(channels[2].notifications, channels[2].followed),
258
(None, false)
259
);
260
}
261
262
#[test]
263
fn a_channel_without_tabs_has_none() {
264
assert!(parse_channel_tabs(&json!({"id": "19:a@thread.tacv2"})).is_empty());
265
}
266
145
267
#[test]
146
268
fn rejects_an_answer_without_teams() {
147
269
assert!(parse_team_layout(&json!({"chats": []})).is_err());
@@ -4,15 +4,29 @@ use session::Request;4
use super::Pins;4
use super::Pins;5
use super::chats::ensure_success;5
use super::chats::ensure_success;6
use super::transport::CsaTransport;6
use super::transport::CsaTransport;7
use crate::channel_notifications::{ChannelNotifications, parse_property};7
use crate::error::{Error, Result};8
use crate::error::{Error, Result};8
9
9
const TEAMS_QUERY: &str = "isPrefetch=false&enableMembershipSummary=true";10
const TEAMS_QUERY: &str = "isPrefetch=false&enableMembershipSummary=true";11
const WIKI_DEFINITION_ID: &str = "com.microsoft.teamspace.tab.wiki";12
const TAB_URL_KEYS: [&str; 3] = ["websiteUrl", "componentUrl", "url"];13
14
#[derive(Debug, Clone, PartialEq, Eq)]15
pub struct ChannelTab {16
pub id: String,17
pub name: String,18
pub definition_id: String,19
pub open_url: Option<String>,20
}10
21
11
#[derive(Debug, Clone, PartialEq, Eq)]22
#[derive(Debug, Clone, PartialEq, Eq)]12
pub struct ChannelLayout {23
pub struct ChannelLayout {13
pub channel_id: String,24
pub channel_id: String,14
pub general: bool,25
pub general: bool,15
pub hidden: bool,26
pub hidden: bool,27
pub tabs: Vec<ChannelTab>,28
pub notifications: Option<ChannelNotifications>,29
pub followed: bool,16
}30
}17
31
18
#[derive(Debug, Clone, PartialEq, Eq)]32
#[derive(Debug, Clone, PartialEq, Eq)]@@ -45,6 +59,46 @@ fn flag(value: &Value, key: &str) -> Option<bool> {45
value.get(key).and_then(Value::as_bool)59
value.get(key).and_then(Value::as_bool)46
}60
}47
61
62
fn tab_open_url(settings: &Value) -> Option<String> {63
TAB_URL_KEYS64
.iter()65
.filter_map(|key| settings.get(key).and_then(Value::as_str))66
.map(str::trim)67
.find(|url| url.starts_with("http") && !url.contains('{'))68
.map(str::to_owned)69
}70
71
fn parse_tab(tab: &Value) -> Option<(i64, ChannelTab)> {72
let definition_id = tab.get("definitionId")?.as_str()?;73
if definition_id == WIKI_DEFINITION_ID {74
return None;75
}76
let order = tab77
.get("order")78
.and_then(|order| order.as_i64().or_else(|| order.as_str()?.parse().ok()))79
.unwrap_or(i64::MAX);80
let settings = tab.get("settings").unwrap_or(&Value::Null);81
Some((82
order,83
ChannelTab {84
id: tab.get("id")?.as_str()?.to_owned(),85
name: tab.get("name")?.as_str()?.to_owned(),86
definition_id: definition_id.to_owned(),87
open_url: tab_open_url(settings),88
},89
))90
}91
92
pub fn parse_channel_tabs(channel: &Value) -> Vec<ChannelTab> {93
let mut tabs: Vec<(i64, ChannelTab)> = channel94
.get("tabs")95
.and_then(Value::as_array)96
.map(|tabs| tabs.iter().filter_map(parse_tab).collect())97
.unwrap_or_default();98
tabs.sort_by_key(|(order, _)| *order);99
tabs.into_iter().map(|(_, tab)| tab).collect()100
}101
48
fn parse_team(team: &Value) -> Option<TeamLayout> {102
fn parse_team(team: &Value) -> Option<TeamLayout> {49
if flag(team, "isDeleted") == Some(true) {103
if flag(team, "isDeleted") == Some(true) {50
return None;104
return None;@@ -68,6 +122,12 @@ fn parse_team(team: &Value) -> Option<TeamLayout> {68
channel_id: channel.get("id")?.as_str()?.to_owned(),122
channel_id: channel.get("id")?.as_str()?.to_owned(),69
general,123
general,70
hidden: !shown,124
hidden: !shown,125
tabs: parse_channel_tabs(channel),126
notifications: channel127
.get("channelNotificationSettings")128
.and_then(Value::as_str)129
.and_then(parse_property),130
followed: flag(channel, "isFollowed").unwrap_or(false),71
})131
})72
})132
})73
.collect()133
.collect()@@ -129,12 +189,18 @@ mod tests {129
ChannelLayout {189
ChannelLayout {130
channel_id: "19:b2@thread.tacv2".into(),190
channel_id: "19:b2@thread.tacv2".into(),131
general: false,191
general: false,132
hidden: true192
hidden: true,193
tabs: Vec::new(),194
notifications: None,195
followed: false,133
},196
},134
ChannelLayout {197
ChannelLayout {135
channel_id: "19:b@thread.tacv2".into(),198
channel_id: "19:b@thread.tacv2".into(),136
general: true,199
general: true,137
hidden: false200
hidden: false,201
tabs: Vec::new(),202
notifications: None,203
followed: false,138
},204
},139
]205
]140
);206
);@@ -142,6 +208,62 @@ mod tests {142
assert!(!layout[1].channels[1].hidden);208
assert!(!layout[1].channels[1].hidden);143
}209
}144
210
211
#[test]212
fn tabs_follow_the_order_field_and_hide_wiki() {213
let channel = json!({"id": "19:a@thread.tacv2", "tabs": [214
{"id": "t3", "name": "Notes", "definitionId": "0d820ecd-def2-4297-adad-78056cde7c78",215
"order": 30, "settings": {216
"url": "https://onenote.example/{tid}/content",217
"websiteUrl": "https://onenote.example/web"}},218
{"id": "t0", "name": "Wiki", "definitionId": "com.microsoft.teamspace.tab.wiki", "order": 5},219
{"id": "t1", "name": "Docs", "definitionId": "com.microsoft.teamspace.tab.web",220
"order": 10, "settings": {"url": "https://docs.example", "websiteUrl": "https://docs.example"}},221
{"id": "t2", "name": "Plan", "definitionId": "com.microsoft.teamspace.tab.planner",222
"order": "20", "settings": {"url": "https://tasks.example/{locale}"}}223
]});224
let tabs = parse_channel_tabs(&channel);225
let names: Vec<&str> = tabs.iter().map(|tab| tab.name.as_str()).collect();226
assert_eq!(names, ["Docs", "Plan", "Notes"]);227
assert_eq!(tabs[0].open_url.as_deref(), Some("https://docs.example"));228
assert_eq!(tabs[1].open_url, None);229
assert_eq!(230
tabs[2].open_url.as_deref(),231
Some("https://onenote.example/web")232
);233
}234
235
#[test]236
fn reads_the_notification_string_and_the_followed_flag() {237
let body = json!({"teams": [238
{"id": "19:a@thread.tacv2", "channels": [239
{"id": "19:a1", "channelNotificationSettings": "{\"allNewPosts\":\"On\",\"dskNotif\":\"On\",\"includeReplies\":true}", "isFollowed": true},240
{"id": "19:a2", "channelNotificationSettings": null, "isFollowed": true},241
{"id": "19:a3"}242
]}243
]});244
let channels = &parse_team_layout(&body).unwrap()[0].channels;245
assert_eq!(246
channels[0].notifications,247
Some(ChannelNotifications {248
level: crate::ChannelNotificationLevel::BannerAndFeed,249
include_replies: true250
})251
);252
assert_eq!(253
(channels[1].notifications, channels[1].followed),254
(None, true)255
);256
assert_eq!(257
(channels[2].notifications, channels[2].followed),258
(None, false)259
);260
}261
262
#[test]263
fn a_channel_without_tabs_has_none() {264
assert!(parse_channel_tabs(&json!({"id": "19:a@thread.tacv2"})).is_empty());265
}266
145
#[test]267
#[test]146
fn rejects_an_answer_without_teams() {268
fn rejects_an_answer_without_teams() {147
assert!(parse_team_layout(&json!({"chats": []})).is_err());269
assert!(parse_team_layout(&json!({"chats": []})).is_err());@@ -16,9 +16,13 @@ pub struct SessionTransport {
16
16
17
17
impl SessionTransport {
18
18
pub fn new(session: &Session) -> Self {
19
SessionTransport::with_scope(session, Scope::new(CSA_RESOURCE, CSA_SCOPE))
20
}
21
22
pub fn with_scope(session: &Session, scope: Scope) -> Self {
19
23
SessionTransport {
20
24
session: session.clone(),
21
scope: Scope::new(CSA_RESOURCE, CSA_SCOPE),
25
scope,
22
26
}
23
27
}
24
28
}
@@ -16,9 +16,13 @@ pub struct SessionTransport {16
16
17
impl SessionTransport {17
impl SessionTransport {18
pub fn new(session: &Session) -> Self {18
pub fn new(session: &Session) -> Self {19
SessionTransport::with_scope(session, Scope::new(CSA_RESOURCE, CSA_SCOPE))20
}21
22
pub fn with_scope(session: &Session, scope: Scope) -> Self {19
SessionTransport {23
SessionTransport {20
session: session.clone(),24
session: session.clone(),21
scope: Scope::new(CSA_RESOURCE, CSA_SCOPE),25
scope,22
}26
}23
}27
}24
}28
}@@ -402,6 +402,20 @@ impl<R: Remote> SyncEngine<R> {
402
402
Ok(())
403
403
}
404
404
405
pub async fn set_channel_notifications(
406
&self,
407
channel_id: &str,
408
notifications: store::ChannelNotifications,
409
) -> Result<()> {
410
self.remote
411
.set_channel_notifications(channel_id, notifications)
412
.await?;
413
self.store
414
.set_channel_notifications(channel_id, notifications)?;
415
let _ = self.events.send(crate::events::CoreEvent::SidebarChanged);
416
Ok(())
417
}
418
405
419
pub async fn hide_chat(&self, chat_id: &str) -> Result<()> {
406
420
let user_id = self.my_user_id().await?;
407
421
let tenant_id = self.my_tenant_id(chat_id).await?;
@@ -402,6 +402,20 @@ impl<R: Remote> SyncEngine<R> {402
Ok(())402
Ok(())403
}403
}404
404
405
pub async fn set_channel_notifications(406
&self,407
channel_id: &str,408
notifications: store::ChannelNotifications,409
) -> Result<()> {410
self.remote411
.set_channel_notifications(channel_id, notifications)412
.await?;413
self.store414
.set_channel_notifications(channel_id, notifications)?;415
let _ = self.events.send(crate::events::CoreEvent::SidebarChanged);416
Ok(())417
}418
405
pub async fn hide_chat(&self, chat_id: &str) -> Result<()> {419
pub async fn hide_chat(&self, chat_id: &str) -> Result<()> {406
let user_id = self.my_user_id().await?;420
let user_id = self.my_user_id().await?;407
let tenant_id = self.my_tenant_id(chat_id).await?;421
let tenant_id = self.my_tenant_id(chat_id).await?;@@ -4,6 +4,15 @@ use crate::engine::SyncEngine;
4
4
use crate::error::Result;
5
5
use crate::remote::Remote;
6
6
7
#[derive(Debug, Clone, PartialEq, Eq)]
8
pub struct LibraryFile {
9
pub drive_id: String,
10
pub item_id: String,
11
pub name: String,
12
pub size: u64,
13
pub cached_url: Option<String>,
14
}
15
7
16
impl<R: Remote> SyncEngine<R> {
8
17
/// Streams the file behind a OneDrive or SharePoint link chunk by chunk into `write`.
9
18
pub async fn download_file(
@@ -13,6 +22,37 @@ impl<R: Remote> SyncEngine<R> {
13
22
progress: impl Fn(u8) + Send + Sync,
14
23
) -> Result<SharedFile> {
15
24
let shared = self.remote.resolve_share(open_url).await?;
25
self.stream_file(shared, &mut write, &progress).await
26
}
27
28
/// Like `download_file` for a library entry. A `cached_url` from the listing skips the lookup.
29
pub async fn download_library_file(
30
&self,
31
file: &LibraryFile,
32
mut write: impl FnMut(&[u8]) -> std::io::Result<()> + Send,
33
progress: impl Fn(u8) + Send + Sync,
34
) -> Result<SharedFile> {
35
let shared = match &file.cached_url {
36
Some(download_url) => SharedFile {
37
name: file.name.clone(),
38
size: file.size,
39
download_url: download_url.clone(),
40
},
41
None => {
42
self.remote
43
.resolve_drive_item(&file.drive_id, &file.item_id)
44
.await?
45
}
46
};
47
self.stream_file(shared, &mut write, &progress).await
48
}
49
50
async fn stream_file(
51
&self,
52
shared: SharedFile,
53
write: &mut (impl FnMut(&[u8]) -> std::io::Result<()> + Send),
54
progress: &(impl Fn(u8) + Send + Sync),
55
) -> Result<SharedFile> {
16
56
progress(0);
17
57
let ranges = download_ranges(shared.size, DOWNLOAD_CHUNK_BYTES);
18
58
let last = ranges.len().saturating_sub(1);
@@ -4,6 +4,15 @@ use crate::engine::SyncEngine;4
use crate::error::Result;4
use crate::error::Result;5
use crate::remote::Remote;5
use crate::remote::Remote;6
6
7
#[derive(Debug, Clone, PartialEq, Eq)]8
pub struct LibraryFile {9
pub drive_id: String,10
pub item_id: String,11
pub name: String,12
pub size: u64,13
pub cached_url: Option<String>,14
}15
7
impl<R: Remote> SyncEngine<R> {16
impl<R: Remote> SyncEngine<R> {8
/// Streams the file behind a OneDrive or SharePoint link chunk by chunk into `write`.17
/// Streams the file behind a OneDrive or SharePoint link chunk by chunk into `write`.9
pub async fn download_file(18
pub async fn download_file(@@ -13,6 +22,37 @@ impl<R: Remote> SyncEngine<R> {13
progress: impl Fn(u8) + Send + Sync,22
progress: impl Fn(u8) + Send + Sync,14
) -> Result<SharedFile> {23
) -> Result<SharedFile> {15
let shared = self.remote.resolve_share(open_url).await?;24
let shared = self.remote.resolve_share(open_url).await?;25
self.stream_file(shared, &mut write, &progress).await26
}27
28
/// Like `download_file` for a library entry. A `cached_url` from the listing skips the lookup.29
pub async fn download_library_file(30
&self,31
file: &LibraryFile,32
mut write: impl FnMut(&[u8]) -> std::io::Result<()> + Send,33
progress: impl Fn(u8) + Send + Sync,34
) -> Result<SharedFile> {35
let shared = match &file.cached_url {36
Some(download_url) => SharedFile {37
name: file.name.clone(),38
size: file.size,39
download_url: download_url.clone(),40
},41
None => {42
self.remote43
.resolve_drive_item(&file.drive_id, &file.item_id)44
.await?45
}46
};47
self.stream_file(shared, &mut write, &progress).await48
}49
50
async fn stream_file(51
&self,52
shared: SharedFile,53
write: &mut (impl FnMut(&[u8]) -> std::io::Result<()> + Send),54
progress: &(impl Fn(u8) + Send + Sync),55
) -> Result<SharedFile> {16
progress(0);56
progress(0);17
let ranges = download_ranges(shared.size, DOWNLOAD_CHUNK_BYTES);57
let ranges = download_ranges(shared.size, DOWNLOAD_CHUNK_BYTES);18
let last = ranges.len().saturating_sub(1);58
let last = ranges.len().saturating_sub(1);@@ -1,11 +1,15 @@
1
use std::collections::HashMap;
1
2
use std::future::Future;
2
3
use std::pin::Pin;
3
4
use std::sync::Arc;
4
5
5
use chatsvc::{ChatSection, ChatSectionSettings, Pins, UserSettings, pins::SessionTransport};
6
use chatsvc::{
7
ChannelNotificationLevel, ChannelNotifications, ChannelSettings, ChatSection,
8
ChatSectionSettings, Pins, UserSettings, pins::SessionTransport,
9
};
6
10
use chrono::Utc;
7
11
use session::Session;
8
use store::{ChannelLayoutRecord, FolderRecord, Store, TeamLayoutRecord};
12
use store::{ChannelLayoutRecord, ChannelTabRecord, FolderRecord, Store, TeamLayoutRecord};
9
13
10
14
use crate::engine::SyncEngine;
11
15
use crate::error::{Error, Result};
@@ -59,6 +63,7 @@ pub trait FolderSource: Send + Sync {
59
63
pub struct ChatsvcFolderSource {
60
64
pins: Pins<SessionTransport>,
61
65
settings: UserSettings,
66
channel_settings: ChannelSettings,
62
67
}
63
68
64
69
impl ChatsvcFolderSource {
@@ -66,6 +71,7 @@ impl ChatsvcFolderSource {
66
71
ChatsvcFolderSource {
67
72
pins: Pins::new(session),
68
73
settings: UserSettings::new(session),
74
channel_settings: ChannelSettings::new(session),
69
75
}
70
76
}
71
77
}
@@ -81,12 +87,24 @@ impl FolderSource for ChatsvcFolderSource {
81
87
82
88
fn team_layout(&self) -> BoxFuture<'_, Result<Vec<TeamLayoutRecord>>> {
83
89
Box::pin(async {
84
Ok(self
85
.pins
86
.team_layout()
87
.await?
90
let layout = self.pins.team_layout().await?;
91
let unknown: Vec<String> = layout
92
.iter()
93
.flat_map(|team| &team.channels)
94
.filter(|channel| channel.notifications.is_none())
95
.map(|channel| channel.channel_id.clone())
96
.collect();
97
let fallback = if unknown.is_empty() {
98
HashMap::new()
99
} else {
100
self.channel_settings
101
.fetch(&unknown)
102
.await
103
.unwrap_or_default()
104
};
105
Ok(layout
88
106
.into_iter()
89
.map(layout_record)
107
.map(|team| layout_record(team, &fallback))
90
108
.collect())
91
109
})
92
110
}
@@ -160,7 +178,48 @@ fn convert(folders: chatsvc::Folders) -> Vec<ChatFolder> {
160
178
.collect()
161
179
}
162
180
163
fn layout_record(team: chatsvc::TeamLayout) -> TeamLayoutRecord {
181
fn resolve_notifications(
182
channel: &chatsvc::ChannelLayout,
183
fallback: &HashMap<String, ChannelNotifications>,
184
) -> ChannelNotifications {
185
channel
186
.notifications
187
.or_else(|| fallback.get(&channel.channel_id).copied())
188
.unwrap_or_else(|| ChannelNotifications::from_followed(channel.followed))
189
}
190
191
fn notification_record(notifications: ChannelNotifications) -> store::ChannelNotifications {
192
store::ChannelNotifications {
193
level: match notifications.level {
194
ChannelNotificationLevel::BannerAndFeed => {
195
store::ChannelNotificationLevel::BannerAndFeed
196
}
197
ChannelNotificationLevel::Feed => store::ChannelNotificationLevel::Feed,
198
ChannelNotificationLevel::Off => store::ChannelNotificationLevel::Off,
199
},
200
include_replies: notifications.include_replies,
201
}
202
}
203
204
pub(crate) fn chatsvc_notifications(
205
notifications: store::ChannelNotifications,
206
) -> ChannelNotifications {
207
ChannelNotifications {
208
level: match notifications.level {
209
store::ChannelNotificationLevel::BannerAndFeed => {
210
ChannelNotificationLevel::BannerAndFeed
211
}
212
store::ChannelNotificationLevel::Feed => ChannelNotificationLevel::Feed,
213
store::ChannelNotificationLevel::Off => ChannelNotificationLevel::Off,
214
},
215
include_replies: notifications.include_replies,
216
}
217
}
218
219
fn layout_record(
220
team: chatsvc::TeamLayout,
221
fallback: &HashMap<String, ChannelNotifications>,
222
) -> TeamLayoutRecord {
164
223
TeamLayoutRecord {
165
224
team_id: team.team_id,
166
225
hidden: team.hidden,
@@ -168,9 +227,20 @@ fn layout_record(team: chatsvc::TeamLayout) -> TeamLayoutRecord {
168
227
.channels
169
228
.into_iter()
170
229
.map(|channel| ChannelLayoutRecord {
230
notifications: notification_record(resolve_notifications(&channel, fallback)),
171
231
channel_id: channel.channel_id,
172
232
general: channel.general,
173
233
hidden: channel.hidden,
234
tabs: channel
235
.tabs
236
.into_iter()
237
.map(|tab| ChannelTabRecord {
238
tab_id: tab.id,
239
name: tab.name,
240
definition_id: tab.definition_id,
241
open_url: tab.open_url,
242
})
243
.collect(),
174
244
})
175
245
.collect(),
176
246
}
@@ -346,3 +416,52 @@ impl<R: Remote> SyncEngine<R> {
346
416
Ok(())
347
417
}
348
418
}
419
420
#[cfg(test)]
421
mod tests {
422
use super::*;
423
424
fn channel(
425
notifications: Option<ChannelNotifications>,
426
followed: bool,
427
) -> chatsvc::ChannelLayout {
428
chatsvc::ChannelLayout {
429
channel_id: "19:a".into(),
430
general: false,
431
hidden: false,
432
tabs: Vec::new(),
433
notifications,
434
followed,
435
}
436
}
437
438
fn level(level: ChannelNotificationLevel, include_replies: bool) -> ChannelNotifications {
439
ChannelNotifications {
440
level,
441
include_replies,
442
}
443
}
444
445
#[test]
446
fn channel_value_beats_the_notification_service_beats_the_followed_flag() {
447
let off = level(ChannelNotificationLevel::Off, false);
448
let banner = level(ChannelNotificationLevel::BannerAndFeed, true);
449
let fallback = HashMap::from([("19:a".to_owned(), banner)]);
450
assert_eq!(
451
resolve_notifications(&channel(Some(off), true), &fallback),
452
off
453
);
454
assert_eq!(
455
resolve_notifications(&channel(None, false), &fallback),
456
banner
457
);
458
assert_eq!(
459
resolve_notifications(&channel(None, true), &HashMap::new()),
460
banner
461
);
462
assert_eq!(
463
resolve_notifications(&channel(None, false), &HashMap::new()),
464
ChannelNotifications::default()
465
);
466
}
467
}
@@ -1,11 +1,15 @@1
use std::collections::HashMap;1
use std::future::Future;2
use std::future::Future;2
use std::pin::Pin;3
use std::pin::Pin;3
use std::sync::Arc;4
use std::sync::Arc;4
5
5
use chatsvc::{ChatSection, ChatSectionSettings, Pins, UserSettings, pins::SessionTransport};6
use chatsvc::{7
ChannelNotificationLevel, ChannelNotifications, ChannelSettings, ChatSection,8
ChatSectionSettings, Pins, UserSettings, pins::SessionTransport,9
};6
use chrono::Utc;10
use chrono::Utc;7
use session::Session;11
use session::Session;8
use store::{ChannelLayoutRecord, FolderRecord, Store, TeamLayoutRecord};12
use store::{ChannelLayoutRecord, ChannelTabRecord, FolderRecord, Store, TeamLayoutRecord};9
13
10
use crate::engine::SyncEngine;14
use crate::engine::SyncEngine;11
use crate::error::{Error, Result};15
use crate::error::{Error, Result};@@ -59,6 +63,7 @@ pub trait FolderSource: Send + Sync {59
pub struct ChatsvcFolderSource {63
pub struct ChatsvcFolderSource {60
pins: Pins<SessionTransport>,64
pins: Pins<SessionTransport>,61
settings: UserSettings,65
settings: UserSettings,66
channel_settings: ChannelSettings,62
}67
}63
68
64
impl ChatsvcFolderSource {69
impl ChatsvcFolderSource {@@ -66,6 +71,7 @@ impl ChatsvcFolderSource {66
ChatsvcFolderSource {71
ChatsvcFolderSource {67
pins: Pins::new(session),72
pins: Pins::new(session),68
settings: UserSettings::new(session),73
settings: UserSettings::new(session),74
channel_settings: ChannelSettings::new(session),69
}75
}70
}76
}71
}77
}@@ -81,12 +87,24 @@ impl FolderSource for ChatsvcFolderSource {81
87
82
fn team_layout(&self) -> BoxFuture<'_, Result<Vec<TeamLayoutRecord>>> {88
fn team_layout(&self) -> BoxFuture<'_, Result<Vec<TeamLayoutRecord>>> {83
Box::pin(async {89
Box::pin(async {84
Ok(self90
let layout = self.pins.team_layout().await?;85
.pins91
let unknown: Vec<String> = layout86
.team_layout()92
.iter()87
.await?93
.flat_map(|team| &team.channels)94
.filter(|channel| channel.notifications.is_none())95
.map(|channel| channel.channel_id.clone())96
.collect();97
let fallback = if unknown.is_empty() {98
HashMap::new()99
} else {100
self.channel_settings101
.fetch(&unknown)102
.await103
.unwrap_or_default()104
};105
Ok(layout88
.into_iter()106
.into_iter()89
.map(layout_record)107
.map(|team| layout_record(team, &fallback))90
.collect())108
.collect())91
})109
})92
}110
}@@ -160,7 +178,48 @@ fn convert(folders: chatsvc::Folders) -> Vec<ChatFolder> {160
.collect()178
.collect()161
}179
}162
180
163
fn layout_record(team: chatsvc::TeamLayout) -> TeamLayoutRecord {181
fn resolve_notifications(182
channel: &chatsvc::ChannelLayout,183
fallback: &HashMap<String, ChannelNotifications>,184
) -> ChannelNotifications {185
channel186
.notifications187
.or_else(|| fallback.get(&channel.channel_id).copied())188
.unwrap_or_else(|| ChannelNotifications::from_followed(channel.followed))189
}190
191
fn notification_record(notifications: ChannelNotifications) -> store::ChannelNotifications {192
store::ChannelNotifications {193
level: match notifications.level {194
ChannelNotificationLevel::BannerAndFeed => {195
store::ChannelNotificationLevel::BannerAndFeed196
}197
ChannelNotificationLevel::Feed => store::ChannelNotificationLevel::Feed,198
ChannelNotificationLevel::Off => store::ChannelNotificationLevel::Off,199
},200
include_replies: notifications.include_replies,201
}202
}203
204
pub(crate) fn chatsvc_notifications(205
notifications: store::ChannelNotifications,206
) -> ChannelNotifications {207
ChannelNotifications {208
level: match notifications.level {209
store::ChannelNotificationLevel::BannerAndFeed => {210
ChannelNotificationLevel::BannerAndFeed211
}212
store::ChannelNotificationLevel::Feed => ChannelNotificationLevel::Feed,213
store::ChannelNotificationLevel::Off => ChannelNotificationLevel::Off,214
},215
include_replies: notifications.include_replies,216
}217
}218
219
fn layout_record(220
team: chatsvc::TeamLayout,221
fallback: &HashMap<String, ChannelNotifications>,222
) -> TeamLayoutRecord {164
TeamLayoutRecord {223
TeamLayoutRecord {165
team_id: team.team_id,224
team_id: team.team_id,166
hidden: team.hidden,225
hidden: team.hidden,@@ -168,9 +227,20 @@ fn layout_record(team: chatsvc::TeamLayout) -> TeamLayoutRecord {168
.channels227
.channels169
.into_iter()228
.into_iter()170
.map(|channel| ChannelLayoutRecord {229
.map(|channel| ChannelLayoutRecord {230
notifications: notification_record(resolve_notifications(&channel, fallback)),171
channel_id: channel.channel_id,231
channel_id: channel.channel_id,172
general: channel.general,232
general: channel.general,173
hidden: channel.hidden,233
hidden: channel.hidden,234
tabs: channel235
.tabs236
.into_iter()237
.map(|tab| ChannelTabRecord {238
tab_id: tab.id,239
name: tab.name,240
definition_id: tab.definition_id,241
open_url: tab.open_url,242
})243
.collect(),174
})244
})175
.collect(),245
.collect(),176
}246
}@@ -346,3 +416,52 @@ impl<R: Remote> SyncEngine<R> {346
Ok(())416
Ok(())347
}417
}348
}418
}419
420
#[cfg(test)]421
mod tests {422
use super::*;423
424
fn channel(425
notifications: Option<ChannelNotifications>,426
followed: bool,427
) -> chatsvc::ChannelLayout {428
chatsvc::ChannelLayout {429
channel_id: "19:a".into(),430
general: false,431
hidden: false,432
tabs: Vec::new(),433
notifications,434
followed,435
}436
}437
438
fn level(level: ChannelNotificationLevel, include_replies: bool) -> ChannelNotifications {439
ChannelNotifications {440
level,441
include_replies,442
}443
}444
445
#[test]446
fn channel_value_beats_the_notification_service_beats_the_followed_flag() {447
let off = level(ChannelNotificationLevel::Off, false);448
let banner = level(ChannelNotificationLevel::BannerAndFeed, true);449
let fallback = HashMap::from([("19:a".to_owned(), banner)]);450
assert_eq!(451
resolve_notifications(&channel(Some(off), true), &fallback),452
off453
);454
assert_eq!(455
resolve_notifications(&channel(None, false), &fallback),456
banner457
);458
assert_eq!(459
resolve_notifications(&channel(None, true), &HashMap::new()),460
banner461
);462
assert_eq!(463
resolve_notifications(&channel(None, false), &HashMap::new()),464
ChannelNotifications::default()465
);466
}467
}@@ -21,6 +21,7 @@ mod gifs;
21
21
mod image_size;
22
22
mod images;
23
23
mod italic;
24
mod library;
24
25
mod link_sync;
25
26
mod links;
26
27
mod mapping;
@@ -89,15 +90,18 @@ pub use folders::{
89
90
stored_section_settings,
90
91
};
91
92
pub use graph::{
92
FileReference, HostedImage, KeptAttachment, MentionTarget, MessageExtras, SharedFile,
93
UploadedFile,
93
DriveEntry, DriveFolder, FileReference, HostedImage, KeptAttachment, MentionTarget,
94
MessageExtras, SharedFile, UploadedFile,
94
95
};
96
pub use download::LibraryFile;
95
97
pub use images::StoredImage;
96
pub use links::{LinkPreview, first_public_link, is_public_link, link_preview};
98
pub use links::{LinkPreview, first_public_link, is_public_link, link_preview, public_links};
97
99
pub use mapping::{chat_record, message_record};
98
100
pub use markdown::{card_markdown_to_html, escape_html, markdown_to_html, plain_text_to_html};
99
101
pub use mentions::MentionInput;
100
pub use message_link::{ChannelLinkInput, channel_message_link, chat_message_link};
102
pub use message_link::{
103
ChannelLinkInput, channel_message_link, channel_tab_link, chat_message_link,
104
};
101
105
pub use people::{MentionCandidate, PersonCandidate, PersonSource};
102
106
pub use presence::{Availability, Presence};
103
107
pub use preview::preview_text;
@@ -21,6 +21,7 @@ mod gifs;21
mod image_size;21
mod image_size;22
mod images;22
mod images;23
mod italic;23
mod italic;24
mod library;24
mod link_sync;25
mod link_sync;25
mod links;26
mod links;26
mod mapping;27
mod mapping;@@ -89,15 +90,18 @@ pub use folders::{89
stored_section_settings,90
stored_section_settings,90
};91
};91
pub use graph::{92
pub use graph::{92
FileReference, HostedImage, KeptAttachment, MentionTarget, MessageExtras, SharedFile,93
DriveEntry, DriveFolder, FileReference, HostedImage, KeptAttachment, MentionTarget,93
UploadedFile,94
MessageExtras, SharedFile, UploadedFile,94
};95
};96
pub use download::LibraryFile;95
pub use images::StoredImage;97
pub use images::StoredImage;96
pub use links::{LinkPreview, first_public_link, is_public_link, link_preview};98
pub use links::{LinkPreview, first_public_link, is_public_link, link_preview, public_links};97
pub use mapping::{chat_record, message_record};99
pub use mapping::{chat_record, message_record};98
pub use markdown::{card_markdown_to_html, escape_html, markdown_to_html, plain_text_to_html};100
pub use markdown::{card_markdown_to_html, escape_html, markdown_to_html, plain_text_to_html};99
pub use mentions::MentionInput;101
pub use mentions::MentionInput;100
pub use message_link::{ChannelLinkInput, channel_message_link, chat_message_link};102
pub use message_link::{103
ChannelLinkInput, channel_message_link, channel_tab_link, chat_message_link,104
};101
pub use people::{MentionCandidate, PersonCandidate, PersonSource};105
pub use people::{MentionCandidate, PersonCandidate, PersonSource};102
pub use presence::{Availability, Presence};106
pub use presence::{Availability, Presence};103
pub use preview::preview_text;107
pub use preview::preview_text;@@ -0,0 +1,56 @@
1
use graph::{DriveEntry, DriveFolder, UploadDestination, UploadedFile};
2
3
use crate::engine::{Conversation, SyncEngine};
4
use crate::error::{Error, Result};
5
use crate::remote::Remote;
6
7
impl<R: Remote> SyncEngine<R> {
8
pub async fn channel_library_root(&self, channel_id: &str) -> Result<DriveEntry> {
9
let Conversation::Channel { team_id } = self.resolve(channel_id)? else {
10
return Err(Error::Unsupported("a library for a chat"));
11
};
12
self.remote.channel_files_root(&team_id, channel_id).await
13
}
14
15
pub async fn channel_tab_web_url(
16
&self,
17
channel_id: &str,
18
tab_id: &str,
19
) -> Result<Option<String>> {
20
let Conversation::Channel { team_id } = self.resolve(channel_id)? else {
21
return Err(Error::Unsupported("a tab link for a chat"));
22
};
23
self.remote
24
.channel_tab_web_url(&team_id, channel_id, tab_id)
25
.await
26
}
27
28
pub async fn library_children(&self, folder: &DriveFolder) -> Result<Vec<DriveEntry>> {
29
self.remote.list_children(folder).await
30
}
31
32
pub async fn create_library_folder(
33
&self,
34
parent: &DriveFolder,
35
name: &str,
36
) -> Result<DriveEntry> {
37
self.remote.create_folder(parent, name).await
38
}
39
40
pub async fn upload_to_library(
41
&self,
42
folder: &DriveFolder,
43
file_name: &str,
44
bytes: &[u8],
45
progress: impl Fn(u8) + Send + Sync,
46
) -> Result<UploadedFile> {
47
self.remote
48
.upload_file(
49
&UploadDestination::Folder(folder.clone()),
50
file_name,
51
bytes,
52
&progress,
53
)
54
.await
55
}
56
}
@@ -0,0 +1,56 @@1
use graph::{DriveEntry, DriveFolder, UploadDestination, UploadedFile};2
3
use crate::engine::{Conversation, SyncEngine};4
use crate::error::{Error, Result};5
use crate::remote::Remote;6
7
impl<R: Remote> SyncEngine<R> {8
pub async fn channel_library_root(&self, channel_id: &str) -> Result<DriveEntry> {9
let Conversation::Channel { team_id } = self.resolve(channel_id)? else {10
return Err(Error::Unsupported("a library for a chat"));11
};12
self.remote.channel_files_root(&team_id, channel_id).await13
}14
15
pub async fn channel_tab_web_url(16
&self,17
channel_id: &str,18
tab_id: &str,19
) -> Result<Option<String>> {20
let Conversation::Channel { team_id } = self.resolve(channel_id)? else {21
return Err(Error::Unsupported("a tab link for a chat"));22
};23
self.remote24
.channel_tab_web_url(&team_id, channel_id, tab_id)25
.await26
}27
28
pub async fn library_children(&self, folder: &DriveFolder) -> Result<Vec<DriveEntry>> {29
self.remote.list_children(folder).await30
}31
32
pub async fn create_library_folder(33
&self,34
parent: &DriveFolder,35
name: &str,36
) -> Result<DriveEntry> {37
self.remote.create_folder(parent, name).await38
}39
40
pub async fn upload_to_library(41
&self,42
folder: &DriveFolder,43
file_name: &str,44
bytes: &[u8],45
progress: impl Fn(u8) + Send + Sync,46
) -> Result<UploadedFile> {47
self.remote48
.upload_file(49
&UploadDestination::Folder(folder.clone()),50
file_name,51
bytes,52
&progress,53
)54
.await55
}56
}@@ -159,6 +159,29 @@ pub fn first_public_link(html: &str) -> Option<String> {
159
159
.map(str::to_owned)
160
160
}
161
161
162
pub fn public_links(record: &MessageRecord) -> Vec<String> {
163
let Ok(selector) = Selector::parse("a[href]") else {
164
return Vec::new();
165
};
166
if record.deleted {
167
return Vec::new();
168
}
169
let mut links: Vec<String> = Vec::new();
170
for anchor in Html::parse_fragment(&record.body_html).select(&selector) {
171
let Some(href) = anchor
172
.value()
173
.attr("href")
174
.filter(|href| is_public_link(href))
175
else {
176
continue;
177
};
178
if !links.iter().any(|known| known == href) {
179
links.push(href.to_owned());
180
}
181
}
182
links
183
}
184
162
185
pub fn is_public_link(url: &str) -> bool {
163
186
let lower = url.to_ascii_lowercase();
164
187
if !(lower.starts_with("http://") || lower.starts_with("https://")) {
@@ -210,6 +233,38 @@ mod tests {
210
233
entries.to_string()
211
234
}
212
235
236
#[test]
237
fn public_links_lists_each_external_link_once() {
238
let record = MessageRecord {
239
body_html: "<p><a href=\"https://a.example/x\">x</a> <a href=\"https://contoso.sharepoint.com/f\">f</a> <a href=\"https://a.example/x\">again</a> <a href=\"https://b.example\">b</a></p>".to_owned(),
240
..demo_record()
241
};
242
assert_eq!(
243
public_links(&record),
244
["https://a.example/x", "https://b.example"]
245
);
246
}
247
248
fn demo_record() -> MessageRecord {
249
MessageRecord {
250
conversation_id: "c".to_owned(),
251
message_id: "m".to_owned(),
252
reply_to_id: None,
253
sender_id: None,
254
sender_name: None,
255
created_at: chrono::Utc::now(),
256
edited_at: None,
257
deleted: false,
258
body_html: String::new(),
259
attachments_json: "[]".to_owned(),
260
reactions_json: "[]".to_owned(),
261
mentions_json: "[]".to_owned(),
262
sender_application_id: None,
263
links_json: "[]".to_owned(),
264
subject: None,
265
}
266
}
267
213
268
#[test]
214
269
fn picks_the_first_public_link_with_a_title() {
215
270
let preview = select_preview(&links(json!([
@@ -159,6 +159,29 @@ pub fn first_public_link(html: &str) -> Option<String> {159
.map(str::to_owned)159
.map(str::to_owned)160
}160
}161
161
162
pub fn public_links(record: &MessageRecord) -> Vec<String> {163
let Ok(selector) = Selector::parse("a[href]") else {164
return Vec::new();165
};166
if record.deleted {167
return Vec::new();168
}169
let mut links: Vec<String> = Vec::new();170
for anchor in Html::parse_fragment(&record.body_html).select(&selector) {171
let Some(href) = anchor172
.value()173
.attr("href")174
.filter(|href| is_public_link(href))175
else {176
continue;177
};178
if !links.iter().any(|known| known == href) {179
links.push(href.to_owned());180
}181
}182
links183
}184
162
pub fn is_public_link(url: &str) -> bool {185
pub fn is_public_link(url: &str) -> bool {163
let lower = url.to_ascii_lowercase();186
let lower = url.to_ascii_lowercase();164
if !(lower.starts_with("http://") || lower.starts_with("https://")) {187
if !(lower.starts_with("http://") || lower.starts_with("https://")) {@@ -210,6 +233,38 @@ mod tests {210
entries.to_string()233
entries.to_string()211
}234
}212
235
236
#[test]237
fn public_links_lists_each_external_link_once() {238
let record = MessageRecord {239
body_html: "<p><a href=\"https://a.example/x\">x</a> <a href=\"https://contoso.sharepoint.com/f\">f</a> <a href=\"https://a.example/x\">again</a> <a href=\"https://b.example\">b</a></p>".to_owned(),240
..demo_record()241
};242
assert_eq!(243
public_links(&record),244
["https://a.example/x", "https://b.example"]245
);246
}247
248
fn demo_record() -> MessageRecord {249
MessageRecord {250
conversation_id: "c".to_owned(),251
message_id: "m".to_owned(),252
reply_to_id: None,253
sender_id: None,254
sender_name: None,255
created_at: chrono::Utc::now(),256
edited_at: None,257
deleted: false,258
body_html: String::new(),259
attachments_json: "[]".to_owned(),260
reactions_json: "[]".to_owned(),261
mentions_json: "[]".to_owned(),262
sender_application_id: None,263
links_json: "[]".to_owned(),264
subject: None,265
}266
}267
213
#[test]268
#[test]214
fn picks_the_first_public_link_with_a_title() {269
fn picks_the_first_public_link_with_a_title() {215
let preview = select_preview(&links(json!([270
let preview = select_preview(&links(json!([@@ -60,6 +60,14 @@ pub fn channel_message_link(input: &ChannelLinkInput) -> String {
60
60
)
61
61
}
62
62
63
pub fn channel_tab_link(channel_id: &str, tab_id: &str, label: &str) -> String {
64
format!(
65
"{LINK_HOST}/l/channel/{channel_id}/tab%3A%3A{}?label={}",
66
encode(tab_id),
67
encode(label)
68
)
69
}
70
63
71
#[cfg(test)]
64
72
mod tests {
65
73
use super::*;
@@ -97,4 +105,12 @@ mod tests {
97
105
"https://teams.microsoft.com/l/message/19:chan@thread.tacv2/1791368000555?tenantId=tenant-1&groupId=group-1&parentMessageId=1791368000000&teamName=R%26D%20Team&channelName=General%3A%20News&createdTime=1791368000555"
98
106
);
99
107
}
108
109
#[test]
110
fn tab_link_points_at_the_tab_in_its_channel() {
111
assert_eq!(
112
channel_tab_link("19:chan@thread.tacv2", "a1-b2", "Sprint board"),
113
"https://teams.microsoft.com/l/channel/19:chan@thread.tacv2/tab%3A%3Aa1-b2?label=Sprint%20board"
114
);
115
}
100
116
}
@@ -60,6 +60,14 @@ pub fn channel_message_link(input: &ChannelLinkInput) -> String {60
)60
)61
}61
}62
62
63
pub fn channel_tab_link(channel_id: &str, tab_id: &str, label: &str) -> String {64
format!(65
"{LINK_HOST}/l/channel/{channel_id}/tab%3A%3A{}?label={}",66
encode(tab_id),67
encode(label)68
)69
}70
63
#[cfg(test)]71
#[cfg(test)]64
mod tests {72
mod tests {65
use super::*;73
use super::*;@@ -97,4 +105,12 @@ mod tests {97
"https://teams.microsoft.com/l/message/19:chan@thread.tacv2/1791368000555?tenantId=tenant-1&groupId=group-1&parentMessageId=1791368000000&teamName=R%26D%20Team&channelName=General%3A%20News&createdTime=1791368000555"105
"https://teams.microsoft.com/l/message/19:chan@thread.tacv2/1791368000555?tenantId=tenant-1&groupId=group-1&parentMessageId=1791368000000&teamName=R%26D%20Team&channelName=General%3A%20News&createdTime=1791368000555"98
);106
);99
}107
}108
109
#[test]110
fn tab_link_points_at_the_tab_in_its_channel() {111
assert_eq!(112
channel_tab_link("19:chan@thread.tacv2", "a1-b2", "Sprint board"),113
"https://teams.microsoft.com/l/channel/19:chan@thread.tacv2/tab%3A%3Aa1-b2?label=Sprint%20board"114
);115
}100
}116
}@@ -6,7 +6,7 @@ use chatsvc::{
6
6
};
7
7
use chrono::{DateTime, Utc};
8
8
use graph::{
9
Channel, Chat, DriveFolder, Graph, Member, Message, MessageExtras, MessageTarget,
9
Channel, Chat, DriveEntry, DriveFolder, Graph, Member, Message, MessageExtras, MessageTarget,
10
10
OutgoingMention, Photo, Presence, SharedFile, Team, UploadDestination, UploadedFile, User,
11
11
};
12
12
@@ -121,6 +121,11 @@ pub trait Remote {
121
121
async fn leave_chat(&self, chat_id: &str, user_id: &str) -> Result<()>;
122
122
async fn muted_chat_states(&self) -> Result<Vec<(String, bool)>>;
123
123
async fn set_chat_muted(&self, chat_id: &str, muted: bool) -> Result<()>;
124
async fn set_channel_notifications(
125
&self,
126
channel_id: &str,
127
notifications: store::ChannelNotifications,
128
) -> Result<()>;
124
129
async fn send_typing(&self, conversation: &ConversationRef, active: bool) -> Result<()>;
125
130
async fn set_reaction(&self, target: &MessageTarget, reaction_type: &str) -> Result<()>;
126
131
async fn unset_reaction(&self, target: &MessageTarget, reaction_type: &str) -> Result<()>;
@@ -156,6 +161,27 @@ pub trait Remote {
156
161
Err(Error::Unsupported("a channel files folder"))
157
162
}
158
163
164
async fn channel_files_root(&self, _team_id: &str, _channel_id: &str) -> Result<DriveEntry> {
165
Err(Error::Unsupported("a channel library"))
166
}
167
168
async fn channel_tab_web_url(
169
&self,
170
_team_id: &str,
171
_channel_id: &str,
172
_tab_id: &str,
173
) -> Result<Option<String>> {
174
Err(Error::Unsupported("a channel tab link"))
175
}
176
177
async fn list_children(&self, _folder: &DriveFolder) -> Result<Vec<DriveEntry>> {
178
Err(Error::Unsupported("a folder listing"))
179
}
180
181
async fn create_folder(&self, _parent: &DriveFolder, _name: &str) -> Result<DriveEntry> {
182
Err(Error::Unsupported("creating a folder"))
183
}
184
159
185
async fn upload_file(
160
186
&self,
161
187
_destination: &UploadDestination,
@@ -178,6 +204,10 @@ pub trait Remote {
178
204
Err(Error::Unsupported("resolving a shared file"))
179
205
}
180
206
207
async fn resolve_drive_item(&self, _drive_id: &str, _item_id: &str) -> Result<SharedFile> {
208
Err(Error::Unsupported("resolving a drive item"))
209
}
210
181
211
async fn download_range(
182
212
&self,
183
213
_download_url: &str,
@@ -527,6 +557,19 @@ impl Remote for Graph {
527
557
.await?)
528
558
}
529
559
560
async fn set_channel_notifications(
561
&self,
562
channel_id: &str,
563
notifications: store::ChannelNotifications,
564
) -> Result<()> {
565
Ok(Conversations::new(self.session())
566
.set_channel_notifications(
567
channel_id,
568
crate::folders::chatsvc_notifications(notifications),
569
)
570
.await?)
571
}
572
530
573
async fn send_typing(&self, conversation: &ConversationRef, active: bool) -> Result<()> {
531
574
Ok(Messages::new(self.session())
532
575
.send_typing(conversation, active)
@@ -617,6 +660,27 @@ impl Remote for Graph {
617
660
Ok(Graph::channel_files_folder(self, team_id, channel_id).await?)
618
661
}
619
662
663
async fn channel_files_root(&self, team_id: &str, channel_id: &str) -> Result<DriveEntry> {
664
Ok(Graph::channel_files_root(self, team_id, channel_id).await?)
665
}
666
667
async fn channel_tab_web_url(
668
&self,
669
team_id: &str,
670
channel_id: &str,
671
tab_id: &str,
672
) -> Result<Option<String>> {
673
Ok(Graph::channel_tab_web_url(self, team_id, channel_id, tab_id).await?)
674
}
675
676
async fn list_children(&self, folder: &DriveFolder) -> Result<Vec<DriveEntry>> {
677
Ok(Graph::list_children(self, folder).await?)
678
}
679
680
async fn create_folder(&self, parent: &DriveFolder, name: &str) -> Result<DriveEntry> {
681
Ok(Graph::create_folder(self, parent, name).await?)
682
}
683
620
684
async fn upload_file(
621
685
&self,
622
686
destination: &UploadDestination,
@@ -639,6 +703,10 @@ impl Remote for Graph {
639
703
Ok(Graph::resolve_share(self, open_url).await?)
640
704
}
641
705
706
async fn resolve_drive_item(&self, drive_id: &str, item_id: &str) -> Result<SharedFile> {
707
Ok(Graph::resolve_drive_item(self, drive_id, item_id).await?)
708
}
709
642
710
async fn download_range(
643
711
&self,
644
712
download_url: &str,
@@ -6,7 +6,7 @@ use chatsvc::{6
};6
};7
use chrono::{DateTime, Utc};7
use chrono::{DateTime, Utc};8
use graph::{8
use graph::{9
Channel, Chat, DriveFolder, Graph, Member, Message, MessageExtras, MessageTarget,9
Channel, Chat, DriveEntry, DriveFolder, Graph, Member, Message, MessageExtras, MessageTarget,10
OutgoingMention, Photo, Presence, SharedFile, Team, UploadDestination, UploadedFile, User,10
OutgoingMention, Photo, Presence, SharedFile, Team, UploadDestination, UploadedFile, User,11
};11
};12
12
@@ -121,6 +121,11 @@ pub trait Remote {121
async fn leave_chat(&self, chat_id: &str, user_id: &str) -> Result<()>;121
async fn leave_chat(&self, chat_id: &str, user_id: &str) -> Result<()>;122
async fn muted_chat_states(&self) -> Result<Vec<(String, bool)>>;122
async fn muted_chat_states(&self) -> Result<Vec<(String, bool)>>;123
async fn set_chat_muted(&self, chat_id: &str, muted: bool) -> Result<()>;123
async fn set_chat_muted(&self, chat_id: &str, muted: bool) -> Result<()>;124
async fn set_channel_notifications(125
&self,126
channel_id: &str,127
notifications: store::ChannelNotifications,128
) -> Result<()>;124
async fn send_typing(&self, conversation: &ConversationRef, active: bool) -> Result<()>;129
async fn send_typing(&self, conversation: &ConversationRef, active: bool) -> Result<()>;125
async fn set_reaction(&self, target: &MessageTarget, reaction_type: &str) -> Result<()>;130
async fn set_reaction(&self, target: &MessageTarget, reaction_type: &str) -> Result<()>;126
async fn unset_reaction(&self, target: &MessageTarget, reaction_type: &str) -> Result<()>;131
async fn unset_reaction(&self, target: &MessageTarget, reaction_type: &str) -> Result<()>;@@ -156,6 +161,27 @@ pub trait Remote {156
Err(Error::Unsupported("a channel files folder"))161
Err(Error::Unsupported("a channel files folder"))157
}162
}158
163
164
async fn channel_files_root(&self, _team_id: &str, _channel_id: &str) -> Result<DriveEntry> {165
Err(Error::Unsupported("a channel library"))166
}167
168
async fn channel_tab_web_url(169
&self,170
_team_id: &str,171
_channel_id: &str,172
_tab_id: &str,173
) -> Result<Option<String>> {174
Err(Error::Unsupported("a channel tab link"))175
}176
177
async fn list_children(&self, _folder: &DriveFolder) -> Result<Vec<DriveEntry>> {178
Err(Error::Unsupported("a folder listing"))179
}180
181
async fn create_folder(&self, _parent: &DriveFolder, _name: &str) -> Result<DriveEntry> {182
Err(Error::Unsupported("creating a folder"))183
}184
159
async fn upload_file(185
async fn upload_file(160
&self,186
&self,161
_destination: &UploadDestination,187
_destination: &UploadDestination,@@ -178,6 +204,10 @@ pub trait Remote {178
Err(Error::Unsupported("resolving a shared file"))204
Err(Error::Unsupported("resolving a shared file"))179
}205
}180
206
207
async fn resolve_drive_item(&self, _drive_id: &str, _item_id: &str) -> Result<SharedFile> {208
Err(Error::Unsupported("resolving a drive item"))209
}210
181
async fn download_range(211
async fn download_range(182
&self,212
&self,183
_download_url: &str,213
_download_url: &str,@@ -527,6 +557,19 @@ impl Remote for Graph {527
.await?)557
.await?)528
}558
}529
559
560
async fn set_channel_notifications(561
&self,562
channel_id: &str,563
notifications: store::ChannelNotifications,564
) -> Result<()> {565
Ok(Conversations::new(self.session())566
.set_channel_notifications(567
channel_id,568
crate::folders::chatsvc_notifications(notifications),569
)570
.await?)571
}572
530
async fn send_typing(&self, conversation: &ConversationRef, active: bool) -> Result<()> {573
async fn send_typing(&self, conversation: &ConversationRef, active: bool) -> Result<()> {531
Ok(Messages::new(self.session())574
Ok(Messages::new(self.session())532
.send_typing(conversation, active)575
.send_typing(conversation, active)@@ -617,6 +660,27 @@ impl Remote for Graph {617
Ok(Graph::channel_files_folder(self, team_id, channel_id).await?)660
Ok(Graph::channel_files_folder(self, team_id, channel_id).await?)618
}661
}619
662
663
async fn channel_files_root(&self, team_id: &str, channel_id: &str) -> Result<DriveEntry> {664
Ok(Graph::channel_files_root(self, team_id, channel_id).await?)665
}666
667
async fn channel_tab_web_url(668
&self,669
team_id: &str,670
channel_id: &str,671
tab_id: &str,672
) -> Result<Option<String>> {673
Ok(Graph::channel_tab_web_url(self, team_id, channel_id, tab_id).await?)674
}675
676
async fn list_children(&self, folder: &DriveFolder) -> Result<Vec<DriveEntry>> {677
Ok(Graph::list_children(self, folder).await?)678
}679
680
async fn create_folder(&self, parent: &DriveFolder, name: &str) -> Result<DriveEntry> {681
Ok(Graph::create_folder(self, parent, name).await?)682
}683
620
async fn upload_file(684
async fn upload_file(621
&self,685
&self,622
destination: &UploadDestination,686
destination: &UploadDestination,@@ -639,6 +703,10 @@ impl Remote for Graph {639
Ok(Graph::resolve_share(self, open_url).await?)703
Ok(Graph::resolve_share(self, open_url).await?)640
}704
}641
705
706
async fn resolve_drive_item(&self, drive_id: &str, item_id: &str) -> Result<SharedFile> {707
Ok(Graph::resolve_drive_item(self, drive_id, item_id).await?)708
}709
642
async fn download_range(710
async fn download_range(643
&self,711
&self,644
download_url: &str,712
download_url: &str,@@ -448,6 +448,19 @@ impl Remote for Handle {
448
448
Ok(())
449
449
}
450
450
451
async fn set_channel_notifications(
452
&self,
453
channel_id: &str,
454
notifications: store::ChannelNotifications,
455
) -> Result<()> {
456
self.record(format!(
457
"channel notifications {channel_id} {} {}",
458
notifications.level.key(),
459
notifications.include_replies
460
));
461
Ok(())
462
}
463
451
464
async fn send_typing(&self, conversation: &ConversationRef, active: bool) -> Result<()> {
452
465
self.record(format!(
453
466
"typing {} {active}",
@@ -572,6 +585,15 @@ impl Remote for Handle {
572
585
})
573
586
}
574
587
588
async fn resolve_drive_item(&self, drive_id: &str, item_id: &str) -> Result<SharedFile> {
589
self.record(format!("resolve item {drive_id}/{item_id}"));
590
Ok(SharedFile {
591
name: "big.bin".into(),
592
size: 2 * graph::DOWNLOAD_CHUNK_BYTES + 3,
593
download_url: "https://dl.example/fresh".into(),
594
})
595
}
596
575
597
async fn download_range(
576
598
&self,
577
599
download_url: &str,
@@ -1590,6 +1612,45 @@ async fn download_streams_every_chunk_and_reports_progress() {
1590
1612
assert!(percents.windows(2).all(|pair| pair[0] <= pair[1]));
1591
1613
}
1592
1614
1615
#[tokio::test]
1616
async fn library_download_uses_the_listing_url_and_refetches_the_item_without_one() {
1617
let library_file = |cached_url: Option<&str>| teams_core::LibraryFile {
1618
drive_id: "drive".into(),
1619
item_id: "item".into(),
1620
name: "big.bin".into(),
1621
size: 2 * graph::DOWNLOAD_CHUNK_BYTES + 3,
1622
cached_url: cached_url.map(str::to_owned),
1623
};
1624
let fake = Arc::new(Fake::default());
1625
let engine = chat_engine(&fake, small_pages()).await;
1626
engine
1627
.download_library_file(
1628
&library_file(Some("https://dl.example/listed")),
1629
|_| Ok(()),
1630
|_| {},
1631
)
1632
.await
1633
.unwrap();
1634
let calls = fake.calls();
1635
assert!(!calls.iter().any(|call| call.starts_with("resolve")));
1636
assert!(
1637
calls
1638
.iter()
1639
.any(|call| call.starts_with("range https://dl.example/listed "))
1640
);
1641
engine
1642
.download_library_file(&library_file(None), |_| Ok(()), |_| {})
1643
.await
1644
.unwrap();
1645
let calls = fake.calls();
1646
assert!(calls.contains(&"resolve item drive/item".to_owned()));
1647
assert!(
1648
calls
1649
.iter()
1650
.any(|call| call.starts_with("range https://dl.example/fresh "))
1651
);
1652
}
1653
1593
1654
#[tokio::test]
1594
1655
async fn download_keeps_a_file_that_grew_past_the_reported_size() {
1595
1656
let fake = Arc::new(Fake::default());
@@ -2344,6 +2405,8 @@ async fn team_layout_from_teams_orders_and_hides_the_sidebar() {
2344
2405
channel_id: "zeta-old".into(),
2345
2406
general: false,
2346
2407
hidden: true,
2408
tabs: Vec::new(),
2409
notifications: Default::default(),
2347
2410
}],
2348
2411
},
2349
2412
TeamLayoutRecord {
@@ -2390,6 +2453,48 @@ async fn team_layout_from_teams_orders_and_hides_the_sidebar() {
2390
2453
assert!(received.contains(&CoreEvent::SidebarChanged));
2391
2454
}
2392
2455
2456
#[tokio::test]
2457
async fn channel_notifications_go_to_the_service_then_the_store() {
2458
let fake = Arc::new(Fake::default());
2459
let engine = engine_with(&fake, SyncConfig::default());
2460
engine
2461
.store()
2462
.upsert_teams(&[TeamRecord {
2463
id: "alpha".into(),
2464
name: "alpha".into(),
2465
}])
2466
.unwrap();
2467
engine
2468
.store()
2469
.upsert_channels(&[ChannelRecord {
2470
id: "alpha-news".into(),
2471
team_id: "alpha".into(),
2472
name: "News".into(),
2473
membership_type: None,
2474
last_message_at: None,
2475
unread: false,
2476
}])
2477
.unwrap();
2478
let mut events = engine.subscribe();
2479
let banner = store::ChannelNotifications {
2480
level: store::ChannelNotificationLevel::BannerAndFeed,
2481
include_replies: true,
2482
};
2483
2484
engine
2485
.set_channel_notifications("alpha-news", banner)
2486
.await
2487
.unwrap();
2488
2489
assert_eq!(
2490
fake.calls().last().unwrap(),
2491
"channel notifications alpha-news banner true"
2492
);
2493
let teams = engine.store().sidebar().unwrap().teams;
2494
assert_eq!(teams[0].channel_notifications("alpha-news"), banner);
2495
assert_eq!(events.try_recv().unwrap(), CoreEvent::SidebarChanged);
2496
}
2497
2393
2498
#[tokio::test]
2394
2499
async fn folders_without_a_source_are_unsupported() {
2395
2500
let fake = Arc::new(Fake::default());
@@ -448,6 +448,19 @@ impl Remote for Handle {448
Ok(())448
Ok(())449
}449
}450
450
451
async fn set_channel_notifications(452
&self,453
channel_id: &str,454
notifications: store::ChannelNotifications,455
) -> Result<()> {456
self.record(format!(457
"channel notifications {channel_id} {} {}",458
notifications.level.key(),459
notifications.include_replies460
));461
Ok(())462
}463
451
async fn send_typing(&self, conversation: &ConversationRef, active: bool) -> Result<()> {464
async fn send_typing(&self, conversation: &ConversationRef, active: bool) -> Result<()> {452
self.record(format!(465
self.record(format!(453
"typing {} {active}",466
"typing {} {active}",@@ -572,6 +585,15 @@ impl Remote for Handle {572
})585
})573
}586
}574
587
588
async fn resolve_drive_item(&self, drive_id: &str, item_id: &str) -> Result<SharedFile> {589
self.record(format!("resolve item {drive_id}/{item_id}"));590
Ok(SharedFile {591
name: "big.bin".into(),592
size: 2 * graph::DOWNLOAD_CHUNK_BYTES + 3,593
download_url: "https://dl.example/fresh".into(),594
})595
}596
575
async fn download_range(597
async fn download_range(576
&self,598
&self,577
download_url: &str,599
download_url: &str,@@ -1590,6 +1612,45 @@ async fn download_streams_every_chunk_and_reports_progress() {1590
assert!(percents.windows(2).all(|pair| pair[0] <= pair[1]));1612
assert!(percents.windows(2).all(|pair| pair[0] <= pair[1]));1591
}1613
}1592
1614
1615
#[tokio::test]1616
async fn library_download_uses_the_listing_url_and_refetches_the_item_without_one() {1617
let library_file = |cached_url: Option<&str>| teams_core::LibraryFile {1618
drive_id: "drive".into(),1619
item_id: "item".into(),1620
name: "big.bin".into(),1621
size: 2 * graph::DOWNLOAD_CHUNK_BYTES + 3,1622
cached_url: cached_url.map(str::to_owned),1623
};1624
let fake = Arc::new(Fake::default());1625
let engine = chat_engine(&fake, small_pages()).await;1626
engine1627
.download_library_file(1628
&library_file(Some("https://dl.example/listed")),1629
|_| Ok(()),1630
|_| {},1631
)1632
.await1633
.unwrap();1634
let calls = fake.calls();1635
assert!(!calls.iter().any(|call| call.starts_with("resolve")));1636
assert!(1637
calls1638
.iter()1639
.any(|call| call.starts_with("range https://dl.example/listed "))1640
);1641
engine1642
.download_library_file(&library_file(None), |_| Ok(()), |_| {})1643
.await1644
.unwrap();1645
let calls = fake.calls();1646
assert!(calls.contains(&"resolve item drive/item".to_owned()));1647
assert!(1648
calls1649
.iter()1650
.any(|call| call.starts_with("range https://dl.example/fresh "))1651
);1652
}1653
1593
#[tokio::test]1654
#[tokio::test]1594
async fn download_keeps_a_file_that_grew_past_the_reported_size() {1655
async fn download_keeps_a_file_that_grew_past_the_reported_size() {1595
let fake = Arc::new(Fake::default());1656
let fake = Arc::new(Fake::default());@@ -2344,6 +2405,8 @@ async fn team_layout_from_teams_orders_and_hides_the_sidebar() {2344
channel_id: "zeta-old".into(),2405
channel_id: "zeta-old".into(),2345
general: false,2406
general: false,2346
hidden: true,2407
hidden: true,2408
tabs: Vec::new(),2409
notifications: Default::default(),2347
}],2410
}],2348
},2411
},2349
TeamLayoutRecord {2412
TeamLayoutRecord {@@ -2390,6 +2453,48 @@ async fn team_layout_from_teams_orders_and_hides_the_sidebar() {2390
assert!(received.contains(&CoreEvent::SidebarChanged));2453
assert!(received.contains(&CoreEvent::SidebarChanged));2391
}2454
}2392
2455
2456
#[tokio::test]2457
async fn channel_notifications_go_to_the_service_then_the_store() {2458
let fake = Arc::new(Fake::default());2459
let engine = engine_with(&fake, SyncConfig::default());2460
engine2461
.store()2462
.upsert_teams(&[TeamRecord {2463
id: "alpha".into(),2464
name: "alpha".into(),2465
}])2466
.unwrap();2467
engine2468
.store()2469
.upsert_channels(&[ChannelRecord {2470
id: "alpha-news".into(),2471
team_id: "alpha".into(),2472
name: "News".into(),2473
membership_type: None,2474
last_message_at: None,2475
unread: false,2476
}])2477
.unwrap();2478
let mut events = engine.subscribe();2479
let banner = store::ChannelNotifications {2480
level: store::ChannelNotificationLevel::BannerAndFeed,2481
include_replies: true,2482
};2483
2484
engine2485
.set_channel_notifications("alpha-news", banner)2486
.await2487
.unwrap();2488
2489
assert_eq!(2490
fake.calls().last().unwrap(),2491
"channel notifications alpha-news banner true"2492
);2493
let teams = engine.store().sidebar().unwrap().teams;2494
assert_eq!(teams[0].channel_notifications("alpha-news"), banner);2495
assert_eq!(events.try_recv().unwrap(), CoreEvent::SidebarChanged);2496
}2497
2393
#[tokio::test]2498
#[tokio::test]2394
async fn folders_without_a_source_are_unsupported() {2499
async fn folders_without_a_source_are_unsupported() {2395
let fake = Arc::new(Fake::default());2500
let fake = Arc::new(Fake::default());@@ -234,7 +234,7 @@ impl Graph {
234
234
Ok(Some(self.get_page(link, page.scope.clone()).await?))
235
235
}
236
236
237
async fn get(&self, url: &str, scope: &Scope) -> Result<Value> {
237
pub(crate) async fn get(&self, url: &str, scope: &Scope) -> Result<Value> {
238
238
ensure_graph_url(url)?;
239
239
Ok(self
240
240
.session
@@ -266,7 +266,11 @@ impl Graph {
266
266
Ok(items)
267
267
}
268
268
269
async fn get_all<T: DeserializeOwned>(&self, url: &str, scope: Scope) -> Result<Vec<T>> {
269
pub(crate) async fn get_all<T: DeserializeOwned>(
270
&self,
271
url: &str,
272
scope: Scope,
273
) -> Result<Vec<T>> {
270
274
let mut page: Page<T> = self.get_page(url, scope).await?;
271
275
let mut items = std::mem::take(&mut page.items);
272
276
while let Some(mut next) = self.next_page(&page).await? {
@@ -234,7 +234,7 @@ impl Graph {234
Ok(Some(self.get_page(link, page.scope.clone()).await?))234
Ok(Some(self.get_page(link, page.scope.clone()).await?))235
}235
}236
236
237
async fn get(&self, url: &str, scope: &Scope) -> Result<Value> {237
pub(crate) async fn get(&self, url: &str, scope: &Scope) -> Result<Value> {238
ensure_graph_url(url)?;238
ensure_graph_url(url)?;239
Ok(self239
Ok(self240
.session240
.session@@ -266,7 +266,11 @@ impl Graph {266
Ok(items)266
Ok(items)267
}267
}268
268
269
async fn get_all<T: DeserializeOwned>(&self, url: &str, scope: Scope) -> Result<Vec<T>> {269
pub(crate) async fn get_all<T: DeserializeOwned>(270
&self,271
url: &str,272
scope: Scope,273
) -> Result<Vec<T>> {270
let mut page: Page<T> = self.get_page(url, scope).await?;274
let mut page: Page<T> = self.get_page(url, scope).await?;271
let mut items = std::mem::take(&mut page.items);275
let mut items = std::mem::take(&mut page.items);272
while let Some(mut next) = self.next_page(&page).await? {276
while let Some(mut next) = self.next_page(&page).await? {@@ -10,7 +10,7 @@ use crate::outgoing::FileReference;
10
10
use crate::people::decode_binary;
11
11
use crate::urls;
12
12
13
const FILES_SCOPE: &str = "Files.ReadWrite";
13
pub(crate) const FILES_SCOPE: &str = "Files.ReadWrite";
14
14
const CHUNK_UNIT_BYTES: u64 = 327_680;
15
15
pub const UPLOAD_CHUNK_BYTES: u64 = 4 * CHUNK_UNIT_BYTES;
16
16
pub const DOWNLOAD_CHUNK_BYTES: u64 = 4 * 1024 * 1024;
@@ -92,6 +92,22 @@ impl DriveItem {
92
92
}
93
93
}
94
94
95
fn shared_file(body: serde_json::Value) -> Result<SharedFile> {
96
let item: SharedItem = serde_json::from_value(body)?;
97
let download_url = item
98
.download_url
99
.filter(|url| !url.is_empty())
100
.ok_or_else(|| Error::Download("the file has no download link".into()))?;
101
let size = item
102
.size
103
.ok_or_else(|| Error::Download("size unknown".into()))?;
104
Ok(SharedFile {
105
name: item.name,
106
size,
107
download_url,
108
})
109
}
110
95
111
/// `"{GUID},3"` becomes `GUID`.
96
112
pub fn etag_guid(etag: &str) -> Option<String> {
97
113
let start = etag.find('{')? + 1;
@@ -351,19 +367,20 @@ impl Graph {
351
367
None,
352
368
)
353
369
.await?;
354
let item: SharedItem = serde_json::from_value(answer.body)?;
355
let download_url = item
356
.download_url
357
.filter(|url| !url.is_empty())
358
.ok_or_else(|| Error::Download("the file has no download link".into()))?;
359
let size = item
360
.size
361
.ok_or_else(|| Error::Download("size unknown".into()))?;
362
Ok(SharedFile {
363
name: item.name,
364
size,
365
download_url,
366
})
370
shared_file(answer.body)
371
}
372
373
pub async fn resolve_drive_item(&self, drive_id: &str, item_id: &str) -> Result<SharedFile> {
374
let answer = self
375
.session()
376
.request(
377
Method::Get,
378
&urls::drive_item(drive_id, item_id),
379
&Scope::graph(FILES_SCOPE),
380
None,
381
)
382
.await?;
383
shared_file(answer.body)
367
384
}
368
385
369
386
pub async fn download_range(
@@ -498,6 +515,22 @@ mod tests {
498
515
assert_eq!(range_header(8_388_608, None), "bytes=8388608-");
499
516
}
500
517
518
#[test]
519
fn share_and_item_lookups_keep_the_download_url_by_not_selecting_fields() {
520
assert!(!urls::shared_drive_item("u!abc").contains("$select"));
521
assert!(!urls::drive_item("b!d", "01ABC").contains("$select"));
522
}
523
524
#[test]
525
fn a_file_without_a_download_link_is_an_error() {
526
assert!(shared_file(json!({"name": "a", "size": 1})).is_err());
527
let shared = shared_file(json!({
528
"name": "a", "size": 1, "@microsoft.graph.downloadUrl": "https://dl.example/a"
529
}))
530
.unwrap();
531
assert_eq!(shared.download_url, "https://dl.example/a");
532
}
533
501
534
#[test]
502
535
fn shared_item_reads_the_download_url() {
503
536
let item: SharedItem = serde_json::from_value(json!({
@@ -10,7 +10,7 @@ use crate::outgoing::FileReference;10
use crate::people::decode_binary;10
use crate::people::decode_binary;11
use crate::urls;11
use crate::urls;12
12
13
const FILES_SCOPE: &str = "Files.ReadWrite";13
pub(crate) const FILES_SCOPE: &str = "Files.ReadWrite";14
const CHUNK_UNIT_BYTES: u64 = 327_680;14
const CHUNK_UNIT_BYTES: u64 = 327_680;15
pub const UPLOAD_CHUNK_BYTES: u64 = 4 * CHUNK_UNIT_BYTES;15
pub const UPLOAD_CHUNK_BYTES: u64 = 4 * CHUNK_UNIT_BYTES;16
pub const DOWNLOAD_CHUNK_BYTES: u64 = 4 * 1024 * 1024;16
pub const DOWNLOAD_CHUNK_BYTES: u64 = 4 * 1024 * 1024;@@ -92,6 +92,22 @@ impl DriveItem {92
}92
}93
}93
}94
94
95
fn shared_file(body: serde_json::Value) -> Result<SharedFile> {96
let item: SharedItem = serde_json::from_value(body)?;97
let download_url = item98
.download_url99
.filter(|url| !url.is_empty())100
.ok_or_else(|| Error::Download("the file has no download link".into()))?;101
let size = item102
.size103
.ok_or_else(|| Error::Download("size unknown".into()))?;104
Ok(SharedFile {105
name: item.name,106
size,107
download_url,108
})109
}110
95
/// `"{GUID},3"` becomes `GUID`.111
/// `"{GUID},3"` becomes `GUID`.96
pub fn etag_guid(etag: &str) -> Option<String> {112
pub fn etag_guid(etag: &str) -> Option<String> {97
let start = etag.find('{')? + 1;113
let start = etag.find('{')? + 1;@@ -351,19 +367,20 @@ impl Graph {351
None,367
None,352
)368
)353
.await?;369
.await?;354
let item: SharedItem = serde_json::from_value(answer.body)?;370
shared_file(answer.body)355
let download_url = item371
}356
.download_url372
357
.filter(|url| !url.is_empty())373
pub async fn resolve_drive_item(&self, drive_id: &str, item_id: &str) -> Result<SharedFile> {358
.ok_or_else(|| Error::Download("the file has no download link".into()))?;374
let answer = self359
let size = item375
.session()360
.size376
.request(361
.ok_or_else(|| Error::Download("size unknown".into()))?;377
Method::Get,362
Ok(SharedFile {378
&urls::drive_item(drive_id, item_id),363
name: item.name,379
&Scope::graph(FILES_SCOPE),364
size,380
None,365
download_url,381
)366
})382
.await?;383
shared_file(answer.body)367
}384
}368
385
369
pub async fn download_range(386
pub async fn download_range(@@ -498,6 +515,22 @@ mod tests {498
assert_eq!(range_header(8_388_608, None), "bytes=8388608-");515
assert_eq!(range_header(8_388_608, None), "bytes=8388608-");499
}516
}500
517
518
#[test]519
fn share_and_item_lookups_keep_the_download_url_by_not_selecting_fields() {520
assert!(!urls::shared_drive_item("u!abc").contains("$select"));521
assert!(!urls::drive_item("b!d", "01ABC").contains("$select"));522
}523
524
#[test]525
fn a_file_without_a_download_link_is_an_error() {526
assert!(shared_file(json!({"name": "a", "size": 1})).is_err());527
let shared = shared_file(json!({528
"name": "a", "size": 1, "@microsoft.graph.downloadUrl": "https://dl.example/a"529
}))530
.unwrap();531
assert_eq!(shared.download_url, "https://dl.example/a");532
}533
501
#[test]534
#[test]502
fn shared_item_reads_the_download_url() {535
fn shared_item_reads_the_download_url() {503
let item: SharedItem = serde_json::from_value(json!({536
let item: SharedItem = serde_json::from_value(json!({@@ -2,11 +2,13 @@ mod client;
2
2
mod content;
3
3
mod error;
4
4
mod files;
5
mod library;
5
6
mod models;
6
7
mod outgoing;
7
8
mod page;
8
9
mod people;
9
10
mod profile;
11
mod tabs;
10
12
mod target;
11
13
mod urls;
12
14
mod writes;
@@ -18,6 +20,7 @@ pub use files::{
18
20
UploadedFile, chunk_range_at, chunk_ranges, download_ranges, etag_guid, next_expected_start,
19
21
percent_done, share_id,
20
22
};
23
pub use library::DriveEntry;
21
24
pub use models::{
22
25
Attachment, Body, Channel, Chat, ChatViewpoint, Identity, Member, Mention, Message, Photo,
23
26
Presence, Reaction, Sender, Team, User,
@@ -2,11 +2,13 @@ mod client;2
mod content;2
mod content;3
mod error;3
mod error;4
mod files;4
mod files;5
mod library;5
mod models;6
mod models;6
mod outgoing;7
mod outgoing;7
mod page;8
mod page;8
mod people;9
mod people;9
mod profile;10
mod profile;11
mod tabs;10
mod target;12
mod target;11
mod urls;13
mod urls;12
mod writes;14
mod writes;@@ -18,6 +20,7 @@ pub use files::{18
UploadedFile, chunk_range_at, chunk_ranges, download_ranges, etag_guid, next_expected_start,20
UploadedFile, chunk_range_at, chunk_ranges, download_ranges, etag_guid, next_expected_start,19
percent_done, share_id,21
percent_done, share_id,20
};22
};23
pub use library::DriveEntry;21
pub use models::{24
pub use models::{22
Attachment, Body, Channel, Chat, ChatViewpoint, Identity, Member, Mention, Message, Photo,25
Attachment, Body, Channel, Chat, ChatViewpoint, Identity, Member, Mention, Message, Photo,23
Presence, Reaction, Sender, Team, User,26
Presence, Reaction, Sender, Team, User,@@ -0,0 +1,214 @@
1
use chrono::{DateTime, Utc};
2
use serde::Deserialize;
3
use serde_json::json;
4
use session::{Method, Scope};
5
6
use crate::client::Graph;
7
use crate::error::{Error, Result};
8
use crate::files::{DriveFolder, FILES_SCOPE};
9
use crate::urls;
10
11
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
12
#[serde(from = "RawEntry")]
13
pub struct DriveEntry {
14
pub drive_id: String,
15
pub id: String,
16
pub name: String,
17
pub web_url: String,
18
pub size: u64,
19
pub modified_at: Option<DateTime<Utc>>,
20
pub modified_by: Option<String>,
21
pub child_count: Option<u64>,
22
pub download_url: Option<String>,
23
}
24
25
impl DriveEntry {
26
pub fn is_folder(&self) -> bool {
27
self.child_count.is_some()
28
}
29
30
pub fn folder(&self) -> DriveFolder {
31
DriveFolder {
32
drive_id: self.drive_id.clone(),
33
item_id: self.id.clone(),
34
}
35
}
36
}
37
38
#[derive(Deserialize)]
39
#[serde(rename_all = "camelCase")]
40
struct RawEntry {
41
id: String,
42
name: String,
43
#[serde(default)]
44
web_url: String,
45
#[serde(default)]
46
size: u64,
47
last_modified_date_time: Option<DateTime<Utc>>,
48
last_modified_by: Option<RawActor>,
49
folder: Option<RawFolder>,
50
#[serde(default, rename = "@microsoft.graph.downloadUrl")]
51
download_url: Option<String>,
52
parent_reference: Option<RawParent>,
53
}
54
55
#[derive(Deserialize)]
56
struct RawActor {
57
user: Option<RawIdentity>,
58
application: Option<RawIdentity>,
59
}
60
61
#[derive(Deserialize)]
62
#[serde(rename_all = "camelCase")]
63
struct RawIdentity {
64
display_name: Option<String>,
65
}
66
67
#[derive(Deserialize)]
68
#[serde(rename_all = "camelCase")]
69
struct RawFolder {
70
#[serde(default)]
71
child_count: u64,
72
}
73
74
#[derive(Deserialize)]
75
#[serde(rename_all = "camelCase")]
76
struct RawParent {
77
drive_id: Option<String>,
78
}
79
80
impl From<RawEntry> for DriveEntry {
81
fn from(raw: RawEntry) -> Self {
82
let modified_by = raw.last_modified_by.and_then(|actor| {
83
actor
84
.user
85
.or(actor.application)
86
.and_then(|identity| identity.display_name)
87
});
88
DriveEntry {
89
drive_id: raw
90
.parent_reference
91
.and_then(|parent| parent.drive_id)
92
.unwrap_or_default(),
93
id: raw.id,
94
name: raw.name,
95
web_url: raw.web_url,
96
size: raw.size,
97
modified_at: raw.last_modified_date_time,
98
modified_by,
99
child_count: raw.folder.map(|folder| folder.child_count),
100
download_url: raw.download_url.filter(|url| !url.is_empty()),
101
}
102
}
103
}
104
105
impl Graph {
106
pub async fn channel_files_root(&self, team_id: &str, channel_id: &str) -> Result<DriveEntry> {
107
let body = self
108
.get(
109
&urls::channel_files_folder(team_id, channel_id),
110
&Scope::graph(FILES_SCOPE),
111
)
112
.await?;
113
let entry: DriveEntry = serde_json::from_value(body)?;
114
if entry.drive_id.is_empty() {
115
return Err(Error::Upload("the channel folder has no drive".into()));
116
}
117
Ok(entry)
118
}
119
120
pub async fn list_children(&self, folder: &DriveFolder) -> Result<Vec<DriveEntry>> {
121
self.get_all(
122
&urls::folder_children(&folder.drive_id, &folder.item_id),
123
Scope::graph(FILES_SCOPE),
124
)
125
.await
126
}
127
128
pub async fn create_folder(&self, parent: &DriveFolder, name: &str) -> Result<DriveEntry> {
129
let answer = self
130
.session()
131
.request(
132
Method::Post,
133
&urls::folder_create(&parent.drive_id, &parent.item_id),
134
&Scope::graph(FILES_SCOPE),
135
Some(json!({
136
"name": name,
137
"folder": {},
138
"@microsoft.graph.conflictBehavior": "rename",
139
})),
140
)
141
.await?;
142
let mut entry: DriveEntry = serde_json::from_value(answer.body)?;
143
if entry.drive_id.is_empty() {
144
entry.drive_id.clone_from(&parent.drive_id);
145
}
146
Ok(entry)
147
}
148
}
149
150
#[cfg(test)]
151
mod tests {
152
use serde_json::json;
153
use session::Scope;
154
155
use super::*;
156
use crate::page::Page;
157
158
fn page(body: serde_json::Value) -> Page<DriveEntry> {
159
Page::parse(body, Scope::graph(FILES_SCOPE)).unwrap()
160
}
161
162
#[test]
163
fn children_parse_files_and_folders() {
164
let parsed = page(json!({"value": [
165
{
166
"id": "f1", "name": "Plans", "webUrl": "https://x/Plans", "size": 0,
167
"folder": {"childCount": 3},
168
"lastModifiedDateTime": "2026-10-01T08:30:00Z",
169
"lastModifiedBy": {"user": {"displayName": "Mara Lindqvist"}},
170
"parentReference": {"driveId": "b!d"}
171
},
172
{
173
"id": "i1", "name": "Plan.pdf", "webUrl": "https://x/Plan.pdf", "size": 2048,
174
"file": {"mimeType": "application/pdf"},
175
"@microsoft.graph.downloadUrl": "https://dl.example/plan",
176
"lastModifiedBy": {"application": {"displayName": "Flow"}},
177
"parentReference": {"driveId": "b!d"}
178
}
179
]}));
180
let [folder, file] = parsed.items.as_slice() else {
181
panic!("two entries");
182
};
183
assert!(folder.is_folder());
184
assert_eq!(folder.child_count, Some(3));
185
assert_eq!(folder.modified_by.as_deref(), Some("Mara Lindqvist"));
186
assert_eq!(folder.folder().drive_id, "b!d");
187
assert!(!file.is_folder());
188
assert_eq!(file.size, 2048);
189
assert_eq!(file.modified_by.as_deref(), Some("Flow"));
190
assert_eq!(
191
file.download_url.as_deref(),
192
Some("https://dl.example/plan")
193
);
194
assert_eq!(file.modified_at, None);
195
}
196
197
#[test]
198
fn a_next_link_continues_the_listing() {
199
let first = page(json!({
200
"value": [{"id": "1", "name": "a"}],
201
"@odata.nextLink": "https://graph.microsoft.com/v1.0/drives/d/items/i/children?$skiptoken=x"
202
}));
203
let last = page(json!({"value": [{"id": "2", "name": "b"}]}));
204
assert!(first.next_link.is_some());
205
assert!(last.next_link.is_none());
206
}
207
208
#[test]
209
fn listing_keeps_the_download_url_by_not_selecting_fields() {
210
let url = urls::folder_children("b!d", "01ABC");
211
assert!(url.ends_with("/children?$top=200"));
212
assert!(!url.contains("$select"));
213
}
214
}
@@ -0,0 +1,214 @@1
use chrono::{DateTime, Utc};2
use serde::Deserialize;3
use serde_json::json;4
use session::{Method, Scope};5
6
use crate::client::Graph;7
use crate::error::{Error, Result};8
use crate::files::{DriveFolder, FILES_SCOPE};9
use crate::urls;10
11
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]12
#[serde(from = "RawEntry")]13
pub struct DriveEntry {14
pub drive_id: String,15
pub id: String,16
pub name: String,17
pub web_url: String,18
pub size: u64,19
pub modified_at: Option<DateTime<Utc>>,20
pub modified_by: Option<String>,21
pub child_count: Option<u64>,22
pub download_url: Option<String>,23
}24
25
impl DriveEntry {26
pub fn is_folder(&self) -> bool {27
self.child_count.is_some()28
}29
30
pub fn folder(&self) -> DriveFolder {31
DriveFolder {32
drive_id: self.drive_id.clone(),33
item_id: self.id.clone(),34
}35
}36
}37
38
#[derive(Deserialize)]39
#[serde(rename_all = "camelCase")]40
struct RawEntry {41
id: String,42
name: String,43
#[serde(default)]44
web_url: String,45
#[serde(default)]46
size: u64,47
last_modified_date_time: Option<DateTime<Utc>>,48
last_modified_by: Option<RawActor>,49
folder: Option<RawFolder>,50
#[serde(default, rename = "@microsoft.graph.downloadUrl")]51
download_url: Option<String>,52
parent_reference: Option<RawParent>,53
}54
55
#[derive(Deserialize)]56
struct RawActor {57
user: Option<RawIdentity>,58
application: Option<RawIdentity>,59
}60
61
#[derive(Deserialize)]62
#[serde(rename_all = "camelCase")]63
struct RawIdentity {64
display_name: Option<String>,65
}66
67
#[derive(Deserialize)]68
#[serde(rename_all = "camelCase")]69
struct RawFolder {70
#[serde(default)]71
child_count: u64,72
}73
74
#[derive(Deserialize)]75
#[serde(rename_all = "camelCase")]76
struct RawParent {77
drive_id: Option<String>,78
}79
80
impl From<RawEntry> for DriveEntry {81
fn from(raw: RawEntry) -> Self {82
let modified_by = raw.last_modified_by.and_then(|actor| {83
actor84
.user85
.or(actor.application)86
.and_then(|identity| identity.display_name)87
});88
DriveEntry {89
drive_id: raw90
.parent_reference91
.and_then(|parent| parent.drive_id)92
.unwrap_or_default(),93
id: raw.id,94
name: raw.name,95
web_url: raw.web_url,96
size: raw.size,97
modified_at: raw.last_modified_date_time,98
modified_by,99
child_count: raw.folder.map(|folder| folder.child_count),100
download_url: raw.download_url.filter(|url| !url.is_empty()),101
}102
}103
}104
105
impl Graph {106
pub async fn channel_files_root(&self, team_id: &str, channel_id: &str) -> Result<DriveEntry> {107
let body = self108
.get(109
&urls::channel_files_folder(team_id, channel_id),110
&Scope::graph(FILES_SCOPE),111
)112
.await?;113
let entry: DriveEntry = serde_json::from_value(body)?;114
if entry.drive_id.is_empty() {115
return Err(Error::Upload("the channel folder has no drive".into()));116
}117
Ok(entry)118
}119
120
pub async fn list_children(&self, folder: &DriveFolder) -> Result<Vec<DriveEntry>> {121
self.get_all(122
&urls::folder_children(&folder.drive_id, &folder.item_id),123
Scope::graph(FILES_SCOPE),124
)125
.await126
}127
128
pub async fn create_folder(&self, parent: &DriveFolder, name: &str) -> Result<DriveEntry> {129
let answer = self130
.session()131
.request(132
Method::Post,133
&urls::folder_create(&parent.drive_id, &parent.item_id),134
&Scope::graph(FILES_SCOPE),135
Some(json!({136
"name": name,137
"folder": {},138
"@microsoft.graph.conflictBehavior": "rename",139
})),140
)141
.await?;142
let mut entry: DriveEntry = serde_json::from_value(answer.body)?;143
if entry.drive_id.is_empty() {144
entry.drive_id.clone_from(&parent.drive_id);145
}146
Ok(entry)147
}148
}149
150
#[cfg(test)]151
mod tests {152
use serde_json::json;153
use session::Scope;154
155
use super::*;156
use crate::page::Page;157
158
fn page(body: serde_json::Value) -> Page<DriveEntry> {159
Page::parse(body, Scope::graph(FILES_SCOPE)).unwrap()160
}161
162
#[test]163
fn children_parse_files_and_folders() {164
let parsed = page(json!({"value": [165
{166
"id": "f1", "name": "Plans", "webUrl": "https://x/Plans", "size": 0,167
"folder": {"childCount": 3},168
"lastModifiedDateTime": "2026-10-01T08:30:00Z",169
"lastModifiedBy": {"user": {"displayName": "Mara Lindqvist"}},170
"parentReference": {"driveId": "b!d"}171
},172
{173
"id": "i1", "name": "Plan.pdf", "webUrl": "https://x/Plan.pdf", "size": 2048,174
"file": {"mimeType": "application/pdf"},175
"@microsoft.graph.downloadUrl": "https://dl.example/plan",176
"lastModifiedBy": {"application": {"displayName": "Flow"}},177
"parentReference": {"driveId": "b!d"}178
}179
]}));180
let [folder, file] = parsed.items.as_slice() else {181
panic!("two entries");182
};183
assert!(folder.is_folder());184
assert_eq!(folder.child_count, Some(3));185
assert_eq!(folder.modified_by.as_deref(), Some("Mara Lindqvist"));186
assert_eq!(folder.folder().drive_id, "b!d");187
assert!(!file.is_folder());188
assert_eq!(file.size, 2048);189
assert_eq!(file.modified_by.as_deref(), Some("Flow"));190
assert_eq!(191
file.download_url.as_deref(),192
Some("https://dl.example/plan")193
);194
assert_eq!(file.modified_at, None);195
}196
197
#[test]198
fn a_next_link_continues_the_listing() {199
let first = page(json!({200
"value": [{"id": "1", "name": "a"}],201
"@odata.nextLink": "https://graph.microsoft.com/v1.0/drives/d/items/i/children?$skiptoken=x"202
}));203
let last = page(json!({"value": [{"id": "2", "name": "b"}]}));204
assert!(first.next_link.is_some());205
assert!(last.next_link.is_none());206
}207
208
#[test]209
fn listing_keeps_the_download_url_by_not_selecting_fields() {210
let url = urls::folder_children("b!d", "01ABC");211
assert!(url.ends_with("/children?$top=200"));212
assert!(!url.contains("$select"));213
}214
}@@ -0,0 +1,62 @@
1
use serde_json::Value;
2
use session::Scope;
3
4
use crate::client::Graph;
5
use crate::error::Result;
6
use crate::urls;
7
8
const TABS_SCOPE: &str = "TeamsTab.ReadWrite.All";
9
10
fn web_url(tab: &Value) -> Option<String> {
11
tab.get("webUrl")
12
.and_then(Value::as_str)
13
.filter(|url| url.starts_with("https://"))
14
.map(str::to_owned)
15
}
16
17
impl Graph {
18
pub async fn channel_tab_web_url(
19
&self,
20
team_id: &str,
21
channel_id: &str,
22
tab_id: &str,
23
) -> Result<Option<String>> {
24
let tab = self
25
.get(
26
&urls::channel_tab(team_id, channel_id, tab_id),
27
&Scope::graph(TABS_SCOPE),
28
)
29
.await?;
30
Ok(web_url(&tab))
31
}
32
}
33
34
#[cfg(test)]
35
mod tests {
36
use serde_json::json;
37
38
use super::*;
39
40
#[test]
41
fn the_tab_deep_link_is_its_web_url() {
42
let tab = json!({"id": "t1", "displayName": "Plan", "webUrl": "https://teams.microsoft.com/l/channel/19%3Ac/tab%3A%3At1?groupId=g&tenantId=t"});
43
assert_eq!(
44
web_url(&tab).as_deref(),
45
Some("https://teams.microsoft.com/l/channel/19%3Ac/tab%3A%3At1?groupId=g&tenantId=t")
46
);
47
}
48
49
#[test]
50
fn a_tab_without_a_usable_web_url_has_none() {
51
assert_eq!(web_url(&json!({"id": "t1"})), None);
52
assert_eq!(web_url(&json!({"webUrl": "javascript:alert(1)"})), None);
53
}
54
55
#[test]
56
fn the_tab_url_names_team_channel_and_tab() {
57
assert_eq!(
58
urls::channel_tab("team", "19:c@thread.tacv2", "tab-1"),
59
"https://graph.microsoft.com/v1.0/teams/team/channels/19%3Ac%40thread.tacv2/tabs/tab-1"
60
);
61
}
62
}
@@ -0,0 +1,62 @@1
use serde_json::Value;2
use session::Scope;3
4
use crate::client::Graph;5
use crate::error::Result;6
use crate::urls;7
8
const TABS_SCOPE: &str = "TeamsTab.ReadWrite.All";9
10
fn web_url(tab: &Value) -> Option<String> {11
tab.get("webUrl")12
.and_then(Value::as_str)13
.filter(|url| url.starts_with("https://"))14
.map(str::to_owned)15
}16
17
impl Graph {18
pub async fn channel_tab_web_url(19
&self,20
team_id: &str,21
channel_id: &str,22
tab_id: &str,23
) -> Result<Option<String>> {24
let tab = self25
.get(26
&urls::channel_tab(team_id, channel_id, tab_id),27
&Scope::graph(TABS_SCOPE),28
)29
.await?;30
Ok(web_url(&tab))31
}32
}33
34
#[cfg(test)]35
mod tests {36
use serde_json::json;37
38
use super::*;39
40
#[test]41
fn the_tab_deep_link_is_its_web_url() {42
let tab = json!({"id": "t1", "displayName": "Plan", "webUrl": "https://teams.microsoft.com/l/channel/19%3Ac/tab%3A%3At1?groupId=g&tenantId=t"});43
assert_eq!(44
web_url(&tab).as_deref(),45
Some("https://teams.microsoft.com/l/channel/19%3Ac/tab%3A%3At1?groupId=g&tenantId=t")46
);47
}48
49
#[test]50
fn a_tab_without_a_usable_web_url_has_none() {51
assert_eq!(web_url(&json!({"id": "t1"})), None);52
assert_eq!(web_url(&json!({"webUrl": "javascript:alert(1)"})), None);53
}54
55
#[test]56
fn the_tab_url_names_team_channel_and_tab() {57
assert_eq!(58
urls::channel_tab("team", "19:c@thread.tacv2", "tab-1"),59
"https://graph.microsoft.com/v1.0/teams/team/channels/19%3Ac%40thread.tacv2/tabs/tab-1"60
);61
}62
}@@ -158,6 +158,33 @@ pub fn channel_files_folder(team_id: &str, channel_id: &str) -> String {
158
158
)
159
159
}
160
160
161
pub fn channel_tab(team_id: &str, channel_id: &str, tab_id: &str) -> String {
162
format!(
163
"{GRAPH}/v1.0/teams/{}/channels/{}/tabs/{}",
164
segment(team_id),
165
segment(channel_id),
166
segment(tab_id)
167
)
168
}
169
170
pub const CHILDREN_PAGE_SIZE: usize = 200;
171
172
pub fn folder_children(drive_id: &str, folder_id: &str) -> String {
173
format!(
174
"{GRAPH}/v1.0/drives/{}/items/{}/children?$top={CHILDREN_PAGE_SIZE}",
175
segment(drive_id),
176
segment(folder_id)
177
)
178
}
179
180
pub fn folder_create(drive_id: &str, folder_id: &str) -> String {
181
format!(
182
"{GRAPH}/v1.0/drives/{}/items/{}/children",
183
segment(drive_id),
184
segment(folder_id)
185
)
186
}
187
161
188
pub fn drive_item(drive_id: &str, item_id: &str) -> String {
162
189
format!(
163
190
"{GRAPH}/v1.0/drives/{}/items/{}",
@@ -168,7 +195,7 @@ pub fn drive_item(drive_id: &str, item_id: &str) -> String {
168
195
169
196
pub fn shared_drive_item(share_id: &str) -> String {
170
197
format!(
171
"{GRAPH}/v1.0/shares/{}/driveItem?$select=id,name,size,@microsoft.graph.downloadUrl",
198
"{GRAPH}/v1.0/shares/{}/driveItem",
172
199
segment(share_id)
173
200
)
174
201
}
@@ -158,6 +158,33 @@ pub fn channel_files_folder(team_id: &str, channel_id: &str) -> String {158
)158
)159
}159
}160
160
161
pub fn channel_tab(team_id: &str, channel_id: &str, tab_id: &str) -> String {162
format!(163
"{GRAPH}/v1.0/teams/{}/channels/{}/tabs/{}",164
segment(team_id),165
segment(channel_id),166
segment(tab_id)167
)168
}169
170
pub const CHILDREN_PAGE_SIZE: usize = 200;171
172
pub fn folder_children(drive_id: &str, folder_id: &str) -> String {173
format!(174
"{GRAPH}/v1.0/drives/{}/items/{}/children?$top={CHILDREN_PAGE_SIZE}",175
segment(drive_id),176
segment(folder_id)177
)178
}179
180
pub fn folder_create(drive_id: &str, folder_id: &str) -> String {181
format!(182
"{GRAPH}/v1.0/drives/{}/items/{}/children",183
segment(drive_id),184
segment(folder_id)185
)186
}187
161
pub fn drive_item(drive_id: &str, item_id: &str) -> String {188
pub fn drive_item(drive_id: &str, item_id: &str) -> String {162
format!(189
format!(163
"{GRAPH}/v1.0/drives/{}/items/{}",190
"{GRAPH}/v1.0/drives/{}/items/{}",@@ -168,7 +195,7 @@ pub fn drive_item(drive_id: &str, item_id: &str) -> String {168
195
169
pub fn shared_drive_item(share_id: &str) -> String {196
pub fn shared_drive_item(share_id: &str) -> String {170
format!(197
format!(171
"{GRAPH}/v1.0/shares/{}/driveItem?$select=id,name,size,@microsoft.graph.downloadUrl",198
"{GRAPH}/v1.0/shares/{}/driveItem",172
segment(share_id)199
segment(share_id)173
)200
)174
}201
}@@ -24,10 +24,10 @@ mod time;
24
24
pub use error::{Error, Result};
25
25
pub use image_files::ImageFileCache;
26
26
pub use models::{
27
ActivityRecord, AttachmentImage, AvatarRecord, ChannelLayoutRecord, ChannelRecord, ChatPreview,
28
ChatRecord, ConversationHit, DraftRecord, FolderRecord, ImageRecord, MemberRecord,
29
MessageRecord, OutboxRecord, OutboxState, OutboxTarget, SearchHit, Sidebar, SidebarTeam,
30
SyncState, TeamLayoutRecord, TeamRecord,
27
ActivityRecord, AttachmentImage, AvatarRecord, ChannelLayoutRecord, ChannelNotificationLevel,
28
ChannelNotifications, ChannelRecord, ChannelTabRecord, ChatPreview, ChatRecord, ConversationHit,
29
DraftRecord, FolderRecord, ImageRecord, MemberRecord, MessageRecord, OutboxRecord, OutboxState,
30
OutboxTarget, SearchHit, Sidebar, SidebarTeam, SyncState, TeamLayoutRecord, TeamRecord,
31
31
};
32
32
pub use search::{HIGHLIGHT_END, HIGHLIGHT_START};
33
33
pub use store::{DATA_DIR_NAME, Store, default_database_path};
@@ -24,10 +24,10 @@ mod time;24
pub use error::{Error, Result};24
pub use error::{Error, Result};25
pub use image_files::ImageFileCache;25
pub use image_files::ImageFileCache;26
pub use models::{26
pub use models::{27
ActivityRecord, AttachmentImage, AvatarRecord, ChannelLayoutRecord, ChannelRecord, ChatPreview,27
ActivityRecord, AttachmentImage, AvatarRecord, ChannelLayoutRecord, ChannelNotificationLevel,28
ChatRecord, ConversationHit, DraftRecord, FolderRecord, ImageRecord, MemberRecord,28
ChannelNotifications, ChannelRecord, ChannelTabRecord, ChatPreview, ChatRecord, ConversationHit,29
MessageRecord, OutboxRecord, OutboxState, OutboxTarget, SearchHit, Sidebar, SidebarTeam,29
DraftRecord, FolderRecord, ImageRecord, MemberRecord, MessageRecord, OutboxRecord, OutboxState,30
SyncState, TeamLayoutRecord, TeamRecord,30
OutboxTarget, SearchHit, Sidebar, SidebarTeam, SyncState, TeamLayoutRecord, TeamRecord,31
};31
};32
pub use search::{HIGHLIGHT_END, HIGHLIGHT_START};32
pub use search::{HIGHLIGHT_END, HIGHLIGHT_START};33
pub use store::{DATA_DIR_NAME, Store, default_database_path};33
pub use store::{DATA_DIR_NAME, Store, default_database_path};@@ -65,6 +65,14 @@ const MIGRATIONS: &[Migration] = &[
65
65
script: include_str!("migrations/0014_folder_expanded.sql"),
66
66
after: None,
67
67
},
68
Migration {
69
script: include_str!("migrations/0015_channel_tabs.sql"),
70
after: None,
71
},
72
Migration {
73
script: include_str!("migrations/0016_channel_notifications.sql"),
74
after: None,
75
},
68
76
];
69
77
70
78
pub fn latest_version() -> i64 {
@@ -65,6 +65,14 @@ const MIGRATIONS: &[Migration] = &[65
script: include_str!("migrations/0014_folder_expanded.sql"),65
script: include_str!("migrations/0014_folder_expanded.sql"),66
after: None,66
after: None,67
},67
},68
Migration {69
script: include_str!("migrations/0015_channel_tabs.sql"),70
after: None,71
},72
Migration {73
script: include_str!("migrations/0016_channel_notifications.sql"),74
after: None,75
},68
];76
];69
77
70
pub fn latest_version() -> i64 {78
pub fn latest_version() -> i64 {@@ -0,0 +1,9 @@
1
CREATE TABLE channel_tabs (
2
channel_id TEXT NOT NULL,
3
position INTEGER NOT NULL,
4
tab_id TEXT NOT NULL,
5
name TEXT NOT NULL,
6
definition_id TEXT NOT NULL,
7
open_url TEXT,
8
PRIMARY KEY (channel_id, position)
9
) WITHOUT ROWID;
@@ -0,0 +1,9 @@1
CREATE TABLE channel_tabs (2
channel_id TEXT NOT NULL,3
position INTEGER NOT NULL,4
tab_id TEXT NOT NULL,5
name TEXT NOT NULL,6
definition_id TEXT NOT NULL,7
open_url TEXT,8
PRIMARY KEY (channel_id, position)9
) WITHOUT ROWID;@@ -0,0 +1,2 @@
1
ALTER TABLE channel_layout ADD COLUMN notification_level TEXT NOT NULL DEFAULT 'feed';
2
ALTER TABLE channel_layout ADD COLUMN include_replies INTEGER NOT NULL DEFAULT 0;
@@ -0,0 +1,2 @@1
ALTER TABLE channel_layout ADD COLUMN notification_level TEXT NOT NULL DEFAULT 'feed';2
ALTER TABLE channel_layout ADD COLUMN include_replies INTEGER NOT NULL DEFAULT 0;@@ -1,3 +1,5 @@
1
use std::collections::HashMap;
2
1
3
use chrono::{DateTime, Utc};
2
4
3
5
#[derive(Debug, Clone, PartialEq, Default)]
@@ -103,6 +105,64 @@ pub struct SidebarTeam {
103
105
pub channels: Vec<ChannelRecord>,
104
106
pub hidden: bool,
105
107
pub hidden_channel_ids: Vec<String>,
108
pub notifications: HashMap<String, ChannelNotifications>,
109
}
110
111
impl SidebarTeam {
112
pub fn channel_notifications(&self, channel_id: &str) -> ChannelNotifications {
113
self.notifications
114
.get(channel_id)
115
.copied()
116
.unwrap_or_default()
117
}
118
}
119
120
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
121
pub enum ChannelNotificationLevel {
122
BannerAndFeed,
123
#[default]
124
Feed,
125
Off,
126
}
127
128
impl ChannelNotificationLevel {
129
pub fn key(self) -> &'static str {
130
match self {
131
ChannelNotificationLevel::BannerAndFeed => "banner",
132
ChannelNotificationLevel::Feed => "feed",
133
ChannelNotificationLevel::Off => "off",
134
}
135
}
136
137
pub fn from_key(key: &str) -> Self {
138
match key {
139
"banner" => ChannelNotificationLevel::BannerAndFeed,
140
"off" => ChannelNotificationLevel::Off,
141
_ => ChannelNotificationLevel::Feed,
142
}
143
}
144
}
145
146
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
147
pub struct ChannelNotifications {
148
pub level: ChannelNotificationLevel,
149
pub include_replies: bool,
150
}
151
152
#[derive(Debug, Clone, PartialEq, Eq)]
153
pub struct ChannelTabRecord {
154
pub tab_id: String,
155
pub name: String,
156
pub definition_id: String,
157
pub open_url: Option<String>,
158
}
159
160
const WEBSITE_DEFINITION_ID: &str = "com.microsoft.teamspace.tab.web";
161
162
impl ChannelTabRecord {
163
pub fn is_website(&self) -> bool {
164
self.definition_id == WEBSITE_DEFINITION_ID && self.open_url.is_some()
165
}
106
166
}
107
167
108
168
#[derive(Debug, Clone, PartialEq, Eq)]
@@ -110,6 +170,8 @@ pub struct ChannelLayoutRecord {
110
170
pub channel_id: String,
111
171
pub general: bool,
112
172
pub hidden: bool,
173
pub tabs: Vec<ChannelTabRecord>,
174
pub notifications: ChannelNotifications,
113
175
}
114
176
115
177
#[derive(Debug, Clone, PartialEq, Eq)]
@@ -1,3 +1,5 @@1
use std::collections::HashMap;2
1
use chrono::{DateTime, Utc};3
use chrono::{DateTime, Utc};2
4
3
#[derive(Debug, Clone, PartialEq, Default)]5
#[derive(Debug, Clone, PartialEq, Default)]@@ -103,6 +105,64 @@ pub struct SidebarTeam {103
pub channels: Vec<ChannelRecord>,105
pub channels: Vec<ChannelRecord>,104
pub hidden: bool,106
pub hidden: bool,105
pub hidden_channel_ids: Vec<String>,107
pub hidden_channel_ids: Vec<String>,108
pub notifications: HashMap<String, ChannelNotifications>,109
}110
111
impl SidebarTeam {112
pub fn channel_notifications(&self, channel_id: &str) -> ChannelNotifications {113
self.notifications114
.get(channel_id)115
.copied()116
.unwrap_or_default()117
}118
}119
120
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]121
pub enum ChannelNotificationLevel {122
BannerAndFeed,123
#[default]124
Feed,125
Off,126
}127
128
impl ChannelNotificationLevel {129
pub fn key(self) -> &'static str {130
match self {131
ChannelNotificationLevel::BannerAndFeed => "banner",132
ChannelNotificationLevel::Feed => "feed",133
ChannelNotificationLevel::Off => "off",134
}135
}136
137
pub fn from_key(key: &str) -> Self {138
match key {139
"banner" => ChannelNotificationLevel::BannerAndFeed,140
"off" => ChannelNotificationLevel::Off,141
_ => ChannelNotificationLevel::Feed,142
}143
}144
}145
146
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]147
pub struct ChannelNotifications {148
pub level: ChannelNotificationLevel,149
pub include_replies: bool,150
}151
152
#[derive(Debug, Clone, PartialEq, Eq)]153
pub struct ChannelTabRecord {154
pub tab_id: String,155
pub name: String,156
pub definition_id: String,157
pub open_url: Option<String>,158
}159
160
const WEBSITE_DEFINITION_ID: &str = "com.microsoft.teamspace.tab.web";161
162
impl ChannelTabRecord {163
pub fn is_website(&self) -> bool {164
self.definition_id == WEBSITE_DEFINITION_ID && self.open_url.is_some()165
}106
}166
}107
167
108
#[derive(Debug, Clone, PartialEq, Eq)]168
#[derive(Debug, Clone, PartialEq, Eq)]@@ -110,6 +170,8 @@ pub struct ChannelLayoutRecord {110
pub channel_id: String,170
pub channel_id: String,111
pub general: bool,171
pub general: bool,112
pub hidden: bool,172
pub hidden: bool,173
pub tabs: Vec<ChannelTabRecord>,174
pub notifications: ChannelNotifications,113
}175
}114
176
115
#[derive(Debug, Clone, PartialEq, Eq)]177
#[derive(Debug, Clone, PartialEq, Eq)]@@ -1,9 +1,13 @@
1
1
use std::cmp::Ordering;
2
use std::collections::HashMap;
2
3
3
4
use rusqlite::params;
4
5
5
6
use crate::error::Result;
6
use crate::models::{ChannelRecord, Sidebar, SidebarTeam, TeamLayoutRecord, TeamRecord};
7
use crate::models::{
8
ChannelNotificationLevel, ChannelNotifications, ChannelRecord, ChannelTabRecord, Sidebar,
9
SidebarTeam, TeamLayoutRecord, TeamRecord,
10
};
7
11
use crate::store::Store;
8
12
use crate::teams::channel_from_row;
9
13
@@ -19,6 +23,7 @@ struct ChannelRow {
19
23
channel: ChannelRecord,
20
24
general: bool,
21
25
hidden: bool,
26
notifications: ChannelNotifications,
22
27
}
23
28
24
29
impl Store {
@@ -54,7 +59,9 @@ impl Store {
54
59
let mut channel_rows: Vec<ChannelRow> = connection
55
60
.prepare_cached(
56
61
"SELECT id, team_id, name, membership_type, last_message_at, unread,
57
COALESCE(channel_layout.general, name = ?1), COALESCE(channel_layout.hidden, 0)
62
COALESCE(channel_layout.general, name = ?1), COALESCE(channel_layout.hidden, 0),
63
COALESCE(channel_layout.notification_level, 'feed'),
64
COALESCE(channel_layout.include_replies, 0)
58
65
FROM channels LEFT JOIN channel_layout ON channel_layout.channel_id = channels.id",
59
66
)?
60
67
.query_map(params![GENERAL_FALLBACK_NAME], |row| {
@@ -62,6 +69,10 @@ impl Store {
62
69
channel: channel_from_row(row)?,
63
70
general: row.get(6)?,
64
71
hidden: row.get(7)?,
72
notifications: ChannelNotifications {
73
level: ChannelNotificationLevel::from_key(&row.get::<_, String>(8)?),
74
include_replies: row.get(9)?,
75
},
65
76
})
66
77
})?
67
78
.collect::<rusqlite::Result<_>>()?;
@@ -79,6 +90,7 @@ impl Store {
79
90
channels: Vec::new(),
80
91
hidden: row.hidden,
81
92
hidden_channel_ids: Vec::new(),
93
notifications: HashMap::new(),
82
94
})
83
95
.collect();
84
96
for row in channel_rows {
@@ -89,6 +101,10 @@ impl Store {
89
101
if row.hidden {
90
102
team.hidden_channel_ids.push(row.channel.id.clone());
91
103
}
104
if row.notifications != ChannelNotifications::default() {
105
team.notifications
106
.insert(row.channel.id.clone(), row.notifications);
107
}
92
108
team.channels.push(row.channel);
93
109
}
94
110
}
@@ -100,12 +116,19 @@ impl Store {
100
116
let transaction = connection.transaction()?;
101
117
transaction.execute("DELETE FROM team_layout", [])?;
102
118
transaction.execute("DELETE FROM channel_layout", [])?;
119
transaction.execute("DELETE FROM channel_tabs", [])?;
103
120
{
104
121
let mut team_insert = transaction.prepare_cached(
105
122
"INSERT OR REPLACE INTO team_layout (team_id, position, hidden) VALUES (?1, ?2, ?3)",
106
123
)?;
107
124
let mut channel_insert = transaction.prepare_cached(
108
"INSERT OR REPLACE INTO channel_layout (channel_id, general, hidden) VALUES (?1, ?2, ?3)",
125
"INSERT OR REPLACE INTO channel_layout
126
(channel_id, general, hidden, notification_level, include_replies)
127
VALUES (?1, ?2, ?3, ?4, ?5)",
128
)?;
129
let mut tab_insert = transaction.prepare_cached(
130
"INSERT OR REPLACE INTO channel_tabs (channel_id, position, tab_id, name, definition_id, open_url)
131
VALUES (?1, ?2, ?3, ?4, ?5, ?6)",
109
132
)?;
110
133
for (position, team) in layout.iter().enumerate() {
111
134
team_insert.execute(params![team.team_id, position as i64, team.hidden])?;
@@ -113,13 +136,67 @@ impl Store {
113
136
channel_insert.execute(params![
114
137
channel.channel_id,
115
138
channel.general,
116
channel.hidden
139
channel.hidden,
140
channel.notifications.level.key(),
141
channel.notifications.include_replies
117
142
])?;
143
for (tab_position, tab) in channel.tabs.iter().enumerate() {
144
tab_insert.execute(params![
145
channel.channel_id,
146
tab_position as i64,
147
tab.tab_id,
148
tab.name,
149
tab.definition_id,
150
tab.open_url
151
])?;
152
}
118
153
}
119
154
}
120
155
}
121
156
Ok(transaction.commit()?)
122
157
}
158
159
pub fn set_channel_notifications(
160
&self,
161
channel_id: &str,
162
notifications: ChannelNotifications,
163
) -> Result<()> {
164
self.lock()?.execute(
165
"INSERT INTO channel_layout (channel_id, general, notification_level, include_replies)
166
SELECT id, name = ?2, ?3, ?4 FROM channels WHERE id = ?1
167
ON CONFLICT (channel_id) DO UPDATE SET
168
notification_level = excluded.notification_level,
169
include_replies = excluded.include_replies",
170
params![
171
channel_id,
172
GENERAL_FALLBACK_NAME,
173
notifications.level.key(),
174
notifications.include_replies
175
],
176
)?;
177
Ok(())
178
}
179
}
180
181
impl Store {
182
pub fn channel_tabs(&self, channel_id: &str) -> Result<Vec<ChannelTabRecord>> {
183
let connection = self.lock()?;
184
let tabs = connection
185
.prepare_cached(
186
"SELECT tab_id, name, definition_id, open_url FROM channel_tabs
187
WHERE channel_id = ?1 ORDER BY position",
188
)?
189
.query_map(params![channel_id], |row| {
190
Ok(ChannelTabRecord {
191
tab_id: row.get(0)?,
192
name: row.get(1)?,
193
definition_id: row.get(2)?,
194
open_url: row.get(3)?,
195
})
196
})?
197
.collect::<rusqlite::Result<_>>()?;
198
Ok(tabs)
199
}
123
200
}
124
201
125
202
fn compare_names(left: &str, right: &str) -> Ordering {
@@ -1,9 +1,13 @@1
use std::cmp::Ordering;1
use std::cmp::Ordering;2
use std::collections::HashMap;2
3
3
use rusqlite::params;4
use rusqlite::params;4
5
5
use crate::error::Result;6
use crate::error::Result;6
use crate::models::{ChannelRecord, Sidebar, SidebarTeam, TeamLayoutRecord, TeamRecord};7
use crate::models::{8
ChannelNotificationLevel, ChannelNotifications, ChannelRecord, ChannelTabRecord, Sidebar,9
SidebarTeam, TeamLayoutRecord, TeamRecord,10
};7
use crate::store::Store;11
use crate::store::Store;8
use crate::teams::channel_from_row;12
use crate::teams::channel_from_row;9
13
@@ -19,6 +23,7 @@ struct ChannelRow {19
channel: ChannelRecord,23
channel: ChannelRecord,20
general: bool,24
general: bool,21
hidden: bool,25
hidden: bool,26
notifications: ChannelNotifications,22
}27
}23
28
24
impl Store {29
impl Store {@@ -54,7 +59,9 @@ impl Store {54
let mut channel_rows: Vec<ChannelRow> = connection59
let mut channel_rows: Vec<ChannelRow> = connection55
.prepare_cached(60
.prepare_cached(56
"SELECT id, team_id, name, membership_type, last_message_at, unread,61
"SELECT id, team_id, name, membership_type, last_message_at, unread,57
COALESCE(channel_layout.general, name = ?1), COALESCE(channel_layout.hidden, 0)62
COALESCE(channel_layout.general, name = ?1), COALESCE(channel_layout.hidden, 0),63
COALESCE(channel_layout.notification_level, 'feed'),64
COALESCE(channel_layout.include_replies, 0)58
FROM channels LEFT JOIN channel_layout ON channel_layout.channel_id = channels.id",65
FROM channels LEFT JOIN channel_layout ON channel_layout.channel_id = channels.id",59
)?66
)?60
.query_map(params![GENERAL_FALLBACK_NAME], |row| {67
.query_map(params![GENERAL_FALLBACK_NAME], |row| {@@ -62,6 +69,10 @@ impl Store {62
channel: channel_from_row(row)?,69
channel: channel_from_row(row)?,63
general: row.get(6)?,70
general: row.get(6)?,64
hidden: row.get(7)?,71
hidden: row.get(7)?,72
notifications: ChannelNotifications {73
level: ChannelNotificationLevel::from_key(&row.get::<_, String>(8)?),74
include_replies: row.get(9)?,75
},65
})76
})66
})?77
})?67
.collect::<rusqlite::Result<_>>()?;78
.collect::<rusqlite::Result<_>>()?;@@ -79,6 +90,7 @@ impl Store {79
channels: Vec::new(),90
channels: Vec::new(),80
hidden: row.hidden,91
hidden: row.hidden,81
hidden_channel_ids: Vec::new(),92
hidden_channel_ids: Vec::new(),93
notifications: HashMap::new(),82
})94
})83
.collect();95
.collect();84
for row in channel_rows {96
for row in channel_rows {@@ -89,6 +101,10 @@ impl Store {89
if row.hidden {101
if row.hidden {90
team.hidden_channel_ids.push(row.channel.id.clone());102
team.hidden_channel_ids.push(row.channel.id.clone());91
}103
}104
if row.notifications != ChannelNotifications::default() {105
team.notifications106
.insert(row.channel.id.clone(), row.notifications);107
}92
team.channels.push(row.channel);108
team.channels.push(row.channel);93
}109
}94
}110
}@@ -100,12 +116,19 @@ impl Store {100
let transaction = connection.transaction()?;116
let transaction = connection.transaction()?;101
transaction.execute("DELETE FROM team_layout", [])?;117
transaction.execute("DELETE FROM team_layout", [])?;102
transaction.execute("DELETE FROM channel_layout", [])?;118
transaction.execute("DELETE FROM channel_layout", [])?;119
transaction.execute("DELETE FROM channel_tabs", [])?;103
{120
{104
let mut team_insert = transaction.prepare_cached(121
let mut team_insert = transaction.prepare_cached(105
"INSERT OR REPLACE INTO team_layout (team_id, position, hidden) VALUES (?1, ?2, ?3)",122
"INSERT OR REPLACE INTO team_layout (team_id, position, hidden) VALUES (?1, ?2, ?3)",106
)?;123
)?;107
let mut channel_insert = transaction.prepare_cached(124
let mut channel_insert = transaction.prepare_cached(108
"INSERT OR REPLACE INTO channel_layout (channel_id, general, hidden) VALUES (?1, ?2, ?3)",125
"INSERT OR REPLACE INTO channel_layout126
(channel_id, general, hidden, notification_level, include_replies)127
VALUES (?1, ?2, ?3, ?4, ?5)",128
)?;129
let mut tab_insert = transaction.prepare_cached(130
"INSERT OR REPLACE INTO channel_tabs (channel_id, position, tab_id, name, definition_id, open_url)131
VALUES (?1, ?2, ?3, ?4, ?5, ?6)",109
)?;132
)?;110
for (position, team) in layout.iter().enumerate() {133
for (position, team) in layout.iter().enumerate() {111
team_insert.execute(params![team.team_id, position as i64, team.hidden])?;134
team_insert.execute(params![team.team_id, position as i64, team.hidden])?;@@ -113,13 +136,67 @@ impl Store {113
channel_insert.execute(params![136
channel_insert.execute(params![114
channel.channel_id,137
channel.channel_id,115
channel.general,138
channel.general,116
channel.hidden139
channel.hidden,140
channel.notifications.level.key(),141
channel.notifications.include_replies117
])?;142
])?;143
for (tab_position, tab) in channel.tabs.iter().enumerate() {144
tab_insert.execute(params![145
channel.channel_id,146
tab_position as i64,147
tab.tab_id,148
tab.name,149
tab.definition_id,150
tab.open_url151
])?;152
}118
}153
}119
}154
}120
}155
}121
Ok(transaction.commit()?)156
Ok(transaction.commit()?)122
}157
}158
159
pub fn set_channel_notifications(160
&self,161
channel_id: &str,162
notifications: ChannelNotifications,163
) -> Result<()> {164
self.lock()?.execute(165
"INSERT INTO channel_layout (channel_id, general, notification_level, include_replies)166
SELECT id, name = ?2, ?3, ?4 FROM channels WHERE id = ?1167
ON CONFLICT (channel_id) DO UPDATE SET168
notification_level = excluded.notification_level,169
include_replies = excluded.include_replies",170
params![171
channel_id,172
GENERAL_FALLBACK_NAME,173
notifications.level.key(),174
notifications.include_replies175
],176
)?;177
Ok(())178
}179
}180
181
impl Store {182
pub fn channel_tabs(&self, channel_id: &str) -> Result<Vec<ChannelTabRecord>> {183
let connection = self.lock()?;184
let tabs = connection185
.prepare_cached(186
"SELECT tab_id, name, definition_id, open_url FROM channel_tabs187
WHERE channel_id = ?1 ORDER BY position",188
)?189
.query_map(params![channel_id], |row| {190
Ok(ChannelTabRecord {191
tab_id: row.get(0)?,192
name: row.get(1)?,193
definition_id: row.get(2)?,194
open_url: row.get(3)?,195
})196
})?197
.collect::<rusqlite::Result<_>>()?;198
Ok(tabs)199
}123
}200
}124
201
125
fn compare_names(left: &str, right: &str) -> Ordering {202
fn compare_names(left: &str, right: &str) -> Ordering {@@ -1,8 +1,9 @@
1
1
use chrono::{DateTime, TimeZone, Utc};
2
2
use rusqlite::Connection;
3
3
use store::{
4
AvatarRecord, ChannelRecord, ChatPreview, ChatRecord, FolderRecord, MemberRecord,
5
MessageRecord, Store, SyncState, TeamRecord,
4
AvatarRecord, ChannelLayoutRecord, ChannelNotificationLevel, ChannelNotifications,
5
ChannelRecord, ChannelTabRecord, ChatPreview, ChatRecord, FolderRecord, MemberRecord,
6
MessageRecord, Store, SyncState, TeamLayoutRecord, TeamRecord,
6
7
};
7
8
8
9
#[test]
@@ -469,11 +470,11 @@ fn file_database_uses_wal_persists_and_migrates_once() {
469
470
let path = directory.path().join("nested").join("cache.sqlite3");
470
471
{
471
472
let store = Store::open(&path).unwrap();
472
assert_eq!(store.schema_version().unwrap(), 14);
473
assert_eq!(store.schema_version().unwrap(), 16);
473
474
store.upsert_messages(&[message("c", "m1", 1)]).unwrap();
474
475
}
475
476
let reopened = Store::open(&path).unwrap();
476
assert_eq!(reopened.schema_version().unwrap(), 14);
477
assert_eq!(reopened.schema_version().unwrap(), 16);
477
478
assert_eq!(reopened.message_count("c").unwrap(), 1);
478
479
drop(reopened);
479
480
let mode: String = rusqlite_open(&path)
@@ -502,10 +503,10 @@ fn old_schema_is_upgraded_in_place() {
502
503
let path = directory.path().join("cache.sqlite3");
503
504
drop(Store::open(&path).unwrap());
504
505
let connection = rusqlite_open(&path);
505
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 presence; DROP TABLE activity; DROP TABLE outbox; DROP TABLE drafts; DROP TABLE attachment_images; PRAGMA user_version = 0").unwrap();
506
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; PRAGMA user_version = 0").unwrap();
506
507
drop(connection);
507
508
let store = Store::open(&path).unwrap();
508
assert_eq!(store.schema_version().unwrap(), 14);
509
assert_eq!(store.schema_version().unwrap(), 16);
509
510
store.upsert_messages(&[message("c", "m1", 1)]).unwrap();
510
511
}
511
512
@@ -571,7 +572,7 @@ fn migration_to_v2_keeps_existing_sync_state() {
571
572
let store = Store::open(&path).unwrap();
572
573
let state = store.sync_state("c").unwrap().unwrap();
573
574
assert_eq!(state.delta_link, None);
574
assert_eq!(store.schema_version().unwrap(), 14);
575
assert_eq!(store.schema_version().unwrap(), 16);
575
576
}
576
577
577
578
#[test]
@@ -589,6 +590,9 @@ fn migration_to_v13_clears_channel_delta_links_only() {
589
590
INSERT INTO sync_state (conversation_id, delta_link) VALUES ('ch', 'link'), ('chat', 'link');
590
591
ALTER TABLE messages DROP COLUMN subject;
591
592
ALTER TABLE folders DROP COLUMN expanded;
593
DROP TABLE channel_tabs;
594
ALTER TABLE channel_layout DROP COLUMN notification_level;
595
ALTER TABLE channel_layout DROP COLUMN include_replies;
592
596
PRAGMA user_version = 12",
593
597
)
594
598
.unwrap();
@@ -837,7 +841,7 @@ fn migration_indexes_rows_that_predate_search() {
837
841
"DROP TRIGGER chats_title_insert; DROP TRIGGER chats_title_update; DROP TRIGGER chats_title_delete;
838
842
DROP TRIGGER channels_title_insert; DROP TRIGGER channels_title_update; DROP TRIGGER channels_title_delete;
839
843
DROP TABLE images; DROP TABLE search_keys; DROP TABLE message_search; DROP TABLE title_search;
840
DROP TABLE team_layout; DROP TABLE channel_layout; DROP TABLE presence; DROP TABLE activity; DROP TABLE outbox; DROP TABLE drafts; DROP TABLE attachment_images;
844
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;
841
845
DROP INDEX messages_by_sender; DROP INDEX chat_members_by_user;
842
846
ALTER TABLE messages DROP COLUMN sender_application_id;
843
847
ALTER TABLE messages DROP COLUMN links_json;
@@ -1095,3 +1099,95 @@ fn display_names_prefer_members_then_latest_sender_name() {
1095
1099
assert_eq!(names["user-sam"], "Sam New");
1096
1100
assert!(store.display_names(&[]).unwrap().is_empty());
1097
1101
}
1102
1103
#[test]
1104
fn channel_tabs_keep_their_saved_order_and_are_replaced_on_refresh() {
1105
let store = Store::open_in_memory().unwrap();
1106
let tab = |tab_id: &str, open_url: Option<&str>| ChannelTabRecord {
1107
tab_id: tab_id.to_owned(),
1108
name: format!("Tab {tab_id}"),
1109
definition_id: "com.microsoft.teamspace.tab.web".to_owned(),
1110
open_url: open_url.map(str::to_owned),
1111
};
1112
let layout = |tabs: Vec<ChannelTabRecord>| {
1113
vec![TeamLayoutRecord {
1114
team_id: "team".to_owned(),
1115
hidden: false,
1116
channels: vec![ChannelLayoutRecord {
1117
channel_id: "channel".to_owned(),
1118
general: false,
1119
hidden: false,
1120
tabs,
1121
notifications: ChannelNotifications::default(),
1122
}],
1123
}]
1124
};
1125
store
1126
.replace_team_layout(&layout(vec![
1127
tab("b", Some("https://b.example")),
1128
tab("a", None),
1129
]))
1130
.unwrap();
1131
let tabs = store.channel_tabs("channel").unwrap();
1132
let ids: Vec<&str> = tabs.iter().map(|tab| tab.tab_id.as_str()).collect();
1133
assert_eq!(ids, ["b", "a"]);
1134
assert_eq!(tabs[0].open_url.as_deref(), Some("https://b.example"));
1135
assert!(store.channel_tabs("other").unwrap().is_empty());
1136
store.replace_team_layout(&layout(Vec::new())).unwrap();
1137
assert!(store.channel_tabs("channel").unwrap().is_empty());
1138
}
1139
1140
#[test]
1141
fn channel_notifications_default_to_feed_and_survive_layout_and_local_writes() {
1142
let store = Store::open_in_memory().unwrap();
1143
store
1144
.upsert_teams(&[TeamRecord {
1145
id: "t1".to_owned(),
1146
name: "Alpha".to_owned(),
1147
}])
1148
.unwrap();
1149
let channel = |id: &str, name: &str| ChannelRecord {
1150
id: id.to_owned(),
1151
team_id: "t1".to_owned(),
1152
name: name.to_owned(),
1153
membership_type: None,
1154
last_message_at: None,
1155
unread: false,
1156
};
1157
store
1158
.upsert_channels(&[channel("c1", "General"), channel("c2", "Random")])
1159
.unwrap();
1160
let team = || store.sidebar().unwrap().teams.remove(0);
1161
assert_eq!(
1162
team().channel_notifications("c2"),
1163
ChannelNotifications::default()
1164
);
1165
1166
let banner = ChannelNotifications {
1167
level: ChannelNotificationLevel::BannerAndFeed,
1168
include_replies: true,
1169
};
1170
store.set_channel_notifications("c2", banner).unwrap();
1171
let sidebar_team = team();
1172
assert_eq!(sidebar_team.channel_notifications("c2"), banner);
1173
assert_eq!(sidebar_team.channels[0].name, "General");
1174
1175
let off = ChannelNotifications {
1176
level: ChannelNotificationLevel::Off,
1177
include_replies: false,
1178
};
1179
store
1180
.replace_team_layout(&[TeamLayoutRecord {
1181
team_id: "t1".to_owned(),
1182
hidden: false,
1183
channels: vec![ChannelLayoutRecord {
1184
channel_id: "c2".to_owned(),
1185
general: false,
1186
hidden: false,
1187
tabs: Vec::new(),
1188
notifications: off,
1189
}],
1190
}])
1191
.unwrap();
1192
assert_eq!(team().channel_notifications("c2"), off);
1193
}
@@ -1,8 +1,9 @@1
use chrono::{DateTime, TimeZone, Utc};1
use chrono::{DateTime, TimeZone, Utc};2
use rusqlite::Connection;2
use rusqlite::Connection;3
use store::{3
use store::{4
AvatarRecord, ChannelRecord, ChatPreview, ChatRecord, FolderRecord, MemberRecord,4
AvatarRecord, ChannelLayoutRecord, ChannelNotificationLevel, ChannelNotifications,5
MessageRecord, Store, SyncState, TeamRecord,5
ChannelRecord, ChannelTabRecord, ChatPreview, ChatRecord, FolderRecord, MemberRecord,6
MessageRecord, Store, SyncState, TeamLayoutRecord, TeamRecord,6
};7
};7
8
8
#[test]9
#[test]@@ -469,11 +470,11 @@ fn file_database_uses_wal_persists_and_migrates_once() {469
let path = directory.path().join("nested").join("cache.sqlite3");470
let path = directory.path().join("nested").join("cache.sqlite3");470
{471
{471
let store = Store::open(&path).unwrap();472
let store = Store::open(&path).unwrap();472
assert_eq!(store.schema_version().unwrap(), 14);473
assert_eq!(store.schema_version().unwrap(), 16);473
store.upsert_messages(&[message("c", "m1", 1)]).unwrap();474
store.upsert_messages(&[message("c", "m1", 1)]).unwrap();474
}475
}475
let reopened = Store::open(&path).unwrap();476
let reopened = Store::open(&path).unwrap();476
assert_eq!(reopened.schema_version().unwrap(), 14);477
assert_eq!(reopened.schema_version().unwrap(), 16);477
assert_eq!(reopened.message_count("c").unwrap(), 1);478
assert_eq!(reopened.message_count("c").unwrap(), 1);478
drop(reopened);479
drop(reopened);479
let mode: String = rusqlite_open(&path)480
let mode: String = rusqlite_open(&path)@@ -502,10 +503,10 @@ fn old_schema_is_upgraded_in_place() {502
let path = directory.path().join("cache.sqlite3");503
let path = directory.path().join("cache.sqlite3");503
drop(Store::open(&path).unwrap());504
drop(Store::open(&path).unwrap());504
let connection = rusqlite_open(&path);505
let connection = rusqlite_open(&path);505
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 presence; DROP TABLE activity; DROP TABLE outbox; DROP TABLE drafts; DROP TABLE attachment_images; PRAGMA user_version = 0").unwrap();506
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; PRAGMA user_version = 0").unwrap();506
drop(connection);507
drop(connection);507
let store = Store::open(&path).unwrap();508
let store = Store::open(&path).unwrap();508
assert_eq!(store.schema_version().unwrap(), 14);509
assert_eq!(store.schema_version().unwrap(), 16);509
store.upsert_messages(&[message("c", "m1", 1)]).unwrap();510
store.upsert_messages(&[message("c", "m1", 1)]).unwrap();510
}511
}511
512
@@ -571,7 +572,7 @@ fn migration_to_v2_keeps_existing_sync_state() {571
let store = Store::open(&path).unwrap();572
let store = Store::open(&path).unwrap();572
let state = store.sync_state("c").unwrap().unwrap();573
let state = store.sync_state("c").unwrap().unwrap();573
assert_eq!(state.delta_link, None);574
assert_eq!(state.delta_link, None);574
assert_eq!(store.schema_version().unwrap(), 14);575
assert_eq!(store.schema_version().unwrap(), 16);575
}576
}576
577
577
#[test]578
#[test]@@ -589,6 +590,9 @@ fn migration_to_v13_clears_channel_delta_links_only() {589
INSERT INTO sync_state (conversation_id, delta_link) VALUES ('ch', 'link'), ('chat', 'link');590
INSERT INTO sync_state (conversation_id, delta_link) VALUES ('ch', 'link'), ('chat', 'link');590
ALTER TABLE messages DROP COLUMN subject;591
ALTER TABLE messages DROP COLUMN subject;591
ALTER TABLE folders DROP COLUMN expanded;592
ALTER TABLE folders DROP COLUMN expanded;593
DROP TABLE channel_tabs;594
ALTER TABLE channel_layout DROP COLUMN notification_level;595
ALTER TABLE channel_layout DROP COLUMN include_replies;592
PRAGMA user_version = 12",596
PRAGMA user_version = 12",593
)597
)594
.unwrap();598
.unwrap();@@ -837,7 +841,7 @@ fn migration_indexes_rows_that_predate_search() {837
"DROP TRIGGER chats_title_insert; DROP TRIGGER chats_title_update; DROP TRIGGER chats_title_delete;841
"DROP TRIGGER chats_title_insert; DROP TRIGGER chats_title_update; DROP TRIGGER chats_title_delete;838
DROP TRIGGER channels_title_insert; DROP TRIGGER channels_title_update; DROP TRIGGER channels_title_delete;842
DROP TRIGGER channels_title_insert; DROP TRIGGER channels_title_update; DROP TRIGGER channels_title_delete;839
DROP TABLE images; DROP TABLE search_keys; DROP TABLE message_search; DROP TABLE title_search;843
DROP TABLE images; DROP TABLE search_keys; DROP TABLE message_search; DROP TABLE title_search;840
DROP TABLE team_layout; DROP TABLE channel_layout; DROP TABLE presence; DROP TABLE activity; DROP TABLE outbox; DROP TABLE drafts; DROP TABLE attachment_images;844
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;841
DROP INDEX messages_by_sender; DROP INDEX chat_members_by_user;845
DROP INDEX messages_by_sender; DROP INDEX chat_members_by_user;842
ALTER TABLE messages DROP COLUMN sender_application_id;846
ALTER TABLE messages DROP COLUMN sender_application_id;843
ALTER TABLE messages DROP COLUMN links_json;847
ALTER TABLE messages DROP COLUMN links_json;@@ -1095,3 +1099,95 @@ fn display_names_prefer_members_then_latest_sender_name() {1095
assert_eq!(names["user-sam"], "Sam New");1099
assert_eq!(names["user-sam"], "Sam New");1096
assert!(store.display_names(&[]).unwrap().is_empty());1100
assert!(store.display_names(&[]).unwrap().is_empty());1097
}1101
}1102
1103
#[test]1104
fn channel_tabs_keep_their_saved_order_and_are_replaced_on_refresh() {1105
let store = Store::open_in_memory().unwrap();1106
let tab = |tab_id: &str, open_url: Option<&str>| ChannelTabRecord {1107
tab_id: tab_id.to_owned(),1108
name: format!("Tab {tab_id}"),1109
definition_id: "com.microsoft.teamspace.tab.web".to_owned(),1110
open_url: open_url.map(str::to_owned),1111
};1112
let layout = |tabs: Vec<ChannelTabRecord>| {1113
vec![TeamLayoutRecord {1114
team_id: "team".to_owned(),1115
hidden: false,1116
channels: vec![ChannelLayoutRecord {1117
channel_id: "channel".to_owned(),1118
general: false,1119
hidden: false,1120
tabs,1121
notifications: ChannelNotifications::default(),1122
}],1123
}]1124
};1125
store1126
.replace_team_layout(&layout(vec![1127
tab("b", Some("https://b.example")),1128
tab("a", None),1129
]))1130
.unwrap();1131
let tabs = store.channel_tabs("channel").unwrap();1132
let ids: Vec<&str> = tabs.iter().map(|tab| tab.tab_id.as_str()).collect();1133
assert_eq!(ids, ["b", "a"]);1134
assert_eq!(tabs[0].open_url.as_deref(), Some("https://b.example"));1135
assert!(store.channel_tabs("other").unwrap().is_empty());1136
store.replace_team_layout(&layout(Vec::new())).unwrap();1137
assert!(store.channel_tabs("channel").unwrap().is_empty());1138
}1139
1140
#[test]1141
fn channel_notifications_default_to_feed_and_survive_layout_and_local_writes() {1142
let store = Store::open_in_memory().unwrap();1143
store1144
.upsert_teams(&[TeamRecord {1145
id: "t1".to_owned(),1146
name: "Alpha".to_owned(),1147
}])1148
.unwrap();1149
let channel = |id: &str, name: &str| ChannelRecord {1150
id: id.to_owned(),1151
team_id: "t1".to_owned(),1152
name: name.to_owned(),1153
membership_type: None,1154
last_message_at: None,1155
unread: false,1156
};1157
store1158
.upsert_channels(&[channel("c1", "General"), channel("c2", "Random")])1159
.unwrap();1160
let team = || store.sidebar().unwrap().teams.remove(0);1161
assert_eq!(1162
team().channel_notifications("c2"),1163
ChannelNotifications::default()1164
);1165
1166
let banner = ChannelNotifications {1167
level: ChannelNotificationLevel::BannerAndFeed,1168
include_replies: true,1169
};1170
store.set_channel_notifications("c2", banner).unwrap();1171
let sidebar_team = team();1172
assert_eq!(sidebar_team.channel_notifications("c2"), banner);1173
assert_eq!(sidebar_team.channels[0].name, "General");1174
1175
let off = ChannelNotifications {1176
level: ChannelNotificationLevel::Off,1177
include_replies: false,1178
};1179
store1180
.replace_team_layout(&[TeamLayoutRecord {1181
team_id: "t1".to_owned(),1182
hidden: false,1183
channels: vec![ChannelLayoutRecord {1184
channel_id: "c2".to_owned(),1185
general: false,1186
hidden: false,1187
tabs: Vec::new(),1188
notifications: off,1189
}],1190
}])1191
.unwrap();1192
assert_eq!(team().channel_notifications("c2"), off);1193
}@@ -0,0 +1,68 @@
1
use std::sync::{Arc, mpsc};
2
3
use crate::transport::UiRequest;
4
5
#[derive(Debug, Clone)]
6
pub struct EmbedSpec {
7
pub parent: isize,
8
pub url: String,
9
pub background: u32,
10
}
11
12
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
13
pub struct EmbedBounds {
14
pub x: i32,
15
pub y: i32,
16
pub width: i32,
17
pub height: i32,
18
}
19
20
#[derive(Debug, Clone, PartialEq, Eq)]
21
pub enum EmbedEvent {
22
Navigated(String),
23
NewWindow(String),
24
Closed,
25
}
26
27
#[derive(Debug)]
28
pub(crate) enum EmbedCommand {
29
Bounds(EmbedBounds),
30
Visible(bool),
31
Navigate(String),
32
Close,
33
}
34
35
#[derive(Clone)]
36
pub struct EmbedHandle {
37
pub(crate) id: u64,
38
pub(crate) requests: mpsc::Sender<UiRequest>,
39
pub(crate) waker: Arc<dyn Fn() + Send + Sync>,
40
}
41
42
impl EmbedHandle {
43
pub fn set_bounds(&self, bounds: EmbedBounds) {
44
self.send(EmbedCommand::Bounds(bounds));
45
}
46
47
pub fn set_visible(&self, visible: bool) {
48
self.send(EmbedCommand::Visible(visible));
49
}
50
51
pub fn navigate(&self, url: String) {
52
self.send(EmbedCommand::Navigate(url));
53
}
54
55
pub fn close(&self) {
56
self.send(EmbedCommand::Close);
57
}
58
59
fn send(&self, command: EmbedCommand) {
60
let request = UiRequest::Embed {
61
id: self.id,
62
command,
63
};
64
if self.requests.send(request).is_ok() {
65
(self.waker)();
66
}
67
}
68
}
@@ -0,0 +1,68 @@1
use std::sync::{Arc, mpsc};2
3
use crate::transport::UiRequest;4
5
#[derive(Debug, Clone)]6
pub struct EmbedSpec {7
pub parent: isize,8
pub url: String,9
pub background: u32,10
}11
12
#[derive(Debug, Clone, Copy, PartialEq, Eq)]13
pub struct EmbedBounds {14
pub x: i32,15
pub y: i32,16
pub width: i32,17
pub height: i32,18
}19
20
#[derive(Debug, Clone, PartialEq, Eq)]21
pub enum EmbedEvent {22
Navigated(String),23
NewWindow(String),24
Closed,25
}26
27
#[derive(Debug)]28
pub(crate) enum EmbedCommand {29
Bounds(EmbedBounds),30
Visible(bool),31
Navigate(String),32
Close,33
}34
35
#[derive(Clone)]36
pub struct EmbedHandle {37
pub(crate) id: u64,38
pub(crate) requests: mpsc::Sender<UiRequest>,39
pub(crate) waker: Arc<dyn Fn() + Send + Sync>,40
}41
42
impl EmbedHandle {43
pub fn set_bounds(&self, bounds: EmbedBounds) {44
self.send(EmbedCommand::Bounds(bounds));45
}46
47
pub fn set_visible(&self, visible: bool) {48
self.send(EmbedCommand::Visible(visible));49
}50
51
pub fn navigate(&self, url: String) {52
self.send(EmbedCommand::Navigate(url));53
}54
55
pub fn close(&self) {56
self.send(EmbedCommand::Close);57
}58
59
fn send(&self, command: EmbedCommand) {60
let request = UiRequest::Embed {61
id: self.id,62
command,63
};64
if self.requests.send(request).is_ok() {65
(self.waker)();66
}67
}68
}@@ -23,6 +23,7 @@ use windows::core::{HSTRING, Interface, PCWSTR, PWSTR, w};
23
23
24
24
use crate::fanout::Subscribers;
25
25
use crate::host_dialog::{self, Dialog};
26
use crate::host_embed::{self, Embed};
26
27
use crate::transport::{HostState, UiRequest, WebViewTransport};
27
28
use crate::{BROWSER_ARGUMENTS, FORWARDED_EVENTS};
28
29
@@ -54,6 +55,7 @@ pub(crate) struct Shared {
54
55
views: RefCell<HashMap<App, View>>,
55
56
pub(crate) environment: RefCell<Option<ICoreWebView2Environment>>,
56
57
pub(crate) dialogs: RefCell<HashMap<u64, Dialog>>,
58
pub(crate) embeds: RefCell<HashMap<u64, Embed>>,
57
59
subscribers: RefCell<Subscribers>,
58
60
state: watch::Sender<HostState>,
59
61
requests: mpsc::Receiver<UiRequest>,
@@ -114,6 +116,7 @@ fn run(
114
116
views: RefCell::new(HashMap::new()),
115
117
environment: RefCell::new(None),
116
118
dialogs: RefCell::new(HashMap::new()),
119
embeds: RefCell::new(HashMap::new()),
117
120
subscribers: RefCell::new(Subscribers::default()),
118
121
state,
119
122
requests,
@@ -431,6 +434,8 @@ fn drain(shared: &Rc<Shared>) {
431
434
host_dialog::open(shared, id, spec, events)
432
435
}
433
436
UiRequest::Dialog { id, command } => host_dialog::run(shared, id, command),
437
UiRequest::OpenEmbed { id, spec, events } => host_embed::open(shared, id, spec, events),
438
UiRequest::Embed { id, command } => host_embed::run(shared, id, command),
434
439
}
435
440
}
436
441
}
@@ -520,6 +525,7 @@ fn restart(shared: &Rc<Shared>) {
520
525
shared.state.send_modify(|state| state.ready = false);
521
526
shared.subscribers.borrow_mut().clear();
522
527
host_dialog::close_all(shared);
528
host_embed::close_all(shared);
523
529
let views: Vec<View> = shared
524
530
.views
525
531
.borrow_mut()
@@ -23,6 +23,7 @@ use windows::core::{HSTRING, Interface, PCWSTR, PWSTR, w};23
23
24
use crate::fanout::Subscribers;24
use crate::fanout::Subscribers;25
use crate::host_dialog::{self, Dialog};25
use crate::host_dialog::{self, Dialog};26
use crate::host_embed::{self, Embed};26
use crate::transport::{HostState, UiRequest, WebViewTransport};27
use crate::transport::{HostState, UiRequest, WebViewTransport};27
use crate::{BROWSER_ARGUMENTS, FORWARDED_EVENTS};28
use crate::{BROWSER_ARGUMENTS, FORWARDED_EVENTS};28
29
@@ -54,6 +55,7 @@ pub(crate) struct Shared {54
views: RefCell<HashMap<App, View>>,55
views: RefCell<HashMap<App, View>>,55
pub(crate) environment: RefCell<Option<ICoreWebView2Environment>>,56
pub(crate) environment: RefCell<Option<ICoreWebView2Environment>>,56
pub(crate) dialogs: RefCell<HashMap<u64, Dialog>>,57
pub(crate) dialogs: RefCell<HashMap<u64, Dialog>>,58
pub(crate) embeds: RefCell<HashMap<u64, Embed>>,57
subscribers: RefCell<Subscribers>,59
subscribers: RefCell<Subscribers>,58
state: watch::Sender<HostState>,60
state: watch::Sender<HostState>,59
requests: mpsc::Receiver<UiRequest>,61
requests: mpsc::Receiver<UiRequest>,@@ -114,6 +116,7 @@ fn run(114
views: RefCell::new(HashMap::new()),116
views: RefCell::new(HashMap::new()),115
environment: RefCell::new(None),117
environment: RefCell::new(None),116
dialogs: RefCell::new(HashMap::new()),118
dialogs: RefCell::new(HashMap::new()),119
embeds: RefCell::new(HashMap::new()),117
subscribers: RefCell::new(Subscribers::default()),120
subscribers: RefCell::new(Subscribers::default()),118
state,121
state,119
requests,122
requests,@@ -431,6 +434,8 @@ fn drain(shared: &Rc<Shared>) {431
host_dialog::open(shared, id, spec, events)434
host_dialog::open(shared, id, spec, events)432
}435
}433
UiRequest::Dialog { id, command } => host_dialog::run(shared, id, command),436
UiRequest::Dialog { id, command } => host_dialog::run(shared, id, command),437
UiRequest::OpenEmbed { id, spec, events } => host_embed::open(shared, id, spec, events),438
UiRequest::Embed { id, command } => host_embed::run(shared, id, command),434
}439
}435
}440
}436
}441
}@@ -520,6 +525,7 @@ fn restart(shared: &Rc<Shared>) {520
shared.state.send_modify(|state| state.ready = false);525
shared.state.send_modify(|state| state.ready = false);521
shared.subscribers.borrow_mut().clear();526
shared.subscribers.borrow_mut().clear();522
host_dialog::close_all(shared);527
host_dialog::close_all(shared);528
host_embed::close_all(shared);523
let views: Vec<View> = shared529
let views: Vec<View> = shared524
.views530
.views525
.borrow_mut()531
.borrow_mut()@@ -0,0 +1,222 @@
1
use std::rc::Rc;
2
3
use tokio::sync::mpsc::UnboundedSender;
4
use webview2_com::Microsoft::Web::WebView2::Win32::*;
5
use webview2_com::{
6
CreateCoreWebView2ControllerCompletedHandler, NewWindowRequestedEventHandler,
7
SourceChangedEventHandler, take_pwstr,
8
};
9
use windows::Win32::Foundation::{HWND, RECT};
10
use windows::core::{HSTRING, Interface, PWSTR};
11
12
use crate::embed::{EmbedBounds, EmbedCommand, EmbedEvent, EmbedSpec};
13
use crate::host::{Shared, shared as running_host};
14
15
struct EmbedView {
16
controller: ICoreWebView2Controller,
17
webview: ICoreWebView2,
18
}
19
20
pub(crate) struct Embed {
21
view: Option<EmbedView>,
22
bounds: Option<EmbedBounds>,
23
visible: bool,
24
events: UnboundedSender<EmbedEvent>,
25
}
26
27
pub(crate) fn open(
28
shared: &Rc<Shared>,
29
id: u64,
30
spec: EmbedSpec,
31
events: UnboundedSender<EmbedEvent>,
32
) {
33
let Some(environment) = shared.environment.borrow().clone() else {
34
let _ = events.send(EmbedEvent::Closed);
35
return;
36
};
37
shared.embeds.borrow_mut().insert(
38
id,
39
Embed {
40
view: None,
41
bounds: None,
42
visible: false,
43
events,
44
},
45
);
46
let parent = HWND(spec.parent as *mut _);
47
let handler =
48
CreateCoreWebView2ControllerCompletedHandler::create(Box::new(move |code, controller| {
49
let Some(shared) = running_host() else {
50
return Ok(());
51
};
52
let attached = code
53
.and_then(|()| {
54
controller.ok_or_else(|| windows::core::Error::from(windows::core::HRESULT(-1)))
55
})
56
.and_then(|controller| attach(&shared, id, controller, &spec));
57
if attached.is_err() {
58
close(&shared, id);
59
}
60
Ok(())
61
}));
62
if unsafe { environment.CreateCoreWebView2Controller(parent, &handler) }.is_err() {
63
close(shared, id);
64
}
65
}
66
67
pub(crate) fn run(shared: &Rc<Shared>, id: u64, command: EmbedCommand) {
68
match command {
69
EmbedCommand::Bounds(bounds) => {
70
let controller = update(shared, id, |embed| embed.bounds = Some(bounds));
71
if let Some(controller) = controller {
72
apply_bounds(&controller, bounds);
73
}
74
}
75
EmbedCommand::Visible(visible) => {
76
let controller = update(shared, id, |embed| embed.visible = visible);
77
if let Some(controller) = controller {
78
unsafe {
79
let _ = controller.SetIsVisible(visible);
80
}
81
}
82
}
83
EmbedCommand::Navigate(url) => {
84
let webview = shared
85
.embeds
86
.borrow()
87
.get(&id)
88
.and_then(|embed| embed.view.as_ref().map(|view| view.webview.clone()));
89
if let Some(webview) = webview {
90
unsafe {
91
let _ = webview.Navigate(&HSTRING::from(url));
92
}
93
}
94
}
95
EmbedCommand::Close => close(shared, id),
96
}
97
}
98
99
pub(crate) fn close(shared: &Rc<Shared>, id: u64) {
100
let Some(embed) = shared.embeds.borrow_mut().remove(&id) else {
101
return;
102
};
103
if let Some(view) = &embed.view {
104
unsafe {
105
let _ = view.controller.Close();
106
}
107
}
108
let _ = embed.events.send(EmbedEvent::Closed);
109
}
110
111
pub(crate) fn close_all(shared: &Rc<Shared>) {
112
let ids: Vec<u64> = shared.embeds.borrow().keys().copied().collect();
113
for id in ids {
114
close(shared, id);
115
}
116
}
117
118
fn update(
119
shared: &Shared,
120
id: u64,
121
change: impl FnOnce(&mut Embed),
122
) -> Option<ICoreWebView2Controller> {
123
let mut embeds = shared.embeds.borrow_mut();
124
let embed = embeds.get_mut(&id)?;
125
change(embed);
126
embed.view.as_ref().map(|view| view.controller.clone())
127
}
128
129
fn emit(id: u64, event: EmbedEvent) {
130
if let Some(shared) = running_host()
131
&& let Some(embed) = shared.embeds.borrow().get(&id)
132
{
133
let _ = embed.events.send(event);
134
}
135
}
136
137
fn apply_bounds(controller: &ICoreWebView2Controller, bounds: EmbedBounds) {
138
unsafe {
139
let _ = controller.SetBounds(RECT {
140
left: bounds.x,
141
top: bounds.y,
142
right: bounds.x + bounds.width,
143
bottom: bounds.y + bounds.height,
144
});
145
}
146
}
147
148
fn attach(
149
shared: &Rc<Shared>,
150
id: u64,
151
controller: ICoreWebView2Controller,
152
spec: &EmbedSpec,
153
) -> windows::core::Result<()> {
154
let Some((bounds, visible)) = shared
155
.embeds
156
.borrow()
157
.get(&id)
158
.map(|embed| (embed.bounds, embed.visible))
159
else {
160
unsafe { controller.Close() }?;
161
return Ok(());
162
};
163
let webview = unsafe { controller.CoreWebView2() }?;
164
unsafe {
165
controller
166
.cast::<ICoreWebView2Controller2>()?
167
.SetDefaultBackgroundColor(COREWEBVIEW2_COLOR {
168
A: 255,
169
R: (spec.background >> 16) as u8,
170
G: (spec.background >> 8) as u8,
171
B: spec.background as u8,
172
})?;
173
webview.Settings()?.SetIsStatusBarEnabled(false)?;
174
}
175
if let Some(bounds) = bounds {
176
apply_bounds(&controller, bounds);
177
}
178
watch_source(&webview, id)?;
179
forward_new_windows(&webview, id)?;
180
unsafe {
181
controller.SetIsVisible(visible)?;
182
webview.Navigate(&HSTRING::from(spec.url.as_str()))?;
183
}
184
if let Some(embed) = shared.embeds.borrow_mut().get_mut(&id) {
185
embed.view = Some(EmbedView {
186
controller,
187
webview,
188
});
189
}
190
Ok(())
191
}
192
193
fn watch_source(webview: &ICoreWebView2, id: u64) -> windows::core::Result<()> {
194
let handler = SourceChangedEventHandler::create(Box::new(move |sender, _| {
195
if let Some(sender) = sender {
196
let mut source = PWSTR::null();
197
if unsafe { sender.Source(&mut source) }.is_ok() {
198
emit(id, EmbedEvent::Navigated(take_pwstr(source)));
199
}
200
}
201
Ok(())
202
}));
203
let mut token = 0;
204
unsafe { webview.add_SourceChanged(&handler, &mut token) }
205
}
206
207
fn forward_new_windows(webview: &ICoreWebView2, id: u64) -> windows::core::Result<()> {
208
let handler = NewWindowRequestedEventHandler::create(Box::new(move |_, arguments| {
209
let Some(arguments) = arguments else {
210
return Ok(());
211
};
212
let mut target = PWSTR::null();
213
unsafe {
214
arguments.Uri(&mut target)?;
215
arguments.SetHandled(true)?;
216
}
217
emit(id, EmbedEvent::NewWindow(take_pwstr(target)));
218
Ok(())
219
}));
220
let mut token = 0;
221
unsafe { webview.add_NewWindowRequested(&handler, &mut token) }
222
}
@@ -0,0 +1,222 @@1
use std::rc::Rc;2
3
use tokio::sync::mpsc::UnboundedSender;4
use webview2_com::Microsoft::Web::WebView2::Win32::*;5
use webview2_com::{6
CreateCoreWebView2ControllerCompletedHandler, NewWindowRequestedEventHandler,7
SourceChangedEventHandler, take_pwstr,8
};9
use windows::Win32::Foundation::{HWND, RECT};10
use windows::core::{HSTRING, Interface, PWSTR};11
12
use crate::embed::{EmbedBounds, EmbedCommand, EmbedEvent, EmbedSpec};13
use crate::host::{Shared, shared as running_host};14
15
struct EmbedView {16
controller: ICoreWebView2Controller,17
webview: ICoreWebView2,18
}19
20
pub(crate) struct Embed {21
view: Option<EmbedView>,22
bounds: Option<EmbedBounds>,23
visible: bool,24
events: UnboundedSender<EmbedEvent>,25
}26
27
pub(crate) fn open(28
shared: &Rc<Shared>,29
id: u64,30
spec: EmbedSpec,31
events: UnboundedSender<EmbedEvent>,32
) {33
let Some(environment) = shared.environment.borrow().clone() else {34
let _ = events.send(EmbedEvent::Closed);35
return;36
};37
shared.embeds.borrow_mut().insert(38
id,39
Embed {40
view: None,41
bounds: None,42
visible: false,43
events,44
},45
);46
let parent = HWND(spec.parent as *mut _);47
let handler =48
CreateCoreWebView2ControllerCompletedHandler::create(Box::new(move |code, controller| {49
let Some(shared) = running_host() else {50
return Ok(());51
};52
let attached = code53
.and_then(|()| {54
controller.ok_or_else(|| windows::core::Error::from(windows::core::HRESULT(-1)))55
})56
.and_then(|controller| attach(&shared, id, controller, &spec));57
if attached.is_err() {58
close(&shared, id);59
}60
Ok(())61
}));62
if unsafe { environment.CreateCoreWebView2Controller(parent, &handler) }.is_err() {63
close(shared, id);64
}65
}66
67
pub(crate) fn run(shared: &Rc<Shared>, id: u64, command: EmbedCommand) {68
match command {69
EmbedCommand::Bounds(bounds) => {70
let controller = update(shared, id, |embed| embed.bounds = Some(bounds));71
if let Some(controller) = controller {72
apply_bounds(&controller, bounds);73
}74
}75
EmbedCommand::Visible(visible) => {76
let controller = update(shared, id, |embed| embed.visible = visible);77
if let Some(controller) = controller {78
unsafe {79
let _ = controller.SetIsVisible(visible);80
}81
}82
}83
EmbedCommand::Navigate(url) => {84
let webview = shared85
.embeds86
.borrow()87
.get(&id)88
.and_then(|embed| embed.view.as_ref().map(|view| view.webview.clone()));89
if let Some(webview) = webview {90
unsafe {91
let _ = webview.Navigate(&HSTRING::from(url));92
}93
}94
}95
EmbedCommand::Close => close(shared, id),96
}97
}98
99
pub(crate) fn close(shared: &Rc<Shared>, id: u64) {100
let Some(embed) = shared.embeds.borrow_mut().remove(&id) else {101
return;102
};103
if let Some(view) = &embed.view {104
unsafe {105
let _ = view.controller.Close();106
}107
}108
let _ = embed.events.send(EmbedEvent::Closed);109
}110
111
pub(crate) fn close_all(shared: &Rc<Shared>) {112
let ids: Vec<u64> = shared.embeds.borrow().keys().copied().collect();113
for id in ids {114
close(shared, id);115
}116
}117
118
fn update(119
shared: &Shared,120
id: u64,121
change: impl FnOnce(&mut Embed),122
) -> Option<ICoreWebView2Controller> {123
let mut embeds = shared.embeds.borrow_mut();124
let embed = embeds.get_mut(&id)?;125
change(embed);126
embed.view.as_ref().map(|view| view.controller.clone())127
}128
129
fn emit(id: u64, event: EmbedEvent) {130
if let Some(shared) = running_host()131
&& let Some(embed) = shared.embeds.borrow().get(&id)132
{133
let _ = embed.events.send(event);134
}135
}136
137
fn apply_bounds(controller: &ICoreWebView2Controller, bounds: EmbedBounds) {138
unsafe {139
let _ = controller.SetBounds(RECT {140
left: bounds.x,141
top: bounds.y,142
right: bounds.x + bounds.width,143
bottom: bounds.y + bounds.height,144
});145
}146
}147
148
fn attach(149
shared: &Rc<Shared>,150
id: u64,151
controller: ICoreWebView2Controller,152
spec: &EmbedSpec,153
) -> windows::core::Result<()> {154
let Some((bounds, visible)) = shared155
.embeds156
.borrow()157
.get(&id)158
.map(|embed| (embed.bounds, embed.visible))159
else {160
unsafe { controller.Close() }?;161
return Ok(());162
};163
let webview = unsafe { controller.CoreWebView2() }?;164
unsafe {165
controller166
.cast::<ICoreWebView2Controller2>()?167
.SetDefaultBackgroundColor(COREWEBVIEW2_COLOR {168
A: 255,169
R: (spec.background >> 16) as u8,170
G: (spec.background >> 8) as u8,171
B: spec.background as u8,172
})?;173
webview.Settings()?.SetIsStatusBarEnabled(false)?;174
}175
if let Some(bounds) = bounds {176
apply_bounds(&controller, bounds);177
}178
watch_source(&webview, id)?;179
forward_new_windows(&webview, id)?;180
unsafe {181
controller.SetIsVisible(visible)?;182
webview.Navigate(&HSTRING::from(spec.url.as_str()))?;183
}184
if let Some(embed) = shared.embeds.borrow_mut().get_mut(&id) {185
embed.view = Some(EmbedView {186
controller,187
webview,188
});189
}190
Ok(())191
}192
193
fn watch_source(webview: &ICoreWebView2, id: u64) -> windows::core::Result<()> {194
let handler = SourceChangedEventHandler::create(Box::new(move |sender, _| {195
if let Some(sender) = sender {196
let mut source = PWSTR::null();197
if unsafe { sender.Source(&mut source) }.is_ok() {198
emit(id, EmbedEvent::Navigated(take_pwstr(source)));199
}200
}201
Ok(())202
}));203
let mut token = 0;204
unsafe { webview.add_SourceChanged(&handler, &mut token) }205
}206
207
fn forward_new_windows(webview: &ICoreWebView2, id: u64) -> windows::core::Result<()> {208
let handler = NewWindowRequestedEventHandler::create(Box::new(move |_, arguments| {209
let Some(arguments) = arguments else {210
return Ok(());211
};212
let mut target = PWSTR::null();213
unsafe {214
arguments.Uri(&mut target)?;215
arguments.SetHandled(true)?;216
}217
emit(id, EmbedEvent::NewWindow(take_pwstr(target)));218
Ok(())219
}));220
let mut token = 0;221
unsafe { webview.add_NewWindowRequested(&handler, &mut token) }222
}@@ -1,12 +1,15 @@
1
1
#![cfg(windows)]
2
2
3
3
mod dialog;
4
mod embed;
4
5
mod fanout;
5
6
mod host;
6
7
mod host_dialog;
8
mod host_embed;
7
9
mod transport;
8
10
9
11
pub use dialog::{DialogEvent, DialogHandle, DialogSpec};
12
pub use embed::{EmbedBounds, EmbedEvent, EmbedHandle, EmbedSpec};
10
13
pub use host::{HostConfig, start};
11
14
pub use transport::{HostState, WebViewTransport};
12
15
@@ -1,12 +1,15 @@1
#![cfg(windows)]1
#![cfg(windows)]2
2
3
mod dialog;3
mod dialog;4
mod embed;4
mod fanout;5
mod fanout;5
mod host;6
mod host;6
mod host_dialog;7
mod host_dialog;8
mod host_embed;7
mod transport;9
mod transport;8
10
9
pub use dialog::{DialogEvent, DialogHandle, DialogSpec};11
pub use dialog::{DialogEvent, DialogHandle, DialogSpec};12
pub use embed::{EmbedBounds, EmbedEvent, EmbedHandle, EmbedSpec};10
pub use host::{HostConfig, start};13
pub use host::{HostConfig, start};11
pub use transport::{HostState, WebViewTransport};14
pub use transport::{HostState, WebViewTransport};12
15
@@ -13,6 +13,7 @@ use tokio::sync::{
13
13
};
14
14
15
15
use crate::dialog::{DialogCommand, DialogEvent, DialogHandle, DialogSpec};
16
use crate::embed::{EmbedCommand, EmbedEvent, EmbedHandle, EmbedSpec};
16
17
17
18
const ENDPOINT_NAME: &str = "WebView2";
18
19
const READY_WAIT: Duration = Duration::from_secs(30);
@@ -39,6 +40,15 @@ pub(crate) enum UiRequest {
39
40
id: u64,
40
41
command: DialogCommand,
41
42
},
43
OpenEmbed {
44
id: u64,
45
spec: EmbedSpec,
46
events: UnboundedSender<EmbedEvent>,
47
},
48
Embed {
49
id: u64,
50
command: EmbedCommand,
51
},
42
52
}
43
53
44
54
#[derive(Debug, Clone, Default)]
@@ -54,6 +64,7 @@ pub struct WebViewTransport {
54
64
state: watch::Receiver<HostState>,
55
65
ready_wait: Duration,
56
66
next_dialog: AtomicU64,
67
next_embed: AtomicU64,
57
68
}
58
69
59
70
impl WebViewTransport {
@@ -68,6 +79,7 @@ impl WebViewTransport {
68
79
state,
69
80
ready_wait: READY_WAIT,
70
81
next_dialog: AtomicU64::new(1),
82
next_embed: AtomicU64::new(1),
71
83
}
72
84
}
73
85
@@ -83,6 +95,18 @@ impl WebViewTransport {
83
95
(handle, receiver)
84
96
}
85
97
98
pub fn open_embed(&self, spec: EmbedSpec) -> (EmbedHandle, UnboundedReceiver<EmbedEvent>) {
99
let id = self.next_embed.fetch_add(1, Ordering::Relaxed);
100
let (events, receiver) = unbounded_channel();
101
let handle = EmbedHandle {
102
id,
103
requests: self.requests.clone(),
104
waker: self.waker.clone(),
105
};
106
let _ = self.send(UiRequest::OpenEmbed { id, spec, events });
107
(handle, receiver)
108
}
109
86
110
fn send(&self, request: UiRequest) -> Result<()> {
87
111
self.requests
88
112
.send(request)
@@ -13,6 +13,7 @@ use tokio::sync::{13
};13
};14
14
15
use crate::dialog::{DialogCommand, DialogEvent, DialogHandle, DialogSpec};15
use crate::dialog::{DialogCommand, DialogEvent, DialogHandle, DialogSpec};16
use crate::embed::{EmbedCommand, EmbedEvent, EmbedHandle, EmbedSpec};16
17
17
const ENDPOINT_NAME: &str = "WebView2";18
const ENDPOINT_NAME: &str = "WebView2";18
const READY_WAIT: Duration = Duration::from_secs(30);19
const READY_WAIT: Duration = Duration::from_secs(30);@@ -39,6 +40,15 @@ pub(crate) enum UiRequest {39
id: u64,40
id: u64,40
command: DialogCommand,41
command: DialogCommand,41
},42
},43
OpenEmbed {44
id: u64,45
spec: EmbedSpec,46
events: UnboundedSender<EmbedEvent>,47
},48
Embed {49
id: u64,50
command: EmbedCommand,51
},42
}52
}43
53
44
#[derive(Debug, Clone, Default)]54
#[derive(Debug, Clone, Default)]@@ -54,6 +64,7 @@ pub struct WebViewTransport {54
state: watch::Receiver<HostState>,64
state: watch::Receiver<HostState>,55
ready_wait: Duration,65
ready_wait: Duration,56
next_dialog: AtomicU64,66
next_dialog: AtomicU64,67
next_embed: AtomicU64,57
}68
}58
69
59
impl WebViewTransport {70
impl WebViewTransport {@@ -68,6 +79,7 @@ impl WebViewTransport {68
state,79
state,69
ready_wait: READY_WAIT,80
ready_wait: READY_WAIT,70
next_dialog: AtomicU64::new(1),81
next_dialog: AtomicU64::new(1),82
next_embed: AtomicU64::new(1),71
}83
}72
}84
}73
85
@@ -83,6 +95,18 @@ impl WebViewTransport {83
(handle, receiver)95
(handle, receiver)84
}96
}85
97
98
pub fn open_embed(&self, spec: EmbedSpec) -> (EmbedHandle, UnboundedReceiver<EmbedEvent>) {99
let id = self.next_embed.fetch_add(1, Ordering::Relaxed);100
let (events, receiver) = unbounded_channel();101
let handle = EmbedHandle {102
id,103
requests: self.requests.clone(),104
waker: self.waker.clone(),105
};106
let _ = self.send(UiRequest::OpenEmbed { id, spec, events });107
(handle, receiver)108
}109
86
fn send(&self, request: UiRequest) -> Result<()> {110
fn send(&self, request: UiRequest) -> Result<()> {87
self.requests111
self.requests88
.send(request)112
.send(request)