feat(presence): own status menu, status message, work location and profile cards
| Before | After | |---|---| | Own avatar shows presence only | Avatar menu like Teams: Available, Busy, Do not disturb, Be right back, Appear away, Appear offline, duration, reset | | Status message only in Teams | Dialog: text (280), "show when people message me", clear after | | No work location | Set work location: Office or Remote for today, clear | | Click on a person does nothing | Profile card on name, avatar or mention: presence, status message or out of office, work location, local time, contact, manager and reports, Chat / Email / Copy email | - Writes go through the Teams presence service (forceavailability, publishnote, workLocation); Graph presence is 403 for this token. - One getpresence parser in chatsvc serves both the own status and the card. - Profile fields from Graph (user, manager, directReports), local time from getSchedule working hours. - Demo mode covers all states. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@@ -37,6 +37,7 @@
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
38
- Chat menu: pin, move to folder, mark as unread, mute, hide, leave
39
39
- Read receipts, typing indicator with faces, presence, unread jump
40
- Own status, status message and work location from the avatar menu; profile cards with org chart
40
41
- Activity bell: new messages, @mentions and reactions, kept for 14 days
41
42
42
43
**Messages**
@@ -37,6 +37,7 @@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 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
- Chat menu: pin, move to folder, mark as unread, mute, hide, leave38
- Chat menu: pin, move to folder, mark as unread, mute, hide, leave39
- Read receipts, typing indicator with faces, presence, unread jump39
- Read receipts, typing indicator with faces, presence, unread jump40
- Own status, status message and work location from the avatar menu; profile cards with org chart40
- Activity bell: new messages, @mentions and reactions, kept for 14 days41
- Activity bell: new messages, @mentions and reactions, kept for 14 days41
42
42
**Messages**43
**Messages**@@ -2,7 +2,7 @@
2
2
3
3
Feature parity with the Microsoft Teams desktop client.
4
4
5
**Parity: 80 %** (69 done, 1 partial, 17 missing of 87). Partial counts half.
5
**Parity: 82 %** (71 done, 1 partial, 15 missing of 87). Partial counts half.
6
6
7
7
## By area
8
8
@@ -16,7 +16,7 @@ Feature parity with the Microsoft Teams desktop client.
16
16
| [Channels](#channels) | 57 % | 4 | 0 | 3 |
17
17
| [Notifications](#notifications) | 88 % | 7 | 0 | 1 |
18
18
| [Search and navigation](#search-and-navigation) | 80 % | 4 | 0 | 1 |
19
| [Presence and people](#presence-and-people) | 50 % | 2 | 0 | 2 |
19
| [Presence and people](#presence-and-people) | 100 % | 4 | 0 | 0 |
20
20
| [Look and settings](#look-and-settings) | 50 % | 2 | 0 | 2 |
21
21
| [Calls and meetings](#calls-and-meetings) | 0 % | 0 | 0 | 5 |
22
22
@@ -147,8 +147,8 @@ Feature parity with the Microsoft Teams desktop client.
147
147
|---|---|---|
148
148
| Presence dots (live push) | Done | |
149
149
| Last known presence at start | Done | |
150
| Set own status and status message | Missing | |
151
| Profile card | Missing | |
150
| Set own status and status message | Done | Avatar menu like Teams: 6 states with duration, reset, status message with clear-after and "show when people message me", work location Office or Remote for today |
151
| Profile card | Done | Click a name, avatar or mention: presence, status message or out of office, work location, local time, contact, manager and direct reports; Chat, Email, Copy email |
152
152
153
153
## Look and settings
154
154
@@ -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: 80 %** (69 done, 1 partial, 17 missing of 87). Partial counts half.5
**Parity: 82 %** (71 done, 1 partial, 15 missing of 87). Partial counts half.6
6
7
## By area7
## By area8
8
@@ -16,7 +16,7 @@ Feature parity with the Microsoft Teams desktop client.16
| [Channels](#channels) | 57 % | 4 | 0 | 3 |16
| [Channels](#channels) | 57 % | 4 | 0 | 3 |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) | 50 % | 2 | 0 | 2 |19
| [Presence and people](#presence-and-people) | 100 % | 4 | 0 | 0 |20
| [Look and settings](#look-and-settings) | 50 % | 2 | 0 | 2 |20
| [Look and settings](#look-and-settings) | 50 % | 2 | 0 | 2 |21
| [Calls and meetings](#calls-and-meetings) | 0 % | 0 | 0 | 5 |21
| [Calls and meetings](#calls-and-meetings) | 0 % | 0 | 0 | 5 |22
22
@@ -147,8 +147,8 @@ Feature parity with the Microsoft Teams desktop client.147
|---|---|---|147
|---|---|---|148
| Presence dots (live push) | Done | |148
| Presence dots (live push) | Done | |149
| Last known presence at start | Done | |149
| Last known presence at start | Done | |150
| Set own status and status message | Missing | |150
| Set own status and status message | Done | Avatar menu like Teams: 6 states with duration, reset, status message with clear-after and "show when people message me", work location Office or Remote for today |151
| Profile card | Missing | |151
| Profile card | Done | Click a name, avatar or mention: presence, status message or out of office, work location, local time, contact, manager and direct reports; Chat, Email, Copy email |152
152
153
## Look and settings153
## Look and settings154
154
@@ -0,0 +1 @@
1
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24"><path fill-rule="evenodd" d="M12 3a9 9 0 1 0 0 18a9 9 0 0 0 0-18ZM10.9 6.5h2.2v5.1l3.2 1.9-1.1 1.9-4.3-2.5Z"/></svg>
@@ -0,0 +1 @@1
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24"><path fill-rule="evenodd" d="M12 3a9 9 0 1 0 0 18a9 9 0 0 0 0-18ZM10.9 6.5h2.2v5.1l3.2 1.9-1.1 1.9-4.3-2.5Z"/></svg>@@ -0,0 +1 @@
1
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24"><path fill-rule="evenodd" d="M12 3a9 9 0 1 0 0 18a9 9 0 0 0 0-18ZM6.5 10.75h11v2.5h-11Z"/></svg>
@@ -0,0 +1 @@1
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24"><path fill-rule="evenodd" d="M12 3a9 9 0 1 0 0 18a9 9 0 0 0 0-18ZM6.5 10.75h11v2.5h-11Z"/></svg>@@ -0,0 +1 @@
1
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24"><circle cx="12" cy="12" r="9"/></svg>
@@ -0,0 +1 @@1
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24"><circle cx="12" cy="12" r="9"/></svg>@@ -0,0 +1 @@
1
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24"><path fill-rule="evenodd" d="M12 3a9 9 0 1 0 0 18a9 9 0 0 0 0-18ZM12 6a6 6 0 1 1 0 12a6 6 0 0 1 0-12Z"/></svg>
@@ -0,0 +1 @@1
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24"><path fill-rule="evenodd" d="M12 3a9 9 0 1 0 0 18a9 9 0 0 0 0-18ZM12 6a6 6 0 1 1 0 12a6 6 0 0 1 0-12Z"/></svg>@@ -6,7 +6,7 @@ use chatsvc::TypingEvent;
6
6
use chrono::{DateTime, Utc};
7
7
use gpui_kit::*;
8
8
use store::{ChatRecord, Sidebar, Store};
9
use teams_core::{ChatApp, CoreEvent, ImageRef, PinnedMessage, ScheduledDraft};
9
use teams_core::{ChatApp, CoreEvent, ImageRef, PinnedMessage, PresenceStatus, ScheduledDraft};
10
10
11
11
use crate::backend::{BackendEvent, ConnectionState, Engine, LiveState};
12
12
use crate::card_state::{CardState, TaskDialogState};
@@ -15,6 +15,7 @@ use crate::local_previews::{LocalPreview, load_local_previews};
15
15
use crate::message_actions::{ForwardSource, SavedSet};
16
16
use crate::notice::Notice;
17
17
use crate::notify;
18
use crate::profile_state::{ProfileCache, ProfileRequest};
18
19
use crate::typing::TypingState;
19
20
20
21
const COLLAPSED_META_KEY: &str = "ui.collapsed_sections";
@@ -51,6 +52,9 @@ pub enum AppEvent {
51
52
Pins(String),
52
53
Saved,
53
54
Forward,
55
StatusMessage,
56
NotificationSettings,
57
Profile,
54
58
}
55
59
56
60
#[derive(Debug, Clone, Copy, Default)]
@@ -91,6 +95,12 @@ pub struct AppState {
91
95
pub saved: SavedSet,
92
96
pub pins: HashMap<String, Vec<PinnedMessage>>,
93
97
pub forward_request: Option<ForwardSource>,
98
pub own_status: PresenceStatus,
99
pub own_email: String,
100
pub status_menu_open: bool,
101
pub status_message_request: bool,
102
pub profiles: ProfileCache,
103
pub profile_request: Option<ProfileRequest>,
94
104
}
95
105
96
106
pub struct AppHandle(pub Entity<AppState>);
@@ -168,6 +178,12 @@ impl AppState {
168
178
saved: SavedSet::default(),
169
179
pins: HashMap::new(),
170
180
forward_request: None,
181
own_status: PresenceStatus::default(),
182
own_email: String::new(),
183
status_menu_open: false,
184
status_message_request: false,
185
profiles: ProfileCache::new(),
186
profile_request: None,
171
187
};
172
188
state.local_previews = load_local_previews(&state.store);
173
189
state.collapsed = state.load_collapsed();
@@ -215,6 +231,12 @@ impl AppState {
215
231
216
232
pub fn reload_directory(&mut self) {
217
233
self.directory.me = data::me(&self.store);
234
self.own_email = self
235
.store
236
.meta("me_email")
237
.ok()
238
.flatten()
239
.unwrap_or_default();
218
240
self.directory.folders = data::folders(&self.store, &self.favorite_ids);
219
241
self.directory.pinned_channels = data::pinned_channels(&self.store);
220
242
if self.directory.pinned_channels.is_empty() {
@@ -582,6 +604,7 @@ impl AppState {
582
604
self.refresh_scheduled(cx);
583
605
let waiting = self.directory.waiting_presence_ids();
584
606
self.request_presence(waiting, cx);
607
self.refresh_own_status(cx);
585
608
cx.emit(AppEvent::Status);
586
609
}
587
610
BackendEvent::Core(CoreEvent::SidebarChanged) => self.reload_sidebar(cx),
@@ -617,6 +640,10 @@ impl AppState {
617
640
cx.emit(AppEvent::Directory);
618
641
cx.notify();
619
642
}
643
BackendEvent::Core(CoreEvent::PresenceStatusChanged(status)) => {
644
self.apply_own_status(status, cx);
645
self.reload_directory();
646
}
620
647
BackendEvent::Core(_) => {
621
648
if !self.mode.demo {
622
649
self.reload_directory();
@@ -6,7 +6,7 @@ use chatsvc::TypingEvent;6
use chrono::{DateTime, Utc};6
use chrono::{DateTime, Utc};7
use gpui_kit::*;7
use gpui_kit::*;8
use store::{ChatRecord, Sidebar, Store};8
use store::{ChatRecord, Sidebar, Store};9
use teams_core::{ChatApp, CoreEvent, ImageRef, PinnedMessage, ScheduledDraft};9
use teams_core::{ChatApp, CoreEvent, ImageRef, PinnedMessage, PresenceStatus, ScheduledDraft};10
10
11
use crate::backend::{BackendEvent, ConnectionState, Engine, LiveState};11
use crate::backend::{BackendEvent, ConnectionState, Engine, LiveState};12
use crate::card_state::{CardState, TaskDialogState};12
use crate::card_state::{CardState, TaskDialogState};@@ -15,6 +15,7 @@ use crate::local_previews::{LocalPreview, load_local_previews};15
use crate::message_actions::{ForwardSource, SavedSet};15
use crate::message_actions::{ForwardSource, SavedSet};16
use crate::notice::Notice;16
use crate::notice::Notice;17
use crate::notify;17
use crate::notify;18
use crate::profile_state::{ProfileCache, ProfileRequest};18
use crate::typing::TypingState;19
use crate::typing::TypingState;19
20
20
const COLLAPSED_META_KEY: &str = "ui.collapsed_sections";21
const COLLAPSED_META_KEY: &str = "ui.collapsed_sections";@@ -51,6 +52,9 @@ pub enum AppEvent {51
Pins(String),52
Pins(String),52
Saved,53
Saved,53
Forward,54
Forward,55
StatusMessage,56
NotificationSettings,57
Profile,54
}58
}55
59
56
#[derive(Debug, Clone, Copy, Default)]60
#[derive(Debug, Clone, Copy, Default)]@@ -91,6 +95,12 @@ pub struct AppState {91
pub saved: SavedSet,95
pub saved: SavedSet,92
pub pins: HashMap<String, Vec<PinnedMessage>>,96
pub pins: HashMap<String, Vec<PinnedMessage>>,93
pub forward_request: Option<ForwardSource>,97
pub forward_request: Option<ForwardSource>,98
pub own_status: PresenceStatus,99
pub own_email: String,100
pub status_menu_open: bool,101
pub status_message_request: bool,102
pub profiles: ProfileCache,103
pub profile_request: Option<ProfileRequest>,94
}104
}95
105
96
pub struct AppHandle(pub Entity<AppState>);106
pub struct AppHandle(pub Entity<AppState>);@@ -168,6 +178,12 @@ impl AppState {168
saved: SavedSet::default(),178
saved: SavedSet::default(),169
pins: HashMap::new(),179
pins: HashMap::new(),170
forward_request: None,180
forward_request: None,181
own_status: PresenceStatus::default(),182
own_email: String::new(),183
status_menu_open: false,184
status_message_request: false,185
profiles: ProfileCache::new(),186
profile_request: None,171
};187
};172
state.local_previews = load_local_previews(&state.store);188
state.local_previews = load_local_previews(&state.store);173
state.collapsed = state.load_collapsed();189
state.collapsed = state.load_collapsed();@@ -215,6 +231,12 @@ impl AppState {215
231
216
pub fn reload_directory(&mut self) {232
pub fn reload_directory(&mut self) {217
self.directory.me = data::me(&self.store);233
self.directory.me = data::me(&self.store);234
self.own_email = self235
.store236
.meta("me_email")237
.ok()238
.flatten()239
.unwrap_or_default();218
self.directory.folders = data::folders(&self.store, &self.favorite_ids);240
self.directory.folders = data::folders(&self.store, &self.favorite_ids);219
self.directory.pinned_channels = data::pinned_channels(&self.store);241
self.directory.pinned_channels = data::pinned_channels(&self.store);220
if self.directory.pinned_channels.is_empty() {242
if self.directory.pinned_channels.is_empty() {@@ -582,6 +604,7 @@ impl AppState {582
self.refresh_scheduled(cx);604
self.refresh_scheduled(cx);583
let waiting = self.directory.waiting_presence_ids();605
let waiting = self.directory.waiting_presence_ids();584
self.request_presence(waiting, cx);606
self.request_presence(waiting, cx);607
self.refresh_own_status(cx);585
cx.emit(AppEvent::Status);608
cx.emit(AppEvent::Status);586
}609
}587
BackendEvent::Core(CoreEvent::SidebarChanged) => self.reload_sidebar(cx),610
BackendEvent::Core(CoreEvent::SidebarChanged) => self.reload_sidebar(cx),@@ -617,6 +640,10 @@ impl AppState {617
cx.emit(AppEvent::Directory);640
cx.emit(AppEvent::Directory);618
cx.notify();641
cx.notify();619
}642
}643
BackendEvent::Core(CoreEvent::PresenceStatusChanged(status)) => {644
self.apply_own_status(status, cx);645
self.reload_directory();646
}620
BackendEvent::Core(_) => {647
BackendEvent::Core(_) => {621
if !self.mode.demo {648
if !self.mode.demo {622
self.reload_directory();649
self.reload_directory();@@ -8,7 +8,7 @@ macro_rules! symbols {
8
8
};
9
9
}
10
10
11
const SYMBOLS: [(&str, &[u8]); 28] = symbols![
11
const SYMBOLS: [(&str, &[u8]); 32] = symbols![
12
12
"done",
13
13
"done_all",
14
14
"keyboard_return",
@@ -37,6 +37,10 @@ const SYMBOLS: [(&str, &[u8]); 28] = symbols![
37
37
"format_list_numbered",
38
38
"format_quote",
39
39
"mood",
40
"status_dot",
41
"status_dnd",
42
"status_away",
43
"status_ring",
40
44
];
41
45
42
46
pub struct AppAssets;
@@ -8,7 +8,7 @@ macro_rules! symbols {8
};8
};9
}9
}10
10
11
const SYMBOLS: [(&str, &[u8]); 28] = symbols![11
const SYMBOLS: [(&str, &[u8]); 32] = symbols![12
"done",12
"done",13
"done_all",13
"done_all",14
"keyboard_return",14
"keyboard_return",@@ -37,6 +37,10 @@ const SYMBOLS: [(&str, &[u8]); 28] = symbols![37
"format_list_numbered",37
"format_list_numbered",38
"format_quote",38
"format_quote",39
"mood",39
"mood",40
"status_dot",41
"status_dnd",42
"status_away",43
"status_ring",40
];44
];41
45
42
pub struct AppAssets;46
pub struct AppAssets;@@ -217,7 +217,13 @@ async fn realtime_loop(
217
217
receipt_engine.handle_receipt_status(&receipt_status).await
218
218
});
219
219
}
220
RealtimeEvent::Presence(updates) => engine.apply_presence(&updates),
220
RealtimeEvent::Presence(updates) => {
221
engine.apply_presence(&updates);
222
if engine.concerns_me(&updates) {
223
let engine = engine.clone();
224
tokio::spawn(async move { engine.refresh_own_status().await });
225
}
226
}
221
227
RealtimeEvent::Endpoint(endpoint) => {
222
228
let engine = engine.clone();
223
229
tokio::spawn(async move { engine.presence_endpoint(endpoint).await });
@@ -217,7 +217,13 @@ async fn realtime_loop(217
receipt_engine.handle_receipt_status(&receipt_status).await217
receipt_engine.handle_receipt_status(&receipt_status).await218
});218
});219
}219
}220
RealtimeEvent::Presence(updates) => engine.apply_presence(&updates),220
RealtimeEvent::Presence(updates) => {221
engine.apply_presence(&updates);222
if engine.concerns_me(&updates) {223
let engine = engine.clone();224
tokio::spawn(async move { engine.refresh_own_status().await });225
}226
}221
RealtimeEvent::Endpoint(endpoint) => {227
RealtimeEvent::Endpoint(endpoint) => {222
let engine = engine.clone();228
let engine = engine.clone();223
tokio::spawn(async move { engine.presence_endpoint(endpoint).await });229
tokio::spawn(async move { engine.presence_endpoint(endpoint).await });@@ -409,17 +409,21 @@ pub fn unread_counts(engine: &Engine, chats: &[ChatRecord]) -> HashMap<String, u
409
409
.collect()
410
410
}
411
411
412
pub fn presence_kind_of(availability: Availability) -> PresenceKind {
413
match availability {
414
Availability::Available => PresenceKind::Available,
415
Availability::Busy => PresenceKind::Busy,
416
Availability::DoNotDisturb => PresenceKind::DoNotDisturb,
417
Availability::Away => PresenceKind::Away,
418
Availability::Offline => PresenceKind::Offline,
419
Availability::Unknown => PresenceKind::Unknown,
420
}
421
}
422
412
423
pub fn presence_kind(engine: &Engine, user_id: &str) -> Option<PresenceKind> {
413
424
engine
414
425
.presence(user_id)
415
.map(|presence| match presence.availability {
416
Availability::Available => PresenceKind::Available,
417
Availability::Busy => PresenceKind::Busy,
418
Availability::DoNotDisturb => PresenceKind::DoNotDisturb,
419
Availability::Away => PresenceKind::Away,
420
Availability::Offline => PresenceKind::Offline,
421
Availability::Unknown => PresenceKind::Unknown,
422
})
426
.map(|presence| presence_kind_of(presence.availability))
423
427
}
424
428
425
429
pub fn in_call(engine: &Engine, user_id: &str) -> bool {
@@ -409,17 +409,21 @@ pub fn unread_counts(engine: &Engine, chats: &[ChatRecord]) -> HashMap<String, u409
.collect()409
.collect()410
}410
}411
411
412
pub fn presence_kind_of(availability: Availability) -> PresenceKind {413
match availability {414
Availability::Available => PresenceKind::Available,415
Availability::Busy => PresenceKind::Busy,416
Availability::DoNotDisturb => PresenceKind::DoNotDisturb,417
Availability::Away => PresenceKind::Away,418
Availability::Offline => PresenceKind::Offline,419
Availability::Unknown => PresenceKind::Unknown,420
}421
}422
412
pub fn presence_kind(engine: &Engine, user_id: &str) -> Option<PresenceKind> {423
pub fn presence_kind(engine: &Engine, user_id: &str) -> Option<PresenceKind> {413
engine424
engine414
.presence(user_id)425
.presence(user_id)415
.map(|presence| match presence.availability {426
.map(|presence| presence_kind_of(presence.availability))416
Availability::Available => PresenceKind::Available,417
Availability::Busy => PresenceKind::Busy,418
Availability::DoNotDisturb => PresenceKind::DoNotDisturb,419
Availability::Away => PresenceKind::Away,420
Availability::Offline => PresenceKind::Offline,421
Availability::Unknown => PresenceKind::Unknown,422
})423
}427
}424
428
425
pub fn in_call(engine: &Engine, user_id: &str) -> bool {429
pub fn in_call(engine: &Engine, user_id: &str) -> bool {@@ -24,6 +24,7 @@ static SEARCHABLE_GIFS: OnceLock<Vec<Gif>> = OnceLock::new();
24
24
25
25
pub const DEMO_USER_ID: &str = "demo-me";
26
26
const DEMO_USER_NAME: &str = "Dana Demo";
27
const DEMO_USER_EMAIL: &str = "dana.demo@example.com";
27
28
const PHOTO_SIZE: usize = 48;
28
29
const STAGING_IMAGE_KEY: &str = "demo://staging-dashboard";
29
30
const PENDING_IMAGE_KEY: &str = "demo://pending-screenshot";
@@ -99,11 +100,11 @@ const TOBIAS: Palette = Palette {
99
100
shirt: [0x0f, 0x76, 0x6e],
100
101
};
101
102
102
const MARA_ID: &str = "demo-mara";
103
const JONAS_ID: &str = "demo-jonas";
104
const PRIYA_ID: &str = "demo-priya";
105
const LEA_ID: &str = "demo-lea";
106
const TOBIAS_ID: &str = "demo-tobias";
103
pub const MARA_ID: &str = "demo-mara";
104
pub const JONAS_ID: &str = "demo-jonas";
105
pub const PRIYA_ID: &str = "demo-priya";
106
pub const LEA_ID: &str = "demo-lea";
107
pub const TOBIAS_ID: &str = "demo-tobias";
107
108
108
109
const DEMO_TEAMS: [(&str, &str, [&str; 3]); 4] = [
109
110
(
@@ -599,6 +600,8 @@ fn photo(palette: &Palette) -> Arc<Image> {
599
600
}
600
601
601
602
pub fn seed_directory(state: &mut AppState) {
603
state.own_status = crate::own_status::demo_status();
604
state.own_email = DEMO_USER_EMAIL.to_owned();
602
605
let directory = &mut state.directory;
603
606
directory.me = Some(Person {
604
607
user_id: DEMO_USER_ID.to_owned(),
@@ -24,6 +24,7 @@ static SEARCHABLE_GIFS: OnceLock<Vec<Gif>> = OnceLock::new();24
24
25
pub const DEMO_USER_ID: &str = "demo-me";25
pub const DEMO_USER_ID: &str = "demo-me";26
const DEMO_USER_NAME: &str = "Dana Demo";26
const DEMO_USER_NAME: &str = "Dana Demo";27
const DEMO_USER_EMAIL: &str = "dana.demo@example.com";27
const PHOTO_SIZE: usize = 48;28
const PHOTO_SIZE: usize = 48;28
const STAGING_IMAGE_KEY: &str = "demo://staging-dashboard";29
const STAGING_IMAGE_KEY: &str = "demo://staging-dashboard";29
const PENDING_IMAGE_KEY: &str = "demo://pending-screenshot";30
const PENDING_IMAGE_KEY: &str = "demo://pending-screenshot";@@ -99,11 +100,11 @@ const TOBIAS: Palette = Palette {99
shirt: [0x0f, 0x76, 0x6e],100
shirt: [0x0f, 0x76, 0x6e],100
};101
};101
102
102
const MARA_ID: &str = "demo-mara";103
pub const MARA_ID: &str = "demo-mara";103
const JONAS_ID: &str = "demo-jonas";104
pub const JONAS_ID: &str = "demo-jonas";104
const PRIYA_ID: &str = "demo-priya";105
pub const PRIYA_ID: &str = "demo-priya";105
const LEA_ID: &str = "demo-lea";106
pub const LEA_ID: &str = "demo-lea";106
const TOBIAS_ID: &str = "demo-tobias";107
pub const TOBIAS_ID: &str = "demo-tobias";107
108
108
const DEMO_TEAMS: [(&str, &str, [&str; 3]); 4] = [109
const DEMO_TEAMS: [(&str, &str, [&str; 3]); 4] = [109
(110
(@@ -599,6 +600,8 @@ fn photo(palette: &Palette) -> Arc<Image> {599
}600
}600
601
601
pub fn seed_directory(state: &mut AppState) {602
pub fn seed_directory(state: &mut AppState) {603
state.own_status = crate::own_status::demo_status();604
state.own_email = DEMO_USER_EMAIL.to_owned();602
let directory = &mut state.directory;605
let directory = &mut state.directory;603
directory.me = Some(Person {606
directory.me = Some(Person {604
user_id: DEMO_USER_ID.to_owned(),607
user_id: DEMO_USER_ID.to_owned(),@@ -0,0 +1,180 @@
1
use std::sync::atomic::{AtomicBool, Ordering};
2
use std::time::Duration;
3
4
use teams_core::{
5
Availability, OrgPerson, PersonProfile, WorkLocation, WorkLocationKind, WorkLocationSource,
6
};
7
8
use crate::demo::{DEMO_USER_ID, JONAS_ID, LEA_ID, MARA_ID, PRIYA_ID, TOBIAS_ID};
9
10
const DELAY_VARIABLE: &str = "TEAMS_DEMO_PROFILE_DELAY_MS";
11
const DEFAULT_DELAY: Duration = Duration::from_millis(500);
12
const HENRIK_ID: &str = "demo-henrik";
13
const SOFIA_ID: &str = "demo-sofia";
14
const OMAR_ID: &str = "demo-omar";
15
const LONG_STATUS: &str = "Heads down on the Q4 roadmap review until Thursday. Please use the Product channel for anything that can wait and call my mobile only for production incidents. Back to normal office hours next week, and I will answer open threads then.";
16
const OUT_OF_OFFICE: &str = "I am out of office until 20 October with limited access to email. For urgent customer matters please contact Tobias Klein.";
17
18
static TOBIAS_FAILED_ONCE: AtomicBool = AtomicBool::new(false);
19
20
fn person(id: &str, name: &str, title: &str) -> OrgPerson {
21
OrgPerson {
22
id: id.to_owned(),
23
display_name: Some(name.to_owned()),
24
job_title: Some(title.to_owned()),
25
}
26
}
27
28
fn base(id: &str, name: &str, title: &str, department: &str) -> PersonProfile {
29
let address = name.to_lowercase().replace(' ', ".");
30
PersonProfile {
31
user_id: id.to_owned(),
32
display_name: Some(name.to_owned()),
33
job_title: Some(title.to_owned()),
34
department: Some(department.to_owned()),
35
company: Some("Example Corp".to_owned()),
36
office_location: Some("Berlin, Building A".to_owned()),
37
email: Some(format!("{address}@example.com")),
38
work_phones: vec!["+49 30 5550 1000".to_owned()],
39
mobile_phone: Some("+49 151 5550 2000".to_owned()),
40
manager: None,
41
direct_reports: Vec::new(),
42
time_zone: Some("W. Europe Standard Time".to_owned()),
43
availability: Some(Availability::Available),
44
status_message: None,
45
out_of_office: None,
46
work_location: None,
47
}
48
}
49
50
fn henrik() -> OrgPerson {
51
person(HENRIK_ID, "Henrik Vogt", "VP Engineering")
52
}
53
54
fn priya() -> OrgPerson {
55
person(PRIYA_ID, "Priya Nair", "Engineering Manager")
56
}
57
58
pub fn profile(user_id: &str) -> Option<PersonProfile> {
59
Some(match user_id {
60
MARA_ID => PersonProfile {
61
manager: Some(henrik()),
62
availability: Some(Availability::Busy),
63
status_message: Some(LONG_STATUS.to_owned()),
64
work_location: Some(WorkLocation {
65
kind: WorkLocationKind::Office,
66
source: WorkLocationSource::Set,
67
}),
68
..base(MARA_ID, "Mara Lindqvist", "Product Owner", "Product")
69
},
70
JONAS_ID => PersonProfile {
71
manager: Some(priya()),
72
work_phones: Vec::new(),
73
..base(JONAS_ID, "Jonas Ortega", "Backend Engineer", "Engineering")
74
},
75
PRIYA_ID => PersonProfile {
76
manager: Some(henrik()),
77
direct_reports: vec![
78
person(JONAS_ID, "Jonas Ortega", "Backend Engineer"),
79
person(TOBIAS_ID, "Tobias Klein", "Support Engineer"),
80
person(DEMO_USER_ID, "Dana Demo", "Software Engineer"),
81
person(SOFIA_ID, "Sofia Marin", "QA Engineer"),
82
],
83
availability: Some(Availability::DoNotDisturb),
84
status_message: Some("In the planning meeting, back at 3".to_owned()),
85
time_zone: Some("Pacific Standard Time".to_owned()),
86
..base(PRIYA_ID, "Priya Nair", "Engineering Manager", "Engineering")
87
},
88
LEA_ID => PersonProfile {
89
manager: Some(person(OMAR_ID, "Omar Haddad", "Head of Customer Success")),
90
availability: Some(Availability::Offline),
91
out_of_office: Some(OUT_OF_OFFICE.to_owned()),
92
time_zone: Some("GMT Standard Time".to_owned()),
93
mobile_phone: None,
94
..base(
95
LEA_ID,
96
"Lea Schneider",
97
"Customer Success Manager",
98
"Customer Success",
99
)
100
},
101
TOBIAS_ID => PersonProfile {
102
manager: Some(priya()),
103
availability: Some(Availability::Away),
104
work_location: Some(WorkLocation {
105
kind: WorkLocationKind::Remote,
106
source: WorkLocationSource::Set,
107
}),
108
time_zone: Some("AUS Eastern Standard Time".to_owned()),
109
office_location: None,
110
..base(
111
TOBIAS_ID,
112
"Tobias Klein",
113
"Support Engineer",
114
"Customer Success",
115
)
116
},
117
DEMO_USER_ID => PersonProfile {
118
manager: Some(priya()),
119
..base(
120
DEMO_USER_ID,
121
"Dana Demo",
122
"Software Engineer",
123
"Engineering",
124
)
125
},
126
HENRIK_ID => PersonProfile {
127
direct_reports: vec![priya(), person(MARA_ID, "Mara Lindqvist", "Product Owner")],
128
..base(HENRIK_ID, "Henrik Vogt", "VP Engineering", "Engineering")
129
},
130
SOFIA_ID => PersonProfile {
131
manager: Some(priya()),
132
..base(SOFIA_ID, "Sofia Marin", "QA Engineer", "Engineering")
133
},
134
OMAR_ID => PersonProfile {
135
direct_reports: vec![person(LEA_ID, "Lea Schneider", "Customer Success Manager")],
136
..base(
137
OMAR_ID,
138
"Omar Haddad",
139
"Head of Customer Success",
140
"Customer Success",
141
)
142
},
143
_ => return None,
144
})
145
}
146
147
pub async fn load(user_id: String) -> Result<PersonProfile, String> {
148
tokio::time::sleep(delay()).await;
149
if user_id == TOBIAS_ID && !TOBIAS_FAILED_ONCE.swap(true, Ordering::SeqCst) {
150
return Err("demo failure".to_owned());
151
}
152
profile(&user_id).ok_or_else(|| "unknown demo person".to_owned())
153
}
154
155
fn delay() -> Duration {
156
std::env::var(DELAY_VARIABLE)
157
.ok()
158
.and_then(|value| value.parse().ok())
159
.map_or(DEFAULT_DELAY, Duration::from_millis)
160
}
161
162
#[cfg(test)]
163
mod tests {
164
use super::*;
165
166
#[test]
167
fn every_demo_person_has_a_profile() {
168
let ids = [MARA_ID, JONAS_ID, PRIYA_ID, LEA_ID, TOBIAS_ID, DEMO_USER_ID];
169
for id in ids {
170
let profile = profile(id).expect("demo profile");
171
assert_eq!(profile.user_id, id);
172
}
173
}
174
175
#[test]
176
fn one_person_is_out_of_office_and_one_has_a_long_message() {
177
assert!(profile(LEA_ID).unwrap().out_of_office.is_some());
178
assert!(profile(MARA_ID).unwrap().status_message.unwrap().len() > 200);
179
}
180
}
@@ -0,0 +1,180 @@1
use std::sync::atomic::{AtomicBool, Ordering};2
use std::time::Duration;3
4
use teams_core::{5
Availability, OrgPerson, PersonProfile, WorkLocation, WorkLocationKind, WorkLocationSource,6
};7
8
use crate::demo::{DEMO_USER_ID, JONAS_ID, LEA_ID, MARA_ID, PRIYA_ID, TOBIAS_ID};9
10
const DELAY_VARIABLE: &str = "TEAMS_DEMO_PROFILE_DELAY_MS";11
const DEFAULT_DELAY: Duration = Duration::from_millis(500);12
const HENRIK_ID: &str = "demo-henrik";13
const SOFIA_ID: &str = "demo-sofia";14
const OMAR_ID: &str = "demo-omar";15
const LONG_STATUS: &str = "Heads down on the Q4 roadmap review until Thursday. Please use the Product channel for anything that can wait and call my mobile only for production incidents. Back to normal office hours next week, and I will answer open threads then.";16
const OUT_OF_OFFICE: &str = "I am out of office until 20 October with limited access to email. For urgent customer matters please contact Tobias Klein.";17
18
static TOBIAS_FAILED_ONCE: AtomicBool = AtomicBool::new(false);19
20
fn person(id: &str, name: &str, title: &str) -> OrgPerson {21
OrgPerson {22
id: id.to_owned(),23
display_name: Some(name.to_owned()),24
job_title: Some(title.to_owned()),25
}26
}27
28
fn base(id: &str, name: &str, title: &str, department: &str) -> PersonProfile {29
let address = name.to_lowercase().replace(' ', ".");30
PersonProfile {31
user_id: id.to_owned(),32
display_name: Some(name.to_owned()),33
job_title: Some(title.to_owned()),34
department: Some(department.to_owned()),35
company: Some("Example Corp".to_owned()),36
office_location: Some("Berlin, Building A".to_owned()),37
email: Some(format!("{address}@example.com")),38
work_phones: vec!["+49 30 5550 1000".to_owned()],39
mobile_phone: Some("+49 151 5550 2000".to_owned()),40
manager: None,41
direct_reports: Vec::new(),42
time_zone: Some("W. Europe Standard Time".to_owned()),43
availability: Some(Availability::Available),44
status_message: None,45
out_of_office: None,46
work_location: None,47
}48
}49
50
fn henrik() -> OrgPerson {51
person(HENRIK_ID, "Henrik Vogt", "VP Engineering")52
}53
54
fn priya() -> OrgPerson {55
person(PRIYA_ID, "Priya Nair", "Engineering Manager")56
}57
58
pub fn profile(user_id: &str) -> Option<PersonProfile> {59
Some(match user_id {60
MARA_ID => PersonProfile {61
manager: Some(henrik()),62
availability: Some(Availability::Busy),63
status_message: Some(LONG_STATUS.to_owned()),64
work_location: Some(WorkLocation {65
kind: WorkLocationKind::Office,66
source: WorkLocationSource::Set,67
}),68
..base(MARA_ID, "Mara Lindqvist", "Product Owner", "Product")69
},70
JONAS_ID => PersonProfile {71
manager: Some(priya()),72
work_phones: Vec::new(),73
..base(JONAS_ID, "Jonas Ortega", "Backend Engineer", "Engineering")74
},75
PRIYA_ID => PersonProfile {76
manager: Some(henrik()),77
direct_reports: vec![78
person(JONAS_ID, "Jonas Ortega", "Backend Engineer"),79
person(TOBIAS_ID, "Tobias Klein", "Support Engineer"),80
person(DEMO_USER_ID, "Dana Demo", "Software Engineer"),81
person(SOFIA_ID, "Sofia Marin", "QA Engineer"),82
],83
availability: Some(Availability::DoNotDisturb),84
status_message: Some("In the planning meeting, back at 3".to_owned()),85
time_zone: Some("Pacific Standard Time".to_owned()),86
..base(PRIYA_ID, "Priya Nair", "Engineering Manager", "Engineering")87
},88
LEA_ID => PersonProfile {89
manager: Some(person(OMAR_ID, "Omar Haddad", "Head of Customer Success")),90
availability: Some(Availability::Offline),91
out_of_office: Some(OUT_OF_OFFICE.to_owned()),92
time_zone: Some("GMT Standard Time".to_owned()),93
mobile_phone: None,94
..base(95
LEA_ID,96
"Lea Schneider",97
"Customer Success Manager",98
"Customer Success",99
)100
},101
TOBIAS_ID => PersonProfile {102
manager: Some(priya()),103
availability: Some(Availability::Away),104
work_location: Some(WorkLocation {105
kind: WorkLocationKind::Remote,106
source: WorkLocationSource::Set,107
}),108
time_zone: Some("AUS Eastern Standard Time".to_owned()),109
office_location: None,110
..base(111
TOBIAS_ID,112
"Tobias Klein",113
"Support Engineer",114
"Customer Success",115
)116
},117
DEMO_USER_ID => PersonProfile {118
manager: Some(priya()),119
..base(120
DEMO_USER_ID,121
"Dana Demo",122
"Software Engineer",123
"Engineering",124
)125
},126
HENRIK_ID => PersonProfile {127
direct_reports: vec![priya(), person(MARA_ID, "Mara Lindqvist", "Product Owner")],128
..base(HENRIK_ID, "Henrik Vogt", "VP Engineering", "Engineering")129
},130
SOFIA_ID => PersonProfile {131
manager: Some(priya()),132
..base(SOFIA_ID, "Sofia Marin", "QA Engineer", "Engineering")133
},134
OMAR_ID => PersonProfile {135
direct_reports: vec![person(LEA_ID, "Lea Schneider", "Customer Success Manager")],136
..base(137
OMAR_ID,138
"Omar Haddad",139
"Head of Customer Success",140
"Customer Success",141
)142
},143
_ => return None,144
})145
}146
147
pub async fn load(user_id: String) -> Result<PersonProfile, String> {148
tokio::time::sleep(delay()).await;149
if user_id == TOBIAS_ID && !TOBIAS_FAILED_ONCE.swap(true, Ordering::SeqCst) {150
return Err("demo failure".to_owned());151
}152
profile(&user_id).ok_or_else(|| "unknown demo person".to_owned())153
}154
155
fn delay() -> Duration {156
std::env::var(DELAY_VARIABLE)157
.ok()158
.and_then(|value| value.parse().ok())159
.map_or(DEFAULT_DELAY, Duration::from_millis)160
}161
162
#[cfg(test)]163
mod tests {164
use super::*;165
166
#[test]167
fn every_demo_person_has_a_profile() {168
let ids = [MARA_ID, JONAS_ID, PRIYA_ID, LEA_ID, TOBIAS_ID, DEMO_USER_ID];169
for id in ids {170
let profile = profile(id).expect("demo profile");171
assert_eq!(profile.user_id, id);172
}173
}174
175
#[test]176
fn one_person_is_out_of_office_and_one_has_a_long_message() {177
assert!(profile(LEA_ID).unwrap().out_of_office.is_some());178
assert!(profile(MARA_ID).unwrap().status_message.unwrap().len() > 200);179
}180
}@@ -20,6 +20,7 @@ mod demo_cards;
20
20
mod demo_chart_cards;
21
21
mod demo_gifs;
22
22
mod demo_input_cards;
23
mod demo_profiles;
23
24
mod downloads;
24
25
mod emoji;
25
26
mod format;
@@ -29,10 +30,13 @@ mod gifs;
29
30
mod local_previews;
30
31
mod message_actions;
31
32
mod notice;
33
mod own_status;
32
34
mod notify;
33
35
mod outbox;
34
36
mod pending_rows;
35
37
mod people;
38
mod profile_model;
39
mod profile_state;
36
40
mod reaction_model;
37
41
mod read_state;
38
42
mod remote_image;
@@ -20,6 +20,7 @@ mod demo_cards;20
mod demo_chart_cards;20
mod demo_chart_cards;21
mod demo_gifs;21
mod demo_gifs;22
mod demo_input_cards;22
mod demo_input_cards;23
mod demo_profiles;23
mod downloads;24
mod downloads;24
mod emoji;25
mod emoji;25
mod format;26
mod format;@@ -29,10 +30,13 @@ mod gifs;29
mod local_previews;30
mod local_previews;30
mod message_actions;31
mod message_actions;31
mod notice;32
mod notice;33
mod own_status;32
mod notify;34
mod notify;33
mod outbox;35
mod outbox;34
mod pending_rows;36
mod pending_rows;35
mod people;37
mod people;38
mod profile_model;39
mod profile_state;36
mod reaction_model;40
mod reaction_model;37
mod read_state;41
mod read_state;38
mod remote_image;42
mod remote_image;@@ -0,0 +1,621 @@
1
use std::sync::Arc;
2
3
use chrono::{DateTime, Datelike, Duration, NaiveTime, TimeZone, Utc};
4
use gpui_kit::*;
5
use teams_core::{
6
ForcedAvailability, ForcedKind, PresenceStatus, StatusNote, WorkLocation, WorkLocationKind,
7
WorkLocationSource,
8
};
9
10
use crate::app_state::{AppEvent, AppState};
11
use crate::backend::Engine;
12
use crate::data::PresenceKind;
13
14
pub const NOTE_LIMIT: usize = 280;
15
const WORK_LOCATION_FAILED: &str = "Work location couldn't be set. Try again.";
16
pub const STATUS_CHOICES: [ForcedKind; 6] = [
17
ForcedKind::Available,
18
ForcedKind::Busy,
19
ForcedKind::DoNotDisturb,
20
ForcedKind::BeRightBack,
21
ForcedKind::Away,
22
ForcedKind::Offline,
23
];
24
pub const STATUS_DURATIONS: [StatusDuration; 5] = [
25
StatusDuration::HalfHour,
26
StatusDuration::OneHour,
27
StatusDuration::TwoHours,
28
StatusDuration::Today,
29
StatusDuration::ThisWeek,
30
];
31
pub const NOTE_DURATIONS: [NoteDuration; 5] = [
32
NoteDuration::Never,
33
NoteDuration::OneHour,
34
NoteDuration::FourHours,
35
NoteDuration::Today,
36
NoteDuration::ThisWeek,
37
];
38
39
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
40
pub enum StatusDuration {
41
HalfHour,
42
OneHour,
43
TwoHours,
44
Today,
45
ThisWeek,
46
}
47
48
impl StatusDuration {
49
pub fn label(self) -> &'static str {
50
match self {
51
StatusDuration::HalfHour => "30 minutes",
52
StatusDuration::OneHour => "1 hour",
53
StatusDuration::TwoHours => "2 hours",
54
StatusDuration::Today => "Today",
55
StatusDuration::ThisWeek => "This week",
56
}
57
}
58
59
pub fn expires_at<Zone: TimeZone>(self, now: DateTime<Zone>) -> DateTime<Utc> {
60
match self {
61
StatusDuration::HalfHour => after(&now, Duration::minutes(30)),
62
StatusDuration::OneHour => after(&now, Duration::hours(1)),
63
StatusDuration::TwoHours => after(&now, Duration::hours(2)),
64
StatusDuration::Today => end_of_day(&now),
65
StatusDuration::ThisWeek => end_of_week(&now),
66
}
67
}
68
}
69
70
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
71
pub enum NoteDuration {
72
Never,
73
OneHour,
74
FourHours,
75
Today,
76
ThisWeek,
77
}
78
79
impl NoteDuration {
80
pub const DEFAULT: NoteDuration = NoteDuration::Today;
81
82
pub fn label(self) -> &'static str {
83
match self {
84
NoteDuration::Never => "Never",
85
NoteDuration::OneHour => "1 hour",
86
NoteDuration::FourHours => "4 hours",
87
NoteDuration::Today => "Today",
88
NoteDuration::ThisWeek => "This week",
89
}
90
}
91
92
pub fn expires_at<Zone: TimeZone>(self, now: DateTime<Zone>) -> Option<DateTime<Utc>> {
93
match self {
94
NoteDuration::Never => None,
95
NoteDuration::OneHour => Some(after(&now, Duration::hours(1))),
96
NoteDuration::FourHours => Some(after(&now, Duration::hours(4))),
97
NoteDuration::Today => Some(end_of_day(&now)),
98
NoteDuration::ThisWeek => Some(end_of_week(&now)),
99
}
100
}
101
}
102
103
fn after<Zone: TimeZone>(now: &DateTime<Zone>, span: Duration) -> DateTime<Utc> {
104
(now.clone() + span).with_timezone(&Utc)
105
}
106
107
fn end_of_local_date<Zone: TimeZone>(now: &DateTime<Zone>, days_ahead: i64) -> DateTime<Utc> {
108
let last_moment = NaiveTime::from_hms_milli_opt(23, 59, 59, 999).unwrap_or(NaiveTime::MIN);
109
let date = now.date_naive() + Duration::days(days_ahead);
110
now.timezone()
111
.from_local_datetime(&date.and_time(last_moment))
112
.latest()
113
.map_or_else(
114
|| after(now, Duration::days(days_ahead + 1)),
115
|moment| moment.with_timezone(&Utc),
116
)
117
}
118
119
pub fn end_of_day<Zone: TimeZone>(now: &DateTime<Zone>) -> DateTime<Utc> {
120
end_of_local_date(now, 0)
121
}
122
123
pub fn end_of_week<Zone: TimeZone>(now: &DateTime<Zone>) -> DateTime<Utc> {
124
let days_since_sunday = i64::from(now.weekday().num_days_from_sunday());
125
end_of_local_date(now, 6 - days_since_sunday)
126
}
127
128
pub fn choice_label(kind: ForcedKind) -> &'static str {
129
match kind {
130
ForcedKind::Away => "Appear away",
131
ForcedKind::Offline => "Appear offline",
132
other => state_label(other),
133
}
134
}
135
136
pub fn state_label(kind: ForcedKind) -> &'static str {
137
match kind {
138
ForcedKind::Available => "Available",
139
ForcedKind::Busy => "Busy",
140
ForcedKind::DoNotDisturb => "Do not disturb",
141
ForcedKind::BeRightBack => "Be right back",
142
ForcedKind::Away => "Away",
143
ForcedKind::Offline => "Offline",
144
}
145
}
146
147
pub fn presence_kind_for(kind: ForcedKind) -> PresenceKind {
148
match kind {
149
ForcedKind::Available => PresenceKind::Available,
150
ForcedKind::Busy => PresenceKind::Busy,
151
ForcedKind::DoNotDisturb => PresenceKind::DoNotDisturb,
152
ForcedKind::BeRightBack | ForcedKind::Away => PresenceKind::Away,
153
ForcedKind::Offline => PresenceKind::Offline,
154
}
155
}
156
157
pub fn until_label<Zone: TimeZone>(expires_at: DateTime<Utc>, now: &DateTime<Zone>) -> String
158
where
159
Zone::Offset: std::fmt::Display,
160
{
161
let local = expires_at.with_timezone(&now.timezone());
162
if local.date_naive() == now.date_naive() {
163
format!("until {}", local.format("%H:%M"))
164
} else {
165
format!("until {}", local.format("%a %H:%M"))
166
}
167
}
168
169
#[derive(Debug, Clone, PartialEq, Eq)]
170
pub struct StateSummary {
171
pub label: &'static str,
172
pub presence: PresenceKind,
173
pub until: Option<String>,
174
}
175
176
pub fn state_summary<Zone: TimeZone>(
177
status: &PresenceStatus,
178
live: PresenceKind,
179
now: &DateTime<Zone>,
180
) -> StateSummary
181
where
182
Zone::Offset: std::fmt::Display,
183
{
184
match status.forced {
185
Some(forced) => StateSummary {
186
label: state_label(forced.kind),
187
presence: presence_kind_for(forced.kind),
188
until: forced
189
.expires_at
190
.map(|expires_at| until_label(expires_at, now)),
191
},
192
None => StateSummary {
193
label: match live.label() {
194
"" => "Set status",
195
label => label,
196
},
197
presence: live,
198
until: None,
199
},
200
}
201
}
202
203
pub fn duration_target(status: &PresenceStatus) -> Option<ForcedKind> {
204
status
205
.forced
206
.map(|forced| forced.kind)
207
.filter(|kind| *kind != ForcedKind::Available)
208
}
209
210
pub fn with_forced(status: &PresenceStatus, forced: Option<ForcedAvailability>) -> PresenceStatus {
211
let availability = match forced {
212
Some(forced) => forced.kind.code().to_owned(),
213
None => status.availability.clone(),
214
};
215
PresenceStatus {
216
availability,
217
forced,
218
..status.clone()
219
}
220
}
221
222
pub fn with_note(status: &PresenceStatus, note: Option<StatusNote>) -> PresenceStatus {
223
PresenceStatus {
224
note,
225
..status.clone()
226
}
227
}
228
229
pub fn work_location_label(location: Option<WorkLocation>) -> &'static str {
230
match location {
231
None => "Set work location",
232
Some(WorkLocation {
233
kind: WorkLocationKind::Office,
234
source: WorkLocationSource::Set,
235
}) => "In the office",
236
Some(WorkLocation {
237
kind: WorkLocationKind::Office,
238
source: WorkLocationSource::Scheduled,
239
}) => "Planned in the office",
240
Some(WorkLocation {
241
kind: WorkLocationKind::Office,
242
source: WorkLocationSource::Verified,
243
}) => "Checked in to the office",
244
Some(WorkLocation {
245
kind: WorkLocationKind::Remote,
246
source: WorkLocationSource::Scheduled,
247
}) => "Planned to work remotely",
248
Some(WorkLocation {
249
kind: WorkLocationKind::Remote,
250
..
251
}) => "Working remotely",
252
}
253
}
254
255
pub fn with_work_location(
256
status: &PresenceStatus,
257
work_location: Option<WorkLocation>,
258
) -> PresenceStatus {
259
PresenceStatus {
260
work_location,
261
..status.clone()
262
}
263
}
264
265
pub fn clamp_note(text: &str) -> String {
266
text.chars().take(NOTE_LIMIT).collect()
267
}
268
269
pub fn demo_status() -> PresenceStatus {
270
PresenceStatus {
271
availability: "Available".to_owned(),
272
..PresenceStatus::default()
273
}
274
}
275
276
impl AppState {
277
pub fn own_presence_kind(&self) -> PresenceKind {
278
match &self.directory.me {
279
Some(me) => self.directory.presence_of(&me.user_id).kind(),
280
None => PresenceKind::Unknown,
281
}
282
}
283
284
pub fn set_status_menu_open(&mut self, open: bool, cx: &mut Context<Self>) {
285
if self.status_menu_open != open {
286
self.status_menu_open = open;
287
cx.notify();
288
}
289
}
290
291
pub fn request_status_message(&mut self, cx: &mut Context<Self>) {
292
self.status_message_request = true;
293
cx.emit(AppEvent::StatusMessage);
294
cx.notify();
295
}
296
297
pub fn take_status_message_request(&mut self) -> bool {
298
std::mem::take(&mut self.status_message_request)
299
}
300
301
pub fn open_notification_settings(&mut self, cx: &mut Context<Self>) {
302
cx.emit(AppEvent::NotificationSettings);
303
}
304
305
pub fn refresh_own_status(&mut self, cx: &mut Context<Self>) {
306
let Some(engine) = self.engine.clone().filter(|_| !self.mode.demo) else {
307
return;
308
};
309
drop(crate::runtime::spawn(async move {
310
engine.refresh_own_status().await
311
}));
312
cx.notify();
313
}
314
315
pub fn apply_own_status(&mut self, status: PresenceStatus, cx: &mut Context<Self>) {
316
self.own_status = status;
317
cx.emit(AppEvent::Directory);
318
cx.notify();
319
}
320
321
pub fn set_own_availability(
322
&mut self,
323
forced: Option<ForcedAvailability>,
324
cx: &mut Context<Self>,
325
) {
326
let Some(engine_or_demo) = self.own_status_engine(cx) else {
327
return;
328
};
329
let previous_status = self.own_status.clone();
330
let previous_presence = self.own_presence_kind();
331
self.own_status = with_forced(&previous_status, forced);
332
if let Some(forced) = forced {
333
self.show_own_presence(presence_kind_for(forced.kind), cx);
334
}
335
let Some(engine) = engine_or_demo else {
336
return;
337
};
338
self.run_chat_action(
339
"Status",
340
async move { engine.set_own_availability(forced).await },
341
move |state, cx| {
342
state.own_status = previous_status;
343
state.show_own_presence(previous_presence, cx);
344
},
345
|_, _| {},
346
cx,
347
);
348
}
349
350
pub fn set_own_status_note(&mut self, note: Option<StatusNote>, cx: &mut Context<Self>) {
351
let Some(engine_or_demo) = self.own_status_engine(cx) else {
352
return;
353
};
354
let previous_status = self.own_status.clone();
355
self.own_status = with_note(&previous_status, note.clone());
356
cx.emit(AppEvent::Directory);
357
cx.notify();
358
let Some(engine) = engine_or_demo else {
359
return;
360
};
361
self.run_chat_action(
362
"Status message",
363
async move { engine.set_own_status_note(note).await },
364
move |state, cx| {
365
state.own_status = previous_status;
366
cx.emit(AppEvent::Directory);
367
cx.notify();
368
},
369
|_, _| {},
370
cx,
371
);
372
}
373
374
pub fn set_own_work_location(
375
&mut self,
376
kind: Option<WorkLocationKind>,
377
cx: &mut Context<Self>,
378
) {
379
let Some(engine_or_demo) = self.own_status_engine(cx) else {
380
return;
381
};
382
let previous_status = self.own_status.clone();
383
let optimistic = kind.map(|kind| WorkLocation {
384
kind,
385
source: WorkLocationSource::Set,
386
});
387
self.own_status = with_work_location(&previous_status, optimistic);
388
cx.emit(AppEvent::Directory);
389
cx.notify();
390
let Some(engine) = engine_or_demo else {
391
return;
392
};
393
let location = kind.map(|kind| (kind, end_of_day(&chrono::Local::now())));
394
let receiver =
395
crate::runtime::spawn(async move { engine.set_own_work_location(location).await });
396
cx.spawn(async move |this, cx| {
397
let succeeded = matches!(receiver.await, Ok(Ok(())));
398
this.update(cx, |state, cx| {
399
if succeeded {
400
return;
401
}
402
state.own_status = previous_status;
403
state.raise_notice(WORK_LOCATION_FAILED.to_owned(), None, cx);
404
})
405
.ok();
406
})
407
.detach();
408
}
409
410
fn show_own_presence(&mut self, kind: PresenceKind, cx: &mut Context<Self>) {
411
if let Some(me) = self
412
.directory
413
.me
414
.clone()
415
.filter(|_| kind != PresenceKind::Unknown)
416
{
417
self.directory.set_presence(&me.user_id, kind);
418
}
419
cx.emit(AppEvent::Directory);
420
cx.notify();
421
}
422
423
fn own_status_engine(&mut self, cx: &mut Context<Self>) -> Option<Option<Arc<Engine>>> {
424
if self.mode.read_only {
425
self.raise_notice("Read-only mode: status not changed".to_owned(), None, cx);
426
return None;
427
}
428
match self.engine.clone() {
429
Some(engine) => Some(Some(engine)),
430
None if self.mode.demo => Some(None),
431
None => None,
432
}
433
}
434
}
435
436
#[cfg(test)]
437
mod tests {
438
use chrono::{DateTime, Duration, FixedOffset, TimeZone, Utc};
439
use teams_core::{
440
ForcedAvailability, ForcedKind, PresenceStatus, WorkLocation, WorkLocationKind,
441
WorkLocationSource,
442
};
443
444
use super::{
445
NOTE_LIMIT, NoteDuration, STATUS_CHOICES, StateSummary, StatusDuration, choice_label,
446
clamp_note, duration_target, end_of_day, end_of_week, state_summary, until_label,
447
with_forced, work_location_label,
448
};
449
use crate::data::PresenceKind;
450
451
fn zone() -> FixedOffset {
452
FixedOffset::east_opt(2 * 3600).unwrap()
453
}
454
455
fn local(day: u32, hour: u32, minute: u32) -> DateTime<FixedOffset> {
456
zone()
457
.with_ymd_and_hms(2026, 10, day, hour, minute, 0)
458
.unwrap()
459
}
460
461
fn utc(day: u32, hour: u32, minute: u32, second: u32) -> DateTime<Utc> {
462
Utc.with_ymd_and_hms(2026, 10, day, hour, minute, second)
463
.unwrap()
464
}
465
466
#[test]
467
fn relative_durations_add_to_now() {
468
let now = local(9, 14, 0);
469
assert_eq!(StatusDuration::HalfHour.expires_at(now), utc(9, 12, 30, 0));
470
assert_eq!(StatusDuration::OneHour.expires_at(now), utc(9, 13, 0, 0));
471
assert_eq!(StatusDuration::TwoHours.expires_at(now), utc(9, 14, 0, 0));
472
assert_eq!(
473
NoteDuration::FourHours.expires_at(now),
474
Some(utc(9, 16, 0, 0))
475
);
476
assert_eq!(
477
NoteDuration::OneHour.expires_at(now),
478
Some(utc(9, 13, 0, 0))
479
);
480
assert_eq!(NoteDuration::Never.expires_at(now), None);
481
}
482
483
#[test]
484
fn today_ends_at_local_midnight() {
485
let expected = utc(9, 21, 59, 59) + Duration::milliseconds(999);
486
assert_eq!(StatusDuration::Today.expires_at(local(9, 14, 0)), expected);
487
assert_eq!(
488
NoteDuration::Today.expires_at(local(9, 0, 5)),
489
Some(expected)
490
);
491
}
492
493
#[test]
494
fn today_uses_the_local_date_not_the_utc_date() {
495
let now = local(10, 0, 30);
496
let expected = utc(10, 21, 59, 59) + Duration::milliseconds(999);
497
assert_eq!(end_of_day(&now), expected);
498
}
499
500
#[test]
501
fn week_ends_saturday_night_with_sunday_as_first_day() {
502
let saturday = utc(10, 21, 59, 59) + Duration::milliseconds(999);
503
let friday = local(9, 14, 0);
504
assert_eq!(StatusDuration::ThisWeek.expires_at(friday), saturday);
505
assert_eq!(end_of_week(&local(10, 8, 0)), saturday);
506
assert_eq!(end_of_week(&local(4, 8, 0)), saturday);
507
let next_saturday = utc(17, 21, 59, 59) + Duration::milliseconds(999);
508
assert_eq!(end_of_week(&local(11, 8, 0)), next_saturday);
509
}
510
511
#[test]
512
fn until_label_shows_the_time_today_and_the_day_later() {
513
let now = local(9, 14, 0);
514
assert_eq!(until_label(utc(9, 13, 30, 0), &now), "until 15:30");
515
assert_eq!(until_label(utc(10, 13, 30, 0), &now), "until Sat 15:30");
516
}
517
518
#[test]
519
fn forced_state_wins_over_the_live_presence_in_the_summary() {
520
let now = local(9, 14, 0);
521
let status = PresenceStatus {
522
forced: Some(ForcedAvailability {
523
kind: ForcedKind::DoNotDisturb,
524
expires_at: Some(utc(9, 13, 30, 0)),
525
}),
526
..PresenceStatus::default()
527
};
528
assert_eq!(
529
state_summary(&status, PresenceKind::Available, &now),
530
StateSummary {
531
label: "Do not disturb",
532
presence: PresenceKind::DoNotDisturb,
533
until: Some("until 15:30".into()),
534
}
535
);
536
let automatic = state_summary(&PresenceStatus::default(), PresenceKind::Away, &now);
537
assert_eq!(automatic.label, "Away");
538
assert_eq!(automatic.until, None);
539
let unknown = state_summary(&PresenceStatus::default(), PresenceKind::Unknown, &now);
540
assert_eq!(unknown.label, "Set status");
541
}
542
543
#[test]
544
fn duration_needs_a_forced_state_other_than_available() {
545
let forced = |kind| PresenceStatus {
546
forced: Some(ForcedAvailability {
547
kind,
548
expires_at: None,
549
}),
550
..PresenceStatus::default()
551
};
552
assert_eq!(duration_target(&PresenceStatus::default()), None);
553
assert_eq!(duration_target(&forced(ForcedKind::Available)), None);
554
assert_eq!(
555
duration_target(&forced(ForcedKind::Busy)),
556
Some(ForcedKind::Busy)
557
);
558
}
559
560
#[test]
561
fn optimistic_forced_state_sets_availability_and_reset_keeps_it() {
562
let busy = ForcedAvailability {
563
kind: ForcedKind::Busy,
564
expires_at: None,
565
};
566
let status = with_forced(&PresenceStatus::default(), Some(busy));
567
assert_eq!(status.availability, "Busy");
568
assert_eq!(status.forced, Some(busy));
569
let reset = with_forced(&status, None);
570
assert_eq!(reset.availability, "Busy");
571
assert_eq!(reset.forced, None);
572
}
573
574
#[test]
575
fn note_text_is_cut_at_the_limit_by_characters() {
576
let long = "ä".repeat(NOTE_LIMIT + 20);
577
assert_eq!(clamp_note(&long).chars().count(), NOTE_LIMIT);
578
assert_eq!(clamp_note("short"), "short");
579
}
580
581
#[test]
582
fn work_location_labels_follow_teams() {
583
let location = |kind, source| Some(WorkLocation { kind, source });
584
assert_eq!(work_location_label(None), "Set work location");
585
assert_eq!(
586
work_location_label(location(WorkLocationKind::Office, WorkLocationSource::Set)),
587
"In the office"
588
);
589
assert_eq!(
590
work_location_label(location(
591
WorkLocationKind::Office,
592
WorkLocationSource::Scheduled
593
)),
594
"Planned in the office"
595
);
596
assert_eq!(
597
work_location_label(location(WorkLocationKind::Remote, WorkLocationSource::Set)),
598
"Working remotely"
599
);
600
}
601
602
#[test]
603
fn labels_follow_the_teams_menu() {
604
let labels: Vec<&str> = STATUS_CHOICES
605
.iter()
606
.map(|kind| choice_label(*kind))
607
.collect();
608
assert_eq!(
609
labels,
610
[
611
"Available",
612
"Busy",
613
"Do not disturb",
614
"Be right back",
615
"Appear away",
616
"Appear offline"
617
]
618
);
619
assert_eq!(NoteDuration::DEFAULT, NoteDuration::Today);
620
}
621
}
@@ -0,0 +1,621 @@1
use std::sync::Arc;2
3
use chrono::{DateTime, Datelike, Duration, NaiveTime, TimeZone, Utc};4
use gpui_kit::*;5
use teams_core::{6
ForcedAvailability, ForcedKind, PresenceStatus, StatusNote, WorkLocation, WorkLocationKind,7
WorkLocationSource,8
};9
10
use crate::app_state::{AppEvent, AppState};11
use crate::backend::Engine;12
use crate::data::PresenceKind;13
14
pub const NOTE_LIMIT: usize = 280;15
const WORK_LOCATION_FAILED: &str = "Work location couldn't be set. Try again.";16
pub const STATUS_CHOICES: [ForcedKind; 6] = [17
ForcedKind::Available,18
ForcedKind::Busy,19
ForcedKind::DoNotDisturb,20
ForcedKind::BeRightBack,21
ForcedKind::Away,22
ForcedKind::Offline,23
];24
pub const STATUS_DURATIONS: [StatusDuration; 5] = [25
StatusDuration::HalfHour,26
StatusDuration::OneHour,27
StatusDuration::TwoHours,28
StatusDuration::Today,29
StatusDuration::ThisWeek,30
];31
pub const NOTE_DURATIONS: [NoteDuration; 5] = [32
NoteDuration::Never,33
NoteDuration::OneHour,34
NoteDuration::FourHours,35
NoteDuration::Today,36
NoteDuration::ThisWeek,37
];38
39
#[derive(Debug, Clone, Copy, PartialEq, Eq)]40
pub enum StatusDuration {41
HalfHour,42
OneHour,43
TwoHours,44
Today,45
ThisWeek,46
}47
48
impl StatusDuration {49
pub fn label(self) -> &'static str {50
match self {51
StatusDuration::HalfHour => "30 minutes",52
StatusDuration::OneHour => "1 hour",53
StatusDuration::TwoHours => "2 hours",54
StatusDuration::Today => "Today",55
StatusDuration::ThisWeek => "This week",56
}57
}58
59
pub fn expires_at<Zone: TimeZone>(self, now: DateTime<Zone>) -> DateTime<Utc> {60
match self {61
StatusDuration::HalfHour => after(&now, Duration::minutes(30)),62
StatusDuration::OneHour => after(&now, Duration::hours(1)),63
StatusDuration::TwoHours => after(&now, Duration::hours(2)),64
StatusDuration::Today => end_of_day(&now),65
StatusDuration::ThisWeek => end_of_week(&now),66
}67
}68
}69
70
#[derive(Debug, Clone, Copy, PartialEq, Eq)]71
pub enum NoteDuration {72
Never,73
OneHour,74
FourHours,75
Today,76
ThisWeek,77
}78
79
impl NoteDuration {80
pub const DEFAULT: NoteDuration = NoteDuration::Today;81
82
pub fn label(self) -> &'static str {83
match self {84
NoteDuration::Never => "Never",85
NoteDuration::OneHour => "1 hour",86
NoteDuration::FourHours => "4 hours",87
NoteDuration::Today => "Today",88
NoteDuration::ThisWeek => "This week",89
}90
}91
92
pub fn expires_at<Zone: TimeZone>(self, now: DateTime<Zone>) -> Option<DateTime<Utc>> {93
match self {94
NoteDuration::Never => None,95
NoteDuration::OneHour => Some(after(&now, Duration::hours(1))),96
NoteDuration::FourHours => Some(after(&now, Duration::hours(4))),97
NoteDuration::Today => Some(end_of_day(&now)),98
NoteDuration::ThisWeek => Some(end_of_week(&now)),99
}100
}101
}102
103
fn after<Zone: TimeZone>(now: &DateTime<Zone>, span: Duration) -> DateTime<Utc> {104
(now.clone() + span).with_timezone(&Utc)105
}106
107
fn end_of_local_date<Zone: TimeZone>(now: &DateTime<Zone>, days_ahead: i64) -> DateTime<Utc> {108
let last_moment = NaiveTime::from_hms_milli_opt(23, 59, 59, 999).unwrap_or(NaiveTime::MIN);109
let date = now.date_naive() + Duration::days(days_ahead);110
now.timezone()111
.from_local_datetime(&date.and_time(last_moment))112
.latest()113
.map_or_else(114
|| after(now, Duration::days(days_ahead + 1)),115
|moment| moment.with_timezone(&Utc),116
)117
}118
119
pub fn end_of_day<Zone: TimeZone>(now: &DateTime<Zone>) -> DateTime<Utc> {120
end_of_local_date(now, 0)121
}122
123
pub fn end_of_week<Zone: TimeZone>(now: &DateTime<Zone>) -> DateTime<Utc> {124
let days_since_sunday = i64::from(now.weekday().num_days_from_sunday());125
end_of_local_date(now, 6 - days_since_sunday)126
}127
128
pub fn choice_label(kind: ForcedKind) -> &'static str {129
match kind {130
ForcedKind::Away => "Appear away",131
ForcedKind::Offline => "Appear offline",132
other => state_label(other),133
}134
}135
136
pub fn state_label(kind: ForcedKind) -> &'static str {137
match kind {138
ForcedKind::Available => "Available",139
ForcedKind::Busy => "Busy",140
ForcedKind::DoNotDisturb => "Do not disturb",141
ForcedKind::BeRightBack => "Be right back",142
ForcedKind::Away => "Away",143
ForcedKind::Offline => "Offline",144
}145
}146
147
pub fn presence_kind_for(kind: ForcedKind) -> PresenceKind {148
match kind {149
ForcedKind::Available => PresenceKind::Available,150
ForcedKind::Busy => PresenceKind::Busy,151
ForcedKind::DoNotDisturb => PresenceKind::DoNotDisturb,152
ForcedKind::BeRightBack | ForcedKind::Away => PresenceKind::Away,153
ForcedKind::Offline => PresenceKind::Offline,154
}155
}156
157
pub fn until_label<Zone: TimeZone>(expires_at: DateTime<Utc>, now: &DateTime<Zone>) -> String158
where159
Zone::Offset: std::fmt::Display,160
{161
let local = expires_at.with_timezone(&now.timezone());162
if local.date_naive() == now.date_naive() {163
format!("until {}", local.format("%H:%M"))164
} else {165
format!("until {}", local.format("%a %H:%M"))166
}167
}168
169
#[derive(Debug, Clone, PartialEq, Eq)]170
pub struct StateSummary {171
pub label: &'static str,172
pub presence: PresenceKind,173
pub until: Option<String>,174
}175
176
pub fn state_summary<Zone: TimeZone>(177
status: &PresenceStatus,178
live: PresenceKind,179
now: &DateTime<Zone>,180
) -> StateSummary181
where182
Zone::Offset: std::fmt::Display,183
{184
match status.forced {185
Some(forced) => StateSummary {186
label: state_label(forced.kind),187
presence: presence_kind_for(forced.kind),188
until: forced189
.expires_at190
.map(|expires_at| until_label(expires_at, now)),191
},192
None => StateSummary {193
label: match live.label() {194
"" => "Set status",195
label => label,196
},197
presence: live,198
until: None,199
},200
}201
}202
203
pub fn duration_target(status: &PresenceStatus) -> Option<ForcedKind> {204
status205
.forced206
.map(|forced| forced.kind)207
.filter(|kind| *kind != ForcedKind::Available)208
}209
210
pub fn with_forced(status: &PresenceStatus, forced: Option<ForcedAvailability>) -> PresenceStatus {211
let availability = match forced {212
Some(forced) => forced.kind.code().to_owned(),213
None => status.availability.clone(),214
};215
PresenceStatus {216
availability,217
forced,218
..status.clone()219
}220
}221
222
pub fn with_note(status: &PresenceStatus, note: Option<StatusNote>) -> PresenceStatus {223
PresenceStatus {224
note,225
..status.clone()226
}227
}228
229
pub fn work_location_label(location: Option<WorkLocation>) -> &'static str {230
match location {231
None => "Set work location",232
Some(WorkLocation {233
kind: WorkLocationKind::Office,234
source: WorkLocationSource::Set,235
}) => "In the office",236
Some(WorkLocation {237
kind: WorkLocationKind::Office,238
source: WorkLocationSource::Scheduled,239
}) => "Planned in the office",240
Some(WorkLocation {241
kind: WorkLocationKind::Office,242
source: WorkLocationSource::Verified,243
}) => "Checked in to the office",244
Some(WorkLocation {245
kind: WorkLocationKind::Remote,246
source: WorkLocationSource::Scheduled,247
}) => "Planned to work remotely",248
Some(WorkLocation {249
kind: WorkLocationKind::Remote,250
..251
}) => "Working remotely",252
}253
}254
255
pub fn with_work_location(256
status: &PresenceStatus,257
work_location: Option<WorkLocation>,258
) -> PresenceStatus {259
PresenceStatus {260
work_location,261
..status.clone()262
}263
}264
265
pub fn clamp_note(text: &str) -> String {266
text.chars().take(NOTE_LIMIT).collect()267
}268
269
pub fn demo_status() -> PresenceStatus {270
PresenceStatus {271
availability: "Available".to_owned(),272
..PresenceStatus::default()273
}274
}275
276
impl AppState {277
pub fn own_presence_kind(&self) -> PresenceKind {278
match &self.directory.me {279
Some(me) => self.directory.presence_of(&me.user_id).kind(),280
None => PresenceKind::Unknown,281
}282
}283
284
pub fn set_status_menu_open(&mut self, open: bool, cx: &mut Context<Self>) {285
if self.status_menu_open != open {286
self.status_menu_open = open;287
cx.notify();288
}289
}290
291
pub fn request_status_message(&mut self, cx: &mut Context<Self>) {292
self.status_message_request = true;293
cx.emit(AppEvent::StatusMessage);294
cx.notify();295
}296
297
pub fn take_status_message_request(&mut self) -> bool {298
std::mem::take(&mut self.status_message_request)299
}300
301
pub fn open_notification_settings(&mut self, cx: &mut Context<Self>) {302
cx.emit(AppEvent::NotificationSettings);303
}304
305
pub fn refresh_own_status(&mut self, cx: &mut Context<Self>) {306
let Some(engine) = self.engine.clone().filter(|_| !self.mode.demo) else {307
return;308
};309
drop(crate::runtime::spawn(async move {310
engine.refresh_own_status().await311
}));312
cx.notify();313
}314
315
pub fn apply_own_status(&mut self, status: PresenceStatus, cx: &mut Context<Self>) {316
self.own_status = status;317
cx.emit(AppEvent::Directory);318
cx.notify();319
}320
321
pub fn set_own_availability(322
&mut self,323
forced: Option<ForcedAvailability>,324
cx: &mut Context<Self>,325
) {326
let Some(engine_or_demo) = self.own_status_engine(cx) else {327
return;328
};329
let previous_status = self.own_status.clone();330
let previous_presence = self.own_presence_kind();331
self.own_status = with_forced(&previous_status, forced);332
if let Some(forced) = forced {333
self.show_own_presence(presence_kind_for(forced.kind), cx);334
}335
let Some(engine) = engine_or_demo else {336
return;337
};338
self.run_chat_action(339
"Status",340
async move { engine.set_own_availability(forced).await },341
move |state, cx| {342
state.own_status = previous_status;343
state.show_own_presence(previous_presence, cx);344
},345
|_, _| {},346
cx,347
);348
}349
350
pub fn set_own_status_note(&mut self, note: Option<StatusNote>, cx: &mut Context<Self>) {351
let Some(engine_or_demo) = self.own_status_engine(cx) else {352
return;353
};354
let previous_status = self.own_status.clone();355
self.own_status = with_note(&previous_status, note.clone());356
cx.emit(AppEvent::Directory);357
cx.notify();358
let Some(engine) = engine_or_demo else {359
return;360
};361
self.run_chat_action(362
"Status message",363
async move { engine.set_own_status_note(note).await },364
move |state, cx| {365
state.own_status = previous_status;366
cx.emit(AppEvent::Directory);367
cx.notify();368
},369
|_, _| {},370
cx,371
);372
}373
374
pub fn set_own_work_location(375
&mut self,376
kind: Option<WorkLocationKind>,377
cx: &mut Context<Self>,378
) {379
let Some(engine_or_demo) = self.own_status_engine(cx) else {380
return;381
};382
let previous_status = self.own_status.clone();383
let optimistic = kind.map(|kind| WorkLocation {384
kind,385
source: WorkLocationSource::Set,386
});387
self.own_status = with_work_location(&previous_status, optimistic);388
cx.emit(AppEvent::Directory);389
cx.notify();390
let Some(engine) = engine_or_demo else {391
return;392
};393
let location = kind.map(|kind| (kind, end_of_day(&chrono::Local::now())));394
let receiver =395
crate::runtime::spawn(async move { engine.set_own_work_location(location).await });396
cx.spawn(async move |this, cx| {397
let succeeded = matches!(receiver.await, Ok(Ok(())));398
this.update(cx, |state, cx| {399
if succeeded {400
return;401
}402
state.own_status = previous_status;403
state.raise_notice(WORK_LOCATION_FAILED.to_owned(), None, cx);404
})405
.ok();406
})407
.detach();408
}409
410
fn show_own_presence(&mut self, kind: PresenceKind, cx: &mut Context<Self>) {411
if let Some(me) = self412
.directory413
.me414
.clone()415
.filter(|_| kind != PresenceKind::Unknown)416
{417
self.directory.set_presence(&me.user_id, kind);418
}419
cx.emit(AppEvent::Directory);420
cx.notify();421
}422
423
fn own_status_engine(&mut self, cx: &mut Context<Self>) -> Option<Option<Arc<Engine>>> {424
if self.mode.read_only {425
self.raise_notice("Read-only mode: status not changed".to_owned(), None, cx);426
return None;427
}428
match self.engine.clone() {429
Some(engine) => Some(Some(engine)),430
None if self.mode.demo => Some(None),431
None => None,432
}433
}434
}435
436
#[cfg(test)]437
mod tests {438
use chrono::{DateTime, Duration, FixedOffset, TimeZone, Utc};439
use teams_core::{440
ForcedAvailability, ForcedKind, PresenceStatus, WorkLocation, WorkLocationKind,441
WorkLocationSource,442
};443
444
use super::{445
NOTE_LIMIT, NoteDuration, STATUS_CHOICES, StateSummary, StatusDuration, choice_label,446
clamp_note, duration_target, end_of_day, end_of_week, state_summary, until_label,447
with_forced, work_location_label,448
};449
use crate::data::PresenceKind;450
451
fn zone() -> FixedOffset {452
FixedOffset::east_opt(2 * 3600).unwrap()453
}454
455
fn local(day: u32, hour: u32, minute: u32) -> DateTime<FixedOffset> {456
zone()457
.with_ymd_and_hms(2026, 10, day, hour, minute, 0)458
.unwrap()459
}460
461
fn utc(day: u32, hour: u32, minute: u32, second: u32) -> DateTime<Utc> {462
Utc.with_ymd_and_hms(2026, 10, day, hour, minute, second)463
.unwrap()464
}465
466
#[test]467
fn relative_durations_add_to_now() {468
let now = local(9, 14, 0);469
assert_eq!(StatusDuration::HalfHour.expires_at(now), utc(9, 12, 30, 0));470
assert_eq!(StatusDuration::OneHour.expires_at(now), utc(9, 13, 0, 0));471
assert_eq!(StatusDuration::TwoHours.expires_at(now), utc(9, 14, 0, 0));472
assert_eq!(473
NoteDuration::FourHours.expires_at(now),474
Some(utc(9, 16, 0, 0))475
);476
assert_eq!(477
NoteDuration::OneHour.expires_at(now),478
Some(utc(9, 13, 0, 0))479
);480
assert_eq!(NoteDuration::Never.expires_at(now), None);481
}482
483
#[test]484
fn today_ends_at_local_midnight() {485
let expected = utc(9, 21, 59, 59) + Duration::milliseconds(999);486
assert_eq!(StatusDuration::Today.expires_at(local(9, 14, 0)), expected);487
assert_eq!(488
NoteDuration::Today.expires_at(local(9, 0, 5)),489
Some(expected)490
);491
}492
493
#[test]494
fn today_uses_the_local_date_not_the_utc_date() {495
let now = local(10, 0, 30);496
let expected = utc(10, 21, 59, 59) + Duration::milliseconds(999);497
assert_eq!(end_of_day(&now), expected);498
}499
500
#[test]501
fn week_ends_saturday_night_with_sunday_as_first_day() {502
let saturday = utc(10, 21, 59, 59) + Duration::milliseconds(999);503
let friday = local(9, 14, 0);504
assert_eq!(StatusDuration::ThisWeek.expires_at(friday), saturday);505
assert_eq!(end_of_week(&local(10, 8, 0)), saturday);506
assert_eq!(end_of_week(&local(4, 8, 0)), saturday);507
let next_saturday = utc(17, 21, 59, 59) + Duration::milliseconds(999);508
assert_eq!(end_of_week(&local(11, 8, 0)), next_saturday);509
}510
511
#[test]512
fn until_label_shows_the_time_today_and_the_day_later() {513
let now = local(9, 14, 0);514
assert_eq!(until_label(utc(9, 13, 30, 0), &now), "until 15:30");515
assert_eq!(until_label(utc(10, 13, 30, 0), &now), "until Sat 15:30");516
}517
518
#[test]519
fn forced_state_wins_over_the_live_presence_in_the_summary() {520
let now = local(9, 14, 0);521
let status = PresenceStatus {522
forced: Some(ForcedAvailability {523
kind: ForcedKind::DoNotDisturb,524
expires_at: Some(utc(9, 13, 30, 0)),525
}),526
..PresenceStatus::default()527
};528
assert_eq!(529
state_summary(&status, PresenceKind::Available, &now),530
StateSummary {531
label: "Do not disturb",532
presence: PresenceKind::DoNotDisturb,533
until: Some("until 15:30".into()),534
}535
);536
let automatic = state_summary(&PresenceStatus::default(), PresenceKind::Away, &now);537
assert_eq!(automatic.label, "Away");538
assert_eq!(automatic.until, None);539
let unknown = state_summary(&PresenceStatus::default(), PresenceKind::Unknown, &now);540
assert_eq!(unknown.label, "Set status");541
}542
543
#[test]544
fn duration_needs_a_forced_state_other_than_available() {545
let forced = |kind| PresenceStatus {546
forced: Some(ForcedAvailability {547
kind,548
expires_at: None,549
}),550
..PresenceStatus::default()551
};552
assert_eq!(duration_target(&PresenceStatus::default()), None);553
assert_eq!(duration_target(&forced(ForcedKind::Available)), None);554
assert_eq!(555
duration_target(&forced(ForcedKind::Busy)),556
Some(ForcedKind::Busy)557
);558
}559
560
#[test]561
fn optimistic_forced_state_sets_availability_and_reset_keeps_it() {562
let busy = ForcedAvailability {563
kind: ForcedKind::Busy,564
expires_at: None,565
};566
let status = with_forced(&PresenceStatus::default(), Some(busy));567
assert_eq!(status.availability, "Busy");568
assert_eq!(status.forced, Some(busy));569
let reset = with_forced(&status, None);570
assert_eq!(reset.availability, "Busy");571
assert_eq!(reset.forced, None);572
}573
574
#[test]575
fn note_text_is_cut_at_the_limit_by_characters() {576
let long = "ä".repeat(NOTE_LIMIT + 20);577
assert_eq!(clamp_note(&long).chars().count(), NOTE_LIMIT);578
assert_eq!(clamp_note("short"), "short");579
}580
581
#[test]582
fn work_location_labels_follow_teams() {583
let location = |kind, source| Some(WorkLocation { kind, source });584
assert_eq!(work_location_label(None), "Set work location");585
assert_eq!(586
work_location_label(location(WorkLocationKind::Office, WorkLocationSource::Set)),587
"In the office"588
);589
assert_eq!(590
work_location_label(location(591
WorkLocationKind::Office,592
WorkLocationSource::Scheduled593
)),594
"Planned in the office"595
);596
assert_eq!(597
work_location_label(location(WorkLocationKind::Remote, WorkLocationSource::Set)),598
"Working remotely"599
);600
}601
602
#[test]603
fn labels_follow_the_teams_menu() {604
let labels: Vec<&str> = STATUS_CHOICES605
.iter()606
.map(|kind| choice_label(*kind))607
.collect();608
assert_eq!(609
labels,610
[611
"Available",612
"Busy",613
"Do not disturb",614
"Be right back",615
"Appear away",616
"Appear offline"617
]618
);619
assert_eq!(NoteDuration::DEFAULT, NoteDuration::Today);620
}621
}@@ -0,0 +1,226 @@
1
use std::time::{Duration, Instant};
2
3
use chrono::{DateTime, Utc};
4
use teams_core::{PersonProfile, WorkLocation, local_time};
5
6
pub const PROFILE_MAX_AGE: Duration = Duration::from_secs(10 * 60);
7
8
#[derive(Debug, Clone, PartialEq, Eq)]
9
pub enum ContactKind {
10
Email,
11
WorkPhone,
12
MobilePhone,
13
Office,
14
}
15
16
#[derive(Debug, Clone, PartialEq, Eq)]
17
pub struct ContactRow {
18
pub kind: ContactKind,
19
pub value: String,
20
}
21
22
#[derive(Debug, Clone, PartialEq, Eq)]
23
pub struct StatusBox {
24
pub text: String,
25
pub out_of_office: bool,
26
}
27
28
pub fn status_line(availability: &str, local_time: Option<&str>) -> String {
29
match (availability.is_empty(), local_time) {
30
(false, Some(time)) => format!("{availability} - {time} local time"),
31
(false, None) => availability.to_owned(),
32
(true, Some(time)) => format!("{time} local time"),
33
(true, None) => String::new(),
34
}
35
}
36
37
pub fn local_time_label(profile: &PersonProfile, now: DateTime<Utc>) -> Option<String> {
38
let zone = profile.time_zone.as_deref()?;
39
Some(local_time(zone, now)?.format("%H:%M").to_string())
40
}
41
42
pub fn work_location_label(location: WorkLocation) -> &'static str {
43
crate::own_status::work_location_label(Some(location))
44
}
45
46
pub fn status_box(profile: &PersonProfile) -> Option<StatusBox> {
47
if let Some(text) = &profile.out_of_office {
48
let text = match text.trim() {
49
"" => "Out of office".to_owned(),
50
text => text.to_owned(),
51
};
52
return Some(StatusBox {
53
text,
54
out_of_office: true,
55
});
56
}
57
profile.status_message.clone().map(|text| StatusBox {
58
text,
59
out_of_office: false,
60
})
61
}
62
63
pub fn contact_rows(profile: &PersonProfile) -> Vec<ContactRow> {
64
let present = |value: &Option<String>| value.clone().filter(|value| !value.trim().is_empty());
65
let mut rows = Vec::new();
66
let mut push = |kind: ContactKind, value: Option<String>| {
67
if let Some(value) = value {
68
rows.push(ContactRow { kind, value });
69
}
70
};
71
push(ContactKind::Email, present(&profile.email));
72
for phone in &profile.work_phones {
73
push(ContactKind::WorkPhone, present(&Some(phone.clone())));
74
}
75
push(ContactKind::MobilePhone, present(&profile.mobile_phone));
76
push(ContactKind::Office, present(&profile.office_location));
77
rows
78
}
79
80
pub fn has_organization(profile: &PersonProfile) -> bool {
81
profile.manager.is_some() || !profile.direct_reports.is_empty()
82
}
83
84
pub fn mailto_url(email: &str) -> String {
85
format!("mailto:{email}")
86
}
87
88
pub fn is_stale(fetched_at: Instant, now: Instant) -> bool {
89
now.duration_since(fetched_at) >= PROFILE_MAX_AGE
90
}
91
92
#[cfg(test)]
93
mod tests {
94
use chrono::TimeZone;
95
use teams_core::{OrgPerson, WorkLocationKind, WorkLocationSource};
96
97
use super::*;
98
99
fn profile() -> PersonProfile {
100
PersonProfile {
101
user_id: "u".into(),
102
display_name: Some("Ada".into()),
103
job_title: None,
104
department: None,
105
company: None,
106
office_location: None,
107
email: None,
108
work_phones: Vec::new(),
109
mobile_phone: None,
110
manager: None,
111
direct_reports: Vec::new(),
112
time_zone: None,
113
availability: None,
114
status_message: None,
115
out_of_office: None,
116
work_location: None,
117
}
118
}
119
120
#[test]
121
fn status_line_joins_availability_and_local_time() {
122
assert_eq!(
123
status_line("Available", Some("14:35")),
124
"Available - 14:35 local time"
125
);
126
assert_eq!(status_line("Busy", None), "Busy");
127
assert_eq!(status_line("", Some("09:05")), "09:05 local time");
128
assert_eq!(status_line("", None), "");
129
}
130
131
#[test]
132
fn local_time_needs_a_known_zone() {
133
let now = Utc.with_ymd_and_hms(2026, 10, 9, 12, 0, 0).unwrap();
134
let mut person = profile();
135
assert_eq!(local_time_label(&person, now), None);
136
person.time_zone = Some("W. Europe Standard Time".into());
137
assert_eq!(local_time_label(&person, now).as_deref(), Some("14:00"));
138
person.time_zone = Some("Unknown Zone".into());
139
assert_eq!(local_time_label(&person, now), None);
140
}
141
142
#[test]
143
fn work_location_labels_follow_the_source() {
144
let at = |kind, source| work_location_label(WorkLocation { kind, source });
145
assert_eq!(
146
at(WorkLocationKind::Office, WorkLocationSource::Set),
147
"In the office"
148
);
149
assert_eq!(
150
at(WorkLocationKind::Office, WorkLocationSource::Scheduled),
151
"Planned in the office"
152
);
153
assert_eq!(
154
at(WorkLocationKind::Office, WorkLocationSource::Verified),
155
"Checked in to the office"
156
);
157
assert_eq!(
158
at(WorkLocationKind::Remote, WorkLocationSource::Set),
159
"Working remotely"
160
);
161
assert_eq!(
162
at(WorkLocationKind::Remote, WorkLocationSource::Scheduled),
163
"Planned to work remotely"
164
);
165
}
166
167
#[test]
168
fn out_of_office_replaces_the_status_message() {
169
let mut person = profile();
170
person.status_message = Some("Focus".into());
171
assert_eq!(
172
status_box(&person),
173
Some(StatusBox {
174
text: "Focus".into(),
175
out_of_office: false
176
})
177
);
178
person.out_of_office = Some("Back Monday".into());
179
assert_eq!(
180
status_box(&person),
181
Some(StatusBox {
182
text: "Back Monday".into(),
183
out_of_office: true
184
})
185
);
186
person.out_of_office = Some(" ".into());
187
assert_eq!(status_box(&person).unwrap().text, "Out of office");
188
}
189
190
#[test]
191
fn contact_rows_hide_empty_fields() {
192
let mut person = profile();
193
person.email = Some("ada@example.com".into());
194
person.work_phones = vec!["+49 1".into(), " ".into()];
195
person.mobile_phone = Some(String::new());
196
person.office_location = Some("Berlin".into());
197
let kinds: Vec<ContactKind> = contact_rows(&person)
198
.into_iter()
199
.map(|row| row.kind)
200
.collect();
201
assert_eq!(
202
kinds,
203
vec![
204
ContactKind::Email,
205
ContactKind::WorkPhone,
206
ContactKind::Office
207
]
208
);
209
assert!(contact_rows(&profile()).is_empty());
210
}
211
212
#[test]
213
fn organization_needs_a_manager_or_reports() {
214
let mut person = profile();
215
assert!(!has_organization(&person));
216
person.direct_reports.push(OrgPerson::default());
217
assert!(has_organization(&person));
218
}
219
220
#[test]
221
fn profiles_go_stale_after_ten_minutes() {
222
let start = Instant::now();
223
assert!(!is_stale(start, start + Duration::from_secs(599)));
224
assert!(is_stale(start, start + Duration::from_secs(600)));
225
}
226
}
@@ -0,0 +1,226 @@1
use std::time::{Duration, Instant};2
3
use chrono::{DateTime, Utc};4
use teams_core::{PersonProfile, WorkLocation, local_time};5
6
pub const PROFILE_MAX_AGE: Duration = Duration::from_secs(10 * 60);7
8
#[derive(Debug, Clone, PartialEq, Eq)]9
pub enum ContactKind {10
Email,11
WorkPhone,12
MobilePhone,13
Office,14
}15
16
#[derive(Debug, Clone, PartialEq, Eq)]17
pub struct ContactRow {18
pub kind: ContactKind,19
pub value: String,20
}21
22
#[derive(Debug, Clone, PartialEq, Eq)]23
pub struct StatusBox {24
pub text: String,25
pub out_of_office: bool,26
}27
28
pub fn status_line(availability: &str, local_time: Option<&str>) -> String {29
match (availability.is_empty(), local_time) {30
(false, Some(time)) => format!("{availability} - {time} local time"),31
(false, None) => availability.to_owned(),32
(true, Some(time)) => format!("{time} local time"),33
(true, None) => String::new(),34
}35
}36
37
pub fn local_time_label(profile: &PersonProfile, now: DateTime<Utc>) -> Option<String> {38
let zone = profile.time_zone.as_deref()?;39
Some(local_time(zone, now)?.format("%H:%M").to_string())40
}41
42
pub fn work_location_label(location: WorkLocation) -> &'static str {43
crate::own_status::work_location_label(Some(location))44
}45
46
pub fn status_box(profile: &PersonProfile) -> Option<StatusBox> {47
if let Some(text) = &profile.out_of_office {48
let text = match text.trim() {49
"" => "Out of office".to_owned(),50
text => text.to_owned(),51
};52
return Some(StatusBox {53
text,54
out_of_office: true,55
});56
}57
profile.status_message.clone().map(|text| StatusBox {58
text,59
out_of_office: false,60
})61
}62
63
pub fn contact_rows(profile: &PersonProfile) -> Vec<ContactRow> {64
let present = |value: &Option<String>| value.clone().filter(|value| !value.trim().is_empty());65
let mut rows = Vec::new();66
let mut push = |kind: ContactKind, value: Option<String>| {67
if let Some(value) = value {68
rows.push(ContactRow { kind, value });69
}70
};71
push(ContactKind::Email, present(&profile.email));72
for phone in &profile.work_phones {73
push(ContactKind::WorkPhone, present(&Some(phone.clone())));74
}75
push(ContactKind::MobilePhone, present(&profile.mobile_phone));76
push(ContactKind::Office, present(&profile.office_location));77
rows78
}79
80
pub fn has_organization(profile: &PersonProfile) -> bool {81
profile.manager.is_some() || !profile.direct_reports.is_empty()82
}83
84
pub fn mailto_url(email: &str) -> String {85
format!("mailto:{email}")86
}87
88
pub fn is_stale(fetched_at: Instant, now: Instant) -> bool {89
now.duration_since(fetched_at) >= PROFILE_MAX_AGE90
}91
92
#[cfg(test)]93
mod tests {94
use chrono::TimeZone;95
use teams_core::{OrgPerson, WorkLocationKind, WorkLocationSource};96
97
use super::*;98
99
fn profile() -> PersonProfile {100
PersonProfile {101
user_id: "u".into(),102
display_name: Some("Ada".into()),103
job_title: None,104
department: None,105
company: None,106
office_location: None,107
email: None,108
work_phones: Vec::new(),109
mobile_phone: None,110
manager: None,111
direct_reports: Vec::new(),112
time_zone: None,113
availability: None,114
status_message: None,115
out_of_office: None,116
work_location: None,117
}118
}119
120
#[test]121
fn status_line_joins_availability_and_local_time() {122
assert_eq!(123
status_line("Available", Some("14:35")),124
"Available - 14:35 local time"125
);126
assert_eq!(status_line("Busy", None), "Busy");127
assert_eq!(status_line("", Some("09:05")), "09:05 local time");128
assert_eq!(status_line("", None), "");129
}130
131
#[test]132
fn local_time_needs_a_known_zone() {133
let now = Utc.with_ymd_and_hms(2026, 10, 9, 12, 0, 0).unwrap();134
let mut person = profile();135
assert_eq!(local_time_label(&person, now), None);136
person.time_zone = Some("W. Europe Standard Time".into());137
assert_eq!(local_time_label(&person, now).as_deref(), Some("14:00"));138
person.time_zone = Some("Unknown Zone".into());139
assert_eq!(local_time_label(&person, now), None);140
}141
142
#[test]143
fn work_location_labels_follow_the_source() {144
let at = |kind, source| work_location_label(WorkLocation { kind, source });145
assert_eq!(146
at(WorkLocationKind::Office, WorkLocationSource::Set),147
"In the office"148
);149
assert_eq!(150
at(WorkLocationKind::Office, WorkLocationSource::Scheduled),151
"Planned in the office"152
);153
assert_eq!(154
at(WorkLocationKind::Office, WorkLocationSource::Verified),155
"Checked in to the office"156
);157
assert_eq!(158
at(WorkLocationKind::Remote, WorkLocationSource::Set),159
"Working remotely"160
);161
assert_eq!(162
at(WorkLocationKind::Remote, WorkLocationSource::Scheduled),163
"Planned to work remotely"164
);165
}166
167
#[test]168
fn out_of_office_replaces_the_status_message() {169
let mut person = profile();170
person.status_message = Some("Focus".into());171
assert_eq!(172
status_box(&person),173
Some(StatusBox {174
text: "Focus".into(),175
out_of_office: false176
})177
);178
person.out_of_office = Some("Back Monday".into());179
assert_eq!(180
status_box(&person),181
Some(StatusBox {182
text: "Back Monday".into(),183
out_of_office: true184
})185
);186
person.out_of_office = Some(" ".into());187
assert_eq!(status_box(&person).unwrap().text, "Out of office");188
}189
190
#[test]191
fn contact_rows_hide_empty_fields() {192
let mut person = profile();193
person.email = Some("ada@example.com".into());194
person.work_phones = vec!["+49 1".into(), " ".into()];195
person.mobile_phone = Some(String::new());196
person.office_location = Some("Berlin".into());197
let kinds: Vec<ContactKind> = contact_rows(&person)198
.into_iter()199
.map(|row| row.kind)200
.collect();201
assert_eq!(202
kinds,203
vec![204
ContactKind::Email,205
ContactKind::WorkPhone,206
ContactKind::Office207
]208
);209
assert!(contact_rows(&profile()).is_empty());210
}211
212
#[test]213
fn organization_needs_a_manager_or_reports() {214
let mut person = profile();215
assert!(!has_organization(&person));216
person.direct_reports.push(OrgPerson::default());217
assert!(has_organization(&person));218
}219
220
#[test]221
fn profiles_go_stale_after_ten_minutes() {222
let start = Instant::now();223
assert!(!is_stale(start, start + Duration::from_secs(599)));224
assert!(is_stale(start, start + Duration::from_secs(600)));225
}226
}@@ -0,0 +1,162 @@
1
use std::collections::HashMap;
2
use std::sync::Arc;
3
use std::time::Instant;
4
5
use gpui_kit::*;
6
use teams_core::PersonProfile;
7
8
use crate::app_state::{AppEvent, AppState, Selection};
9
use crate::demo_profiles;
10
use crate::notice::short_error;
11
use crate::profile_model::is_stale;
12
use crate::views::new_chat::existing_one_on_one;
13
14
#[derive(Default)]
15
pub struct ProfileEntry {
16
pub profile: Option<Arc<PersonProfile>>,
17
pub fetching: bool,
18
pub failed: bool,
19
fetched_at: Option<Instant>,
20
}
21
22
impl ProfileEntry {
23
fn is_fresh(&self, now: Instant) -> bool {
24
self.profile.is_some() && self.fetched_at.is_some_and(|at| !is_stale(at, now))
25
}
26
}
27
28
pub struct ProfileRequest {
29
pub user_id: String,
30
pub anchor: Point<Pixels>,
31
}
32
33
pub type ProfileCache = HashMap<String, ProfileEntry>;
34
35
impl AppState {
36
pub fn open_profile_card(
37
&mut self,
38
user_id: &str,
39
anchor: Point<Pixels>,
40
cx: &mut Context<Self>,
41
) {
42
self.profile_request = Some(ProfileRequest {
43
user_id: user_id.to_owned(),
44
anchor,
45
});
46
self.request_profile(user_id, false, cx);
47
self.request_avatars(vec![user_id.to_owned()], cx);
48
cx.emit(AppEvent::Profile);
49
cx.notify();
50
}
51
52
pub fn take_profile_request(&mut self) -> Option<ProfileRequest> {
53
self.profile_request.take()
54
}
55
56
pub fn request_profile(&mut self, user_id: &str, force: bool, cx: &mut Context<Self>) {
57
let now = Instant::now();
58
let entry = self.profiles.entry(user_id.to_owned()).or_default();
59
if entry.fetching || (!force && entry.is_fresh(now)) {
60
return;
61
}
62
let owned_id = user_id.to_owned();
63
let receiver = if self.mode.demo {
64
crate::runtime::spawn(demo_profiles::load(owned_id.clone()))
65
} else if let Some(engine) = self.engine.clone() {
66
let id = owned_id.clone();
67
crate::runtime::spawn(async move {
68
engine
69
.person_profile(&id)
70
.await
71
.map_err(|error| short_error(&error))
72
})
73
} else {
74
entry.failed = true;
75
cx.notify();
76
return;
77
};
78
entry.fetching = true;
79
entry.failed = false;
80
cx.notify();
81
cx.spawn(async move |this, cx| {
82
let result = receiver
83
.await
84
.unwrap_or_else(|_| Err("cancelled".to_owned()));
85
this.update(cx, |state, cx| state.finish_profile(&owned_id, result, cx))
86
.ok();
87
})
88
.detach();
89
}
90
91
fn finish_profile(
92
&mut self,
93
user_id: &str,
94
result: Result<PersonProfile, String>,
95
cx: &mut Context<Self>,
96
) {
97
let entry = self.profiles.entry(user_id.to_owned()).or_default();
98
entry.fetching = false;
99
match result {
100
Ok(profile) => {
101
let related: Vec<String> = profile
102
.manager
103
.iter()
104
.chain(&profile.direct_reports)
105
.map(|person| person.id.clone())
106
.collect();
107
entry.profile = Some(Arc::new(profile));
108
entry.failed = false;
109
entry.fetched_at = Some(Instant::now());
110
self.request_avatars(related, cx);
111
}
112
Err(_) => entry.failed = true,
113
}
114
cx.notify();
115
}
116
117
pub fn copy_profile_email(&mut self, email: &str, cx: &mut Context<Self>) {
118
cx.write_to_clipboard(ClipboardItem::new_string(email.to_owned()));
119
self.raise_notice("Email copied".to_owned(), None, cx);
120
}
121
122
pub fn open_chat_with(&mut self, user_id: &str, cx: &mut Context<Self>) {
123
let existing =
124
existing_one_on_one(&self.sidebar.chats, self.directory.me.as_ref(), user_id)
125
.map(|chat| chat.id.clone());
126
if let Some(chat_id) = existing {
127
self.select(Selection::Chat(chat_id), cx);
128
return;
129
}
130
if self.mode.read_only {
131
self.raise_notice("Read-only mode: chat not created".to_owned(), None, cx);
132
return;
133
}
134
let Some(engine) = self.engine.clone() else {
135
self.raise_notice("No chat with this person yet".to_owned(), None, cx);
136
return;
137
};
138
let user_id = user_id.to_owned();
139
let receiver = crate::runtime::spawn(async move {
140
engine
141
.create_one_on_one(&user_id)
142
.await
143
.map_err(|error| short_error(&error))
144
});
145
cx.spawn(async move |this, cx| {
146
let outcome = receiver
147
.await
148
.unwrap_or_else(|_| Err("cancelled".to_owned()));
149
this.update(cx, |state, cx| match outcome {
150
Ok(chat_id) => {
151
state.reload_sidebar(cx);
152
state.select(Selection::Chat(chat_id), cx);
153
}
154
Err(reason) => {
155
state.raise_notice(format!("Chat could not be opened: {reason}"), None, cx)
156
}
157
})
158
.ok();
159
})
160
.detach();
161
}
162
}
@@ -0,0 +1,162 @@1
use std::collections::HashMap;2
use std::sync::Arc;3
use std::time::Instant;4
5
use gpui_kit::*;6
use teams_core::PersonProfile;7
8
use crate::app_state::{AppEvent, AppState, Selection};9
use crate::demo_profiles;10
use crate::notice::short_error;11
use crate::profile_model::is_stale;12
use crate::views::new_chat::existing_one_on_one;13
14
#[derive(Default)]15
pub struct ProfileEntry {16
pub profile: Option<Arc<PersonProfile>>,17
pub fetching: bool,18
pub failed: bool,19
fetched_at: Option<Instant>,20
}21
22
impl ProfileEntry {23
fn is_fresh(&self, now: Instant) -> bool {24
self.profile.is_some() && self.fetched_at.is_some_and(|at| !is_stale(at, now))25
}26
}27
28
pub struct ProfileRequest {29
pub user_id: String,30
pub anchor: Point<Pixels>,31
}32
33
pub type ProfileCache = HashMap<String, ProfileEntry>;34
35
impl AppState {36
pub fn open_profile_card(37
&mut self,38
user_id: &str,39
anchor: Point<Pixels>,40
cx: &mut Context<Self>,41
) {42
self.profile_request = Some(ProfileRequest {43
user_id: user_id.to_owned(),44
anchor,45
});46
self.request_profile(user_id, false, cx);47
self.request_avatars(vec![user_id.to_owned()], cx);48
cx.emit(AppEvent::Profile);49
cx.notify();50
}51
52
pub fn take_profile_request(&mut self) -> Option<ProfileRequest> {53
self.profile_request.take()54
}55
56
pub fn request_profile(&mut self, user_id: &str, force: bool, cx: &mut Context<Self>) {57
let now = Instant::now();58
let entry = self.profiles.entry(user_id.to_owned()).or_default();59
if entry.fetching || (!force && entry.is_fresh(now)) {60
return;61
}62
let owned_id = user_id.to_owned();63
let receiver = if self.mode.demo {64
crate::runtime::spawn(demo_profiles::load(owned_id.clone()))65
} else if let Some(engine) = self.engine.clone() {66
let id = owned_id.clone();67
crate::runtime::spawn(async move {68
engine69
.person_profile(&id)70
.await71
.map_err(|error| short_error(&error))72
})73
} else {74
entry.failed = true;75
cx.notify();76
return;77
};78
entry.fetching = true;79
entry.failed = false;80
cx.notify();81
cx.spawn(async move |this, cx| {82
let result = receiver83
.await84
.unwrap_or_else(|_| Err("cancelled".to_owned()));85
this.update(cx, |state, cx| state.finish_profile(&owned_id, result, cx))86
.ok();87
})88
.detach();89
}90
91
fn finish_profile(92
&mut self,93
user_id: &str,94
result: Result<PersonProfile, String>,95
cx: &mut Context<Self>,96
) {97
let entry = self.profiles.entry(user_id.to_owned()).or_default();98
entry.fetching = false;99
match result {100
Ok(profile) => {101
let related: Vec<String> = profile102
.manager103
.iter()104
.chain(&profile.direct_reports)105
.map(|person| person.id.clone())106
.collect();107
entry.profile = Some(Arc::new(profile));108
entry.failed = false;109
entry.fetched_at = Some(Instant::now());110
self.request_avatars(related, cx);111
}112
Err(_) => entry.failed = true,113
}114
cx.notify();115
}116
117
pub fn copy_profile_email(&mut self, email: &str, cx: &mut Context<Self>) {118
cx.write_to_clipboard(ClipboardItem::new_string(email.to_owned()));119
self.raise_notice("Email copied".to_owned(), None, cx);120
}121
122
pub fn open_chat_with(&mut self, user_id: &str, cx: &mut Context<Self>) {123
let existing =124
existing_one_on_one(&self.sidebar.chats, self.directory.me.as_ref(), user_id)125
.map(|chat| chat.id.clone());126
if let Some(chat_id) = existing {127
self.select(Selection::Chat(chat_id), cx);128
return;129
}130
if self.mode.read_only {131
self.raise_notice("Read-only mode: chat not created".to_owned(), None, cx);132
return;133
}134
let Some(engine) = self.engine.clone() else {135
self.raise_notice("No chat with this person yet".to_owned(), None, cx);136
return;137
};138
let user_id = user_id.to_owned();139
let receiver = crate::runtime::spawn(async move {140
engine141
.create_one_on_one(&user_id)142
.await143
.map_err(|error| short_error(&error))144
});145
cx.spawn(async move |this, cx| {146
let outcome = receiver147
.await148
.unwrap_or_else(|_| Err("cancelled".to_owned()));149
this.update(cx, |state, cx| match outcome {150
Ok(chat_id) => {151
state.reload_sidebar(cx);152
state.select(Selection::Chat(chat_id), cx);153
}154
Err(reason) => {155
state.raise_notice(format!("Chat could not be opened: {reason}"), None, cx)156
}157
})158
.ok();159
})160
.detach();161
}162
}@@ -1,6 +1,6 @@
1
1
use std::ops::Range;
2
2
3
use teams_core::{FontSize, Span};
3
use teams_core::{FontSize, PROFILE_LINK_PREFIX, Span};
4
4
5
5
pub const IMAGE_PLACEHOLDER: &str = "[image]";
6
6
pub const CODE_PADDING: &str = "\u{2004}";
@@ -551,15 +551,18 @@ fn append_inline(spans: &[Span], style: StyleFlags, link: Option<&str>, out: &mu
551
551
Some(url.as_str()),
552
552
out,
553
553
),
554
Span::Mention { name, .. } => {
554
Span::Mention { name, id } => {
555
555
let label = format!("@{}", name.trim_start_matches('@'));
556
let profile_link = id
557
.as_deref()
558
.filter(|id| id.starts_with(PROFILE_LINK_PREFIX));
556
559
out.push(
557
560
&label,
558
561
StyleFlags {
559
562
mention: true,
560
563
..style
561
564
},
562
link,
565
profile_link.or(link),
563
566
);
564
567
}
565
568
Span::LineBreak | Span::Rule => out.push("\n", style, link),
@@ -1,6 +1,6 @@1
use std::ops::Range;1
use std::ops::Range;2
2
3
use teams_core::{FontSize, Span};3
use teams_core::{FontSize, PROFILE_LINK_PREFIX, Span};4
4
5
pub const IMAGE_PLACEHOLDER: &str = "[image]";5
pub const IMAGE_PLACEHOLDER: &str = "[image]";6
pub const CODE_PADDING: &str = "\u{2004}";6
pub const CODE_PADDING: &str = "\u{2004}";@@ -551,15 +551,18 @@ fn append_inline(spans: &[Span], style: StyleFlags, link: Option<&str>, out: &mu551
Some(url.as_str()),551
Some(url.as_str()),552
out,552
out,553
),553
),554
Span::Mention { name, .. } => {554
Span::Mention { name, id } => {555
let label = format!("@{}", name.trim_start_matches('@'));555
let label = format!("@{}", name.trim_start_matches('@'));556
let profile_link = id557
.as_deref()558
.filter(|id| id.starts_with(PROFILE_LINK_PREFIX));556
out.push(559
out.push(557
&label,560
&label,558
StyleFlags {561
StyleFlags {559
mention: true,562
mention: true,560
..style563
..style561
},564
},562
link,565
profile_link.or(link),563
);566
);564
}567
}565
Span::LineBreak | Span::Rule => out.push("\n", style, link),568
Span::LineBreak | Span::Rule => out.push("\n", style, link),@@ -6,6 +6,7 @@ use gpui_kit::base::{TextSelection, TextSelectionRegistration, TextSelectionRun,
6
6
use gpui_kit::*;
7
7
8
8
use super::blocks::CODE_PADDING;
9
use crate::views::profile_card::open_profile_link;
9
10
use super::selectable::{HIT_SLOP, PILL_INSET_Y, PILL_OUTSET, Participant, Pill, TIME_ROOM};
10
11
11
12
const WRAP_TOLERANCE: f32 = 0.5;
@@ -741,7 +742,9 @@ impl Element for FlowText {
741
742
.find(|(range, _)| range.contains(&(offset + index)))
742
743
.map(|(_, url)| url.clone())
743
744
});
744
if let Some(url) = url {
745
if let Some(url) = url
746
&& !open_profile_link(&url, event.position, cx)
747
{
745
748
cx.open_url(&url);
746
749
}
747
750
});
@@ -6,6 +6,7 @@ use gpui_kit::base::{TextSelection, TextSelectionRegistration, TextSelectionRun,6
use gpui_kit::*;6
use gpui_kit::*;7
7
8
use super::blocks::CODE_PADDING;8
use super::blocks::CODE_PADDING;9
use crate::views::profile_card::open_profile_link;9
use super::selectable::{HIT_SLOP, PILL_INSET_Y, PILL_OUTSET, Participant, Pill, TIME_ROOM};10
use super::selectable::{HIT_SLOP, PILL_INSET_Y, PILL_OUTSET, Participant, Pill, TIME_ROOM};10
11
11
const WRAP_TOLERANCE: f32 = 0.5;12
const WRAP_TOLERANCE: f32 = 0.5;@@ -741,7 +742,9 @@ impl Element for FlowText {741
.find(|(range, _)| range.contains(&(offset + index)))742
.find(|(range, _)| range.contains(&(offset + index)))742
.map(|(_, url)| url.clone())743
.map(|(_, url)| url.clone())743
});744
});744
if let Some(url) = url {745
if let Some(url) = url746
&& !open_profile_link(&url, event.position, cx)747
{745
cx.open_url(&url);748
cx.open_url(&url);746
}749
}747
});750
});@@ -8,6 +8,7 @@ use gpui_kit::base::{
8
8
use gpui_kit::*;
9
9
10
10
use super::blocks::CODE_PADDING;
11
use crate::views::profile_card::open_profile_link;
11
12
12
13
pub(super) const TIME_ROOM: char = '\u{2007}';
13
14
pub(super) const HIT_SLOP: f32 = 12.;
@@ -354,7 +355,9 @@ impl Element for SelectableRichText {
354
355
if !TextSelection::selected_text(window, cx).is_empty() {
355
356
return;
356
357
}
357
if let Some(url) = link_at(&layout, &links, event.position) {
358
if let Some(url) = link_at(&layout, &links, event.position)
359
&& !open_profile_link(&url, event.position, cx)
360
{
358
361
cx.open_url(&url);
359
362
}
360
363
});
@@ -8,6 +8,7 @@ use gpui_kit::base::{8
use gpui_kit::*;8
use gpui_kit::*;9
9
10
use super::blocks::CODE_PADDING;10
use super::blocks::CODE_PADDING;11
use crate::views::profile_card::open_profile_link;11
12
12
pub(super) const TIME_ROOM: char = '\u{2007}';13
pub(super) const TIME_ROOM: char = '\u{2007}';13
pub(super) const HIT_SLOP: f32 = 12.;14
pub(super) const HIT_SLOP: f32 = 12.;@@ -354,7 +355,9 @@ impl Element for SelectableRichText {354
if !TextSelection::selected_text(window, cx).is_empty() {355
if !TextSelection::selected_text(window, cx).is_empty() {355
return;356
return;356
}357
}357
if let Some(url) = link_at(&layout, &links, event.position) {358
if let Some(url) = link_at(&layout, &links, event.position)359
&& !open_profile_link(&url, event.position, cx)360
{358
cx.open_url(&url);361
cx.open_url(&url);359
}362
}360
});363
});@@ -7,7 +7,7 @@ use gpui_kit::Image;
7
7
use store::MessageRecord;
8
8
use teams_core::{
9
9
AdaptiveCard, Draft, FileCard, ImageRef, LinkPreview, ReactionInfo, Span, adaptive_cards,
10
card_texts, files, images, link_preview, message_spans, reactions,
10
card_texts, files, images, link_preview, linked_message_spans, message_spans, reactions,
11
11
};
12
12
13
13
use crate::card_state::CardOverride;
@@ -529,7 +529,7 @@ pub fn message_row(record: &MessageRecord, context: &RowContext) -> MessageRow {
529
529
let blocks = if record.deleted {
530
530
vec![Block::Paragraph(Inline::plain(DELETED_TEXT))]
531
531
} else {
532
layout_blocks(&message_spans(record))
532
layout_blocks(&linked_message_spans(record))
533
533
};
534
534
let blocks = if images.is_empty() {
535
535
blocks
@@ -7,7 +7,7 @@ use gpui_kit::Image;7
use store::MessageRecord;7
use store::MessageRecord;8
use teams_core::{8
use teams_core::{9
AdaptiveCard, Draft, FileCard, ImageRef, LinkPreview, ReactionInfo, Span, adaptive_cards,9
AdaptiveCard, Draft, FileCard, ImageRef, LinkPreview, ReactionInfo, Span, adaptive_cards,10
card_texts, files, images, link_preview, message_spans, reactions,10
card_texts, files, images, link_preview, linked_message_spans, message_spans, reactions,11
};11
};12
12
13
use crate::card_state::CardOverride;13
use crate::card_state::CardOverride;@@ -529,7 +529,7 @@ pub fn message_row(record: &MessageRecord, context: &RowContext) -> MessageRow {529
let blocks = if record.deleted {529
let blocks = if record.deleted {530
vec![Block::Paragraph(Inline::plain(DELETED_TEXT))]530
vec![Block::Paragraph(Inline::plain(DELETED_TEXT))]531
} else {531
} else {532
layout_blocks(&message_spans(record))532
layout_blocks(&linked_message_spans(record))533
};533
};534
let blocks = if images.is_empty() {534
let blocks = if images.is_empty() {535
blocks535
blocks@@ -10,11 +10,12 @@ use crate::data::{AvatarState, Directory, Presence, PresenceKind};
10
10
use crate::format;
11
11
use crate::sidebar_model::{AvatarSpec, Face};
12
12
use crate::theme;
13
use crate::views::profile_card::opens_profile;
13
14
use crate::views::widgets::icon;
14
15
15
16
const PAIR_RATIO: f32 = 24. / 36.;
16
17
const PRESENCE_MIN: f32 = 10.;
17
const PRESENCE_MAX: f32 = 14.;
18
const PRESENCE_MAX: f32 = 15.;
18
19
const PRESENCE_RATIO: f32 = 0.38;
19
20
const PRESENCE_RING: f32 = 2.;
20
21
const PRESENCE_SPIN_PERIOD: Duration = Duration::from_millis(1600);
@@ -250,7 +251,10 @@ pub fn member_stack(directory: &Directory, faces: &[Face], total: usize) -> Div
250
251
let mut stack = div().flex().flex_none().w(px(width)).items_center();
251
252
for (index, face) in faces.iter().take(LIMIT).enumerate() {
252
253
stack = stack.child(
253
div()
254
opens_profile(
255
div().id(ElementId::Name(format!("member-face-{index}").into())),
256
face.user_id.as_deref(),
257
)
254
258
.when(index > 0, |element| element.ml(px(-OVERLAP)))
255
259
.size(px(SIZE))
256
260
.flex_none()
@@ -10,11 +10,12 @@ use crate::data::{AvatarState, Directory, Presence, PresenceKind};10
use crate::format;10
use crate::format;11
use crate::sidebar_model::{AvatarSpec, Face};11
use crate::sidebar_model::{AvatarSpec, Face};12
use crate::theme;12
use crate::theme;13
use crate::views::profile_card::opens_profile;13
use crate::views::widgets::icon;14
use crate::views::widgets::icon;14
15
15
const PAIR_RATIO: f32 = 24. / 36.;16
const PAIR_RATIO: f32 = 24. / 36.;16
const PRESENCE_MIN: f32 = 10.;17
const PRESENCE_MIN: f32 = 10.;17
const PRESENCE_MAX: f32 = 14.;18
const PRESENCE_MAX: f32 = 15.;18
const PRESENCE_RATIO: f32 = 0.38;19
const PRESENCE_RATIO: f32 = 0.38;19
const PRESENCE_RING: f32 = 2.;20
const PRESENCE_RING: f32 = 2.;20
const PRESENCE_SPIN_PERIOD: Duration = Duration::from_millis(1600);21
const PRESENCE_SPIN_PERIOD: Duration = Duration::from_millis(1600);@@ -250,7 +251,10 @@ pub fn member_stack(directory: &Directory, faces: &[Face], total: usize) -> Div250
let mut stack = div().flex().flex_none().w(px(width)).items_center();251
let mut stack = div().flex().flex_none().w(px(width)).items_center();251
for (index, face) in faces.iter().take(LIMIT).enumerate() {252
for (index, face) in faces.iter().take(LIMIT).enumerate() {252
stack = stack.child(253
stack = stack.child(253
div()254
opens_profile(255
div().id(ElementId::Name(format!("member-face-{index}").into())),256
face.user_id.as_deref(),257
)254
.when(index > 0, |element| element.ml(px(-OVERLAP)))258
.when(index > 0, |element| element.ml(px(-OVERLAP)))255
.size(px(SIZE))259
.size(px(SIZE))256
.flex_none()260
.flex_none()@@ -25,6 +25,7 @@ mod render_env;
25
25
mod scheduled;
26
26
27
27
use super::attachments::FileActions;
28
use super::profile_card::opens_profile;
28
29
use super::avatar::{member_stack, person_avatar, spec_avatar, square_avatar, with_presence};
29
30
use super::composer::{Composer, ComposerEvent, EditPreview, Outgoing, ReplyPreview};
30
31
use super::message_actions::{Action, MessageMenu, QUICK_REACTION_COUNT};
@@ -507,7 +508,12 @@ impl ConversationView {
507
508
self.refresh_reactor_names(cx);
508
509
cx.notify();
509
510
}
510
AppEvent::TaskDialog | AppEvent::LocalPreviews | AppEvent::Forward => {}
511
AppEvent::TaskDialog
512
| AppEvent::LocalPreviews
513
| AppEvent::Forward
514
| AppEvent::StatusMessage
515
| AppEvent::NotificationSettings
516
| AppEvent::Profile => {}
511
517
AppEvent::Saved => cx.notify(),
512
518
AppEvent::Pins(conversation_id) => self.on_pins_changed(conversation_id, cx),
513
519
AppEvent::Typing => cx.notify(),
@@ -2803,11 +2809,16 @@ impl ConversationView {
2803
2809
let user_id = first.as_ref().and_then(|face| face.user_id.as_deref());
2804
2810
let avatar = person_avatar(directory, user_id, name, 36.);
2805
2811
let presence = user_id.map(|id| directory.presence_of(id));
2806
lead = Some(match presence {
2812
let avatar = match presence {
2807
2813
Some(kind) => with_presence(avatar, kind, 36., theme::background())
2808
2814
.into_any_element(),
2809
2815
None => avatar,
2810
});
2816
};
2817
lead = Some(
2818
opens_profile(div().id("header-avatar").flex_none(), user_id)
2819
.child(avatar)
2820
.into_any_element(),
2821
);
2811
2822
subline = presence
2812
2823
.map(|presence| presence.kind().label().to_owned())
2813
2824
.unwrap_or_default();
@@ -25,6 +25,7 @@ mod render_env;25
mod scheduled;25
mod scheduled;26
26
27
use super::attachments::FileActions;27
use super::attachments::FileActions;28
use super::profile_card::opens_profile;28
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};29
use super::composer::{Composer, ComposerEvent, EditPreview, Outgoing, ReplyPreview};30
use super::composer::{Composer, ComposerEvent, EditPreview, Outgoing, ReplyPreview};30
use super::message_actions::{Action, MessageMenu, QUICK_REACTION_COUNT};31
use super::message_actions::{Action, MessageMenu, QUICK_REACTION_COUNT};@@ -507,7 +508,12 @@ impl ConversationView {507
self.refresh_reactor_names(cx);508
self.refresh_reactor_names(cx);508
cx.notify();509
cx.notify();509
}510
}510
AppEvent::TaskDialog | AppEvent::LocalPreviews | AppEvent::Forward => {}511
AppEvent::TaskDialog512
| AppEvent::LocalPreviews513
| AppEvent::Forward514
| AppEvent::StatusMessage515
| AppEvent::NotificationSettings516
| AppEvent::Profile => {}511
AppEvent::Saved => cx.notify(),517
AppEvent::Saved => cx.notify(),512
AppEvent::Pins(conversation_id) => self.on_pins_changed(conversation_id, cx),518
AppEvent::Pins(conversation_id) => self.on_pins_changed(conversation_id, cx),513
AppEvent::Typing => cx.notify(),519
AppEvent::Typing => cx.notify(),@@ -2803,11 +2809,16 @@ impl ConversationView {2803
let user_id = first.as_ref().and_then(|face| face.user_id.as_deref());2809
let user_id = first.as_ref().and_then(|face| face.user_id.as_deref());2804
let avatar = person_avatar(directory, user_id, name, 36.);2810
let avatar = person_avatar(directory, user_id, name, 36.);2805
let presence = user_id.map(|id| directory.presence_of(id));2811
let presence = user_id.map(|id| directory.presence_of(id));2806
lead = Some(match presence {2812
let avatar = match presence {2807
Some(kind) => with_presence(avatar, kind, 36., theme::background())2813
Some(kind) => with_presence(avatar, kind, 36., theme::background())2808
.into_any_element(),2814
.into_any_element(),2809
None => avatar,2815
None => avatar,2810
});2816
};2817
lead = Some(2818
opens_profile(div().id("header-avatar").flex_none(), user_id)2819
.child(avatar)2820
.into_any_element(),2821
);2811
subline = presence2822
subline = presence2812
.map(|presence| presence.kind().label().to_owned())2823
.map(|presence| presence.kind().label().to_owned())2813
.unwrap_or_default();2824
.unwrap_or_default();@@ -9,6 +9,7 @@ use super::attachments::{FileActions, attachments_view, message_body};
9
9
use super::avatar::{bot_avatar, person_avatar};
10
10
use super::link_preview::link_preview_card;
11
11
use super::message_actions::{HoverChange, MessageMenu, message_toolbar};
12
use super::profile_card::opens_profile;
12
13
use super::reaction_picker::PickHandler;
13
14
use super::reaction_pills::{ReactionControls, reaction_pills};
14
15
use super::scheduled_toolbar::{ScheduledMenu, scheduled_toolbar};
@@ -461,6 +462,7 @@ fn others_row(
461
462
) -> Div {
462
463
let first = !row.series.has_prev;
463
464
let author = bot.map_or_else(|| row.author.clone(), |bot| bot.name.clone());
465
let profile_user = row.sender_id.as_deref().filter(|_| bot.is_none());
464
466
let mut column = v_flex()
465
467
.gap(px(2.))
466
468
.max_w(relative(MAX_WIDTH_RATIO))
@@ -468,7 +470,10 @@ fn others_row(
468
470
if first {
469
471
column = column.child(
470
472
h_flex().gap(px(8.)).items_baseline().pl(px(2.)).child(
471
div()
473
opens_profile(
474
div().id(ElementId::Name(format!("author-{index}").into())),
475
profile_user,
476
)
472
477
.text_size(px(12.))
473
478
.font_weight(FontWeight::SEMIBOLD)
474
479
.text_color(theme::text_soft())
@@ -496,7 +501,15 @@ fn others_row(
496
501
.w_full()
497
502
.gap(px(AVATAR_GAP))
498
503
.items_start()
499
.child(div().w(px(AVATAR_SIZE)).flex_none().child(lead))
504
.child(
505
opens_profile(
506
div().id(ElementId::Name(format!("author-avatar-{index}").into())),
507
profile_user.filter(|_| first),
508
)
509
.w(px(AVATAR_SIZE))
510
.flex_none()
511
.child(lead),
512
)
500
513
.child(column)
501
514
}
502
515
@@ -9,6 +9,7 @@ use super::attachments::{FileActions, attachments_view, message_body};9
use super::avatar::{bot_avatar, person_avatar};9
use super::avatar::{bot_avatar, person_avatar};10
use super::link_preview::link_preview_card;10
use super::link_preview::link_preview_card;11
use super::message_actions::{HoverChange, MessageMenu, message_toolbar};11
use super::message_actions::{HoverChange, MessageMenu, message_toolbar};12
use super::profile_card::opens_profile;12
use super::reaction_picker::PickHandler;13
use super::reaction_picker::PickHandler;13
use super::reaction_pills::{ReactionControls, reaction_pills};14
use super::reaction_pills::{ReactionControls, reaction_pills};14
use super::scheduled_toolbar::{ScheduledMenu, scheduled_toolbar};15
use super::scheduled_toolbar::{ScheduledMenu, scheduled_toolbar};@@ -461,6 +462,7 @@ fn others_row(461
) -> Div {462
) -> Div {462
let first = !row.series.has_prev;463
let first = !row.series.has_prev;463
let author = bot.map_or_else(|| row.author.clone(), |bot| bot.name.clone());464
let author = bot.map_or_else(|| row.author.clone(), |bot| bot.name.clone());465
let profile_user = row.sender_id.as_deref().filter(|_| bot.is_none());464
let mut column = v_flex()466
let mut column = v_flex()465
.gap(px(2.))467
.gap(px(2.))466
.max_w(relative(MAX_WIDTH_RATIO))468
.max_w(relative(MAX_WIDTH_RATIO))@@ -468,7 +470,10 @@ fn others_row(468
if first {470
if first {469
column = column.child(471
column = column.child(470
h_flex().gap(px(8.)).items_baseline().pl(px(2.)).child(472
h_flex().gap(px(8.)).items_baseline().pl(px(2.)).child(471
div()473
opens_profile(474
div().id(ElementId::Name(format!("author-{index}").into())),475
profile_user,476
)472
.text_size(px(12.))477
.text_size(px(12.))473
.font_weight(FontWeight::SEMIBOLD)478
.font_weight(FontWeight::SEMIBOLD)474
.text_color(theme::text_soft())479
.text_color(theme::text_soft())@@ -496,7 +501,15 @@ fn others_row(496
.w_full()501
.w_full()497
.gap(px(AVATAR_GAP))502
.gap(px(AVATAR_GAP))498
.items_start()503
.items_start()499
.child(div().w(px(AVATAR_SIZE)).flex_none().child(lead))504
.child(505
opens_profile(506
div().id(ElementId::Name(format!("author-avatar-{index}").into())),507
profile_user.filter(|_| first),508
)509
.w(px(AVATAR_SIZE))510
.flex_none()511
.child(lead),512
)500
.child(column)513
.child(column)501
}514
}502
515
@@ -25,6 +25,7 @@ pub mod message_row;
25
25
pub mod new_chat;
26
26
pub mod pin_banner;
27
27
pub mod post_card;
28
pub mod profile_card;
28
29
pub mod reaction_picker;
29
30
pub mod reaction_pills;
30
31
pub mod saved_panel;
@@ -32,6 +33,8 @@ pub mod scheduled_toolbar;
32
33
pub mod shell;
33
34
pub mod sidebar;
34
35
pub mod status_bar;
36
pub mod status_menu;
37
pub mod status_message_dialog;
35
38
pub mod switcher;
36
39
pub mod title_bar;
37
40
pub mod widgets;
@@ -25,6 +25,7 @@ pub mod message_row;25
pub mod new_chat;25
pub mod new_chat;26
pub mod pin_banner;26
pub mod pin_banner;27
pub mod post_card;27
pub mod post_card;28
pub mod profile_card;28
pub mod reaction_picker;29
pub mod reaction_picker;29
pub mod reaction_pills;30
pub mod reaction_pills;30
pub mod saved_panel;31
pub mod saved_panel;@@ -32,6 +33,8 @@ pub mod scheduled_toolbar;32
pub mod shell;33
pub mod shell;33
pub mod sidebar;34
pub mod sidebar;34
pub mod status_bar;35
pub mod status_bar;36
pub mod status_menu;37
pub mod status_message_dialog;35
pub mod switcher;38
pub mod switcher;36
pub mod title_bar;39
pub mod title_bar;37
pub mod widgets;40
pub mod widgets;@@ -6,6 +6,7 @@ use gpui_kit::*;
6
6
use super::adaptive_card::cards_view;
7
7
use super::attachments::{attachments_view, message_body};
8
8
use super::avatar::{bot_avatar, person_avatar};
9
use super::profile_card::opens_profile;
9
10
use super::link_preview::link_preview_card;
10
11
use super::message_actions::message_toolbar;
11
12
use super::message_row::{BODY_SIZE, RowActions, delivery_note, forwarded_header, has_text};
@@ -130,12 +131,21 @@ fn message_content(
130
131
content
131
132
}
132
133
133
fn message_header(row: &MessageRow, author: String, saved: bool) -> Div {
134
fn message_header(
135
row: &MessageRow,
136
index: usize,
137
author: String,
138
profile_user: Option<&str>,
139
saved: bool,
140
) -> Div {
134
141
h_flex()
135
142
.gap(px(6.))
136
143
.items_center()
137
144
.child(
138
div()
145
opens_profile(
146
div().id(ElementId::Name(format!("post-author-{index}").into())),
147
profile_user,
148
)
139
149
.text_size(px(13.))
140
150
.font_weight(FontWeight::SEMIBOLD)
141
151
.text_color(theme::text())
@@ -177,6 +187,7 @@ fn message_block(
177
187
Some(bot) => bot_avatar(bot, size),
178
188
None => person_avatar(directory, row.sender_id.as_deref(), &row.author, size),
179
189
};
190
let profile_user = row.sender_id.as_deref().filter(|_| actions.bot.is_none());
180
191
let content = message_content(row, index, directory, &actions, cx);
181
192
let saved = actions.saved;
182
193
let RowActions {
@@ -193,7 +204,7 @@ fn message_block(
193
204
.flex_1()
194
205
.min_w_0()
195
206
.gap(px(6.))
196
.child(message_header(row, author, saved))
207
.child(message_header(row, index, author, profile_user, saved))
197
208
.when_some(
198
209
row.subject.clone().filter(|_| role == Role::Root),
199
210
|column, subject| {
@@ -230,7 +241,15 @@ fn message_block(
230
241
h_flex()
231
242
.items_start()
232
243
.gap(px(if role == Role::Root { AVATAR_GAP } else { 8. }))
233
.child(div().w(px(size)).flex_none().child(avatar))
244
.child(
245
opens_profile(
246
div().id(ElementId::Name(format!("post-avatar-{index}").into())),
247
profile_user,
248
)
249
.w(px(size))
250
.flex_none()
251
.child(avatar),
252
)
234
253
.child(body),
235
254
)
236
255
.when_some(menu, |block, menu| {
@@ -6,6 +6,7 @@ use gpui_kit::*;6
use super::adaptive_card::cards_view;6
use super::adaptive_card::cards_view;7
use super::attachments::{attachments_view, message_body};7
use super::attachments::{attachments_view, message_body};8
use super::avatar::{bot_avatar, person_avatar};8
use super::avatar::{bot_avatar, person_avatar};9
use super::profile_card::opens_profile;9
use super::link_preview::link_preview_card;10
use super::link_preview::link_preview_card;10
use super::message_actions::message_toolbar;11
use super::message_actions::message_toolbar;11
use super::message_row::{BODY_SIZE, RowActions, delivery_note, forwarded_header, has_text};12
use super::message_row::{BODY_SIZE, RowActions, delivery_note, forwarded_header, has_text};@@ -130,12 +131,21 @@ fn message_content(130
content131
content131
}132
}132
133
133
fn message_header(row: &MessageRow, author: String, saved: bool) -> Div {134
fn message_header(135
row: &MessageRow,136
index: usize,137
author: String,138
profile_user: Option<&str>,139
saved: bool,140
) -> Div {134
h_flex()141
h_flex()135
.gap(px(6.))142
.gap(px(6.))136
.items_center()143
.items_center()137
.child(144
.child(138
div()145
opens_profile(146
div().id(ElementId::Name(format!("post-author-{index}").into())),147
profile_user,148
)139
.text_size(px(13.))149
.text_size(px(13.))140
.font_weight(FontWeight::SEMIBOLD)150
.font_weight(FontWeight::SEMIBOLD)141
.text_color(theme::text())151
.text_color(theme::text())@@ -177,6 +187,7 @@ fn message_block(177
Some(bot) => bot_avatar(bot, size),187
Some(bot) => bot_avatar(bot, size),178
None => person_avatar(directory, row.sender_id.as_deref(), &row.author, size),188
None => person_avatar(directory, row.sender_id.as_deref(), &row.author, size),179
};189
};190
let profile_user = row.sender_id.as_deref().filter(|_| actions.bot.is_none());180
let content = message_content(row, index, directory, &actions, cx);191
let content = message_content(row, index, directory, &actions, cx);181
let saved = actions.saved;192
let saved = actions.saved;182
let RowActions {193
let RowActions {@@ -193,7 +204,7 @@ fn message_block(193
.flex_1()204
.flex_1()194
.min_w_0()205
.min_w_0()195
.gap(px(6.))206
.gap(px(6.))196
.child(message_header(row, author, saved))207
.child(message_header(row, index, author, profile_user, saved))197
.when_some(208
.when_some(198
row.subject.clone().filter(|_| role == Role::Root),209
row.subject.clone().filter(|_| role == Role::Root),199
|column, subject| {210
|column, subject| {@@ -230,7 +241,15 @@ fn message_block(230
h_flex()241
h_flex()231
.items_start()242
.items_start()232
.gap(px(if role == Role::Root { AVATAR_GAP } else { 8. }))243
.gap(px(if role == Role::Root { AVATAR_GAP } else { 8. }))233
.child(div().w(px(size)).flex_none().child(avatar))244
.child(245
opens_profile(246
div().id(ElementId::Name(format!("post-avatar-{index}").into())),247
profile_user,248
)249
.w(px(size))250
.flex_none()251
.child(avatar),252
)234
.child(body),253
.child(body),235
)254
)236
.when_some(menu, |block, menu| {255
.when_some(menu, |block, menu| {@@ -0,0 +1,675 @@
1
use std::sync::Arc;
2
3
use chrono::Utc;
4
use gpui_kit::assets::IconName;
5
use gpui_kit::base::GlobalState;
6
use gpui_kit::component::{h_flex, tooltip::Tooltip, v_flex};
7
use gpui_kit::prelude::FluentBuilder as _;
8
use gpui_kit::*;
9
use teams_core::{OrgPerson, PROFILE_LINK_PREFIX, PersonProfile, WorkLocationKind};
10
11
use super::avatar::{person_avatar, with_presence};
12
use super::widgets::icon;
13
use crate::app_state::{AppHandle, AppState};
14
use crate::data::{Presence, PresenceKind, presence_kind_of};
15
use crate::people::resolve_names;
16
use crate::profile_model::{
17
ContactKind, ContactRow, StatusBox, contact_rows, has_organization, local_time_label,
18
mailto_url, status_box, status_line, work_location_label,
19
};
20
use crate::theme;
21
22
const CARD_WIDTH: f32 = 340.;
23
const CARD_RADIUS: f32 = 10.;
24
const CARD_PADDING: f32 = 16.;
25
const CARD_GAP: f32 = 12.;
26
const CARD_MARGIN: f32 = 8.;
27
const CLICK_OFFSET: f32 = 4.;
28
const PHOTO_SIZE: f32 = 56.;
29
const PERSON_ROW_AVATAR: f32 = 22.;
30
const STATUS_LINES: usize = 3;
31
const REPORTS_MAX_HEIGHT: f32 = 168.;
32
const ACTION_HEIGHT: f32 = 30.;
33
const SKELETON_HEIGHT: f32 = 10.;
34
35
pub enum ProfileCardEvent {
36
Close,
37
}
38
39
pub struct ProfileCard {
40
app: Entity<AppState>,
41
user_id: String,
42
history: Vec<String>,
43
anchor: Point<Pixels>,
44
contact_open: bool,
45
organization_open: bool,
46
reports_open: bool,
47
focus_handle: FocusHandle,
48
_observation: Subscription,
49
}
50
51
impl EventEmitter<ProfileCardEvent> for ProfileCard {}
52
53
pub fn open_profile(user_id: &str, position: Point<Pixels>, cx: &mut App) {
54
let Some(handle) = cx.try_global::<AppHandle>() else {
55
return;
56
};
57
let (app, user_id) = (handle.0.clone(), user_id.to_owned());
58
app.update(cx, |state, cx| {
59
state.open_profile_card(&user_id, position, cx)
60
});
61
}
62
63
/// `true` when the link was a profile link and has been handled.
64
pub fn open_profile_link(url: &str, position: Point<Pixels>, cx: &mut App) -> bool {
65
match url.strip_prefix(PROFILE_LINK_PREFIX) {
66
Some(user_id) => {
67
open_profile(user_id, position, cx);
68
true
69
}
70
None => false,
71
}
72
}
73
74
pub fn opens_profile(element: Stateful<Div>, user_id: Option<&str>) -> Stateful<Div> {
75
match user_id {
76
Some(user_id) => {
77
let user_id = user_id.to_owned();
78
element.cursor_pointer().on_click(move |event, _, cx| {
79
cx.stop_propagation();
80
open_profile(&user_id, event.position(), cx)
81
})
82
}
83
None => element,
84
}
85
}
86
87
impl ProfileCard {
88
pub fn new(
89
app: Entity<AppState>,
90
user_id: String,
91
anchor: Point<Pixels>,
92
window: &mut Window,
93
cx: &mut Context<Self>,
94
) -> Self {
95
let focus_handle = cx.focus_handle();
96
window.focus(&focus_handle, cx);
97
let observation = cx.observe(&app, |_, _, cx| cx.notify());
98
ProfileCard {
99
app,
100
user_id,
101
history: Vec::new(),
102
anchor,
103
contact_open: true,
104
organization_open: true,
105
reports_open: false,
106
focus_handle,
107
_observation: observation,
108
}
109
}
110
111
pub fn move_to(&mut self, user_id: String, anchor: Point<Pixels>, cx: &mut Context<Self>) {
112
self.history.clear();
113
self.anchor = anchor;
114
self.show(user_id, false, cx);
115
}
116
117
fn show(&mut self, user_id: String, remember: bool, cx: &mut Context<Self>) {
118
if remember {
119
self.history
120
.push(std::mem::replace(&mut self.user_id, user_id));
121
} else {
122
self.user_id = user_id;
123
}
124
self.reports_open = false;
125
let id = self.user_id.clone();
126
self.app.update(cx, |state, cx| {
127
state.request_profile(&id, false, cx);
128
state.request_avatars(vec![id.clone()], cx);
129
});
130
cx.notify();
131
}
132
133
fn go_back(&mut self, cx: &mut Context<Self>) {
134
if let Some(previous) = self.history.pop() {
135
self.show(previous, false, cx);
136
}
137
}
138
139
fn on_key_down(&mut self, event: &KeyDownEvent, _: &mut Window, cx: &mut Context<Self>) {
140
if event.keystroke.key == "escape" {
141
cx.emit(ProfileCardEvent::Close);
142
}
143
}
144
145
fn display_name(&self, profile: Option<&PersonProfile>, cx: &App) -> String {
146
profile
147
.and_then(|profile| profile.display_name.clone())
148
.or_else(|| {
149
resolve_names(self.app.read(cx), std::slice::from_ref(&self.user_id))
150
.remove(&self.user_id)
151
})
152
.unwrap_or_else(|| "Unknown person".to_owned())
153
}
154
155
fn presence(&self, profile: Option<&PersonProfile>, cx: &App) -> Presence {
156
let directory = self.app.read(cx).directory.presence_of(&self.user_id);
157
match (directory, profile.and_then(|profile| profile.availability)) {
158
(Presence::Live(kind), _) if kind != PresenceKind::Unknown => directory,
159
(_, Some(availability)) => Presence::Live(presence_kind_of(availability)),
160
_ => directory,
161
}
162
}
163
164
fn header(&self, profile: Option<&PersonProfile>, failed: bool, cx: &App) -> Div {
165
let name = self.display_name(profile, cx);
166
let presence = self.presence(profile, cx);
167
let directory = &self.app.read(cx).directory;
168
let photo = with_presence(
169
person_avatar(directory, Some(&self.user_id), &name, PHOTO_SIZE),
170
presence,
171
PHOTO_SIZE,
172
theme::surface_raised(),
173
);
174
let availability = presence.kind().label();
175
let local_time = profile.and_then(|profile| local_time_label(profile, Utc::now()));
176
let subline = status_line(availability, local_time.as_deref());
177
let details = v_flex()
178
.gap(px(1.))
179
.children(profile.into_iter().flat_map(|profile| {
180
[&profile.job_title, &profile.department]
181
.into_iter()
182
.flatten()
183
.filter(|text| !text.trim().is_empty())
184
.map(|text| muted_line(text.clone()))
185
.collect::<Vec<_>>()
186
}));
187
let work_location = profile
188
.and_then(|profile| profile.work_location)
189
.map(|location| {
190
let glyph = match location.kind {
191
WorkLocationKind::Office => IconName::Building2,
192
WorkLocationKind::Remote => IconName::House,
193
};
194
h_flex()
195
.gap(px(5.))
196
.items_center()
197
.child(icon(glyph, 13., theme::text_muted()))
198
.child(muted_line(work_location_label(location).to_owned()))
199
});
200
let loading = profile.is_none() && !failed;
201
h_flex().gap(px(12.)).items_center().child(photo).child(
202
v_flex()
203
.flex_1()
204
.min_w_0()
205
.gap(px(2.))
206
.child(
207
div()
208
.truncate()
209
.text_size(px(15.))
210
.font_weight(FontWeight::SEMIBOLD)
211
.text_color(theme::text())
212
.child(name),
213
)
214
.when(!subline.is_empty(), |column| {
215
column.child(muted_line(subline))
216
})
217
.children(work_location)
218
.child(details)
219
.when(loading, |column| column.child(skeleton(0.6))),
220
)
221
}
222
223
fn status_box(&self, status: &StatusBox) -> AnyElement {
224
let (background, foreground) = if status.out_of_office {
225
(theme::amber().opacity(0.12), theme::amber())
226
} else {
227
(theme::surface(), theme::text_soft())
228
};
229
let full_text = status.text.clone();
230
div()
231
.id("profile-status")
232
.w_full()
233
.px(px(10.))
234
.py(px(8.))
235
.rounded(px(6.))
236
.bg(background)
237
.text_color(foreground)
238
.text_size(px(12.))
239
.line_height(relative(1.4))
240
.child(
241
div()
242
.line_clamp(STATUS_LINES)
243
.text_ellipsis()
244
.child(status.text.clone()),
245
)
246
.tooltip(move |window, cx| Tooltip::new(full_text.clone()).build(window, cx))
247
.into_any_element()
248
}
249
250
fn actions(&self, email: Option<String>, cx: &mut Context<Self>) -> Div {
251
let is_me = self
252
.app
253
.read(cx)
254
.directory
255
.me
256
.as_ref()
257
.is_some_and(|me| me.user_id == self.user_id);
258
let user_id = self.user_id.clone();
259
let (mail_email, copy_email) = (email.clone(), email.clone());
260
h_flex()
261
.gap(px(8.))
262
.when(!is_me, |row| {
263
row.child(
264
action_button("profile-chat", "Chat", IconName::MessageSquare, true).on_click(
265
cx.listener(move |this, _, _, cx| {
266
let user_id = user_id.clone();
267
this.app
268
.update(cx, |state, cx| state.open_chat_with(&user_id, cx));
269
cx.emit(ProfileCardEvent::Close);
270
}),
271
),
272
)
273
})
274
.when_some(mail_email, |row, address| {
275
row.child(
276
action_button("profile-email", "Email", IconName::Mail, false).on_click(
277
cx.listener(move |_, _, _, cx| {
278
cx.open_url(&mailto_url(&address));
279
cx.emit(ProfileCardEvent::Close);
280
}),
281
),
282
)
283
})
284
.when_some(copy_email, |row, address| {
285
row.child(
286
action_button("profile-copy-email", "Copy email", IconName::Copy, false)
287
.on_click(cx.listener(move |this, _, _, cx| {
288
this.app
289
.update(cx, |state, cx| state.copy_profile_email(&address, cx));
290
cx.emit(ProfileCardEvent::Close);
291
})),
292
)
293
})
294
}
295
296
fn section_header(
297
&self,
298
id: &'static str,
299
label: &'static str,
300
open: bool,
301
cx: &mut Context<Self>,
302
) -> Stateful<Div> {
303
h_flex()
304
.id(id)
305
.gap(px(4.))
306
.items_center()
307
.cursor_pointer()
308
.text_size(px(12.))
309
.font_weight(FontWeight::SEMIBOLD)
310
.text_color(theme::text_muted())
311
.child(icon(
312
if open {
313
IconName::ChevronDown
314
} else {
315
IconName::ChevronRight
316
},
317
14.,
318
theme::text_muted(),
319
))
320
.child(label)
321
.on_click(cx.listener(move |this, _, _, cx| {
322
match id {
323
"profile-contact-header" => this.contact_open = !this.contact_open,
324
_ => this.organization_open = !this.organization_open,
325
}
326
cx.notify();
327
}))
328
}
329
330
fn contact_section(&self, rows: Vec<ContactRow>, cx: &mut Context<Self>) -> Div {
331
let open = self.contact_open;
332
v_flex()
333
.gap(px(6.))
334
.child(self.section_header("profile-contact-header", "Contact", open, cx))
335
.when(open, |section| {
336
section.children(rows.into_iter().map(contact_row))
337
})
338
}
339
340
fn person_row(
341
&self,
342
id: String,
343
person: &OrgPerson,
344
caption: Option<&'static str>,
345
cx: &mut Context<Self>,
346
) -> Stateful<Div> {
347
let name = person.display_name.clone().unwrap_or_default();
348
let subtitle = caption
349
.map(str::to_owned)
350
.or_else(|| person.job_title.clone())
351
.filter(|text| !text.is_empty());
352
let target = person.id.clone();
353
let directory = &self.app.read(cx).directory;
354
h_flex()
355
.id(ElementId::Name(id.into()))
356
.gap(px(8.))
357
.px(px(4.))
358
.py(px(3.))
359
.items_center()
360
.rounded(px(6.))
361
.cursor_pointer()
362
.hover(|row| row.bg(theme::row_hover()))
363
.child(person_avatar(
364
directory,
365
Some(&person.id),
366
&name,
367
PERSON_ROW_AVATAR,
368
))
369
.child(
370
div()
371
.truncate()
372
.text_size(px(12.5))
373
.text_color(theme::text())
374
.child(name),
375
)
376
.children(
377
subtitle.map(|text| div().flex_1().min_w_0().truncate().child(muted_text(text))),
378
)
379
.on_click(cx.listener(move |this, _, _, cx| this.show(target.clone(), true, cx)))
380
}
381
382
fn organization_section(&self, profile: &PersonProfile, cx: &mut Context<Self>) -> Div {
383
let open = self.organization_open;
384
let mut section = v_flex().gap(px(4.)).child(self.section_header(
385
"profile-organization-header",
386
"Organization",
387
open,
388
cx,
389
));
390
if !open {
391
return section;
392
}
393
if let Some(manager) = &profile.manager {
394
section = section.child(self.person_row(
395
"profile-manager".to_owned(),
396
manager,
397
Some("Manager"),
398
cx,
399
));
400
}
401
let count = profile.direct_reports.len();
402
if count > 0 {
403
let label = match count {
404
1 => "1 direct report".to_owned(),
405
count => format!("{count} direct reports"),
406
};
407
let reports_open = self.reports_open;
408
section = section.child(
409
h_flex()
410
.id("profile-reports-toggle")
411
.gap(px(4.))
412
.px(px(4.))
413
.py(px(3.))
414
.items_center()
415
.cursor_pointer()
416
.text_size(px(12.5))
417
.text_color(theme::text_soft())
418
.child(label)
419
.child(icon(
420
if reports_open {
421
IconName::ChevronDown
422
} else {
423
IconName::ChevronRight
424
},
425
14.,
426
theme::text_muted(),
427
))
428
.on_click(cx.listener(|this, _, _, cx| {
429
this.reports_open = !this.reports_open;
430
cx.notify();
431
})),
432
);
433
if reports_open {
434
let rows: Vec<Stateful<Div>> = profile
435
.direct_reports
436
.iter()
437
.enumerate()
438
.map(|(index, person)| {
439
self.person_row(format!("profile-report-{index}"), person, None, cx)
440
})
441
.collect();
442
section = section.child(
443
v_flex()
444
.id("profile-reports")
445
.max_h(px(REPORTS_MAX_HEIGHT))
446
.overflow_y_scroll()
447
.children(rows),
448
);
449
}
450
}
451
section
452
}
453
454
fn loading_sections(&self) -> Div {
455
v_flex()
456
.gap(px(8.))
457
.child(skeleton(1.))
458
.child(skeleton(0.8))
459
.child(skeleton(0.5))
460
}
461
462
fn failure(&self, cx: &mut Context<Self>) -> Div {
463
h_flex()
464
.gap(px(6.))
465
.text_size(px(12.))
466
.text_color(theme::red_soft())
467
.child("Profile details could not be loaded.")
468
.child(
469
div()
470
.id("profile-retry")
471
.cursor_pointer()
472
.underline()
473
.text_color(theme::red_tint())
474
.child("Retry")
475
.on_click(cx.listener(|this, _, _, cx| {
476
let id = this.user_id.clone();
477
this.app
478
.update(cx, |state, cx| state.request_profile(&id, true, cx));
479
})),
480
)
481
}
482
483
fn body(&self, entry_state: EntryState, cx: &mut Context<Self>) -> Vec<AnyElement> {
484
let EntryState { profile, failed } = entry_state;
485
let mut parts: Vec<AnyElement> = Vec::new();
486
let Some(profile) = profile else {
487
parts.push(self.actions(None, cx).into_any_element());
488
parts.push(if failed {
489
self.failure(cx).into_any_element()
490
} else {
491
self.loading_sections().into_any_element()
492
});
493
return parts;
494
};
495
if let Some(status) = status_box(&profile) {
496
parts.push(self.status_box(&status));
497
}
498
parts.push(self.actions(profile.email.clone(), cx).into_any_element());
499
let rows = contact_rows(&profile);
500
if !rows.is_empty() {
501
parts.push(self.contact_section(rows, cx).into_any_element());
502
}
503
if has_organization(&profile) {
504
parts.push(self.organization_section(&profile, cx).into_any_element());
505
}
506
if failed {
507
parts.push(self.failure(cx).into_any_element());
508
}
509
parts
510
}
511
}
512
513
struct EntryState {
514
profile: Option<Arc<PersonProfile>>,
515
failed: bool,
516
}
517
518
fn muted_text(text: String) -> Div {
519
div()
520
.text_size(px(12.))
521
.text_color(theme::text_muted())
522
.child(text)
523
}
524
525
fn muted_line(text: String) -> Div {
526
muted_text(text).truncate()
527
}
528
529
fn skeleton(width_ratio: f32) -> Div {
530
div()
531
.h(px(SKELETON_HEIGHT))
532
.w(relative(width_ratio))
533
.rounded(px(4.))
534
.bg(theme::border_strong())
535
}
536
537
fn contact_row(row: ContactRow) -> Div {
538
let glyph = match row.kind {
539
ContactKind::Email => IconName::Mail,
540
ContactKind::WorkPhone => IconName::Phone,
541
ContactKind::MobilePhone => IconName::Smartphone,
542
ContactKind::Office => IconName::MapPin,
543
};
544
h_flex()
545
.gap(px(8.))
546
.px(px(4.))
547
.items_center()
548
.child(icon(glyph, 14., theme::text_muted()))
549
.child(
550
div()
551
.flex_1()
552
.min_w_0()
553
.truncate()
554
.text_size(px(12.5))
555
.text_color(theme::text())
556
.child(row.value),
557
)
558
}
559
560
fn action_button(
561
id: &'static str,
562
label: &'static str,
563
glyph: IconName,
564
filled: bool,
565
) -> Stateful<Div> {
566
let (foreground, background) = if filled {
567
(theme::on_accent(), theme::accent())
568
} else {
569
(theme::text_soft(), theme::surface())
570
};
571
h_flex()
572
.id(id)
573
.h(px(ACTION_HEIGHT))
574
.px(px(10.))
575
.gap(px(6.))
576
.items_center()
577
.justify_center()
578
.rounded(px(6.))
579
.cursor_pointer()
580
.bg(background)
581
.text_color(foreground)
582
.text_size(px(12.5))
583
.font_weight(FontWeight::SEMIBOLD)
584
.when(!filled, |button| {
585
button
586
.border_1()
587
.border_color(theme::border_strong())
588
.hover(|button| button.bg(theme::row_hover()))
589
})
590
.when(filled, |button| button.hover(|button| button.opacity(0.9)))
591
.child(icon(glyph, 14., foreground))
592
.child(label)
593
}
594
595
impl Render for ProfileCard {
596
fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
597
let entry_state = self
598
.app
599
.read(cx)
600
.profiles
601
.get(&self.user_id)
602
.map(|entry| EntryState {
603
profile: entry.profile.clone(),
604
failed: entry.failed,
605
})
606
.unwrap_or(EntryState {
607
profile: None,
608
failed: false,
609
});
610
let profile = entry_state.profile.clone();
611
let header = self.header(profile.as_deref(), entry_state.failed, cx);
612
let body = self.body(entry_state, cx);
613
let back = (!self.history.is_empty()).then(|| {
614
h_flex()
615
.id("profile-back")
616
.gap(px(4.))
617
.items_center()
618
.cursor_pointer()
619
.text_size(px(12.))
620
.text_color(theme::text_muted())
621
.hover(|button| button.text_color(theme::text()))
622
.child(icon(IconName::ArrowLeft, 14., theme::text_muted()))
623
.child("Back")
624
.on_click(cx.listener(|this, _, _, cx| this.go_back(cx)))
625
});
626
let card = v_flex()
627
.id("profile-card")
628
.track_focus(&self.focus_handle)
629
.w(px(CARD_WIDTH))
630
.p(px(CARD_PADDING))
631
.gap(px(CARD_GAP))
632
.rounded(px(CARD_RADIUS))
633
.border_1()
634
.border_color(theme::border_strong())
635
.bg(theme::surface_raised())
636
.text_color(theme::text())
637
.shadow_lg()
638
.occlude()
639
.on_key_down(cx.listener(Self::on_key_down))
640
.on_mouse_down(MouseButton::Left, |_, _, cx| {
641
GlobalState::suppress_text_selection(cx);
642
cx.stop_propagation();
643
})
644
.on_mouse_down(MouseButton::Right, |_, _, cx| cx.stop_propagation())
645
.children(back)
646
.child(header)
647
.children(body);
648
let offset = point(px(CLICK_OFFSET), px(CLICK_OFFSET));
649
div()
650
.id("profile-layer")
651
.absolute()
652
.top_0()
653
.left_0()
654
.size_full()
655
.occlude()
656
.on_mouse_down(
657
MouseButton::Left,
658
cx.listener(|_, _, _, cx| cx.emit(ProfileCardEvent::Close)),
659
)
660
.on_mouse_down(
661
MouseButton::Right,
662
cx.listener(|_, _, _, cx| cx.emit(ProfileCardEvent::Close)),
663
)
664
.child(
665
deferred(
666
anchored()
667
.position(self.anchor + offset)
668
.anchor(Anchor::TopLeft)
669
.snap_to_window_with_margin(px(CARD_MARGIN))
670
.child(card),
671
)
672
.with_priority(2),
673
)
674
}
675
}
@@ -0,0 +1,675 @@1
use std::sync::Arc;2
3
use chrono::Utc;4
use gpui_kit::assets::IconName;5
use gpui_kit::base::GlobalState;6
use gpui_kit::component::{h_flex, tooltip::Tooltip, v_flex};7
use gpui_kit::prelude::FluentBuilder as _;8
use gpui_kit::*;9
use teams_core::{OrgPerson, PROFILE_LINK_PREFIX, PersonProfile, WorkLocationKind};10
11
use super::avatar::{person_avatar, with_presence};12
use super::widgets::icon;13
use crate::app_state::{AppHandle, AppState};14
use crate::data::{Presence, PresenceKind, presence_kind_of};15
use crate::people::resolve_names;16
use crate::profile_model::{17
ContactKind, ContactRow, StatusBox, contact_rows, has_organization, local_time_label,18
mailto_url, status_box, status_line, work_location_label,19
};20
use crate::theme;21
22
const CARD_WIDTH: f32 = 340.;23
const CARD_RADIUS: f32 = 10.;24
const CARD_PADDING: f32 = 16.;25
const CARD_GAP: f32 = 12.;26
const CARD_MARGIN: f32 = 8.;27
const CLICK_OFFSET: f32 = 4.;28
const PHOTO_SIZE: f32 = 56.;29
const PERSON_ROW_AVATAR: f32 = 22.;30
const STATUS_LINES: usize = 3;31
const REPORTS_MAX_HEIGHT: f32 = 168.;32
const ACTION_HEIGHT: f32 = 30.;33
const SKELETON_HEIGHT: f32 = 10.;34
35
pub enum ProfileCardEvent {36
Close,37
}38
39
pub struct ProfileCard {40
app: Entity<AppState>,41
user_id: String,42
history: Vec<String>,43
anchor: Point<Pixels>,44
contact_open: bool,45
organization_open: bool,46
reports_open: bool,47
focus_handle: FocusHandle,48
_observation: Subscription,49
}50
51
impl EventEmitter<ProfileCardEvent> for ProfileCard {}52
53
pub fn open_profile(user_id: &str, position: Point<Pixels>, cx: &mut App) {54
let Some(handle) = cx.try_global::<AppHandle>() else {55
return;56
};57
let (app, user_id) = (handle.0.clone(), user_id.to_owned());58
app.update(cx, |state, cx| {59
state.open_profile_card(&user_id, position, cx)60
});61
}62
63
/// `true` when the link was a profile link and has been handled.64
pub fn open_profile_link(url: &str, position: Point<Pixels>, cx: &mut App) -> bool {65
match url.strip_prefix(PROFILE_LINK_PREFIX) {66
Some(user_id) => {67
open_profile(user_id, position, cx);68
true69
}70
None => false,71
}72
}73
74
pub fn opens_profile(element: Stateful<Div>, user_id: Option<&str>) -> Stateful<Div> {75
match user_id {76
Some(user_id) => {77
let user_id = user_id.to_owned();78
element.cursor_pointer().on_click(move |event, _, cx| {79
cx.stop_propagation();80
open_profile(&user_id, event.position(), cx)81
})82
}83
None => element,84
}85
}86
87
impl ProfileCard {88
pub fn new(89
app: Entity<AppState>,90
user_id: String,91
anchor: Point<Pixels>,92
window: &mut Window,93
cx: &mut Context<Self>,94
) -> Self {95
let focus_handle = cx.focus_handle();96
window.focus(&focus_handle, cx);97
let observation = cx.observe(&app, |_, _, cx| cx.notify());98
ProfileCard {99
app,100
user_id,101
history: Vec::new(),102
anchor,103
contact_open: true,104
organization_open: true,105
reports_open: false,106
focus_handle,107
_observation: observation,108
}109
}110
111
pub fn move_to(&mut self, user_id: String, anchor: Point<Pixels>, cx: &mut Context<Self>) {112
self.history.clear();113
self.anchor = anchor;114
self.show(user_id, false, cx);115
}116
117
fn show(&mut self, user_id: String, remember: bool, cx: &mut Context<Self>) {118
if remember {119
self.history120
.push(std::mem::replace(&mut self.user_id, user_id));121
} else {122
self.user_id = user_id;123
}124
self.reports_open = false;125
let id = self.user_id.clone();126
self.app.update(cx, |state, cx| {127
state.request_profile(&id, false, cx);128
state.request_avatars(vec![id.clone()], cx);129
});130
cx.notify();131
}132
133
fn go_back(&mut self, cx: &mut Context<Self>) {134
if let Some(previous) = self.history.pop() {135
self.show(previous, false, cx);136
}137
}138
139
fn on_key_down(&mut self, event: &KeyDownEvent, _: &mut Window, cx: &mut Context<Self>) {140
if event.keystroke.key == "escape" {141
cx.emit(ProfileCardEvent::Close);142
}143
}144
145
fn display_name(&self, profile: Option<&PersonProfile>, cx: &App) -> String {146
profile147
.and_then(|profile| profile.display_name.clone())148
.or_else(|| {149
resolve_names(self.app.read(cx), std::slice::from_ref(&self.user_id))150
.remove(&self.user_id)151
})152
.unwrap_or_else(|| "Unknown person".to_owned())153
}154
155
fn presence(&self, profile: Option<&PersonProfile>, cx: &App) -> Presence {156
let directory = self.app.read(cx).directory.presence_of(&self.user_id);157
match (directory, profile.and_then(|profile| profile.availability)) {158
(Presence::Live(kind), _) if kind != PresenceKind::Unknown => directory,159
(_, Some(availability)) => Presence::Live(presence_kind_of(availability)),160
_ => directory,161
}162
}163
164
fn header(&self, profile: Option<&PersonProfile>, failed: bool, cx: &App) -> Div {165
let name = self.display_name(profile, cx);166
let presence = self.presence(profile, cx);167
let directory = &self.app.read(cx).directory;168
let photo = with_presence(169
person_avatar(directory, Some(&self.user_id), &name, PHOTO_SIZE),170
presence,171
PHOTO_SIZE,172
theme::surface_raised(),173
);174
let availability = presence.kind().label();175
let local_time = profile.and_then(|profile| local_time_label(profile, Utc::now()));176
let subline = status_line(availability, local_time.as_deref());177
let details = v_flex()178
.gap(px(1.))179
.children(profile.into_iter().flat_map(|profile| {180
[&profile.job_title, &profile.department]181
.into_iter()182
.flatten()183
.filter(|text| !text.trim().is_empty())184
.map(|text| muted_line(text.clone()))185
.collect::<Vec<_>>()186
}));187
let work_location = profile188
.and_then(|profile| profile.work_location)189
.map(|location| {190
let glyph = match location.kind {191
WorkLocationKind::Office => IconName::Building2,192
WorkLocationKind::Remote => IconName::House,193
};194
h_flex()195
.gap(px(5.))196
.items_center()197
.child(icon(glyph, 13., theme::text_muted()))198
.child(muted_line(work_location_label(location).to_owned()))199
});200
let loading = profile.is_none() && !failed;201
h_flex().gap(px(12.)).items_center().child(photo).child(202
v_flex()203
.flex_1()204
.min_w_0()205
.gap(px(2.))206
.child(207
div()208
.truncate()209
.text_size(px(15.))210
.font_weight(FontWeight::SEMIBOLD)211
.text_color(theme::text())212
.child(name),213
)214
.when(!subline.is_empty(), |column| {215
column.child(muted_line(subline))216
})217
.children(work_location)218
.child(details)219
.when(loading, |column| column.child(skeleton(0.6))),220
)221
}222
223
fn status_box(&self, status: &StatusBox) -> AnyElement {224
let (background, foreground) = if status.out_of_office {225
(theme::amber().opacity(0.12), theme::amber())226
} else {227
(theme::surface(), theme::text_soft())228
};229
let full_text = status.text.clone();230
div()231
.id("profile-status")232
.w_full()233
.px(px(10.))234
.py(px(8.))235
.rounded(px(6.))236
.bg(background)237
.text_color(foreground)238
.text_size(px(12.))239
.line_height(relative(1.4))240
.child(241
div()242
.line_clamp(STATUS_LINES)243
.text_ellipsis()244
.child(status.text.clone()),245
)246
.tooltip(move |window, cx| Tooltip::new(full_text.clone()).build(window, cx))247
.into_any_element()248
}249
250
fn actions(&self, email: Option<String>, cx: &mut Context<Self>) -> Div {251
let is_me = self252
.app253
.read(cx)254
.directory255
.me256
.as_ref()257
.is_some_and(|me| me.user_id == self.user_id);258
let user_id = self.user_id.clone();259
let (mail_email, copy_email) = (email.clone(), email.clone());260
h_flex()261
.gap(px(8.))262
.when(!is_me, |row| {263
row.child(264
action_button("profile-chat", "Chat", IconName::MessageSquare, true).on_click(265
cx.listener(move |this, _, _, cx| {266
let user_id = user_id.clone();267
this.app268
.update(cx, |state, cx| state.open_chat_with(&user_id, cx));269
cx.emit(ProfileCardEvent::Close);270
}),271
),272
)273
})274
.when_some(mail_email, |row, address| {275
row.child(276
action_button("profile-email", "Email", IconName::Mail, false).on_click(277
cx.listener(move |_, _, _, cx| {278
cx.open_url(&mailto_url(&address));279
cx.emit(ProfileCardEvent::Close);280
}),281
),282
)283
})284
.when_some(copy_email, |row, address| {285
row.child(286
action_button("profile-copy-email", "Copy email", IconName::Copy, false)287
.on_click(cx.listener(move |this, _, _, cx| {288
this.app289
.update(cx, |state, cx| state.copy_profile_email(&address, cx));290
cx.emit(ProfileCardEvent::Close);291
})),292
)293
})294
}295
296
fn section_header(297
&self,298
id: &'static str,299
label: &'static str,300
open: bool,301
cx: &mut Context<Self>,302
) -> Stateful<Div> {303
h_flex()304
.id(id)305
.gap(px(4.))306
.items_center()307
.cursor_pointer()308
.text_size(px(12.))309
.font_weight(FontWeight::SEMIBOLD)310
.text_color(theme::text_muted())311
.child(icon(312
if open {313
IconName::ChevronDown314
} else {315
IconName::ChevronRight316
},317
14.,318
theme::text_muted(),319
))320
.child(label)321
.on_click(cx.listener(move |this, _, _, cx| {322
match id {323
"profile-contact-header" => this.contact_open = !this.contact_open,324
_ => this.organization_open = !this.organization_open,325
}326
cx.notify();327
}))328
}329
330
fn contact_section(&self, rows: Vec<ContactRow>, cx: &mut Context<Self>) -> Div {331
let open = self.contact_open;332
v_flex()333
.gap(px(6.))334
.child(self.section_header("profile-contact-header", "Contact", open, cx))335
.when(open, |section| {336
section.children(rows.into_iter().map(contact_row))337
})338
}339
340
fn person_row(341
&self,342
id: String,343
person: &OrgPerson,344
caption: Option<&'static str>,345
cx: &mut Context<Self>,346
) -> Stateful<Div> {347
let name = person.display_name.clone().unwrap_or_default();348
let subtitle = caption349
.map(str::to_owned)350
.or_else(|| person.job_title.clone())351
.filter(|text| !text.is_empty());352
let target = person.id.clone();353
let directory = &self.app.read(cx).directory;354
h_flex()355
.id(ElementId::Name(id.into()))356
.gap(px(8.))357
.px(px(4.))358
.py(px(3.))359
.items_center()360
.rounded(px(6.))361
.cursor_pointer()362
.hover(|row| row.bg(theme::row_hover()))363
.child(person_avatar(364
directory,365
Some(&person.id),366
&name,367
PERSON_ROW_AVATAR,368
))369
.child(370
div()371
.truncate()372
.text_size(px(12.5))373
.text_color(theme::text())374
.child(name),375
)376
.children(377
subtitle.map(|text| div().flex_1().min_w_0().truncate().child(muted_text(text))),378
)379
.on_click(cx.listener(move |this, _, _, cx| this.show(target.clone(), true, cx)))380
}381
382
fn organization_section(&self, profile: &PersonProfile, cx: &mut Context<Self>) -> Div {383
let open = self.organization_open;384
let mut section = v_flex().gap(px(4.)).child(self.section_header(385
"profile-organization-header",386
"Organization",387
open,388
cx,389
));390
if !open {391
return section;392
}393
if let Some(manager) = &profile.manager {394
section = section.child(self.person_row(395
"profile-manager".to_owned(),396
manager,397
Some("Manager"),398
cx,399
));400
}401
let count = profile.direct_reports.len();402
if count > 0 {403
let label = match count {404
1 => "1 direct report".to_owned(),405
count => format!("{count} direct reports"),406
};407
let reports_open = self.reports_open;408
section = section.child(409
h_flex()410
.id("profile-reports-toggle")411
.gap(px(4.))412
.px(px(4.))413
.py(px(3.))414
.items_center()415
.cursor_pointer()416
.text_size(px(12.5))417
.text_color(theme::text_soft())418
.child(label)419
.child(icon(420
if reports_open {421
IconName::ChevronDown422
} else {423
IconName::ChevronRight424
},425
14.,426
theme::text_muted(),427
))428
.on_click(cx.listener(|this, _, _, cx| {429
this.reports_open = !this.reports_open;430
cx.notify();431
})),432
);433
if reports_open {434
let rows: Vec<Stateful<Div>> = profile435
.direct_reports436
.iter()437
.enumerate()438
.map(|(index, person)| {439
self.person_row(format!("profile-report-{index}"), person, None, cx)440
})441
.collect();442
section = section.child(443
v_flex()444
.id("profile-reports")445
.max_h(px(REPORTS_MAX_HEIGHT))446
.overflow_y_scroll()447
.children(rows),448
);449
}450
}451
section452
}453
454
fn loading_sections(&self) -> Div {455
v_flex()456
.gap(px(8.))457
.child(skeleton(1.))458
.child(skeleton(0.8))459
.child(skeleton(0.5))460
}461
462
fn failure(&self, cx: &mut Context<Self>) -> Div {463
h_flex()464
.gap(px(6.))465
.text_size(px(12.))466
.text_color(theme::red_soft())467
.child("Profile details could not be loaded.")468
.child(469
div()470
.id("profile-retry")471
.cursor_pointer()472
.underline()473
.text_color(theme::red_tint())474
.child("Retry")475
.on_click(cx.listener(|this, _, _, cx| {476
let id = this.user_id.clone();477
this.app478
.update(cx, |state, cx| state.request_profile(&id, true, cx));479
})),480
)481
}482
483
fn body(&self, entry_state: EntryState, cx: &mut Context<Self>) -> Vec<AnyElement> {484
let EntryState { profile, failed } = entry_state;485
let mut parts: Vec<AnyElement> = Vec::new();486
let Some(profile) = profile else {487
parts.push(self.actions(None, cx).into_any_element());488
parts.push(if failed {489
self.failure(cx).into_any_element()490
} else {491
self.loading_sections().into_any_element()492
});493
return parts;494
};495
if let Some(status) = status_box(&profile) {496
parts.push(self.status_box(&status));497
}498
parts.push(self.actions(profile.email.clone(), cx).into_any_element());499
let rows = contact_rows(&profile);500
if !rows.is_empty() {501
parts.push(self.contact_section(rows, cx).into_any_element());502
}503
if has_organization(&profile) {504
parts.push(self.organization_section(&profile, cx).into_any_element());505
}506
if failed {507
parts.push(self.failure(cx).into_any_element());508
}509
parts510
}511
}512
513
struct EntryState {514
profile: Option<Arc<PersonProfile>>,515
failed: bool,516
}517
518
fn muted_text(text: String) -> Div {519
div()520
.text_size(px(12.))521
.text_color(theme::text_muted())522
.child(text)523
}524
525
fn muted_line(text: String) -> Div {526
muted_text(text).truncate()527
}528
529
fn skeleton(width_ratio: f32) -> Div {530
div()531
.h(px(SKELETON_HEIGHT))532
.w(relative(width_ratio))533
.rounded(px(4.))534
.bg(theme::border_strong())535
}536
537
fn contact_row(row: ContactRow) -> Div {538
let glyph = match row.kind {539
ContactKind::Email => IconName::Mail,540
ContactKind::WorkPhone => IconName::Phone,541
ContactKind::MobilePhone => IconName::Smartphone,542
ContactKind::Office => IconName::MapPin,543
};544
h_flex()545
.gap(px(8.))546
.px(px(4.))547
.items_center()548
.child(icon(glyph, 14., theme::text_muted()))549
.child(550
div()551
.flex_1()552
.min_w_0()553
.truncate()554
.text_size(px(12.5))555
.text_color(theme::text())556
.child(row.value),557
)558
}559
560
fn action_button(561
id: &'static str,562
label: &'static str,563
glyph: IconName,564
filled: bool,565
) -> Stateful<Div> {566
let (foreground, background) = if filled {567
(theme::on_accent(), theme::accent())568
} else {569
(theme::text_soft(), theme::surface())570
};571
h_flex()572
.id(id)573
.h(px(ACTION_HEIGHT))574
.px(px(10.))575
.gap(px(6.))576
.items_center()577
.justify_center()578
.rounded(px(6.))579
.cursor_pointer()580
.bg(background)581
.text_color(foreground)582
.text_size(px(12.5))583
.font_weight(FontWeight::SEMIBOLD)584
.when(!filled, |button| {585
button586
.border_1()587
.border_color(theme::border_strong())588
.hover(|button| button.bg(theme::row_hover()))589
})590
.when(filled, |button| button.hover(|button| button.opacity(0.9)))591
.child(icon(glyph, 14., foreground))592
.child(label)593
}594
595
impl Render for ProfileCard {596
fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {597
let entry_state = self598
.app599
.read(cx)600
.profiles601
.get(&self.user_id)602
.map(|entry| EntryState {603
profile: entry.profile.clone(),604
failed: entry.failed,605
})606
.unwrap_or(EntryState {607
profile: None,608
failed: false,609
});610
let profile = entry_state.profile.clone();611
let header = self.header(profile.as_deref(), entry_state.failed, cx);612
let body = self.body(entry_state, cx);613
let back = (!self.history.is_empty()).then(|| {614
h_flex()615
.id("profile-back")616
.gap(px(4.))617
.items_center()618
.cursor_pointer()619
.text_size(px(12.))620
.text_color(theme::text_muted())621
.hover(|button| button.text_color(theme::text()))622
.child(icon(IconName::ArrowLeft, 14., theme::text_muted()))623
.child("Back")624
.on_click(cx.listener(|this, _, _, cx| this.go_back(cx)))625
});626
let card = v_flex()627
.id("profile-card")628
.track_focus(&self.focus_handle)629
.w(px(CARD_WIDTH))630
.p(px(CARD_PADDING))631
.gap(px(CARD_GAP))632
.rounded(px(CARD_RADIUS))633
.border_1()634
.border_color(theme::border_strong())635
.bg(theme::surface_raised())636
.text_color(theme::text())637
.shadow_lg()638
.occlude()639
.on_key_down(cx.listener(Self::on_key_down))640
.on_mouse_down(MouseButton::Left, |_, _, cx| {641
GlobalState::suppress_text_selection(cx);642
cx.stop_propagation();643
})644
.on_mouse_down(MouseButton::Right, |_, _, cx| cx.stop_propagation())645
.children(back)646
.child(header)647
.children(body);648
let offset = point(px(CLICK_OFFSET), px(CLICK_OFFSET));649
div()650
.id("profile-layer")651
.absolute()652
.top_0()653
.left_0()654
.size_full()655
.occlude()656
.on_mouse_down(657
MouseButton::Left,658
cx.listener(|_, _, _, cx| cx.emit(ProfileCardEvent::Close)),659
)660
.on_mouse_down(661
MouseButton::Right,662
cx.listener(|_, _, _, cx| cx.emit(ProfileCardEvent::Close)),663
)664
.child(665
deferred(666
anchored()667
.position(self.anchor + offset)668
.anchor(Anchor::TopLeft)669
.snap_to_window_with_margin(px(CARD_MARGIN))670
.child(card),671
)672
.with_priority(2),673
)674
}675
}@@ -5,9 +5,12 @@ use super::activity_panel::{ActivityPanel, ActivityPanelEvent};
5
5
use super::conversation::{ConversationView, ReplyToHovered};
6
6
use super::dialog_overlay::render_task_dialog;
7
7
use super::forward_dialog::{ForwardDialog, ForwardDialogEvent};
8
use super::profile_card::{ProfileCard, ProfileCardEvent};
8
9
use super::saved_panel::{SavedPanel, SavedPanelEvent};
9
10
use super::sidebar::SidebarView;
10
11
use super::status_bar::render_status_bar;
12
use super::status_menu::own_status_button;
13
use super::status_message_dialog::{StatusMessageDialog, StatusMessageDialogEvent};
11
14
use super::switcher::{Switcher, SwitcherEvent, candidates_from};
12
15
use super::title_bar::render_title_bar;
13
16
use crate::activity::ActivityCenter;
@@ -55,6 +58,8 @@ pub struct AppShell {
55
58
activity_panel: Option<Entity<ActivityPanel>>,
56
59
saved_panel: Option<Entity<SavedPanel>>,
57
60
forward_dialog: Option<Entity<ForwardDialog>>,
61
status_dialog: Option<Entity<StatusMessageDialog>>,
62
profile_card: Option<Entity<ProfileCard>>,
58
63
focus_handle: FocusHandle,
59
64
open_target: Option<OpenTarget>,
60
65
update: UpdateStatus,
@@ -80,6 +85,16 @@ impl AppShell {
80
85
if matches!(event, AppEvent::Forward) {
81
86
this.open_forward_dialog(window, cx);
82
87
}
88
if matches!(event, AppEvent::StatusMessage) {
89
this.open_status_dialog(window, cx);
90
}
91
if matches!(event, AppEvent::NotificationSettings) {
92
this.notifications
93
.update(cx, |center, cx| center.open_settings(cx));
94
}
95
if matches!(event, AppEvent::Profile) {
96
this.open_profile_card(window, cx);
97
}
83
98
cx.notify();
84
99
});
85
100
let focus_handle = cx.focus_handle();
@@ -99,6 +114,8 @@ impl AppShell {
99
114
activity_panel: None,
100
115
saved_panel: None,
101
116
forward_dialog: None,
117
status_dialog: None,
118
profile_card: None,
102
119
focus_handle,
103
120
open_target,
104
121
update: UpdateStatus::UpToDate,
@@ -333,6 +350,60 @@ impl AppShell {
333
350
cx.notify();
334
351
}
335
352
353
fn open_status_dialog(&mut self, window: &mut Window, cx: &mut Context<Self>) {
354
if !self
355
.state
356
.update(cx, |state, _| state.take_status_message_request())
357
{
358
return;
359
}
360
self.switcher = None;
361
self.activity_panel = None;
362
self.saved_panel = None;
363
let app = self.state.clone();
364
let dialog = cx.new(|cx| StatusMessageDialog::new(app, window, cx));
365
cx.subscribe_in(
366
&dialog,
367
window,
368
|this, _, _: &StatusMessageDialogEvent, window, cx| {
369
this.status_dialog = None;
370
window.focus(&this.focus_handle, cx);
371
cx.notify();
372
},
373
)
374
.detach();
375
self.status_dialog = Some(dialog);
376
cx.notify();
377
}
378
379
fn open_profile_card(&mut self, window: &mut Window, cx: &mut Context<Self>) {
380
let Some(request) = self
381
.state
382
.update(cx, |state, _| state.take_profile_request())
383
else {
384
return;
385
};
386
if let Some(card) = &self.profile_card {
387
card.update(cx, |card, cx| card.move_to(request.user_id, request.anchor, cx));
388
return;
389
}
390
let app = self.state.clone();
391
let card =
392
cx.new(|cx| ProfileCard::new(app, request.user_id, request.anchor, window, cx));
393
cx.subscribe_in(
394
&card,
395
window,
396
|this, _, _: &ProfileCardEvent, window, cx| {
397
this.profile_card = None;
398
window.focus(&this.focus_handle, cx);
399
cx.notify();
400
},
401
)
402
.detach();
403
self.profile_card = Some(card);
404
cx.notify();
405
}
406
336
407
fn open_forward_dialog(&mut self, window: &mut Window, cx: &mut Context<Self>) {
337
408
let Some(source) = self
338
409
.state
@@ -403,7 +474,7 @@ impl Render for AppShell {
403
474
}),
404
475
);
405
476
let title_bar = render_title_bar(
406
&state.directory,
477
own_status_button(&self.state, state),
407
478
self.activity.read(cx).feed().unread_count(),
408
479
cx.listener(|this, _, window, cx| this.toggle_switcher("", window, cx)),
409
480
cx.listener(|this, _, window, cx| this.toggle_saved_panel(window, cx)),
@@ -449,6 +520,8 @@ impl Render for AppShell {
449
520
.children(self.switcher.clone())
450
521
.children(render_task_dialog(self.state.read(cx), cx))
451
522
.children(self.forward_dialog.clone())
523
.children(self.status_dialog.clone())
524
.children(self.profile_card.clone())
452
525
.child(crate::frame_log::probe("last"))
453
526
}
454
527
}
@@ -5,9 +5,12 @@ use super::activity_panel::{ActivityPanel, ActivityPanelEvent};5
use super::conversation::{ConversationView, ReplyToHovered};5
use super::conversation::{ConversationView, ReplyToHovered};6
use super::dialog_overlay::render_task_dialog;6
use super::dialog_overlay::render_task_dialog;7
use super::forward_dialog::{ForwardDialog, ForwardDialogEvent};7
use super::forward_dialog::{ForwardDialog, ForwardDialogEvent};8
use super::profile_card::{ProfileCard, ProfileCardEvent};8
use super::saved_panel::{SavedPanel, SavedPanelEvent};9
use super::saved_panel::{SavedPanel, SavedPanelEvent};9
use super::sidebar::SidebarView;10
use super::sidebar::SidebarView;10
use super::status_bar::render_status_bar;11
use super::status_bar::render_status_bar;12
use super::status_menu::own_status_button;13
use super::status_message_dialog::{StatusMessageDialog, StatusMessageDialogEvent};11
use super::switcher::{Switcher, SwitcherEvent, candidates_from};14
use super::switcher::{Switcher, SwitcherEvent, candidates_from};12
use super::title_bar::render_title_bar;15
use super::title_bar::render_title_bar;13
use crate::activity::ActivityCenter;16
use crate::activity::ActivityCenter;@@ -55,6 +58,8 @@ pub struct AppShell {55
activity_panel: Option<Entity<ActivityPanel>>,58
activity_panel: Option<Entity<ActivityPanel>>,56
saved_panel: Option<Entity<SavedPanel>>,59
saved_panel: Option<Entity<SavedPanel>>,57
forward_dialog: Option<Entity<ForwardDialog>>,60
forward_dialog: Option<Entity<ForwardDialog>>,61
status_dialog: Option<Entity<StatusMessageDialog>>,62
profile_card: Option<Entity<ProfileCard>>,58
focus_handle: FocusHandle,63
focus_handle: FocusHandle,59
open_target: Option<OpenTarget>,64
open_target: Option<OpenTarget>,60
update: UpdateStatus,65
update: UpdateStatus,@@ -80,6 +85,16 @@ impl AppShell {80
if matches!(event, AppEvent::Forward) {85
if matches!(event, AppEvent::Forward) {81
this.open_forward_dialog(window, cx);86
this.open_forward_dialog(window, cx);82
}87
}88
if matches!(event, AppEvent::StatusMessage) {89
this.open_status_dialog(window, cx);90
}91
if matches!(event, AppEvent::NotificationSettings) {92
this.notifications93
.update(cx, |center, cx| center.open_settings(cx));94
}95
if matches!(event, AppEvent::Profile) {96
this.open_profile_card(window, cx);97
}83
cx.notify();98
cx.notify();84
});99
});85
let focus_handle = cx.focus_handle();100
let focus_handle = cx.focus_handle();@@ -99,6 +114,8 @@ impl AppShell {99
activity_panel: None,114
activity_panel: None,100
saved_panel: None,115
saved_panel: None,101
forward_dialog: None,116
forward_dialog: None,117
status_dialog: None,118
profile_card: None,102
focus_handle,119
focus_handle,103
open_target,120
open_target,104
update: UpdateStatus::UpToDate,121
update: UpdateStatus::UpToDate,@@ -333,6 +350,60 @@ impl AppShell {333
cx.notify();350
cx.notify();334
}351
}335
352
353
fn open_status_dialog(&mut self, window: &mut Window, cx: &mut Context<Self>) {354
if !self355
.state356
.update(cx, |state, _| state.take_status_message_request())357
{358
return;359
}360
self.switcher = None;361
self.activity_panel = None;362
self.saved_panel = None;363
let app = self.state.clone();364
let dialog = cx.new(|cx| StatusMessageDialog::new(app, window, cx));365
cx.subscribe_in(366
&dialog,367
window,368
|this, _, _: &StatusMessageDialogEvent, window, cx| {369
this.status_dialog = None;370
window.focus(&this.focus_handle, cx);371
cx.notify();372
},373
)374
.detach();375
self.status_dialog = Some(dialog);376
cx.notify();377
}378
379
fn open_profile_card(&mut self, window: &mut Window, cx: &mut Context<Self>) {380
let Some(request) = self381
.state382
.update(cx, |state, _| state.take_profile_request())383
else {384
return;385
};386
if let Some(card) = &self.profile_card {387
card.update(cx, |card, cx| card.move_to(request.user_id, request.anchor, cx));388
return;389
}390
let app = self.state.clone();391
let card =392
cx.new(|cx| ProfileCard::new(app, request.user_id, request.anchor, window, cx));393
cx.subscribe_in(394
&card,395
window,396
|this, _, _: &ProfileCardEvent, window, cx| {397
this.profile_card = None;398
window.focus(&this.focus_handle, cx);399
cx.notify();400
},401
)402
.detach();403
self.profile_card = Some(card);404
cx.notify();405
}406
336
fn open_forward_dialog(&mut self, window: &mut Window, cx: &mut Context<Self>) {407
fn open_forward_dialog(&mut self, window: &mut Window, cx: &mut Context<Self>) {337
let Some(source) = self408
let Some(source) = self338
.state409
.state@@ -403,7 +474,7 @@ impl Render for AppShell {403
}),474
}),404
);475
);405
let title_bar = render_title_bar(476
let title_bar = render_title_bar(406
&state.directory,477
own_status_button(&self.state, state),407
self.activity.read(cx).feed().unread_count(),478
self.activity.read(cx).feed().unread_count(),408
cx.listener(|this, _, window, cx| this.toggle_switcher("", window, cx)),479
cx.listener(|this, _, window, cx| this.toggle_switcher("", window, cx)),409
cx.listener(|this, _, window, cx| this.toggle_saved_panel(window, cx)),480
cx.listener(|this, _, window, cx| this.toggle_saved_panel(window, cx)),@@ -449,6 +520,8 @@ impl Render for AppShell {449
.children(self.switcher.clone())520
.children(self.switcher.clone())450
.children(render_task_dialog(self.state.read(cx), cx))521
.children(render_task_dialog(self.state.read(cx), cx))451
.children(self.forward_dialog.clone())522
.children(self.forward_dialog.clone())523
.children(self.status_dialog.clone())524
.children(self.profile_card.clone())452
.child(crate::frame_log::probe("last"))525
.child(crate::frame_log::probe("last"))453
}526
}454
}527
}@@ -0,0 +1,327 @@
1
use chrono::Local;
2
use gpui_kit::assets::IconName;
3
use gpui_kit::component::{
4
button::{Button, ButtonVariants as _},
5
checkbox::Checkbox,
6
h_flex,
7
input::{InputEvent, Textarea, TextareaState},
8
menu::{DropdownMenu as _, PopupMenuItem},
9
v_flex,
10
};
11
use gpui_kit::prelude::FluentBuilder as _;
12
use gpui_kit::*;
13
use teams_core::StatusNote;
14
15
use super::widgets::symbol;
16
use crate::app_state::AppState;
17
use crate::own_status::{NOTE_DURATIONS, NOTE_LIMIT, NoteDuration, clamp_note};
18
use crate::theme;
19
20
const CARD_WIDTH: f32 = 440.;
21
const CARD_RADIUS: f32 = 12.;
22
const CARD_PADDING: f32 = 16.;
23
const CARD_MARGIN: f32 = 32.;
24
const SECTION_GAP: f32 = 12.;
25
const BACKDROP_OPACITY: f32 = 0.55;
26
const CLOSE_SIZE: f32 = 28.;
27
const BUTTON_HEIGHT: f32 = 32.;
28
const DISABLED_OPACITY: f32 = 0.4;
29
const FIELD_MIN_ROWS: usize = 3;
30
const FIELD_MAX_ROWS: usize = 6;
31
const EXPIRY_WIDTH: f32 = 160.;
32
33
pub enum StatusMessageDialogEvent {
34
Close,
35
}
36
37
pub struct StatusMessageDialog {
38
app: Entity<AppState>,
39
input: Entity<TextareaState>,
40
show_when_messaged: bool,
41
expiry: NoteDuration,
42
has_message: bool,
43
length: usize,
44
_subscription: Subscription,
45
}
46
47
impl EventEmitter<StatusMessageDialogEvent> for StatusMessageDialog {}
48
49
pub fn can_finish(length: usize) -> bool {
50
length > 0
51
}
52
53
impl StatusMessageDialog {
54
pub fn new(app: Entity<AppState>, window: &mut Window, cx: &mut Context<Self>) -> Self {
55
let note = app.read(cx).own_status.note.clone();
56
let text = note
57
.as_ref()
58
.map(|note| note.text.clone())
59
.unwrap_or_default();
60
let input = cx.new(|cx| {
61
TextareaState::new(window, cx)
62
.auto_grow(FIELD_MIN_ROWS, FIELD_MAX_ROWS)
63
.placeholder("What's your status message?")
64
.default_value(text.clone())
65
});
66
let subscription = cx.subscribe_in(&input, window, Self::on_input_event);
67
input.update(cx, |input, cx| input.focus(window, cx));
68
StatusMessageDialog {
69
app,
70
input,
71
show_when_messaged: note.as_ref().is_some_and(|note| note.show_when_messaged),
72
expiry: NoteDuration::DEFAULT,
73
has_message: note.is_some(),
74
length: text.trim().chars().count(),
75
_subscription: subscription,
76
}
77
}
78
79
fn on_input_event(
80
&mut self,
81
input: &Entity<TextareaState>,
82
event: &InputEvent,
83
window: &mut Window,
84
cx: &mut Context<Self>,
85
) {
86
if !matches!(event, InputEvent::Change) {
87
return;
88
}
89
let value = input.read(cx).value().to_string();
90
let clamped = clamp_note(&value);
91
if clamped != value {
92
input.update(cx, |input, cx| input.set_value(clamped.clone(), window, cx));
93
}
94
self.length = clamped.trim().chars().count();
95
cx.notify();
96
}
97
98
fn finish(&mut self, cx: &mut Context<Self>) {
99
let text = clamp_note(self.input.read(cx).value().trim());
100
if !can_finish(text.chars().count()) {
101
return;
102
}
103
let note = StatusNote {
104
text,
105
show_when_messaged: self.show_when_messaged,
106
expires_at: self.expiry.expires_at(Local::now()),
107
};
108
self.app
109
.update(cx, |state, cx| state.set_own_status_note(Some(note), cx));
110
cx.emit(StatusMessageDialogEvent::Close);
111
}
112
113
fn clear(&mut self, cx: &mut Context<Self>) {
114
self.app
115
.update(cx, |state, cx| state.set_own_status_note(None, cx));
116
cx.emit(StatusMessageDialogEvent::Close);
117
}
118
119
fn on_key_down(&mut self, event: &KeyDownEvent, _: &mut Window, cx: &mut Context<Self>) {
120
match event.keystroke.key.as_str() {
121
"escape" => cx.emit(StatusMessageDialogEvent::Close),
122
"enter" if event.keystroke.modifiers.control => self.finish(cx),
123
_ => return,
124
}
125
cx.stop_propagation();
126
}
127
128
fn header(&self, cx: &mut Context<Self>) -> Div {
129
h_flex()
130
.w_full()
131
.items_center()
132
.gap(px(SECTION_GAP))
133
.child(
134
div()
135
.flex_1()
136
.text_size(px(15.))
137
.font_weight(FontWeight::SEMIBOLD)
138
.child("Set status message"),
139
)
140
.child(
141
div()
142
.id("status-message-close")
143
.size(px(CLOSE_SIZE))
144
.flex_none()
145
.flex()
146
.items_center()
147
.justify_center()
148
.rounded_full()
149
.cursor_pointer()
150
.hover(|button| button.bg(theme::row_hover()))
151
.on_click(cx.listener(|_, _, _, cx| cx.emit(StatusMessageDialogEvent::Close)))
152
.child(symbol("close", 16., theme::text_muted())),
153
)
154
}
155
156
fn field(&self) -> Div {
157
v_flex()
158
.w_full()
159
.gap(px(4.))
160
.child(
161
div()
162
.w_full()
163
.px(px(10.))
164
.py(px(6.))
165
.rounded(px(6.))
166
.bg(theme::surface())
167
.border_1()
168
.border_color(theme::border())
169
.child(Textarea::new(&self.input).appearance(false).bordered(false)),
170
)
171
.child(
172
div()
173
.w_full()
174
.flex()
175
.justify_end()
176
.text_size(px(11.))
177
.text_color(theme::text_muted())
178
.child(format!("{}/{NOTE_LIMIT}", self.length)),
179
)
180
}
181
182
fn expiry_row(&self, cx: &mut Context<Self>) -> Div {
183
let dialog = cx.entity();
184
let current = self.expiry;
185
h_flex()
186
.w_full()
187
.items_center()
188
.justify_between()
189
.gap(px(SECTION_GAP))
190
.child(div().text_size(px(13.)).child("Clear status message after"))
191
.child(
192
Button::new("status-message-expiry")
193
.outline()
194
.w(px(EXPIRY_WIDTH))
195
.label(current.label())
196
.icon(IconName::ChevronDown)
197
.dropdown_menu(move |menu, _, _| {
198
NOTE_DURATIONS.iter().fold(menu, |menu, duration| {
199
let (dialog, duration) = (dialog.clone(), *duration);
200
menu.item(
201
PopupMenuItem::new(duration.label())
202
.checked(duration == current)
203
.on_click(move |_, _, cx| {
204
dialog.update(cx, |this, cx| {
205
this.expiry = duration;
206
cx.notify();
207
});
208
}),
209
)
210
})
211
}),
212
)
213
}
214
215
fn done_button(&self, enabled: bool, cx: &mut Context<Self>) -> Stateful<Div> {
216
let button = h_flex()
217
.id("status-message-done")
218
.h(px(BUTTON_HEIGHT))
219
.px(px(16.))
220
.items_center()
221
.rounded(px(6.))
222
.bg(theme::accent())
223
.text_color(theme::on_accent())
224
.text_size(px(13.))
225
.font_weight(FontWeight::SEMIBOLD)
226
.child("Done");
227
if enabled {
228
button
229
.cursor_pointer()
230
.hover(|button| button.bg(theme::accent_text()))
231
.on_click(cx.listener(|this, _, _, cx| this.finish(cx)))
232
} else {
233
button.opacity(DISABLED_OPACITY)
234
}
235
}
236
}
237
238
impl Render for StatusMessageDialog {
239
fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
240
let enabled = can_finish(self.length);
241
div()
242
.id("status-message-layer")
243
.absolute()
244
.top_0()
245
.left_0()
246
.size_full()
247
.flex()
248
.items_center()
249
.justify_center()
250
.child(
251
div()
252
.id("status-message-backdrop")
253
.absolute()
254
.top_0()
255
.left_0()
256
.size_full()
257
.bg(black().opacity(BACKDROP_OPACITY))
258
.occlude()
259
.on_click(cx.listener(|_, _, _, cx| cx.emit(StatusMessageDialogEvent::Close))),
260
)
261
.child(
262
v_flex()
263
.id("status-message-card")
264
.w(px(CARD_WIDTH))
265
.max_w(relative(1.))
266
.max_h(relative(1.))
267
.m(px(CARD_MARGIN))
268
.p(px(CARD_PADDING))
269
.gap(px(SECTION_GAP))
270
.rounded(px(CARD_RADIUS))
271
.bg(theme::background())
272
.border_1()
273
.border_color(theme::border_strong())
274
.text_color(theme::text())
275
.shadow_lg()
276
.occlude()
277
.capture_key_down(cx.listener(Self::on_key_down))
278
.child(self.header(cx))
279
.child(self.field())
280
.child(
281
Checkbox::new("status-message-pinned")
282
.label("Show when people message me")
283
.checked(self.show_when_messaged)
284
.on_click(cx.listener(|this, checked: &bool, _, cx| {
285
this.show_when_messaged = *checked;
286
cx.notify();
287
})),
288
)
289
.child(self.expiry_row(cx))
290
.child(
291
h_flex()
292
.w_full()
293
.items_center()
294
.gap(px(8.))
295
.when(self.has_message, |row| {
296
row.child(
297
Button::new("status-message-clear")
298
.ghost()
299
.label("Clear message")
300
.on_click(cx.listener(|this, _, _, cx| this.clear(cx))),
301
)
302
})
303
.child(div().flex_1())
304
.child(
305
Button::new("status-message-cancel")
306
.ghost()
307
.label("Cancel")
308
.on_click(cx.listener(|_, _, _, cx| {
309
cx.emit(StatusMessageDialogEvent::Close)
310
})),
311
)
312
.child(self.done_button(enabled, cx)),
313
),
314
)
315
}
316
}
317
318
#[cfg(test)]
319
mod tests {
320
use super::can_finish;
321
322
#[test]
323
fn done_needs_at_least_one_character() {
324
assert!(!can_finish(0));
325
assert!(can_finish(1));
326
}
327
}
@@ -0,0 +1,327 @@1
use chrono::Local;2
use gpui_kit::assets::IconName;3
use gpui_kit::component::{4
button::{Button, ButtonVariants as _},5
checkbox::Checkbox,6
h_flex,7
input::{InputEvent, Textarea, TextareaState},8
menu::{DropdownMenu as _, PopupMenuItem},9
v_flex,10
};11
use gpui_kit::prelude::FluentBuilder as _;12
use gpui_kit::*;13
use teams_core::StatusNote;14
15
use super::widgets::symbol;16
use crate::app_state::AppState;17
use crate::own_status::{NOTE_DURATIONS, NOTE_LIMIT, NoteDuration, clamp_note};18
use crate::theme;19
20
const CARD_WIDTH: f32 = 440.;21
const CARD_RADIUS: f32 = 12.;22
const CARD_PADDING: f32 = 16.;23
const CARD_MARGIN: f32 = 32.;24
const SECTION_GAP: f32 = 12.;25
const BACKDROP_OPACITY: f32 = 0.55;26
const CLOSE_SIZE: f32 = 28.;27
const BUTTON_HEIGHT: f32 = 32.;28
const DISABLED_OPACITY: f32 = 0.4;29
const FIELD_MIN_ROWS: usize = 3;30
const FIELD_MAX_ROWS: usize = 6;31
const EXPIRY_WIDTH: f32 = 160.;32
33
pub enum StatusMessageDialogEvent {34
Close,35
}36
37
pub struct StatusMessageDialog {38
app: Entity<AppState>,39
input: Entity<TextareaState>,40
show_when_messaged: bool,41
expiry: NoteDuration,42
has_message: bool,43
length: usize,44
_subscription: Subscription,45
}46
47
impl EventEmitter<StatusMessageDialogEvent> for StatusMessageDialog {}48
49
pub fn can_finish(length: usize) -> bool {50
length > 051
}52
53
impl StatusMessageDialog {54
pub fn new(app: Entity<AppState>, window: &mut Window, cx: &mut Context<Self>) -> Self {55
let note = app.read(cx).own_status.note.clone();56
let text = note57
.as_ref()58
.map(|note| note.text.clone())59
.unwrap_or_default();60
let input = cx.new(|cx| {61
TextareaState::new(window, cx)62
.auto_grow(FIELD_MIN_ROWS, FIELD_MAX_ROWS)63
.placeholder("What's your status message?")64
.default_value(text.clone())65
});66
let subscription = cx.subscribe_in(&input, window, Self::on_input_event);67
input.update(cx, |input, cx| input.focus(window, cx));68
StatusMessageDialog {69
app,70
input,71
show_when_messaged: note.as_ref().is_some_and(|note| note.show_when_messaged),72
expiry: NoteDuration::DEFAULT,73
has_message: note.is_some(),74
length: text.trim().chars().count(),75
_subscription: subscription,76
}77
}78
79
fn on_input_event(80
&mut self,81
input: &Entity<TextareaState>,82
event: &InputEvent,83
window: &mut Window,84
cx: &mut Context<Self>,85
) {86
if !matches!(event, InputEvent::Change) {87
return;88
}89
let value = input.read(cx).value().to_string();90
let clamped = clamp_note(&value);91
if clamped != value {92
input.update(cx, |input, cx| input.set_value(clamped.clone(), window, cx));93
}94
self.length = clamped.trim().chars().count();95
cx.notify();96
}97
98
fn finish(&mut self, cx: &mut Context<Self>) {99
let text = clamp_note(self.input.read(cx).value().trim());100
if !can_finish(text.chars().count()) {101
return;102
}103
let note = StatusNote {104
text,105
show_when_messaged: self.show_when_messaged,106
expires_at: self.expiry.expires_at(Local::now()),107
};108
self.app109
.update(cx, |state, cx| state.set_own_status_note(Some(note), cx));110
cx.emit(StatusMessageDialogEvent::Close);111
}112
113
fn clear(&mut self, cx: &mut Context<Self>) {114
self.app115
.update(cx, |state, cx| state.set_own_status_note(None, cx));116
cx.emit(StatusMessageDialogEvent::Close);117
}118
119
fn on_key_down(&mut self, event: &KeyDownEvent, _: &mut Window, cx: &mut Context<Self>) {120
match event.keystroke.key.as_str() {121
"escape" => cx.emit(StatusMessageDialogEvent::Close),122
"enter" if event.keystroke.modifiers.control => self.finish(cx),123
_ => return,124
}125
cx.stop_propagation();126
}127
128
fn header(&self, cx: &mut Context<Self>) -> Div {129
h_flex()130
.w_full()131
.items_center()132
.gap(px(SECTION_GAP))133
.child(134
div()135
.flex_1()136
.text_size(px(15.))137
.font_weight(FontWeight::SEMIBOLD)138
.child("Set status message"),139
)140
.child(141
div()142
.id("status-message-close")143
.size(px(CLOSE_SIZE))144
.flex_none()145
.flex()146
.items_center()147
.justify_center()148
.rounded_full()149
.cursor_pointer()150
.hover(|button| button.bg(theme::row_hover()))151
.on_click(cx.listener(|_, _, _, cx| cx.emit(StatusMessageDialogEvent::Close)))152
.child(symbol("close", 16., theme::text_muted())),153
)154
}155
156
fn field(&self) -> Div {157
v_flex()158
.w_full()159
.gap(px(4.))160
.child(161
div()162
.w_full()163
.px(px(10.))164
.py(px(6.))165
.rounded(px(6.))166
.bg(theme::surface())167
.border_1()168
.border_color(theme::border())169
.child(Textarea::new(&self.input).appearance(false).bordered(false)),170
)171
.child(172
div()173
.w_full()174
.flex()175
.justify_end()176
.text_size(px(11.))177
.text_color(theme::text_muted())178
.child(format!("{}/{NOTE_LIMIT}", self.length)),179
)180
}181
182
fn expiry_row(&self, cx: &mut Context<Self>) -> Div {183
let dialog = cx.entity();184
let current = self.expiry;185
h_flex()186
.w_full()187
.items_center()188
.justify_between()189
.gap(px(SECTION_GAP))190
.child(div().text_size(px(13.)).child("Clear status message after"))191
.child(192
Button::new("status-message-expiry")193
.outline()194
.w(px(EXPIRY_WIDTH))195
.label(current.label())196
.icon(IconName::ChevronDown)197
.dropdown_menu(move |menu, _, _| {198
NOTE_DURATIONS.iter().fold(menu, |menu, duration| {199
let (dialog, duration) = (dialog.clone(), *duration);200
menu.item(201
PopupMenuItem::new(duration.label())202
.checked(duration == current)203
.on_click(move |_, _, cx| {204
dialog.update(cx, |this, cx| {205
this.expiry = duration;206
cx.notify();207
});208
}),209
)210
})211
}),212
)213
}214
215
fn done_button(&self, enabled: bool, cx: &mut Context<Self>) -> Stateful<Div> {216
let button = h_flex()217
.id("status-message-done")218
.h(px(BUTTON_HEIGHT))219
.px(px(16.))220
.items_center()221
.rounded(px(6.))222
.bg(theme::accent())223
.text_color(theme::on_accent())224
.text_size(px(13.))225
.font_weight(FontWeight::SEMIBOLD)226
.child("Done");227
if enabled {228
button229
.cursor_pointer()230
.hover(|button| button.bg(theme::accent_text()))231
.on_click(cx.listener(|this, _, _, cx| this.finish(cx)))232
} else {233
button.opacity(DISABLED_OPACITY)234
}235
}236
}237
238
impl Render for StatusMessageDialog {239
fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {240
let enabled = can_finish(self.length);241
div()242
.id("status-message-layer")243
.absolute()244
.top_0()245
.left_0()246
.size_full()247
.flex()248
.items_center()249
.justify_center()250
.child(251
div()252
.id("status-message-backdrop")253
.absolute()254
.top_0()255
.left_0()256
.size_full()257
.bg(black().opacity(BACKDROP_OPACITY))258
.occlude()259
.on_click(cx.listener(|_, _, _, cx| cx.emit(StatusMessageDialogEvent::Close))),260
)261
.child(262
v_flex()263
.id("status-message-card")264
.w(px(CARD_WIDTH))265
.max_w(relative(1.))266
.max_h(relative(1.))267
.m(px(CARD_MARGIN))268
.p(px(CARD_PADDING))269
.gap(px(SECTION_GAP))270
.rounded(px(CARD_RADIUS))271
.bg(theme::background())272
.border_1()273
.border_color(theme::border_strong())274
.text_color(theme::text())275
.shadow_lg()276
.occlude()277
.capture_key_down(cx.listener(Self::on_key_down))278
.child(self.header(cx))279
.child(self.field())280
.child(281
Checkbox::new("status-message-pinned")282
.label("Show when people message me")283
.checked(self.show_when_messaged)284
.on_click(cx.listener(|this, checked: &bool, _, cx| {285
this.show_when_messaged = *checked;286
cx.notify();287
})),288
)289
.child(self.expiry_row(cx))290
.child(291
h_flex()292
.w_full()293
.items_center()294
.gap(px(8.))295
.when(self.has_message, |row| {296
row.child(297
Button::new("status-message-clear")298
.ghost()299
.label("Clear message")300
.on_click(cx.listener(|this, _, _, cx| this.clear(cx))),301
)302
})303
.child(div().flex_1())304
.child(305
Button::new("status-message-cancel")306
.ghost()307
.label("Cancel")308
.on_click(cx.listener(|_, _, _, cx| {309
cx.emit(StatusMessageDialogEvent::Close)310
})),311
)312
.child(self.done_button(enabled, cx)),313
),314
)315
}316
}317
318
#[cfg(test)]319
mod tests {320
use super::can_finish;321
322
#[test]323
fn done_needs_at_least_one_character() {324
assert!(!can_finish(0));325
assert!(can_finish(1));326
}327
}@@ -5,16 +5,13 @@ use gpui_kit::component::{TitleBar, h_flex};
5
5
use gpui_kit::prelude::FluentBuilder as _;
6
6
use gpui_kit::*;
7
7
8
use super::avatar::{person_avatar, with_presence};
9
8
use super::widgets::{count_badge, icon, symbol};
10
use crate::data::Directory;
11
9
use crate::theme;
12
10
13
11
pub const TITLE_BAR_HEIGHT: f32 = 40.;
14
12
const SEARCH_WIDTH: f32 = 380.;
15
13
const SEARCH_HINT: &str = "Search chats, people and channels";
16
14
const SHORTCUT_HINT: &str = "Ctrl K";
17
const OWN_AVATAR_SIZE: f32 = 26.;
18
15
const APP_ICON_SIZE: f32 = 18.;
19
16
const APP_ICON_PNG: &[u8] = include_bytes!("../../assets/icon/teams-fast-256.png");
20
17
@@ -25,7 +22,7 @@ fn app_icon() -> Arc<Image> {
25
22
}
26
23
27
24
pub fn render_title_bar(
28
directory: &Directory,
25
own: Option<AnyElement>,
29
26
activity_unread: usize,
30
27
on_search: impl Fn(&ClickEvent, &mut Window, &mut App) + 'static,
31
28
on_saved: impl Fn(&ClickEvent, &mut Window, &mut App) + 'static,
@@ -99,20 +96,6 @@ pub fn render_title_bar(
99
96
.child(SHORTCUT_HINT),
100
97
)
101
98
.on_click(on_search);
102
let own = directory.me.as_ref().map(|me| {
103
let avatar = person_avatar(
104
directory,
105
Some(&me.user_id),
106
&me.display_name,
107
OWN_AVATAR_SIZE,
108
);
109
with_presence(
110
avatar,
111
directory.presence_of(&me.user_id),
112
OWN_AVATAR_SIZE,
113
theme::background(),
114
)
115
});
116
99
TitleBar::new()
117
100
.h(px(TITLE_BAR_HEIGHT))
118
101
.bg(theme::background())
@@ -5,16 +5,13 @@ use gpui_kit::component::{TitleBar, h_flex};5
use gpui_kit::prelude::FluentBuilder as _;5
use gpui_kit::prelude::FluentBuilder as _;6
use gpui_kit::*;6
use gpui_kit::*;7
7
8
use super::avatar::{person_avatar, with_presence};9
use super::widgets::{count_badge, icon, symbol};8
use super::widgets::{count_badge, icon, symbol};10
use crate::data::Directory;11
use crate::theme;9
use crate::theme;12
10
13
pub const TITLE_BAR_HEIGHT: f32 = 40.;11
pub const TITLE_BAR_HEIGHT: f32 = 40.;14
const SEARCH_WIDTH: f32 = 380.;12
const SEARCH_WIDTH: f32 = 380.;15
const SEARCH_HINT: &str = "Search chats, people and channels";13
const SEARCH_HINT: &str = "Search chats, people and channels";16
const SHORTCUT_HINT: &str = "Ctrl K";14
const SHORTCUT_HINT: &str = "Ctrl K";17
const OWN_AVATAR_SIZE: f32 = 26.;18
const APP_ICON_SIZE: f32 = 18.;15
const APP_ICON_SIZE: f32 = 18.;19
const APP_ICON_PNG: &[u8] = include_bytes!("../../assets/icon/teams-fast-256.png");16
const APP_ICON_PNG: &[u8] = include_bytes!("../../assets/icon/teams-fast-256.png");20
17
@@ -25,7 +22,7 @@ fn app_icon() -> Arc<Image> {25
}22
}26
23
27
pub fn render_title_bar(24
pub fn render_title_bar(28
directory: &Directory,25
own: Option<AnyElement>,29
activity_unread: usize,26
activity_unread: usize,30
on_search: impl Fn(&ClickEvent, &mut Window, &mut App) + 'static,27
on_search: impl Fn(&ClickEvent, &mut Window, &mut App) + 'static,31
on_saved: impl Fn(&ClickEvent, &mut Window, &mut App) + 'static,28
on_saved: impl Fn(&ClickEvent, &mut Window, &mut App) + 'static,@@ -99,20 +96,6 @@ pub fn render_title_bar(99
.child(SHORTCUT_HINT),96
.child(SHORTCUT_HINT),100
)97
)101
.on_click(on_search);98
.on_click(on_search);102
let own = directory.me.as_ref().map(|me| {103
let avatar = person_avatar(104
directory,105
Some(&me.user_id),106
&me.display_name,107
OWN_AVATAR_SIZE,108
);109
with_presence(110
avatar,111
directory.presence_of(&me.user_id),112
OWN_AVATAR_SIZE,113
theme::background(),114
)115
});116
TitleBar::new()99
TitleBar::new()117
.h(px(TITLE_BAR_HEIGHT))100
.h(px(TITLE_BAR_HEIGHT))118
.bg(theme::background())101
.bg(theme::background())@@ -8,6 +8,7 @@ pub mod links;
8
8
mod mask;
9
9
pub mod messages;
10
10
pub mod pins;
11
pub mod presence;
11
12
pub mod reactions;
12
13
pub mod realtime;
13
14
pub mod receipts;
@@ -28,6 +29,10 @@ pub use pins::{
28
29
ChannelLayout, Folder, FolderKind, Folders, PinnedChannels, PinnedChats, PinnedMessage, Pins,
29
30
TeamLayout,
30
31
};
32
pub use presence::{
33
ForcedAvailability, ForcedKind, PresenceService, PresenceStatus, StatusNote, WorkLocation,
34
WorkLocationKind, WorkLocationSource,
35
};
31
36
pub use reactions::{emotion_key, emotion_keys};
32
37
pub use realtime::{
33
38
EventKind, MessageEvent, PresenceUpdate, Realtime, RealtimeConfig, RealtimeEvent, StatusEvent,
@@ -8,6 +8,7 @@ pub mod links;8
mod mask;8
mod mask;9
pub mod messages;9
pub mod messages;10
pub mod pins;10
pub mod pins;11
pub mod presence;11
pub mod reactions;12
pub mod reactions;12
pub mod realtime;13
pub mod realtime;13
pub mod receipts;14
pub mod receipts;@@ -28,6 +29,10 @@ pub use pins::{28
ChannelLayout, Folder, FolderKind, Folders, PinnedChannels, PinnedChats, PinnedMessage, Pins,29
ChannelLayout, Folder, FolderKind, Folders, PinnedChannels, PinnedChats, PinnedMessage, Pins,29
TeamLayout,30
TeamLayout,30
};31
};32
pub use presence::{33
ForcedAvailability, ForcedKind, PresenceService, PresenceStatus, StatusNote, WorkLocation,34
WorkLocationKind, WorkLocationSource,35
};31
pub use reactions::{emotion_key, emotion_keys};36
pub use reactions::{emotion_key, emotion_keys};32
pub use realtime::{37
pub use realtime::{33
EventKind, MessageEvent, PresenceUpdate, Realtime, RealtimeConfig, RealtimeEvent, StatusEvent,38
EventKind, MessageEvent, PresenceUpdate, Realtime, RealtimeConfig, RealtimeEvent, StatusEvent,@@ -0,0 +1,724 @@
1
use chrono::{DateTime, Datelike, SecondsFormat, Utc};
2
use serde_json::{Value, json};
3
use session::{Method, PRESENCE, Request, Scope, Session};
4
use uuid::Uuid;
5
6
use crate::cards::{CardTransport, SessionCardTransport};
7
use crate::error::{Error, Result};
8
9
const BASE_URL: &str = "https://presence.teams.microsoft.com/v1";
10
const PRESENCE_SCOPE: &str = "user_impersonation";
11
const CLIENT_VERSION: &str = "1415/26091712213";
12
const ORGID_PREFIX: &str = "8:orgid:";
13
const PINNED_NOTE_SUFFIX: &str = "<pinnednote></pinnednote>";
14
const NEVER_EXPIRES: &str = "9999-12-31T23:59:59.999Z";
15
const NEVER_YEAR: i32 = 9999;
16
const OFFLINE_ACTIVITY: &str = "OffWork";
17
18
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
19
pub enum ForcedKind {
20
Available,
21
Busy,
22
DoNotDisturb,
23
BeRightBack,
24
Away,
25
Offline,
26
}
27
28
impl ForcedKind {
29
pub fn code(self) -> &'static str {
30
match self {
31
ForcedKind::Available => "Available",
32
ForcedKind::Busy => "Busy",
33
ForcedKind::DoNotDisturb => "DoNotDisturb",
34
ForcedKind::BeRightBack => "BeRightBack",
35
ForcedKind::Away => "Away",
36
ForcedKind::Offline => "Offline",
37
}
38
}
39
40
pub fn from_code(code: &str) -> Option<Self> {
41
match code {
42
"Available" => Some(ForcedKind::Available),
43
"Busy" => Some(ForcedKind::Busy),
44
"DoNotDisturb" => Some(ForcedKind::DoNotDisturb),
45
"BeRightBack" => Some(ForcedKind::BeRightBack),
46
"Away" => Some(ForcedKind::Away),
47
"Offline" => Some(ForcedKind::Offline),
48
_ => None,
49
}
50
}
51
}
52
53
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
54
pub struct ForcedAvailability {
55
pub kind: ForcedKind,
56
pub expires_at: Option<DateTime<Utc>>,
57
}
58
59
#[derive(Debug, Clone, PartialEq, Eq)]
60
pub struct StatusNote {
61
pub text: String,
62
pub show_when_messaged: bool,
63
pub expires_at: Option<DateTime<Utc>>,
64
}
65
66
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
67
pub enum WorkLocationKind {
68
Office,
69
Remote,
70
}
71
72
impl WorkLocationKind {
73
fn code(self) -> u8 {
74
match self {
75
WorkLocationKind::Office => 1,
76
WorkLocationKind::Remote => 2,
77
}
78
}
79
}
80
81
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
82
pub enum WorkLocationSource {
83
Set,
84
Scheduled,
85
Verified,
86
}
87
88
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
89
pub struct WorkLocation {
90
pub kind: WorkLocationKind,
91
pub source: WorkLocationSource,
92
}
93
94
#[derive(Debug, Clone, Default, PartialEq, Eq)]
95
pub struct PresenceStatus {
96
pub availability: String,
97
pub activity: Option<String>,
98
pub forced: Option<ForcedAvailability>,
99
pub note: Option<StatusNote>,
100
pub out_of_office: bool,
101
pub out_of_office_note: Option<String>,
102
pub work_location: Option<WorkLocation>,
103
}
104
105
pub struct PresenceService<T: CardTransport = SessionCardTransport> {
106
transport: T,
107
}
108
109
impl PresenceService<SessionCardTransport> {
110
pub fn new(session: &Session) -> Self {
111
PresenceService::with_transport(SessionCardTransport::new(session))
112
}
113
}
114
115
impl<T: CardTransport> PresenceService<T> {
116
pub fn with_transport(transport: T) -> Self {
117
PresenceService { transport }
118
}
119
120
pub async fn set_availability(&self, forced: Option<&ForcedAvailability>) -> Result<()> {
121
let url = format!("{BASE_URL}/me/forceavailability/");
122
let request = match forced {
123
Some(forced) => Request::with_body(Method::Put, &url, availability_body(forced)),
124
None => Request {
125
method: Method::Put,
126
..Request::get(&url)
127
},
128
};
129
self.send(request, &url).await.map(drop)
130
}
131
132
pub async fn set_note(&self, note: Option<&StatusNote>) -> Result<()> {
133
let url = format!("{BASE_URL}/me/publishnote");
134
let body = note.map_or_else(|| json!({"message": ""}), note_body);
135
self.send(Request::with_body(Method::Put, &url, body), &url)
136
.await
137
.map(drop)
138
}
139
140
pub async fn set_work_location(
141
&self,
142
location: Option<(WorkLocationKind, DateTime<Utc>)>,
143
) -> Result<()> {
144
let url = format!("{BASE_URL}/me/workLocation/");
145
let body = match location {
146
Some((kind, expires_at)) => json!({
147
"location": kind.code(),
148
"expirationTime": format_expiry(Some(expires_at)),
149
}),
150
None => json!({"location": 0}),
151
};
152
self.send(Request::with_body(Method::Put, &url, body), &url)
153
.await
154
.map(drop)
155
}
156
157
pub async fn status(&self, user_id: &str) -> Result<PresenceStatus> {
158
let url = format!("{BASE_URL}/presence/getpresence/");
159
let mri = format!("{ORGID_PREFIX}{user_id}");
160
let body = json!([{ "mri": mri }]);
161
let answer = self
162
.send(Request::with_body(Method::Post, &url, body), &url)
163
.await?;
164
parse_status(&answer, &mri, Utc::now())
165
}
166
167
async fn send(&self, mut request: Request, url: &str) -> Result<Value> {
168
request.headers = service_headers();
169
let answer = self
170
.transport
171
.send(request, Scope::new(PRESENCE, PRESENCE_SCOPE))
172
.await?;
173
if !answer.is_success() {
174
return Err(Error::Session(session::Error::api(
175
answer.status,
176
url,
177
answer.body,
178
)));
179
}
180
Ok(answer.body)
181
}
182
}
183
184
fn service_headers() -> Vec<(String, String)> {
185
vec![
186
("x-ms-client-user-agent".into(), "Teams-V2-Web".into()),
187
("x-ms-correlation-id".into(), Uuid::new_v4().to_string()),
188
("x-ms-client-version".into(), CLIENT_VERSION.into()),
189
]
190
}
191
192
pub fn format_expiry(expires_at: Option<DateTime<Utc>>) -> String {
193
match expires_at {
194
Some(expires_at) => expires_at.to_rfc3339_opts(SecondsFormat::Millis, true),
195
None => NEVER_EXPIRES.to_owned(),
196
}
197
}
198
199
fn availability_body(forced: &ForcedAvailability) -> Value {
200
let mut body = json!({"availability": forced.kind.code()});
201
if forced.kind == ForcedKind::Offline {
202
body["activity"] = json!(OFFLINE_ACTIVITY);
203
}
204
if let Some(expires_at) = forced.expires_at {
205
body["desiredExpirationTime"] = json!(format_expiry(Some(expires_at)));
206
}
207
body
208
}
209
210
fn note_body(note: &StatusNote) -> Value {
211
let suffix = if note.show_when_messaged {
212
PINNED_NOTE_SUFFIX
213
} else {
214
""
215
};
216
json!({
217
"message": format!("{}{suffix}", escape_text(¬e.text)),
218
"expiry": format_expiry(note.expires_at),
219
})
220
}
221
222
fn escape_text(text: &str) -> String {
223
text.replace('&', "&")
224
.replace('<', "<")
225
.replace('>', ">")
226
.replace('"', """)
227
.replace('\'', "'")
228
}
229
230
fn unescape_text(text: &str) -> String {
231
text.replace("<", "<")
232
.replace(">", ">")
233
.replace(""", "\"")
234
.replace("'", "'")
235
.replace("&", "&")
236
}
237
238
fn plain_text(message: &str) -> Option<String> {
239
let mut text = String::with_capacity(message.len());
240
let mut inside_tag = false;
241
for character in message.chars() {
242
match character {
243
'<' => inside_tag = true,
244
'>' if inside_tag => inside_tag = false,
245
_ if !inside_tag => text.push(character),
246
_ => {}
247
}
248
}
249
let text = unescape_text(&text);
250
let text = text.trim();
251
(!text.is_empty()).then(|| text.to_owned())
252
}
253
254
fn split_pinned(message: &str) -> (String, bool) {
255
let pinned = message
256
.find(PINNED_NOTE_SUFFIX)
257
.is_some_and(|index| index > 0);
258
(message.replace(PINNED_NOTE_SUFFIX, ""), pinned)
259
}
260
261
fn parse_expiry(value: Option<&Value>) -> Option<DateTime<Utc>> {
262
let parsed = DateTime::parse_from_rfc3339(value?.as_str()?)
263
.ok()?
264
.with_timezone(&Utc);
265
(parsed.year() < NEVER_YEAR).then_some(parsed)
266
}
267
268
fn parse_forced(forced: &Value) -> Option<ForcedAvailability> {
269
Some(ForcedAvailability {
270
kind: ForcedKind::from_code(forced.get("availability")?.as_str()?)?,
271
expires_at: parse_expiry(forced.get("expiry")),
272
})
273
}
274
275
fn parse_note(note: &Value, now: DateTime<Utc>) -> Option<StatusNote> {
276
let (message, show_when_messaged) = split_pinned(note.get("message")?.as_str()?);
277
let text = plain_text(&message)?;
278
let expires_at = parse_expiry(note.get("expiry"));
279
let expired = expires_at.is_some_and(|expires_at| expires_at <= now);
280
(!expired).then_some(StatusNote {
281
text,
282
show_when_messaged,
283
expires_at,
284
})
285
}
286
287
fn parse_work_location(location: &Value, now: DateTime<Utc>) -> Option<WorkLocation> {
288
let kind = match location.get("location")?.as_str()? {
289
"Office" => WorkLocationKind::Office,
290
"Remote" => WorkLocationKind::Remote,
291
_ => return None,
292
};
293
let expired = parse_expiry(location.get("expiry")).is_some_and(|expires_at| expires_at <= now);
294
(!expired).then(|| WorkLocation {
295
kind,
296
source: match location.get("locationSource").and_then(Value::as_str) {
297
Some("ScheduledLocation") => WorkLocationSource::Scheduled,
298
Some("VerifiedLocation") => WorkLocationSource::Verified,
299
_ => WorkLocationSource::Set,
300
},
301
})
302
}
303
304
pub fn parse_status(body: &Value, mri: &str, now: DateTime<Utc>) -> Result<PresenceStatus> {
305
let entries = body
306
.as_array()
307
.ok_or_else(|| Error::UnexpectedAnswer("no presence list".into()))?;
308
let presence = entries
309
.iter()
310
.find(|entry| entry.get("mri").and_then(Value::as_str) == Some(mri))
311
.or_else(|| entries.first())
312
.and_then(|entry| entry.get("presence"))
313
.ok_or_else(|| Error::UnexpectedAnswer("no own presence".into()))?;
314
Ok(PresenceStatus {
315
availability: presence
316
.get("availability")
317
.and_then(Value::as_str)
318
.unwrap_or_default()
319
.to_owned(),
320
activity: presence
321
.get("activity")
322
.and_then(Value::as_str)
323
.map(str::to_owned),
324
forced: presence.get("forcedAvailability").and_then(parse_forced),
325
note: presence.get("note").and_then(|note| parse_note(note, now)),
326
out_of_office: presence
327
.pointer("/calendarData/isOutOfOffice")
328
.and_then(Value::as_bool)
329
.unwrap_or(false),
330
out_of_office_note: presence
331
.pointer("/calendarData/outOfOfficeNote/message")
332
.and_then(Value::as_str)
333
.and_then(plain_text),
334
work_location: presence
335
.get("workLocation")
336
.and_then(|location| parse_work_location(location, now)),
337
})
338
}
339
340
#[cfg(test)]
341
mod tests {
342
use std::sync::Mutex;
343
344
use chrono::TimeZone;
345
use session::{ApiResponse, Method};
346
347
use super::*;
348
349
struct Recorder {
350
status: u16,
351
body: Value,
352
sent: Mutex<Vec<(Request, Scope)>>,
353
}
354
355
impl CardTransport for Recorder {
356
async fn send(&self, request: Request, scope: Scope) -> Result<ApiResponse> {
357
self.sent.lock().unwrap().push((request, scope));
358
Ok(ApiResponse {
359
status: self.status,
360
body: self.body.clone(),
361
retry_after: None,
362
})
363
}
364
}
365
366
fn service(status: u16, body: Value) -> PresenceService<Recorder> {
367
PresenceService::with_transport(Recorder {
368
status,
369
body,
370
sent: Mutex::new(Vec::new()),
371
})
372
}
373
374
fn only_request(service: &PresenceService<Recorder>) -> (Request, Scope) {
375
let mut sent = service.transport.sent.lock().unwrap();
376
assert_eq!(sent.len(), 1);
377
sent.remove(0)
378
}
379
380
fn at(hour: u32, minute: u32) -> DateTime<Utc> {
381
Utc.with_ymd_and_hms(2026, 10, 9, hour, minute, 0).unwrap()
382
}
383
384
#[tokio::test]
385
async fn busy_with_expiry_puts_availability_and_desired_expiration() {
386
let service = service(200, Value::Null);
387
let forced = ForcedAvailability {
388
kind: ForcedKind::Busy,
389
expires_at: Some(at(15, 30)),
390
};
391
service.set_availability(Some(&forced)).await.unwrap();
392
let (request, scope) = only_request(&service);
393
assert_eq!(request.method, Method::Put);
394
assert_eq!(
395
request.url,
396
"https://presence.teams.microsoft.com/v1/me/forceavailability/"
397
);
398
assert_eq!(
399
request.body,
400
Some(json!({
401
"availability": "Busy",
402
"desiredExpirationTime": "2026-10-09T15:30:00.000Z",
403
}))
404
);
405
assert_eq!(scope, Scope::new(PRESENCE, "user_impersonation"));
406
let names: Vec<&str> = request
407
.headers
408
.iter()
409
.map(|(name, _)| name.as_str())
410
.collect();
411
assert_eq!(
412
names,
413
[
414
"x-ms-client-user-agent",
415
"x-ms-correlation-id",
416
"x-ms-client-version"
417
]
418
);
419
}
420
421
#[tokio::test]
422
async fn offline_carries_the_off_work_activity_and_no_expiry_when_open() {
423
let service = service(200, Value::Null);
424
let forced = ForcedAvailability {
425
kind: ForcedKind::Offline,
426
expires_at: None,
427
};
428
service.set_availability(Some(&forced)).await.unwrap();
429
let (request, _) = only_request(&service);
430
assert_eq!(
431
request.body,
432
Some(json!({"availability": "Offline", "activity": "OffWork"}))
433
);
434
}
435
436
#[tokio::test]
437
async fn reset_is_a_put_without_body() {
438
let service = service(200, Value::Null);
439
service.set_availability(None).await.unwrap();
440
let (request, _) = only_request(&service);
441
assert_eq!(request.method, Method::Put);
442
assert_eq!(request.body, None);
443
assert!(request.url.ends_with("/v1/me/forceavailability/"));
444
}
445
446
#[tokio::test]
447
async fn note_with_pin_marker_and_escaped_text() {
448
let service = service(200, Value::Null);
449
let note = StatusNote {
450
text: "Out <b> & about".into(),
451
show_when_messaged: true,
452
expires_at: Some(at(18, 0)),
453
};
454
service.set_note(Some(¬e)).await.unwrap();
455
let (request, _) = only_request(&service);
456
assert_eq!(request.method, Method::Put);
457
assert_eq!(
458
request.url,
459
"https://presence.teams.microsoft.com/v1/me/publishnote"
460
);
461
assert_eq!(
462
request.body,
463
Some(json!({
464
"message": "Out <b> & about<pinnednote></pinnednote>",
465
"expiry": "2026-10-09T18:00:00.000Z",
466
}))
467
);
468
}
469
470
#[tokio::test]
471
async fn note_without_pin_and_never_expiring() {
472
let service = service(200, Value::Null);
473
let note = StatusNote {
474
text: "Focus".into(),
475
show_when_messaged: false,
476
expires_at: None,
477
};
478
service.set_note(Some(¬e)).await.unwrap();
479
let (request, _) = only_request(&service);
480
assert_eq!(
481
request.body,
482
Some(json!({"message": "Focus", "expiry": "9999-12-31T23:59:59.999Z"}))
483
);
484
}
485
486
#[tokio::test]
487
async fn clearing_the_note_sends_an_empty_message_only() {
488
let service = service(200, Value::Null);
489
service.set_note(None).await.unwrap();
490
let (request, _) = only_request(&service);
491
assert_eq!(request.body, Some(json!({"message": ""})));
492
}
493
494
#[tokio::test]
495
async fn failures_surface_as_errors() {
496
let service = service(400, json!({"message": "bad"}));
497
assert!(service.set_note(None).await.is_err());
498
}
499
500
#[tokio::test]
501
async fn reads_own_presence_by_mri() {
502
let body = json!([{
503
"mri": "8:orgid:me",
504
"presence": {"availability": "Available", "activity": "Available"}
505
}]);
506
let service = service(200, body);
507
let status = service.status("me").await.unwrap();
508
assert_eq!(status.availability, "Available");
509
let (request, _) = only_request(&service);
510
assert_eq!(request.method, Method::Post);
511
assert_eq!(
512
request.url,
513
"https://presence.teams.microsoft.com/v1/presence/getpresence/"
514
);
515
assert_eq!(request.body, Some(json!([{"mri": "8:orgid:me"}])));
516
}
517
518
#[test]
519
fn parses_forced_note_and_out_of_office() {
520
let body = json!([{
521
"mri": "8:orgid:me",
522
"presence": {
523
"availability": "Busy",
524
"activity": "Busy",
525
"forcedAvailability": {
526
"availability": "Busy",
527
"expiry": "2026-10-09T15:30:00Z",
528
"publishTime": "2026-10-09T15:00:00Z"
529
},
530
"note": {
531
"message": "In <focus><pinnednote></pinnednote>",
532
"expiry": "2026-10-09T18:00:00Z"
533
},
534
"calendarData": {"isOutOfOffice": true}
535
}
536
}]);
537
let status = parse_status(&body, "8:orgid:me", at(12, 0)).unwrap();
538
assert_eq!(status.availability, "Busy");
539
assert_eq!(
540
status.forced,
541
Some(ForcedAvailability {
542
kind: ForcedKind::Busy,
543
expires_at: Some(at(15, 30)),
544
})
545
);
546
assert_eq!(
547
status.note,
548
Some(StatusNote {
549
text: "In <focus>".into(),
550
show_when_messaged: true,
551
expires_at: Some(at(18, 0)),
552
})
553
);
554
assert!(status.out_of_office);
555
}
556
557
#[test]
558
fn never_expiry_reads_back_as_none() {
559
let body = json!([{
560
"mri": "8:orgid:me",
561
"presence": {
562
"availability": "Available",
563
"note": {"message": "Hi", "expiry": "9999-12-31T23:59:59.9999999Z"}
564
}
565
}]);
566
let status = parse_status(&body, "8:orgid:me", at(12, 0)).unwrap();
567
let note = status.note.unwrap();
568
assert_eq!(note.expires_at, None);
569
assert!(!note.show_when_messaged);
570
}
571
572
#[test]
573
fn expired_and_empty_notes_are_dropped() {
574
let expired = json!([{"mri": "m", "presence": {
575
"availability": "Available",
576
"note": {"message": "Old", "expiry": "2026-10-09T08:00:00Z"}
577
}}]);
578
let empty = json!([{"mri": "m", "presence": {
579
"availability": "Available",
580
"note": {"message": "", "expiry": "9999-12-31T23:59:59.9999999Z"}
581
}}]);
582
assert_eq!(parse_status(&expired, "m", at(12, 0)).unwrap().note, None);
583
assert_eq!(parse_status(&empty, "m", at(12, 0)).unwrap().note, None);
584
}
585
586
#[test]
587
fn pin_marker_at_the_start_does_not_count() {
588
let (text, pinned) = split_pinned("<pinnednote></pinnednote>");
589
assert_eq!(text, "");
590
assert!(!pinned);
591
}
592
593
#[test]
594
fn unknown_forced_availability_is_ignored() {
595
let body = json!([{"mri": "m", "presence": {
596
"availability": "Away",
597
"forcedAvailability": {"availability": "Mystery"}
598
}}]);
599
assert_eq!(parse_status(&body, "m", at(12, 0)).unwrap().forced, None);
600
}
601
602
#[test]
603
fn missing_presence_is_unexpected() {
604
assert!(matches!(
605
parse_status(&json!({}), "m", at(12, 0)),
606
Err(Error::UnexpectedAnswer(_))
607
));
608
}
609
610
#[tokio::test]
611
async fn work_location_puts_numbers_and_end_of_day_expiry() {
612
let service = service(200, Value::Null);
613
service
614
.set_work_location(Some((WorkLocationKind::Remote, at(21, 59))))
615
.await
616
.unwrap();
617
let (request, scope) = only_request(&service);
618
assert_eq!(request.method, Method::Put);
619
assert_eq!(
620
request.url,
621
"https://presence.teams.microsoft.com/v1/me/workLocation/"
622
);
623
assert_eq!(
624
request.body,
625
Some(json!({"location": 2, "expirationTime": "2026-10-09T21:59:00.000Z"}))
626
);
627
assert_eq!(scope, Scope::new(PRESENCE, "user_impersonation"));
628
service
629
.set_work_location(Some((WorkLocationKind::Office, at(21, 59))))
630
.await
631
.unwrap();
632
let (request, _) = only_request(&service);
633
assert_eq!(request.body.unwrap()["location"], json!(1));
634
}
635
636
#[tokio::test]
637
async fn clearing_the_work_location_sends_zero_without_expiry() {
638
let service = service(200, Value::Null);
639
service.set_work_location(None).await.unwrap();
640
let (request, _) = only_request(&service);
641
assert_eq!(request.body, Some(json!({"location": 0})));
642
}
643
644
#[test]
645
fn parses_work_location_and_hides_unknown_or_expired() {
646
let read = |location: Value| {
647
let body = json!([{"mri": "m", "presence": {
648
"availability": "Available", "workLocation": location
649
}}]);
650
parse_status(&body, "m", at(12, 0)).unwrap().work_location
651
};
652
assert_eq!(
653
read(
654
json!({"location": "Remote", "expiry": "2026-10-09T21:59:59.9999999Z",
655
"isForced": true, "locationSource": "ForcedLocation"})
656
),
657
Some(WorkLocation {
658
kind: WorkLocationKind::Remote,
659
source: WorkLocationSource::Set
660
})
661
);
662
assert_eq!(
663
read(
664
json!({"location": "Office", "locationSource": "ScheduledLocation",
665
"expiry": "2026-10-09T21:59:59Z"})
666
),
667
Some(WorkLocation {
668
kind: WorkLocationKind::Office,
669
source: WorkLocationSource::Scheduled
670
})
671
);
672
assert_eq!(
673
read(json!({"location": "Office", "locationSource": "VerifiedLocation"}))
674
.map(|found| found.source),
675
Some(WorkLocationSource::Verified)
676
);
677
assert_eq!(read(json!({"location": "Unknown"})), None);
678
assert_eq!(read(json!({"location": "TimeOff"})), None);
679
assert_eq!(
680
read(json!({"location": "Office", "expiry": "2026-10-09T08:00:00Z"})),
681
None
682
);
683
}
684
685
#[test]
686
fn note_text_is_unescaped_and_the_pin_marker_stripped() {
687
let body = json!([{"mri": "m", "presence": {
688
"availability": "Busy",
689
"note": {
690
"message": "Back at 3 & later<pinnednote></pinnednote>",
691
"expiry": "9999-12-31T23:59:59.9999999Z"
692
},
693
"calendarData": {"isOutOfOffice": false}
694
}}]);
695
let status = parse_status(&body, "m", at(12, 0)).unwrap();
696
assert_eq!(status.note.unwrap().text, "Back at 3 & later");
697
assert!(!status.out_of_office);
698
assert_eq!(status.out_of_office_note, None);
699
}
700
701
#[test]
702
fn out_of_office_carries_its_plain_text() {
703
let read = |calendar: Value| {
704
let body = json!([{"mri": "m", "presence": {
705
"availability": "Away", "calendarData": calendar
706
}}]);
707
parse_status(&body, "m", at(12, 0)).unwrap()
708
};
709
let with_text = read(
710
json!({"isOutOfOffice": true, "outOfOfficeNote": {"message": "<p>On & leave</p>"}}),
711
);
712
assert!(with_text.out_of_office);
713
assert_eq!(with_text.out_of_office_note.as_deref(), Some("On & leave"));
714
let bare = read(json!({"isOutOfOffice": true}));
715
assert!(bare.out_of_office);
716
assert_eq!(bare.out_of_office_note, None);
717
}
718
719
#[test]
720
fn expiry_formats_to_milliseconds_utc() {
721
assert_eq!(format_expiry(Some(at(15, 30))), "2026-10-09T15:30:00.000Z");
722
assert_eq!(format_expiry(None), "9999-12-31T23:59:59.999Z");
723
}
724
}
@@ -0,0 +1,724 @@1
use chrono::{DateTime, Datelike, SecondsFormat, Utc};2
use serde_json::{Value, json};3
use session::{Method, PRESENCE, Request, Scope, Session};4
use uuid::Uuid;5
6
use crate::cards::{CardTransport, SessionCardTransport};7
use crate::error::{Error, Result};8
9
const BASE_URL: &str = "https://presence.teams.microsoft.com/v1";10
const PRESENCE_SCOPE: &str = "user_impersonation";11
const CLIENT_VERSION: &str = "1415/26091712213";12
const ORGID_PREFIX: &str = "8:orgid:";13
const PINNED_NOTE_SUFFIX: &str = "<pinnednote></pinnednote>";14
const NEVER_EXPIRES: &str = "9999-12-31T23:59:59.999Z";15
const NEVER_YEAR: i32 = 9999;16
const OFFLINE_ACTIVITY: &str = "OffWork";17
18
#[derive(Debug, Clone, Copy, PartialEq, Eq)]19
pub enum ForcedKind {20
Available,21
Busy,22
DoNotDisturb,23
BeRightBack,24
Away,25
Offline,26
}27
28
impl ForcedKind {29
pub fn code(self) -> &'static str {30
match self {31
ForcedKind::Available => "Available",32
ForcedKind::Busy => "Busy",33
ForcedKind::DoNotDisturb => "DoNotDisturb",34
ForcedKind::BeRightBack => "BeRightBack",35
ForcedKind::Away => "Away",36
ForcedKind::Offline => "Offline",37
}38
}39
40
pub fn from_code(code: &str) -> Option<Self> {41
match code {42
"Available" => Some(ForcedKind::Available),43
"Busy" => Some(ForcedKind::Busy),44
"DoNotDisturb" => Some(ForcedKind::DoNotDisturb),45
"BeRightBack" => Some(ForcedKind::BeRightBack),46
"Away" => Some(ForcedKind::Away),47
"Offline" => Some(ForcedKind::Offline),48
_ => None,49
}50
}51
}52
53
#[derive(Debug, Clone, Copy, PartialEq, Eq)]54
pub struct ForcedAvailability {55
pub kind: ForcedKind,56
pub expires_at: Option<DateTime<Utc>>,57
}58
59
#[derive(Debug, Clone, PartialEq, Eq)]60
pub struct StatusNote {61
pub text: String,62
pub show_when_messaged: bool,63
pub expires_at: Option<DateTime<Utc>>,64
}65
66
#[derive(Debug, Clone, Copy, PartialEq, Eq)]67
pub enum WorkLocationKind {68
Office,69
Remote,70
}71
72
impl WorkLocationKind {73
fn code(self) -> u8 {74
match self {75
WorkLocationKind::Office => 1,76
WorkLocationKind::Remote => 2,77
}78
}79
}80
81
#[derive(Debug, Clone, Copy, PartialEq, Eq)]82
pub enum WorkLocationSource {83
Set,84
Scheduled,85
Verified,86
}87
88
#[derive(Debug, Clone, Copy, PartialEq, Eq)]89
pub struct WorkLocation {90
pub kind: WorkLocationKind,91
pub source: WorkLocationSource,92
}93
94
#[derive(Debug, Clone, Default, PartialEq, Eq)]95
pub struct PresenceStatus {96
pub availability: String,97
pub activity: Option<String>,98
pub forced: Option<ForcedAvailability>,99
pub note: Option<StatusNote>,100
pub out_of_office: bool,101
pub out_of_office_note: Option<String>,102
pub work_location: Option<WorkLocation>,103
}104
105
pub struct PresenceService<T: CardTransport = SessionCardTransport> {106
transport: T,107
}108
109
impl PresenceService<SessionCardTransport> {110
pub fn new(session: &Session) -> Self {111
PresenceService::with_transport(SessionCardTransport::new(session))112
}113
}114
115
impl<T: CardTransport> PresenceService<T> {116
pub fn with_transport(transport: T) -> Self {117
PresenceService { transport }118
}119
120
pub async fn set_availability(&self, forced: Option<&ForcedAvailability>) -> Result<()> {121
let url = format!("{BASE_URL}/me/forceavailability/");122
let request = match forced {123
Some(forced) => Request::with_body(Method::Put, &url, availability_body(forced)),124
None => Request {125
method: Method::Put,126
..Request::get(&url)127
},128
};129
self.send(request, &url).await.map(drop)130
}131
132
pub async fn set_note(&self, note: Option<&StatusNote>) -> Result<()> {133
let url = format!("{BASE_URL}/me/publishnote");134
let body = note.map_or_else(|| json!({"message": ""}), note_body);135
self.send(Request::with_body(Method::Put, &url, body), &url)136
.await137
.map(drop)138
}139
140
pub async fn set_work_location(141
&self,142
location: Option<(WorkLocationKind, DateTime<Utc>)>,143
) -> Result<()> {144
let url = format!("{BASE_URL}/me/workLocation/");145
let body = match location {146
Some((kind, expires_at)) => json!({147
"location": kind.code(),148
"expirationTime": format_expiry(Some(expires_at)),149
}),150
None => json!({"location": 0}),151
};152
self.send(Request::with_body(Method::Put, &url, body), &url)153
.await154
.map(drop)155
}156
157
pub async fn status(&self, user_id: &str) -> Result<PresenceStatus> {158
let url = format!("{BASE_URL}/presence/getpresence/");159
let mri = format!("{ORGID_PREFIX}{user_id}");160
let body = json!([{ "mri": mri }]);161
let answer = self162
.send(Request::with_body(Method::Post, &url, body), &url)163
.await?;164
parse_status(&answer, &mri, Utc::now())165
}166
167
async fn send(&self, mut request: Request, url: &str) -> Result<Value> {168
request.headers = service_headers();169
let answer = self170
.transport171
.send(request, Scope::new(PRESENCE, PRESENCE_SCOPE))172
.await?;173
if !answer.is_success() {174
return Err(Error::Session(session::Error::api(175
answer.status,176
url,177
answer.body,178
)));179
}180
Ok(answer.body)181
}182
}183
184
fn service_headers() -> Vec<(String, String)> {185
vec![186
("x-ms-client-user-agent".into(), "Teams-V2-Web".into()),187
("x-ms-correlation-id".into(), Uuid::new_v4().to_string()),188
("x-ms-client-version".into(), CLIENT_VERSION.into()),189
]190
}191
192
pub fn format_expiry(expires_at: Option<DateTime<Utc>>) -> String {193
match expires_at {194
Some(expires_at) => expires_at.to_rfc3339_opts(SecondsFormat::Millis, true),195
None => NEVER_EXPIRES.to_owned(),196
}197
}198
199
fn availability_body(forced: &ForcedAvailability) -> Value {200
let mut body = json!({"availability": forced.kind.code()});201
if forced.kind == ForcedKind::Offline {202
body["activity"] = json!(OFFLINE_ACTIVITY);203
}204
if let Some(expires_at) = forced.expires_at {205
body["desiredExpirationTime"] = json!(format_expiry(Some(expires_at)));206
}207
body208
}209
210
fn note_body(note: &StatusNote) -> Value {211
let suffix = if note.show_when_messaged {212
PINNED_NOTE_SUFFIX213
} else {214
""215
};216
json!({217
"message": format!("{}{suffix}", escape_text(¬e.text)),218
"expiry": format_expiry(note.expires_at),219
})220
}221
222
fn escape_text(text: &str) -> String {223
text.replace('&', "&")224
.replace('<', "<")225
.replace('>', ">")226
.replace('"', """)227
.replace('\'', "'")228
}229
230
fn unescape_text(text: &str) -> String {231
text.replace("<", "<")232
.replace(">", ">")233
.replace(""", "\"")234
.replace("'", "'")235
.replace("&", "&")236
}237
238
fn plain_text(message: &str) -> Option<String> {239
let mut text = String::with_capacity(message.len());240
let mut inside_tag = false;241
for character in message.chars() {242
match character {243
'<' => inside_tag = true,244
'>' if inside_tag => inside_tag = false,245
_ if !inside_tag => text.push(character),246
_ => {}247
}248
}249
let text = unescape_text(&text);250
let text = text.trim();251
(!text.is_empty()).then(|| text.to_owned())252
}253
254
fn split_pinned(message: &str) -> (String, bool) {255
let pinned = message256
.find(PINNED_NOTE_SUFFIX)257
.is_some_and(|index| index > 0);258
(message.replace(PINNED_NOTE_SUFFIX, ""), pinned)259
}260
261
fn parse_expiry(value: Option<&Value>) -> Option<DateTime<Utc>> {262
let parsed = DateTime::parse_from_rfc3339(value?.as_str()?)263
.ok()?264
.with_timezone(&Utc);265
(parsed.year() < NEVER_YEAR).then_some(parsed)266
}267
268
fn parse_forced(forced: &Value) -> Option<ForcedAvailability> {269
Some(ForcedAvailability {270
kind: ForcedKind::from_code(forced.get("availability")?.as_str()?)?,271
expires_at: parse_expiry(forced.get("expiry")),272
})273
}274
275
fn parse_note(note: &Value, now: DateTime<Utc>) -> Option<StatusNote> {276
let (message, show_when_messaged) = split_pinned(note.get("message")?.as_str()?);277
let text = plain_text(&message)?;278
let expires_at = parse_expiry(note.get("expiry"));279
let expired = expires_at.is_some_and(|expires_at| expires_at <= now);280
(!expired).then_some(StatusNote {281
text,282
show_when_messaged,283
expires_at,284
})285
}286
287
fn parse_work_location(location: &Value, now: DateTime<Utc>) -> Option<WorkLocation> {288
let kind = match location.get("location")?.as_str()? {289
"Office" => WorkLocationKind::Office,290
"Remote" => WorkLocationKind::Remote,291
_ => return None,292
};293
let expired = parse_expiry(location.get("expiry")).is_some_and(|expires_at| expires_at <= now);294
(!expired).then(|| WorkLocation {295
kind,296
source: match location.get("locationSource").and_then(Value::as_str) {297
Some("ScheduledLocation") => WorkLocationSource::Scheduled,298
Some("VerifiedLocation") => WorkLocationSource::Verified,299
_ => WorkLocationSource::Set,300
},301
})302
}303
304
pub fn parse_status(body: &Value, mri: &str, now: DateTime<Utc>) -> Result<PresenceStatus> {305
let entries = body306
.as_array()307
.ok_or_else(|| Error::UnexpectedAnswer("no presence list".into()))?;308
let presence = entries309
.iter()310
.find(|entry| entry.get("mri").and_then(Value::as_str) == Some(mri))311
.or_else(|| entries.first())312
.and_then(|entry| entry.get("presence"))313
.ok_or_else(|| Error::UnexpectedAnswer("no own presence".into()))?;314
Ok(PresenceStatus {315
availability: presence316
.get("availability")317
.and_then(Value::as_str)318
.unwrap_or_default()319
.to_owned(),320
activity: presence321
.get("activity")322
.and_then(Value::as_str)323
.map(str::to_owned),324
forced: presence.get("forcedAvailability").and_then(parse_forced),325
note: presence.get("note").and_then(|note| parse_note(note, now)),326
out_of_office: presence327
.pointer("/calendarData/isOutOfOffice")328
.and_then(Value::as_bool)329
.unwrap_or(false),330
out_of_office_note: presence331
.pointer("/calendarData/outOfOfficeNote/message")332
.and_then(Value::as_str)333
.and_then(plain_text),334
work_location: presence335
.get("workLocation")336
.and_then(|location| parse_work_location(location, now)),337
})338
}339
340
#[cfg(test)]341
mod tests {342
use std::sync::Mutex;343
344
use chrono::TimeZone;345
use session::{ApiResponse, Method};346
347
use super::*;348
349
struct Recorder {350
status: u16,351
body: Value,352
sent: Mutex<Vec<(Request, Scope)>>,353
}354
355
impl CardTransport for Recorder {356
async fn send(&self, request: Request, scope: Scope) -> Result<ApiResponse> {357
self.sent.lock().unwrap().push((request, scope));358
Ok(ApiResponse {359
status: self.status,360
body: self.body.clone(),361
retry_after: None,362
})363
}364
}365
366
fn service(status: u16, body: Value) -> PresenceService<Recorder> {367
PresenceService::with_transport(Recorder {368
status,369
body,370
sent: Mutex::new(Vec::new()),371
})372
}373
374
fn only_request(service: &PresenceService<Recorder>) -> (Request, Scope) {375
let mut sent = service.transport.sent.lock().unwrap();376
assert_eq!(sent.len(), 1);377
sent.remove(0)378
}379
380
fn at(hour: u32, minute: u32) -> DateTime<Utc> {381
Utc.with_ymd_and_hms(2026, 10, 9, hour, minute, 0).unwrap()382
}383
384
#[tokio::test]385
async fn busy_with_expiry_puts_availability_and_desired_expiration() {386
let service = service(200, Value::Null);387
let forced = ForcedAvailability {388
kind: ForcedKind::Busy,389
expires_at: Some(at(15, 30)),390
};391
service.set_availability(Some(&forced)).await.unwrap();392
let (request, scope) = only_request(&service);393
assert_eq!(request.method, Method::Put);394
assert_eq!(395
request.url,396
"https://presence.teams.microsoft.com/v1/me/forceavailability/"397
);398
assert_eq!(399
request.body,400
Some(json!({401
"availability": "Busy",402
"desiredExpirationTime": "2026-10-09T15:30:00.000Z",403
}))404
);405
assert_eq!(scope, Scope::new(PRESENCE, "user_impersonation"));406
let names: Vec<&str> = request407
.headers408
.iter()409
.map(|(name, _)| name.as_str())410
.collect();411
assert_eq!(412
names,413
[414
"x-ms-client-user-agent",415
"x-ms-correlation-id",416
"x-ms-client-version"417
]418
);419
}420
421
#[tokio::test]422
async fn offline_carries_the_off_work_activity_and_no_expiry_when_open() {423
let service = service(200, Value::Null);424
let forced = ForcedAvailability {425
kind: ForcedKind::Offline,426
expires_at: None,427
};428
service.set_availability(Some(&forced)).await.unwrap();429
let (request, _) = only_request(&service);430
assert_eq!(431
request.body,432
Some(json!({"availability": "Offline", "activity": "OffWork"}))433
);434
}435
436
#[tokio::test]437
async fn reset_is_a_put_without_body() {438
let service = service(200, Value::Null);439
service.set_availability(None).await.unwrap();440
let (request, _) = only_request(&service);441
assert_eq!(request.method, Method::Put);442
assert_eq!(request.body, None);443
assert!(request.url.ends_with("/v1/me/forceavailability/"));444
}445
446
#[tokio::test]447
async fn note_with_pin_marker_and_escaped_text() {448
let service = service(200, Value::Null);449
let note = StatusNote {450
text: "Out <b> & about".into(),451
show_when_messaged: true,452
expires_at: Some(at(18, 0)),453
};454
service.set_note(Some(¬e)).await.unwrap();455
let (request, _) = only_request(&service);456
assert_eq!(request.method, Method::Put);457
assert_eq!(458
request.url,459
"https://presence.teams.microsoft.com/v1/me/publishnote"460
);461
assert_eq!(462
request.body,463
Some(json!({464
"message": "Out <b> & about<pinnednote></pinnednote>",465
"expiry": "2026-10-09T18:00:00.000Z",466
}))467
);468
}469
470
#[tokio::test]471
async fn note_without_pin_and_never_expiring() {472
let service = service(200, Value::Null);473
let note = StatusNote {474
text: "Focus".into(),475
show_when_messaged: false,476
expires_at: None,477
};478
service.set_note(Some(¬e)).await.unwrap();479
let (request, _) = only_request(&service);480
assert_eq!(481
request.body,482
Some(json!({"message": "Focus", "expiry": "9999-12-31T23:59:59.999Z"}))483
);484
}485
486
#[tokio::test]487
async fn clearing_the_note_sends_an_empty_message_only() {488
let service = service(200, Value::Null);489
service.set_note(None).await.unwrap();490
let (request, _) = only_request(&service);491
assert_eq!(request.body, Some(json!({"message": ""})));492
}493
494
#[tokio::test]495
async fn failures_surface_as_errors() {496
let service = service(400, json!({"message": "bad"}));497
assert!(service.set_note(None).await.is_err());498
}499
500
#[tokio::test]501
async fn reads_own_presence_by_mri() {502
let body = json!([{503
"mri": "8:orgid:me",504
"presence": {"availability": "Available", "activity": "Available"}505
}]);506
let service = service(200, body);507
let status = service.status("me").await.unwrap();508
assert_eq!(status.availability, "Available");509
let (request, _) = only_request(&service);510
assert_eq!(request.method, Method::Post);511
assert_eq!(512
request.url,513
"https://presence.teams.microsoft.com/v1/presence/getpresence/"514
);515
assert_eq!(request.body, Some(json!([{"mri": "8:orgid:me"}])));516
}517
518
#[test]519
fn parses_forced_note_and_out_of_office() {520
let body = json!([{521
"mri": "8:orgid:me",522
"presence": {523
"availability": "Busy",524
"activity": "Busy",525
"forcedAvailability": {526
"availability": "Busy",527
"expiry": "2026-10-09T15:30:00Z",528
"publishTime": "2026-10-09T15:00:00Z"529
},530
"note": {531
"message": "In <focus><pinnednote></pinnednote>",532
"expiry": "2026-10-09T18:00:00Z"533
},534
"calendarData": {"isOutOfOffice": true}535
}536
}]);537
let status = parse_status(&body, "8:orgid:me", at(12, 0)).unwrap();538
assert_eq!(status.availability, "Busy");539
assert_eq!(540
status.forced,541
Some(ForcedAvailability {542
kind: ForcedKind::Busy,543
expires_at: Some(at(15, 30)),544
})545
);546
assert_eq!(547
status.note,548
Some(StatusNote {549
text: "In <focus>".into(),550
show_when_messaged: true,551
expires_at: Some(at(18, 0)),552
})553
);554
assert!(status.out_of_office);555
}556
557
#[test]558
fn never_expiry_reads_back_as_none() {559
let body = json!([{560
"mri": "8:orgid:me",561
"presence": {562
"availability": "Available",563
"note": {"message": "Hi", "expiry": "9999-12-31T23:59:59.9999999Z"}564
}565
}]);566
let status = parse_status(&body, "8:orgid:me", at(12, 0)).unwrap();567
let note = status.note.unwrap();568
assert_eq!(note.expires_at, None);569
assert!(!note.show_when_messaged);570
}571
572
#[test]573
fn expired_and_empty_notes_are_dropped() {574
let expired = json!([{"mri": "m", "presence": {575
"availability": "Available",576
"note": {"message": "Old", "expiry": "2026-10-09T08:00:00Z"}577
}}]);578
let empty = json!([{"mri": "m", "presence": {579
"availability": "Available",580
"note": {"message": "", "expiry": "9999-12-31T23:59:59.9999999Z"}581
}}]);582
assert_eq!(parse_status(&expired, "m", at(12, 0)).unwrap().note, None);583
assert_eq!(parse_status(&empty, "m", at(12, 0)).unwrap().note, None);584
}585
586
#[test]587
fn pin_marker_at_the_start_does_not_count() {588
let (text, pinned) = split_pinned("<pinnednote></pinnednote>");589
assert_eq!(text, "");590
assert!(!pinned);591
}592
593
#[test]594
fn unknown_forced_availability_is_ignored() {595
let body = json!([{"mri": "m", "presence": {596
"availability": "Away",597
"forcedAvailability": {"availability": "Mystery"}598
}}]);599
assert_eq!(parse_status(&body, "m", at(12, 0)).unwrap().forced, None);600
}601
602
#[test]603
fn missing_presence_is_unexpected() {604
assert!(matches!(605
parse_status(&json!({}), "m", at(12, 0)),606
Err(Error::UnexpectedAnswer(_))607
));608
}609
610
#[tokio::test]611
async fn work_location_puts_numbers_and_end_of_day_expiry() {612
let service = service(200, Value::Null);613
service614
.set_work_location(Some((WorkLocationKind::Remote, at(21, 59))))615
.await616
.unwrap();617
let (request, scope) = only_request(&service);618
assert_eq!(request.method, Method::Put);619
assert_eq!(620
request.url,621
"https://presence.teams.microsoft.com/v1/me/workLocation/"622
);623
assert_eq!(624
request.body,625
Some(json!({"location": 2, "expirationTime": "2026-10-09T21:59:00.000Z"}))626
);627
assert_eq!(scope, Scope::new(PRESENCE, "user_impersonation"));628
service629
.set_work_location(Some((WorkLocationKind::Office, at(21, 59))))630
.await631
.unwrap();632
let (request, _) = only_request(&service);633
assert_eq!(request.body.unwrap()["location"], json!(1));634
}635
636
#[tokio::test]637
async fn clearing_the_work_location_sends_zero_without_expiry() {638
let service = service(200, Value::Null);639
service.set_work_location(None).await.unwrap();640
let (request, _) = only_request(&service);641
assert_eq!(request.body, Some(json!({"location": 0})));642
}643
644
#[test]645
fn parses_work_location_and_hides_unknown_or_expired() {646
let read = |location: Value| {647
let body = json!([{"mri": "m", "presence": {648
"availability": "Available", "workLocation": location649
}}]);650
parse_status(&body, "m", at(12, 0)).unwrap().work_location651
};652
assert_eq!(653
read(654
json!({"location": "Remote", "expiry": "2026-10-09T21:59:59.9999999Z",655
"isForced": true, "locationSource": "ForcedLocation"})656
),657
Some(WorkLocation {658
kind: WorkLocationKind::Remote,659
source: WorkLocationSource::Set660
})661
);662
assert_eq!(663
read(664
json!({"location": "Office", "locationSource": "ScheduledLocation",665
"expiry": "2026-10-09T21:59:59Z"})666
),667
Some(WorkLocation {668
kind: WorkLocationKind::Office,669
source: WorkLocationSource::Scheduled670
})671
);672
assert_eq!(673
read(json!({"location": "Office", "locationSource": "VerifiedLocation"}))674
.map(|found| found.source),675
Some(WorkLocationSource::Verified)676
);677
assert_eq!(read(json!({"location": "Unknown"})), None);678
assert_eq!(read(json!({"location": "TimeOff"})), None);679
assert_eq!(680
read(json!({"location": "Office", "expiry": "2026-10-09T08:00:00Z"})),681
None682
);683
}684
685
#[test]686
fn note_text_is_unescaped_and_the_pin_marker_stripped() {687
let body = json!([{"mri": "m", "presence": {688
"availability": "Busy",689
"note": {690
"message": "Back at 3 & later<pinnednote></pinnednote>",691
"expiry": "9999-12-31T23:59:59.9999999Z"692
},693
"calendarData": {"isOutOfOffice": false}694
}}]);695
let status = parse_status(&body, "m", at(12, 0)).unwrap();696
assert_eq!(status.note.unwrap().text, "Back at 3 & later");697
assert!(!status.out_of_office);698
assert_eq!(status.out_of_office_note, None);699
}700
701
#[test]702
fn out_of_office_carries_its_plain_text() {703
let read = |calendar: Value| {704
let body = json!([{"mri": "m", "presence": {705
"availability": "Away", "calendarData": calendar706
}}]);707
parse_status(&body, "m", at(12, 0)).unwrap()708
};709
let with_text = read(710
json!({"isOutOfOffice": true, "outOfOfficeNote": {"message": "<p>On & leave</p>"}}),711
);712
assert!(with_text.out_of_office);713
assert_eq!(with_text.out_of_office_note.as_deref(), Some("On & leave"));714
let bare = read(json!({"isOutOfOffice": true}));715
assert!(bare.out_of_office);716
assert_eq!(bare.out_of_office_note, None);717
}718
719
#[test]720
fn expiry_formats_to_milliseconds_utc() {721
assert_eq!(format_expiry(Some(at(15, 30))), "2026-10-09T15:30:00.000Z");722
assert_eq!(format_expiry(None), "9999-12-31T23:59:59.999Z");723
}724
}@@ -23,6 +23,7 @@ const EVENT_CAPACITY: usize = 64;
23
23
pub(crate) const META_USER_ID: &str = "me_user_id";
24
24
const META_TENANT_ID: &str = "me_tenant_id";
25
25
const META_DISPLAY_NAME: &str = "me_display_name";
26
const META_EMAIL: &str = "me_email";
26
27
27
28
#[derive(Debug, Clone)]
28
29
pub struct SyncConfig {
@@ -263,7 +264,7 @@ impl<R: Remote> SyncEngine<R> {
263
264
}
264
265
265
266
pub(crate) async fn ensure_display_name(&self) -> Result<()> {
266
if self.store.meta(META_DISPLAY_NAME)?.is_none() {
267
if self.store.meta(META_DISPLAY_NAME)?.is_none() || self.store.meta(META_EMAIL)?.is_none() {
267
268
self.remember_me().await?;
268
269
}
269
270
Ok(())
@@ -275,6 +276,8 @@ impl<R: Remote> SyncEngine<R> {
275
276
if let Some(name) = user.display_name.as_deref() {
276
277
self.store.set_meta(META_DISPLAY_NAME, name)?;
277
278
}
279
let email = user.mail.as_deref().or(user.user_principal_name.as_deref());
280
self.store.set_meta(META_EMAIL, email.unwrap_or_default())?;
278
281
Ok(user.id)
279
282
}
280
283
@@ -23,6 +23,7 @@ const EVENT_CAPACITY: usize = 64;23
pub(crate) const META_USER_ID: &str = "me_user_id";23
pub(crate) const META_USER_ID: &str = "me_user_id";24
const META_TENANT_ID: &str = "me_tenant_id";24
const META_TENANT_ID: &str = "me_tenant_id";25
const META_DISPLAY_NAME: &str = "me_display_name";25
const META_DISPLAY_NAME: &str = "me_display_name";26
const META_EMAIL: &str = "me_email";26
27
27
#[derive(Debug, Clone)]28
#[derive(Debug, Clone)]28
pub struct SyncConfig {29
pub struct SyncConfig {@@ -263,7 +264,7 @@ impl<R: Remote> SyncEngine<R> {263
}264
}264
265
265
pub(crate) async fn ensure_display_name(&self) -> Result<()> {266
pub(crate) async fn ensure_display_name(&self) -> Result<()> {266
if self.store.meta(META_DISPLAY_NAME)?.is_none() {267
if self.store.meta(META_DISPLAY_NAME)?.is_none() || self.store.meta(META_EMAIL)?.is_none() {267
self.remember_me().await?;268
self.remember_me().await?;268
}269
}269
Ok(())270
Ok(())@@ -275,6 +276,8 @@ impl<R: Remote> SyncEngine<R> {275
if let Some(name) = user.display_name.as_deref() {276
if let Some(name) = user.display_name.as_deref() {276
self.store.set_meta(META_DISPLAY_NAME, name)?;277
self.store.set_meta(META_DISPLAY_NAME, name)?;277
}278
}279
let email = user.mail.as_deref().or(user.user_principal_name.as_deref());280
self.store.set_meta(META_EMAIL, email.unwrap_or_default())?;278
Ok(user.id)281
Ok(user.id)279
}282
}280
283
@@ -1,3 +1,5 @@
1
use chatsvc::PresenceStatus;
2
1
3
#[derive(Debug, Clone, PartialEq, Eq)]
2
4
pub enum CoreEvent {
3
5
SidebarChanged,
@@ -8,5 +10,6 @@ pub enum CoreEvent {
8
10
ImagesChanged { keys: Vec<String> },
9
11
FoldersChanged,
10
12
PresenceChanged,
13
PresenceStatusChanged(PresenceStatus),
11
14
Error { message: String },
12
15
}
@@ -1,3 +1,5 @@1
use chatsvc::PresenceStatus;2
1
#[derive(Debug, Clone, PartialEq, Eq)]3
#[derive(Debug, Clone, PartialEq, Eq)]2
pub enum CoreEvent {4
pub enum CoreEvent {3
SidebarChanged,5
SidebarChanged,@@ -8,5 +10,6 @@ pub enum CoreEvent {8
ImagesChanged { keys: Vec<String> },10
ImagesChanged { keys: Vec<String> },9
FoldersChanged,11
FoldersChanged,10
PresenceChanged,12
PresenceChanged,13
PresenceStatusChanged(PresenceStatus),11
Error { message: String },14
Error { message: String },12
}15
}@@ -20,10 +20,10 @@ mod folders;
20
20
mod gifs;
21
21
mod image_size;
22
22
mod images;
23
mod italic;
23
24
mod link_sync;
24
25
mod links;
25
26
mod mapping;
26
mod italic;
27
27
mod markdown;
28
28
mod mentions;
29
29
mod message_actions;
@@ -31,6 +31,7 @@ mod message_link;
31
31
mod people;
32
32
mod presence;
33
33
mod preview;
34
mod profile;
34
35
mod receipts;
35
36
mod remote;
36
37
mod scheduled;
@@ -38,23 +39,15 @@ mod search;
38
39
mod sidebar_sync;
39
40
mod spans;
40
41
mod stored;
42
mod time_zone;
41
43
42
44
pub use adaptive_card::{
43
ActionSplit, AdaptiveCard, CARD_THEME, CardAction, CardActionIcon, CardActionKind, CardColumn, CardElement,
44
CardFact, CardIcon, CardImage, CardItem, CardMedia, CardRefresh, CardSpacing, CardText,
45
ColumnWidth, ContainerStyle, ExecuteAction, ExecuteTrigger, IconSize, ImageSize,
45
ActionSplit, AdaptiveCard, CARD_THEME, CardAction, CardActionIcon, CardActionKind, CardColumn,
46
CardElement, CardFact, CardIcon, CardImage, CardItem, CardMedia, CardRefresh, CardSpacing,
47
CardText, ColumnWidth, ContainerStyle, ExecuteAction, ExecuteTrigger, IconSize, ImageSize,
46
48
InvokePayload, SubmitAction, TextColor, TextSize, ToggleTarget, VerticalAlignment,
47
49
card_content_text, split_overflow, task_value,
48
50
};
49
pub use card_date::{format_card_dates, format_card_dates_in};
50
pub use card_layout::{ContainerLayout, HorizontalAlignment};
51
pub use card_table::{CardTable, TableCell, TableColumn, TableRow};
52
pub use card_widgets::{
53
BadgeAppearance, BadgeShape, BadgeSize, BadgeStyle, CardBadge, CardCarousel, CardCarouselPage,
54
CardCodeBlock, CardCompoundButton, CardProgressBar, CardProgressRing, IconPosition,
55
LabelPosition, RingSize,
56
};
57
pub use card_width::{TargetWidth, WidthClass};
58
51
pub use avatars::Avatar;
59
52
pub use card_actions::{CardActionOutcome, DialogIdentity, TaskDialog, TaskDialogKind};
60
53
pub use card_chart::{
@@ -62,6 +55,7 @@ pub use card_chart::{
62
55
ChartSeries, GaugeSegment, GaugeValueFormat, format_chart_value, label_stride, nice_scale,
63
56
series_categories, series_maximum, series_value, slice_angles, unit_fraction,
64
57
};
58
pub use card_date::{format_card_dates, format_card_dates_in};
65
59
pub use card_inputs::{
66
60
CardInput, CardInputKind, ChoiceInput, ChoiceQuery, ChoiceStyle, DATE_PLACEHOLDER,
67
61
InlineAction, InputChoice, InputError, MomentInput, NumberInput, RatingColor, RatingDisplay,
@@ -69,7 +63,18 @@ pub use card_inputs::{
69
63
TextStyle, ToggleInput, collect_input_values, format_date, format_time, merge_input_data,
70
64
parse_search_results, search_request_value,
71
65
};
72
pub use chatsvc::{ChatApp, ForwardResult, Gif, PinnedMessage, SavedMessage, ScheduledDraft};
66
pub use card_layout::{ContainerLayout, HorizontalAlignment};
67
pub use card_table::{CardTable, TableCell, TableColumn, TableRow};
68
pub use card_widgets::{
69
BadgeAppearance, BadgeShape, BadgeSize, BadgeStyle, CardBadge, CardCarousel, CardCarouselPage,
70
CardCodeBlock, CardCompoundButton, CardProgressBar, CardProgressRing, IconPosition,
71
LabelPosition, RingSize,
72
};
73
pub use card_width::{TargetWidth, WidthClass};
74
pub use chatsvc::{
75
ChatApp, ForcedAvailability, ForcedKind, ForwardResult, Gif, PinnedMessage, PresenceStatus,
76
SavedMessage, ScheduledDraft, StatusNote, WorkLocation, WorkLocationKind, WorkLocationSource,
77
};
73
78
pub use draft::{
74
79
Draft, DraftLine, Edit, FormatState, LineKind, MAX_DEPTH, Mark, MarkKind, OBJECT_MARK,
75
80
SizeStep, TypingStyle, changed_span, has_markdown, link_url, map_offset, reverse_edits,
@@ -92,13 +97,15 @@ pub use message_link::{ChannelLinkInput, channel_message_link, chat_message_link
92
97
pub use people::{MentionCandidate, PersonCandidate, PersonSource};
93
98
pub use presence::{Availability, Presence};
94
99
pub use preview::preview_text;
100
pub use profile::{OrgPerson, PersonProfile};
95
101
pub use receipts::{ReceiptReader, ReceiptState};
96
102
pub use remote::{ChatsPage, DeltaPage, Remote, RemotePage};
97
103
pub use scheduled::NOTES_CHAT_ID;
98
104
pub use spans::{FontSize, Span, html_to_spans};
99
105
pub use store::{ConversationHit, HIGHLIGHT_END, HIGHLIGHT_START, SearchHit};
100
106
pub use stored::{
101
AttachmentInfo, FileCard, FileKind, ImageRef, MentionInfo, QuoteInfo, ReactionInfo,
102
adaptive_cards, attachments, can_delete, can_edit, card_texts, copy_text, files, images,
103
mentions, message_spans, quotes, reactions, user_mention_inputs,
107
AttachmentInfo, FileCard, FileKind, ImageRef, MentionInfo, PROFILE_LINK_PREFIX, QuoteInfo,
108
ReactionInfo, adaptive_cards, attachments, can_delete, can_edit, card_texts, copy_text, files,
109
images, linked_message_spans, mentions, message_spans, quotes, reactions, user_mention_inputs,
104
110
};
111
pub use time_zone::local_time;
@@ -20,10 +20,10 @@ mod folders;20
mod gifs;20
mod gifs;21
mod image_size;21
mod image_size;22
mod images;22
mod images;23
mod italic;23
mod link_sync;24
mod link_sync;24
mod links;25
mod links;25
mod mapping;26
mod mapping;26
mod italic;27
mod markdown;27
mod markdown;28
mod mentions;28
mod mentions;29
mod message_actions;29
mod message_actions;@@ -31,6 +31,7 @@ mod message_link;31
mod people;31
mod people;32
mod presence;32
mod presence;33
mod preview;33
mod preview;34
mod profile;34
mod receipts;35
mod receipts;35
mod remote;36
mod remote;36
mod scheduled;37
mod scheduled;@@ -38,23 +39,15 @@ mod search;38
mod sidebar_sync;39
mod sidebar_sync;39
mod spans;40
mod spans;40
mod stored;41
mod stored;42
mod time_zone;41
43
42
pub use adaptive_card::{44
pub use adaptive_card::{43
ActionSplit, AdaptiveCard, CARD_THEME, CardAction, CardActionIcon, CardActionKind, CardColumn, CardElement,45
ActionSplit, AdaptiveCard, CARD_THEME, CardAction, CardActionIcon, CardActionKind, CardColumn,44
CardFact, CardIcon, CardImage, CardItem, CardMedia, CardRefresh, CardSpacing, CardText,46
CardElement, CardFact, CardIcon, CardImage, CardItem, CardMedia, CardRefresh, CardSpacing,45
ColumnWidth, ContainerStyle, ExecuteAction, ExecuteTrigger, IconSize, ImageSize,47
CardText, ColumnWidth, ContainerStyle, ExecuteAction, ExecuteTrigger, IconSize, ImageSize,46
InvokePayload, SubmitAction, TextColor, TextSize, ToggleTarget, VerticalAlignment,48
InvokePayload, SubmitAction, TextColor, TextSize, ToggleTarget, VerticalAlignment,47
card_content_text, split_overflow, task_value,49
card_content_text, split_overflow, task_value,48
};50
};49
pub use card_date::{format_card_dates, format_card_dates_in};50
pub use card_layout::{ContainerLayout, HorizontalAlignment};51
pub use card_table::{CardTable, TableCell, TableColumn, TableRow};52
pub use card_widgets::{53
BadgeAppearance, BadgeShape, BadgeSize, BadgeStyle, CardBadge, CardCarousel, CardCarouselPage,54
CardCodeBlock, CardCompoundButton, CardProgressBar, CardProgressRing, IconPosition,55
LabelPosition, RingSize,56
};57
pub use card_width::{TargetWidth, WidthClass};58
pub use avatars::Avatar;51
pub use avatars::Avatar;59
pub use card_actions::{CardActionOutcome, DialogIdentity, TaskDialog, TaskDialogKind};52
pub use card_actions::{CardActionOutcome, DialogIdentity, TaskDialog, TaskDialogKind};60
pub use card_chart::{53
pub use card_chart::{@@ -62,6 +55,7 @@ pub use card_chart::{62
ChartSeries, GaugeSegment, GaugeValueFormat, format_chart_value, label_stride, nice_scale,55
ChartSeries, GaugeSegment, GaugeValueFormat, format_chart_value, label_stride, nice_scale,63
series_categories, series_maximum, series_value, slice_angles, unit_fraction,56
series_categories, series_maximum, series_value, slice_angles, unit_fraction,64
};57
};58
pub use card_date::{format_card_dates, format_card_dates_in};65
pub use card_inputs::{59
pub use card_inputs::{66
CardInput, CardInputKind, ChoiceInput, ChoiceQuery, ChoiceStyle, DATE_PLACEHOLDER,60
CardInput, CardInputKind, ChoiceInput, ChoiceQuery, ChoiceStyle, DATE_PLACEHOLDER,67
InlineAction, InputChoice, InputError, MomentInput, NumberInput, RatingColor, RatingDisplay,61
InlineAction, InputChoice, InputError, MomentInput, NumberInput, RatingColor, RatingDisplay,@@ -69,7 +63,18 @@ pub use card_inputs::{69
TextStyle, ToggleInput, collect_input_values, format_date, format_time, merge_input_data,63
TextStyle, ToggleInput, collect_input_values, format_date, format_time, merge_input_data,70
parse_search_results, search_request_value,64
parse_search_results, search_request_value,71
};65
};72
pub use chatsvc::{ChatApp, ForwardResult, Gif, PinnedMessage, SavedMessage, ScheduledDraft};66
pub use card_layout::{ContainerLayout, HorizontalAlignment};67
pub use card_table::{CardTable, TableCell, TableColumn, TableRow};68
pub use card_widgets::{69
BadgeAppearance, BadgeShape, BadgeSize, BadgeStyle, CardBadge, CardCarousel, CardCarouselPage,70
CardCodeBlock, CardCompoundButton, CardProgressBar, CardProgressRing, IconPosition,71
LabelPosition, RingSize,72
};73
pub use card_width::{TargetWidth, WidthClass};74
pub use chatsvc::{75
ChatApp, ForcedAvailability, ForcedKind, ForwardResult, Gif, PinnedMessage, PresenceStatus,76
SavedMessage, ScheduledDraft, StatusNote, WorkLocation, WorkLocationKind, WorkLocationSource,77
};73
pub use draft::{78
pub use draft::{74
Draft, DraftLine, Edit, FormatState, LineKind, MAX_DEPTH, Mark, MarkKind, OBJECT_MARK,79
Draft, DraftLine, Edit, FormatState, LineKind, MAX_DEPTH, Mark, MarkKind, OBJECT_MARK,75
SizeStep, TypingStyle, changed_span, has_markdown, link_url, map_offset, reverse_edits,80
SizeStep, TypingStyle, changed_span, has_markdown, link_url, map_offset, reverse_edits,@@ -92,13 +97,15 @@ pub use message_link::{ChannelLinkInput, channel_message_link, chat_message_link92
pub use people::{MentionCandidate, PersonCandidate, PersonSource};97
pub use people::{MentionCandidate, PersonCandidate, PersonSource};93
pub use presence::{Availability, Presence};98
pub use presence::{Availability, Presence};94
pub use preview::preview_text;99
pub use preview::preview_text;100
pub use profile::{OrgPerson, PersonProfile};95
pub use receipts::{ReceiptReader, ReceiptState};101
pub use receipts::{ReceiptReader, ReceiptState};96
pub use remote::{ChatsPage, DeltaPage, Remote, RemotePage};102
pub use remote::{ChatsPage, DeltaPage, Remote, RemotePage};97
pub use scheduled::NOTES_CHAT_ID;103
pub use scheduled::NOTES_CHAT_ID;98
pub use spans::{FontSize, Span, html_to_spans};104
pub use spans::{FontSize, Span, html_to_spans};99
pub use store::{ConversationHit, HIGHLIGHT_END, HIGHLIGHT_START, SearchHit};105
pub use store::{ConversationHit, HIGHLIGHT_END, HIGHLIGHT_START, SearchHit};100
pub use stored::{106
pub use stored::{101
AttachmentInfo, FileCard, FileKind, ImageRef, MentionInfo, QuoteInfo, ReactionInfo,107
AttachmentInfo, FileCard, FileKind, ImageRef, MentionInfo, PROFILE_LINK_PREFIX, QuoteInfo,102
adaptive_cards, attachments, can_delete, can_edit, card_texts, copy_text, files, images,108
ReactionInfo, adaptive_cards, attachments, can_delete, can_edit, card_texts, copy_text, files,103
mentions, message_spans, quotes, reactions, user_mention_inputs,109
images, linked_message_spans, mentions, message_spans, quotes, reactions, user_mention_inputs,104
};110
};111
pub use time_zone::local_time;@@ -1,7 +1,12 @@
1
use chatsvc::{PresenceUpdate, TrouterEndpoint};
1
use chatsvc::{
2
ForcedAvailability, PresenceStatus, PresenceUpdate, StatusNote, TrouterEndpoint,
3
WorkLocationKind,
4
};
2
5
use graph::MAX_PRESENCE_IDS;
3
6
4
use crate::engine::SyncEngine;
7
use chrono::{DateTime, Utc};
8
9
use crate::engine::{META_USER_ID, SyncEngine};
5
10
use crate::error::Result;
6
11
use crate::events::CoreEvent;
7
12
use crate::receipts::locked;
@@ -83,6 +88,52 @@ impl<R: Remote> SyncEngine<R> {
83
88
}
84
89
}
85
90
91
pub fn concerns_me(&self, updates: &[PresenceUpdate]) -> bool {
92
let my_user_id = self.store.meta(META_USER_ID).ok().flatten();
93
updates
94
.iter()
95
.any(|update| my_user_id.as_deref() == Some(update.user_id.as_str()))
96
}
97
98
pub async fn refresh_own_status(&self) -> Result<PresenceStatus> {
99
let _ = self.ensure_display_name().await;
100
let my_user_id = self.my_user_id().await?;
101
let status = self.remote.own_status(&my_user_id).await?;
102
let changed = self.record_presences(std::iter::once((
103
&my_user_id,
104
status.availability.as_str(),
105
status.activity.as_deref(),
106
)));
107
let _ = self
108
.events
109
.send(CoreEvent::PresenceStatusChanged(status.clone()));
110
if changed {
111
let _ = self.events.send(CoreEvent::PresenceChanged);
112
}
113
Ok(status)
114
}
115
116
pub async fn set_own_availability(&self, forced: Option<ForcedAvailability>) -> Result<()> {
117
self.remote.set_availability(forced.as_ref()).await?;
118
let _ = self.refresh_own_status().await;
119
Ok(())
120
}
121
122
pub async fn set_own_status_note(&self, note: Option<StatusNote>) -> Result<()> {
123
self.remote.set_status_note(note.as_ref()).await?;
124
let _ = self.refresh_own_status().await;
125
Ok(())
126
}
127
128
pub async fn set_own_work_location(
129
&self,
130
location: Option<(WorkLocationKind, DateTime<Utc>)>,
131
) -> Result<()> {
132
self.remote.set_work_location(location).await?;
133
let _ = self.refresh_own_status().await;
134
Ok(())
135
}
136
86
137
pub async fn watch_presence(&self, user_ids: &[String]) -> Result<()> {
87
138
let _subscribing = self.presence_subscribing.lock().await;
88
139
let added = {
@@ -1,7 +1,12 @@1
use chatsvc::{PresenceUpdate, TrouterEndpoint};1
use chatsvc::{2
ForcedAvailability, PresenceStatus, PresenceUpdate, StatusNote, TrouterEndpoint,3
WorkLocationKind,4
};2
use graph::MAX_PRESENCE_IDS;5
use graph::MAX_PRESENCE_IDS;3
6
4
use crate::engine::SyncEngine;7
use chrono::{DateTime, Utc};8
9
use crate::engine::{META_USER_ID, SyncEngine};5
use crate::error::Result;10
use crate::error::Result;6
use crate::events::CoreEvent;11
use crate::events::CoreEvent;7
use crate::receipts::locked;12
use crate::receipts::locked;@@ -83,6 +88,52 @@ impl<R: Remote> SyncEngine<R> {83
}88
}84
}89
}85
90
91
pub fn concerns_me(&self, updates: &[PresenceUpdate]) -> bool {92
let my_user_id = self.store.meta(META_USER_ID).ok().flatten();93
updates94
.iter()95
.any(|update| my_user_id.as_deref() == Some(update.user_id.as_str()))96
}97
98
pub async fn refresh_own_status(&self) -> Result<PresenceStatus> {99
let _ = self.ensure_display_name().await;100
let my_user_id = self.my_user_id().await?;101
let status = self.remote.own_status(&my_user_id).await?;102
let changed = self.record_presences(std::iter::once((103
&my_user_id,104
status.availability.as_str(),105
status.activity.as_deref(),106
)));107
let _ = self108
.events109
.send(CoreEvent::PresenceStatusChanged(status.clone()));110
if changed {111
let _ = self.events.send(CoreEvent::PresenceChanged);112
}113
Ok(status)114
}115
116
pub async fn set_own_availability(&self, forced: Option<ForcedAvailability>) -> Result<()> {117
self.remote.set_availability(forced.as_ref()).await?;118
let _ = self.refresh_own_status().await;119
Ok(())120
}121
122
pub async fn set_own_status_note(&self, note: Option<StatusNote>) -> Result<()> {123
self.remote.set_status_note(note.as_ref()).await?;124
let _ = self.refresh_own_status().await;125
Ok(())126
}127
128
pub async fn set_own_work_location(129
&self,130
location: Option<(WorkLocationKind, DateTime<Utc>)>,131
) -> Result<()> {132
self.remote.set_work_location(location).await?;133
let _ = self.refresh_own_status().await;134
Ok(())135
}136
86
pub async fn watch_presence(&self, user_ids: &[String]) -> Result<()> {137
pub async fn watch_presence(&self, user_ids: &[String]) -> Result<()> {87
let _subscribing = self.presence_subscribing.lock().await;138
let _subscribing = self.presence_subscribing.lock().await;88
let added = {139
let added = {@@ -0,0 +1,150 @@
1
use chatsvc::{PresenceService, PresenceStatus, WorkLocation};
2
use graph::{Graph, ProfileDetails};
3
4
pub use graph::OrgPerson;
5
6
use crate::engine::SyncEngine;
7
use crate::error::Result;
8
use crate::presence::Availability;
9
use crate::remote::Remote;
10
11
#[derive(Debug, Clone, PartialEq, Eq)]
12
pub struct PersonProfile {
13
pub user_id: String,
14
pub display_name: Option<String>,
15
pub job_title: Option<String>,
16
pub department: Option<String>,
17
pub company: Option<String>,
18
pub office_location: Option<String>,
19
pub email: Option<String>,
20
pub work_phones: Vec<String>,
21
pub mobile_phone: Option<String>,
22
pub manager: Option<OrgPerson>,
23
pub direct_reports: Vec<OrgPerson>,
24
pub time_zone: Option<String>,
25
pub availability: Option<Availability>,
26
pub status_message: Option<String>,
27
pub out_of_office: Option<String>,
28
pub work_location: Option<WorkLocation>,
29
}
30
31
impl PersonProfile {
32
pub fn from_remote(
33
details: ProfileDetails,
34
time_zone: Option<String>,
35
presence: Option<PresenceStatus>,
36
) -> Self {
37
let ProfileDetails {
38
user,
39
manager,
40
direct_reports,
41
} = details;
42
let email = user.mail.or(user.user_principal_name);
43
PersonProfile {
44
user_id: user.id,
45
display_name: user.display_name,
46
job_title: user.job_title,
47
department: user.department,
48
company: user.company_name,
49
office_location: user.office_location,
50
email,
51
work_phones: user.business_phones,
52
mobile_phone: user.mobile_phone,
53
manager,
54
direct_reports,
55
time_zone,
56
availability: presence
57
.as_ref()
58
.map(|detail| Availability::from_service(&detail.availability)),
59
status_message: presence
60
.as_ref()
61
.and_then(|detail| detail.note.as_ref().map(|note| note.text.clone())),
62
work_location: presence.as_ref().and_then(|detail| detail.work_location),
63
out_of_office: presence.and_then(|detail| {
64
detail
65
.out_of_office
66
.then(|| detail.out_of_office_note.unwrap_or_default())
67
}),
68
}
69
}
70
}
71
72
pub(crate) async fn load_profile(graph: &Graph, user_id: &str) -> Result<PersonProfile> {
73
let details = graph.user_profile(user_id).await?;
74
let mail = details
75
.user
76
.mail
77
.clone()
78
.or_else(|| details.user.user_principal_name.clone());
79
let zone = async {
80
match mail {
81
Some(mail) => graph.time_zone_name(&mail).await.ok().flatten(),
82
None => None,
83
}
84
};
85
let presence_service = PresenceService::new(graph.session());
86
let (time_zone, presence) = tokio::join!(zone, presence_service.status(user_id));
87
Ok(PersonProfile::from_remote(
88
details,
89
time_zone,
90
presence.ok(),
91
))
92
}
93
94
impl<R: Remote> SyncEngine<R> {
95
pub async fn person_profile(&self, user_id: &str) -> Result<PersonProfile> {
96
self.remote.person_profile(user_id).await
97
}
98
}
99
100
#[cfg(test)]
101
mod tests {
102
use chatsvc::StatusNote;
103
use graph::UserProfile;
104
105
use super::*;
106
107
fn details(user: UserProfile) -> ProfileDetails {
108
ProfileDetails {
109
user,
110
manager: None,
111
direct_reports: Vec::new(),
112
}
113
}
114
115
#[test]
116
fn the_user_principal_name_stands_in_for_a_missing_mail() {
117
let user = UserProfile {
118
id: "u".into(),
119
user_principal_name: Some("ada@example.com".into()),
120
..Default::default()
121
};
122
let profile = PersonProfile::from_remote(details(user), None, None);
123
assert_eq!(profile.email.as_deref(), Some("ada@example.com"));
124
assert_eq!(profile.availability, None);
125
}
126
127
#[test]
128
fn presence_fills_availability_note_and_out_of_office() {
129
let presence = PresenceStatus {
130
availability: "DoNotDisturb".into(),
131
note: Some(StatusNote {
132
text: "Focus".into(),
133
show_when_messaged: false,
134
expires_at: None,
135
}),
136
out_of_office: true,
137
out_of_office_note: Some("Away until Monday".into()),
138
..PresenceStatus::default()
139
};
140
let profile = PersonProfile::from_remote(
141
details(UserProfile::default()),
142
Some("UTC".into()),
143
Some(presence),
144
);
145
assert_eq!(profile.availability, Some(Availability::DoNotDisturb));
146
assert_eq!(profile.status_message.as_deref(), Some("Focus"));
147
assert_eq!(profile.out_of_office.as_deref(), Some("Away until Monday"));
148
assert_eq!(profile.time_zone.as_deref(), Some("UTC"));
149
}
150
}
@@ -0,0 +1,150 @@1
use chatsvc::{PresenceService, PresenceStatus, WorkLocation};2
use graph::{Graph, ProfileDetails};3
4
pub use graph::OrgPerson;5
6
use crate::engine::SyncEngine;7
use crate::error::Result;8
use crate::presence::Availability;9
use crate::remote::Remote;10
11
#[derive(Debug, Clone, PartialEq, Eq)]12
pub struct PersonProfile {13
pub user_id: String,14
pub display_name: Option<String>,15
pub job_title: Option<String>,16
pub department: Option<String>,17
pub company: Option<String>,18
pub office_location: Option<String>,19
pub email: Option<String>,20
pub work_phones: Vec<String>,21
pub mobile_phone: Option<String>,22
pub manager: Option<OrgPerson>,23
pub direct_reports: Vec<OrgPerson>,24
pub time_zone: Option<String>,25
pub availability: Option<Availability>,26
pub status_message: Option<String>,27
pub out_of_office: Option<String>,28
pub work_location: Option<WorkLocation>,29
}30
31
impl PersonProfile {32
pub fn from_remote(33
details: ProfileDetails,34
time_zone: Option<String>,35
presence: Option<PresenceStatus>,36
) -> Self {37
let ProfileDetails {38
user,39
manager,40
direct_reports,41
} = details;42
let email = user.mail.or(user.user_principal_name);43
PersonProfile {44
user_id: user.id,45
display_name: user.display_name,46
job_title: user.job_title,47
department: user.department,48
company: user.company_name,49
office_location: user.office_location,50
email,51
work_phones: user.business_phones,52
mobile_phone: user.mobile_phone,53
manager,54
direct_reports,55
time_zone,56
availability: presence57
.as_ref()58
.map(|detail| Availability::from_service(&detail.availability)),59
status_message: presence60
.as_ref()61
.and_then(|detail| detail.note.as_ref().map(|note| note.text.clone())),62
work_location: presence.as_ref().and_then(|detail| detail.work_location),63
out_of_office: presence.and_then(|detail| {64
detail65
.out_of_office66
.then(|| detail.out_of_office_note.unwrap_or_default())67
}),68
}69
}70
}71
72
pub(crate) async fn load_profile(graph: &Graph, user_id: &str) -> Result<PersonProfile> {73
let details = graph.user_profile(user_id).await?;74
let mail = details75
.user76
.mail77
.clone()78
.or_else(|| details.user.user_principal_name.clone());79
let zone = async {80
match mail {81
Some(mail) => graph.time_zone_name(&mail).await.ok().flatten(),82
None => None,83
}84
};85
let presence_service = PresenceService::new(graph.session());86
let (time_zone, presence) = tokio::join!(zone, presence_service.status(user_id));87
Ok(PersonProfile::from_remote(88
details,89
time_zone,90
presence.ok(),91
))92
}93
94
impl<R: Remote> SyncEngine<R> {95
pub async fn person_profile(&self, user_id: &str) -> Result<PersonProfile> {96
self.remote.person_profile(user_id).await97
}98
}99
100
#[cfg(test)]101
mod tests {102
use chatsvc::StatusNote;103
use graph::UserProfile;104
105
use super::*;106
107
fn details(user: UserProfile) -> ProfileDetails {108
ProfileDetails {109
user,110
manager: None,111
direct_reports: Vec::new(),112
}113
}114
115
#[test]116
fn the_user_principal_name_stands_in_for_a_missing_mail() {117
let user = UserProfile {118
id: "u".into(),119
user_principal_name: Some("ada@example.com".into()),120
..Default::default()121
};122
let profile = PersonProfile::from_remote(details(user), None, None);123
assert_eq!(profile.email.as_deref(), Some("ada@example.com"));124
assert_eq!(profile.availability, None);125
}126
127
#[test]128
fn presence_fills_availability_note_and_out_of_office() {129
let presence = PresenceStatus {130
availability: "DoNotDisturb".into(),131
note: Some(StatusNote {132
text: "Focus".into(),133
show_when_messaged: false,134
expires_at: None,135
}),136
out_of_office: true,137
out_of_office_note: Some("Away until Monday".into()),138
..PresenceStatus::default()139
};140
let profile = PersonProfile::from_remote(141
details(UserProfile::default()),142
Some("UTC".into()),143
Some(presence),144
);145
assert_eq!(profile.availability, Some(Availability::DoNotDisturb));146
assert_eq!(profile.status_message.as_deref(), Some("Focus"));147
assert_eq!(profile.out_of_office.as_deref(), Some("Away until Monday"));148
assert_eq!(profile.time_zone.as_deref(), Some("UTC"));149
}150
}@@ -1,7 +1,8 @@
1
1
use chatsvc::{
2
CardActions, ChatApp, ConversationRef, Conversations, ForwardResult, Gif, Gifs, InvokeRequest,
3
InvokeResponse, LinkInfo, MemberHorizon, MessageLinks, Messages, PinnedMessage, Pins, Receipts,
4
SavedMessage, ScheduledDraft, ScheduledDrafts,
2
CardActions, ChatApp, ConversationRef, Conversations, ForcedAvailability, ForwardResult, Gif,
3
Gifs, InvokeRequest, InvokeResponse, LinkInfo, MemberHorizon, MessageLinks, Messages,
4
PinnedMessage, Pins, PresenceService, PresenceStatus, Receipts, SavedMessage, ScheduledDraft,
5
ScheduledDrafts, StatusNote, WorkLocationKind,
5
6
};
6
7
use chrono::{DateTime, Utc};
7
8
use graph::{
@@ -10,6 +11,7 @@ use graph::{
10
11
};
11
12
12
13
use crate::error::{Error, Result};
14
use crate::profile::PersonProfile;
13
15
14
16
pub const CHATSVC_CHAT_WRITES: bool = false;
15
17
@@ -201,6 +203,10 @@ pub trait Remote {
201
203
Err(Error::Unsupported("presence"))
202
204
}
203
205
206
async fn person_profile(&self, _user_id: &str) -> Result<PersonProfile> {
207
Err(Error::Unsupported("profile cards"))
208
}
209
204
210
async fn subscribe_presence(
205
211
&self,
206
212
_endpoint_id: &str,
@@ -211,6 +217,25 @@ pub trait Remote {
211
217
Err(Error::Unsupported("presence subscriptions"))
212
218
}
213
219
220
async fn own_status(&self, _user_id: &str) -> Result<PresenceStatus> {
221
Err(Error::Unsupported("own status"))
222
}
223
224
async fn set_availability(&self, _forced: Option<&ForcedAvailability>) -> Result<()> {
225
Err(Error::Unsupported("setting availability"))
226
}
227
228
async fn set_status_note(&self, _note: Option<&StatusNote>) -> Result<()> {
229
Err(Error::Unsupported("setting the status message"))
230
}
231
232
async fn set_work_location(
233
&self,
234
_location: Option<(WorkLocationKind, DateTime<Utc>)>,
235
) -> Result<()> {
236
Err(Error::Unsupported("setting the work location"))
237
}
238
214
239
async fn consumption_horizons(&self, _conversation_id: &str) -> Result<Vec<MemberHorizon>> {
215
240
Err(Error::Unsupported("read receipts"))
216
241
}
@@ -650,6 +675,10 @@ impl Remote for Graph {
650
675
Ok(Graph::presences(self, user_ids).await?)
651
676
}
652
677
678
async fn person_profile(&self, user_id: &str) -> Result<PersonProfile> {
679
crate::profile::load_profile(self, user_id).await
680
}
681
653
682
async fn subscribe_presence(
654
683
&self,
655
684
endpoint_id: &str,
@@ -660,6 +689,29 @@ impl Remote for Graph {
660
689
Ok(Graph::subscribe_presence(self, endpoint_id, trouter_uri, user_ids, purge).await?)
661
690
}
662
691
692
async fn own_status(&self, user_id: &str) -> Result<PresenceStatus> {
693
Ok(PresenceService::new(self.session()).status(user_id).await?)
694
}
695
696
async fn set_availability(&self, forced: Option<&ForcedAvailability>) -> Result<()> {
697
Ok(PresenceService::new(self.session())
698
.set_availability(forced)
699
.await?)
700
}
701
702
async fn set_status_note(&self, note: Option<&StatusNote>) -> Result<()> {
703
Ok(PresenceService::new(self.session()).set_note(note).await?)
704
}
705
706
async fn set_work_location(
707
&self,
708
location: Option<(WorkLocationKind, DateTime<Utc>)>,
709
) -> Result<()> {
710
Ok(PresenceService::new(self.session())
711
.set_work_location(location)
712
.await?)
713
}
714
663
715
async fn consumption_horizons(&self, conversation_id: &str) -> Result<Vec<MemberHorizon>> {
664
716
Ok(Receipts::new(self.session())
665
717
.consumption_horizons(conversation_id)
@@ -1,7 +1,8 @@1
use chatsvc::{1
use chatsvc::{2
CardActions, ChatApp, ConversationRef, Conversations, ForwardResult, Gif, Gifs, InvokeRequest,2
CardActions, ChatApp, ConversationRef, Conversations, ForcedAvailability, ForwardResult, Gif,3
InvokeResponse, LinkInfo, MemberHorizon, MessageLinks, Messages, PinnedMessage, Pins, Receipts,3
Gifs, InvokeRequest, InvokeResponse, LinkInfo, MemberHorizon, MessageLinks, Messages,4
SavedMessage, ScheduledDraft, ScheduledDrafts,4
PinnedMessage, Pins, PresenceService, PresenceStatus, Receipts, SavedMessage, ScheduledDraft,5
ScheduledDrafts, StatusNote, WorkLocationKind,5
};6
};6
use chrono::{DateTime, Utc};7
use chrono::{DateTime, Utc};7
use graph::{8
use graph::{@@ -10,6 +11,7 @@ use graph::{10
};11
};11
12
12
use crate::error::{Error, Result};13
use crate::error::{Error, Result};14
use crate::profile::PersonProfile;13
15
14
pub const CHATSVC_CHAT_WRITES: bool = false;16
pub const CHATSVC_CHAT_WRITES: bool = false;15
17
@@ -201,6 +203,10 @@ pub trait Remote {201
Err(Error::Unsupported("presence"))203
Err(Error::Unsupported("presence"))202
}204
}203
205
206
async fn person_profile(&self, _user_id: &str) -> Result<PersonProfile> {207
Err(Error::Unsupported("profile cards"))208
}209
204
async fn subscribe_presence(210
async fn subscribe_presence(205
&self,211
&self,206
_endpoint_id: &str,212
_endpoint_id: &str,@@ -211,6 +217,25 @@ pub trait Remote {211
Err(Error::Unsupported("presence subscriptions"))217
Err(Error::Unsupported("presence subscriptions"))212
}218
}213
219
220
async fn own_status(&self, _user_id: &str) -> Result<PresenceStatus> {221
Err(Error::Unsupported("own status"))222
}223
224
async fn set_availability(&self, _forced: Option<&ForcedAvailability>) -> Result<()> {225
Err(Error::Unsupported("setting availability"))226
}227
228
async fn set_status_note(&self, _note: Option<&StatusNote>) -> Result<()> {229
Err(Error::Unsupported("setting the status message"))230
}231
232
async fn set_work_location(233
&self,234
_location: Option<(WorkLocationKind, DateTime<Utc>)>,235
) -> Result<()> {236
Err(Error::Unsupported("setting the work location"))237
}238
214
async fn consumption_horizons(&self, _conversation_id: &str) -> Result<Vec<MemberHorizon>> {239
async fn consumption_horizons(&self, _conversation_id: &str) -> Result<Vec<MemberHorizon>> {215
Err(Error::Unsupported("read receipts"))240
Err(Error::Unsupported("read receipts"))216
}241
}@@ -650,6 +675,10 @@ impl Remote for Graph {650
Ok(Graph::presences(self, user_ids).await?)675
Ok(Graph::presences(self, user_ids).await?)651
}676
}652
677
678
async fn person_profile(&self, user_id: &str) -> Result<PersonProfile> {679
crate::profile::load_profile(self, user_id).await680
}681
653
async fn subscribe_presence(682
async fn subscribe_presence(654
&self,683
&self,655
endpoint_id: &str,684
endpoint_id: &str,@@ -660,6 +689,29 @@ impl Remote for Graph {660
Ok(Graph::subscribe_presence(self, endpoint_id, trouter_uri, user_ids, purge).await?)689
Ok(Graph::subscribe_presence(self, endpoint_id, trouter_uri, user_ids, purge).await?)661
}690
}662
691
692
async fn own_status(&self, user_id: &str) -> Result<PresenceStatus> {693
Ok(PresenceService::new(self.session()).status(user_id).await?)694
}695
696
async fn set_availability(&self, forced: Option<&ForcedAvailability>) -> Result<()> {697
Ok(PresenceService::new(self.session())698
.set_availability(forced)699
.await?)700
}701
702
async fn set_status_note(&self, note: Option<&StatusNote>) -> Result<()> {703
Ok(PresenceService::new(self.session()).set_note(note).await?)704
}705
706
async fn set_work_location(707
&self,708
location: Option<(WorkLocationKind, DateTime<Utc>)>,709
) -> Result<()> {710
Ok(PresenceService::new(self.session())711
.set_work_location(location)712
.await?)713
}714
663
async fn consumption_horizons(&self, conversation_id: &str) -> Result<Vec<MemberHorizon>> {715
async fn consumption_horizons(&self, conversation_id: &str) -> Result<Vec<MemberHorizon>> {664
Ok(Receipts::new(self.session())716
Ok(Receipts::new(self.session())665
.consumption_horizons(conversation_id)717
.consumption_horizons(conversation_id)@@ -436,6 +436,53 @@ pub fn message_spans(record: &MessageRecord) -> Vec<Span> {
436
436
spans_with_mentions(record, &mentions(record))
437
437
}
438
438
439
pub const PROFILE_LINK_PREFIX: &str = "teams-profile:";
440
441
/// Like `message_spans`, with the id of each user mention replaced by a profile link.
442
pub fn linked_message_spans(record: &MessageRecord) -> Vec<Span> {
443
let infos = mentions(record);
444
let mut spans = spans_with_mentions(record, &infos);
445
link_user_mentions(&mut spans, &infos);
446
spans
447
}
448
449
fn link_user_mentions(spans: &mut [Span], infos: &[MentionInfo]) {
450
for span in spans {
451
match span {
452
Span::Bold(children)
453
| Span::Italic(children)
454
| Span::Strike(children)
455
| Span::Superscript(children)
456
| Span::Subscript(children)
457
| Span::Sized(_, children)
458
| Span::Underline(children)
459
| Span::Colored { children, .. }
460
| Span::Heading { children, .. }
461
| Span::Quote(children)
462
| Span::BlockQuote(children)
463
| Span::Link { children, .. } => link_user_mentions(children, infos),
464
Span::List { items, .. } => items
465
.iter_mut()
466
.for_each(|item| link_user_mentions(item, infos)),
467
Span::Table { rows, .. } => rows
468
.iter_mut()
469
.flatten()
470
.for_each(|cell| link_user_mentions(cell, infos)),
471
Span::Mention { id, .. } => {
472
let parsed: Option<i64> = id.as_deref().and_then(|id| id.parse().ok());
473
let user_id = infos
474
.iter()
475
.find(|info| parsed.is_some() && info.id == parsed)
476
.and_then(|info| info.user_id.as_deref());
477
if let Some(user_id) = user_id {
478
*id = Some(format!("{PROFILE_LINK_PREFIX}{user_id}"));
479
}
480
}
481
_ => {}
482
}
483
}
484
}
485
439
486
fn spans_with_mentions(record: &MessageRecord, infos: &[MentionInfo]) -> Vec<Span> {
440
487
let mut spans = html_to_spans(&with_inline_quotes(record));
441
488
merge_split_mentions(&mut spans, infos);
@@ -825,6 +872,23 @@ mod tests {
825
872
.collect()
826
873
}
827
874
875
#[test]
876
fn user_mentions_link_to_their_profile_and_groups_do_not() {
877
let json = r#"[
878
{"user_id":"U1","name":"Ada","id":0,"target_id":"U1"},
879
{"user_id":null,"name":"Team","id":1,"target_id":"T1"}
880
]"#;
881
let html = r#"<at id="0">Ada</at> <at id="1">Team</at>"#;
882
let ids: Vec<Option<String>> = linked_message_spans(&with_mentions(html, json))
883
.into_iter()
884
.filter_map(|span| match span {
885
Span::Mention { id, .. } => Some(id),
886
_ => None,
887
})
888
.collect();
889
assert_eq!(ids, vec![Some("teams-profile:U1".to_owned()), Some("1".to_owned())]);
890
}
891
828
892
#[test]
829
893
fn a_tag_mention_split_per_word_merges_into_one() {
830
894
let json = r#"[
@@ -436,6 +436,53 @@ pub fn message_spans(record: &MessageRecord) -> Vec<Span> {436
spans_with_mentions(record, &mentions(record))436
spans_with_mentions(record, &mentions(record))437
}437
}438
438
439
pub const PROFILE_LINK_PREFIX: &str = "teams-profile:";440
441
/// Like `message_spans`, with the id of each user mention replaced by a profile link.442
pub fn linked_message_spans(record: &MessageRecord) -> Vec<Span> {443
let infos = mentions(record);444
let mut spans = spans_with_mentions(record, &infos);445
link_user_mentions(&mut spans, &infos);446
spans447
}448
449
fn link_user_mentions(spans: &mut [Span], infos: &[MentionInfo]) {450
for span in spans {451
match span {452
Span::Bold(children)453
| Span::Italic(children)454
| Span::Strike(children)455
| Span::Superscript(children)456
| Span::Subscript(children)457
| Span::Sized(_, children)458
| Span::Underline(children)459
| Span::Colored { children, .. }460
| Span::Heading { children, .. }461
| Span::Quote(children)462
| Span::BlockQuote(children)463
| Span::Link { children, .. } => link_user_mentions(children, infos),464
Span::List { items, .. } => items465
.iter_mut()466
.for_each(|item| link_user_mentions(item, infos)),467
Span::Table { rows, .. } => rows468
.iter_mut()469
.flatten()470
.for_each(|cell| link_user_mentions(cell, infos)),471
Span::Mention { id, .. } => {472
let parsed: Option<i64> = id.as_deref().and_then(|id| id.parse().ok());473
let user_id = infos474
.iter()475
.find(|info| parsed.is_some() && info.id == parsed)476
.and_then(|info| info.user_id.as_deref());477
if let Some(user_id) = user_id {478
*id = Some(format!("{PROFILE_LINK_PREFIX}{user_id}"));479
}480
}481
_ => {}482
}483
}484
}485
439
fn spans_with_mentions(record: &MessageRecord, infos: &[MentionInfo]) -> Vec<Span> {486
fn spans_with_mentions(record: &MessageRecord, infos: &[MentionInfo]) -> Vec<Span> {440
let mut spans = html_to_spans(&with_inline_quotes(record));487
let mut spans = html_to_spans(&with_inline_quotes(record));441
merge_split_mentions(&mut spans, infos);488
merge_split_mentions(&mut spans, infos);@@ -825,6 +872,23 @@ mod tests {825
.collect()872
.collect()826
}873
}827
874
875
#[test]876
fn user_mentions_link_to_their_profile_and_groups_do_not() {877
let json = r#"[878
{"user_id":"U1","name":"Ada","id":0,"target_id":"U1"},879
{"user_id":null,"name":"Team","id":1,"target_id":"T1"}880
]"#;881
let html = r#"<at id="0">Ada</at> <at id="1">Team</at>"#;882
let ids: Vec<Option<String>> = linked_message_spans(&with_mentions(html, json))883
.into_iter()884
.filter_map(|span| match span {885
Span::Mention { id, .. } => Some(id),886
_ => None,887
})888
.collect();889
assert_eq!(ids, vec![Some("teams-profile:U1".to_owned()), Some("1".to_owned())]);890
}891
828
#[test]892
#[test]829
fn a_tag_mention_split_per_word_merges_into_one() {893
fn a_tag_mention_split_per_word_merges_into_one() {830
let json = r#"[894
let json = r#"[@@ -0,0 +1,261 @@
1
use chrono::{DateTime, Datelike, Duration, FixedOffset, NaiveDate, TimeZone, Utc, Weekday};
2
3
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
4
enum Dst {
5
None,
6
Europe,
7
NorthAmerica,
8
Australia,
9
NewZealand,
10
}
11
12
const ZONES: &[(&str, i32, Dst)] = &[
13
("UTC", 0, Dst::None),
14
("Dateline Standard Time", -720, Dst::None),
15
("UTC-11", -660, Dst::None),
16
("Hawaiian Standard Time", -600, Dst::None),
17
("Alaskan Standard Time", -540, Dst::NorthAmerica),
18
("Pacific Standard Time", -480, Dst::NorthAmerica),
19
("US Mountain Standard Time", -420, Dst::None),
20
("Mountain Standard Time", -420, Dst::NorthAmerica),
21
("Central Standard Time", -360, Dst::NorthAmerica),
22
("Central America Standard Time", -360, Dst::None),
23
("Canada Central Standard Time", -360, Dst::None),
24
("Mexico Standard Time", -360, Dst::None),
25
("Eastern Standard Time", -300, Dst::NorthAmerica),
26
("US Eastern Standard Time", -300, Dst::NorthAmerica),
27
("SA Pacific Standard Time", -300, Dst::None),
28
("Atlantic Standard Time", -240, Dst::NorthAmerica),
29
("Newfoundland Standard Time", -210, Dst::NorthAmerica),
30
("E. South America Standard Time", -180, Dst::None),
31
("Argentina Standard Time", -180, Dst::None),
32
("GMT Standard Time", 0, Dst::Europe),
33
("Greenwich Standard Time", 0, Dst::None),
34
("W. Europe Standard Time", 60, Dst::Europe),
35
("Central Europe Standard Time", 60, Dst::Europe),
36
("Romance Standard Time", 60, Dst::Europe),
37
("Central European Standard Time", 60, Dst::Europe),
38
("W. Central Africa Standard Time", 60, Dst::None),
39
("South Africa Standard Time", 120, Dst::None),
40
("E. Europe Standard Time", 120, Dst::Europe),
41
("GTB Standard Time", 120, Dst::Europe),
42
("FLE Standard Time", 120, Dst::Europe),
43
("Turkey Standard Time", 180, Dst::None),
44
("Arab Standard Time", 180, Dst::None),
45
("Russian Standard Time", 180, Dst::None),
46
("E. Africa Standard Time", 180, Dst::None),
47
("Iran Standard Time", 210, Dst::None),
48
("Arabian Standard Time", 240, Dst::None),
49
("Pakistan Standard Time", 300, Dst::None),
50
("West Asia Standard Time", 300, Dst::None),
51
("India Standard Time", 330, Dst::None),
52
("Sri Lanka Standard Time", 330, Dst::None),
53
("Nepal Standard Time", 345, Dst::None),
54
("Central Asia Standard Time", 360, Dst::None),
55
("Bangladesh Standard Time", 360, Dst::None),
56
("SE Asia Standard Time", 420, Dst::None),
57
("China Standard Time", 480, Dst::None),
58
("Singapore Standard Time", 480, Dst::None),
59
("W. Australia Standard Time", 480, Dst::None),
60
("Taipei Standard Time", 480, Dst::None),
61
("Tokyo Standard Time", 540, Dst::None),
62
("Korea Standard Time", 540, Dst::None),
63
("AUS Central Standard Time", 570, Dst::None),
64
("Cen. Australia Standard Time", 570, Dst::Australia),
65
("E. Australia Standard Time", 600, Dst::None),
66
("AUS Eastern Standard Time", 600, Dst::Australia),
67
("Tasmania Standard Time", 600, Dst::Australia),
68
("New Zealand Standard Time", 720, Dst::NewZealand),
69
];
70
71
/// `None` for a zone outside the table.
72
pub fn local_time(zone_name: &str, now: DateTime<Utc>) -> Option<DateTime<FixedOffset>> {
73
let (_, standard_minutes, dst) = ZONES
74
.iter()
75
.find(|(name, _, _)| name.eq_ignore_ascii_case(zone_name.trim()))?;
76
let saving = if is_daylight_time(*dst, *standard_minutes, now) {
77
60
78
} else {
79
0
80
};
81
let offset = FixedOffset::east_opt((standard_minutes + saving) * 60)?;
82
Some(now.with_timezone(&offset))
83
}
84
85
fn is_daylight_time(rule: Dst, standard_minutes: i32, now: DateTime<Utc>) -> bool {
86
let year = now.year();
87
let utc = |date: NaiveDate, local_standard_minutes: i32| {
88
Utc.from_utc_datetime(
89
&date
90
.and_hms_opt(0, 0, 0)
91
.expect("midnight exists")
92
.checked_add_signed(Duration::minutes(i64::from(
93
local_standard_minutes - standard_minutes,
94
)))
95
.expect("transition is in range"),
96
)
97
};
98
let sunday = |month: u32, nth: Option<u32>| match nth {
99
Some(nth) => nth_sunday(year, month, nth),
100
None => last_sunday(year, month),
101
};
102
match rule {
103
Dst::None => false,
104
Dst::Europe => {
105
utc(sunday(3, None), 60 + standard_minutes) <= now
106
&& now < utc(sunday(10, None), 60 + standard_minutes)
107
}
108
Dst::NorthAmerica => {
109
utc(sunday(3, Some(2)), 120) <= now && now < utc(sunday(11, Some(1)), 60)
110
}
111
Dst::Australia => {
112
utc(sunday(10, Some(1)), 120) <= now || now < utc(sunday(4, Some(1)), 120)
113
}
114
Dst::NewZealand => utc(sunday(9, None), 120) <= now || now < utc(sunday(4, Some(1)), 120),
115
}
116
}
117
118
fn nth_sunday(year: i32, month: u32, nth: u32) -> NaiveDate {
119
let first = NaiveDate::from_ymd_opt(year, month, 1).expect("month is valid");
120
let to_sunday = (7 - first.weekday().num_days_from_sunday()) % 7;
121
first + Duration::days(i64::from(to_sunday + 7 * (nth - 1)))
122
}
123
124
fn last_sunday(year: i32, month: u32) -> NaiveDate {
125
let (next_year, next_month) = if month == 12 {
126
(year + 1, 1)
127
} else {
128
(year, month + 1)
129
};
130
let mut day = NaiveDate::from_ymd_opt(next_year, next_month, 1).expect("month is valid")
131
- Duration::days(1);
132
while day.weekday() != Weekday::Sun {
133
day -= Duration::days(1);
134
}
135
day
136
}
137
138
#[cfg(test)]
139
mod tests {
140
use chrono::TimeZone;
141
142
use super::*;
143
144
fn clock(
145
zone: &str,
146
year: i32,
147
month: u32,
148
day: u32,
149
hour: u32,
150
minute: u32,
151
) -> Option<String> {
152
let now = Utc
153
.with_ymd_and_hms(year, month, day, hour, minute, 0)
154
.unwrap();
155
local_time(zone, now).map(|time| time.format("%H:%M %z").to_string())
156
}
157
158
#[test]
159
fn europe_switches_on_the_last_sunday_at_one_utc() {
160
let zone = "W. Europe Standard Time";
161
assert_eq!(
162
clock(zone, 2026, 1, 15, 12, 0).as_deref(),
163
Some("13:00 +0100")
164
);
165
assert_eq!(
166
clock(zone, 2026, 3, 29, 0, 59).as_deref(),
167
Some("01:59 +0100")
168
);
169
assert_eq!(
170
clock(zone, 2026, 3, 29, 1, 0).as_deref(),
171
Some("03:00 +0200")
172
);
173
assert_eq!(
174
clock(zone, 2026, 10, 9, 12, 0).as_deref(),
175
Some("14:00 +0200")
176
);
177
assert_eq!(
178
clock(zone, 2026, 10, 25, 0, 59).as_deref(),
179
Some("02:59 +0200")
180
);
181
assert_eq!(
182
clock(zone, 2026, 10, 25, 1, 0).as_deref(),
183
Some("02:00 +0100")
184
);
185
}
186
187
#[test]
188
fn gmt_and_eastern_europe_follow_the_same_utc_instant() {
189
assert_eq!(
190
clock("GMT Standard Time", 2026, 7, 1, 12, 0).as_deref(),
191
Some("13:00 +0100")
192
);
193
assert_eq!(
194
clock("GTB Standard Time", 2026, 3, 29, 1, 0).as_deref(),
195
Some("04:00 +0300")
196
);
197
}
198
199
#[test]
200
fn north_america_switches_on_the_second_sunday_of_march() {
201
let zone = "Pacific Standard Time";
202
assert_eq!(
203
clock(zone, 2026, 3, 8, 9, 59).as_deref(),
204
Some("01:59 -0800")
205
);
206
assert_eq!(
207
clock(zone, 2026, 3, 8, 10, 0).as_deref(),
208
Some("03:00 -0700")
209
);
210
assert_eq!(
211
clock(zone, 2026, 11, 1, 8, 59).as_deref(),
212
Some("01:59 -0700")
213
);
214
assert_eq!(
215
clock(zone, 2026, 11, 1, 9, 0).as_deref(),
216
Some("01:00 -0800")
217
);
218
}
219
220
#[test]
221
fn southern_zones_are_daylight_time_over_the_new_year() {
222
assert_eq!(
223
clock("AUS Eastern Standard Time", 2026, 1, 15, 0, 0).as_deref(),
224
Some("11:00 +1100")
225
);
226
assert_eq!(
227
clock("AUS Eastern Standard Time", 2026, 7, 15, 0, 0).as_deref(),
228
Some("10:00 +1000")
229
);
230
assert_eq!(
231
clock("New Zealand Standard Time", 2026, 12, 1, 0, 0).as_deref(),
232
Some("13:00 +1300")
233
);
234
assert_eq!(
235
clock("New Zealand Standard Time", 2026, 6, 1, 0, 0).as_deref(),
236
Some("12:00 +1200")
237
);
238
}
239
240
#[test]
241
fn zones_without_daylight_time_keep_their_offset() {
242
assert_eq!(
243
clock("India Standard Time", 2026, 7, 1, 12, 0).as_deref(),
244
Some("17:30 +0530")
245
);
246
assert_eq!(
247
clock("UTC", 2026, 7, 1, 12, 0).as_deref(),
248
Some("12:00 +0000")
249
);
250
}
251
252
#[test]
253
fn unknown_zones_have_no_clock() {
254
assert_eq!(clock("Custom Zone", 2026, 7, 1, 12, 0), None);
255
}
256
257
#[test]
258
fn zone_names_ignore_case() {
259
assert!(clock("w. europe standard time", 2026, 7, 1, 12, 0).is_some());
260
}
261
}
@@ -0,0 +1,261 @@1
use chrono::{DateTime, Datelike, Duration, FixedOffset, NaiveDate, TimeZone, Utc, Weekday};2
3
#[derive(Debug, Clone, Copy, PartialEq, Eq)]4
enum Dst {5
None,6
Europe,7
NorthAmerica,8
Australia,9
NewZealand,10
}11
12
const ZONES: &[(&str, i32, Dst)] = &[13
("UTC", 0, Dst::None),14
("Dateline Standard Time", -720, Dst::None),15
("UTC-11", -660, Dst::None),16
("Hawaiian Standard Time", -600, Dst::None),17
("Alaskan Standard Time", -540, Dst::NorthAmerica),18
("Pacific Standard Time", -480, Dst::NorthAmerica),19
("US Mountain Standard Time", -420, Dst::None),20
("Mountain Standard Time", -420, Dst::NorthAmerica),21
("Central Standard Time", -360, Dst::NorthAmerica),22
("Central America Standard Time", -360, Dst::None),23
("Canada Central Standard Time", -360, Dst::None),24
("Mexico Standard Time", -360, Dst::None),25
("Eastern Standard Time", -300, Dst::NorthAmerica),26
("US Eastern Standard Time", -300, Dst::NorthAmerica),27
("SA Pacific Standard Time", -300, Dst::None),28
("Atlantic Standard Time", -240, Dst::NorthAmerica),29
("Newfoundland Standard Time", -210, Dst::NorthAmerica),30
("E. South America Standard Time", -180, Dst::None),31
("Argentina Standard Time", -180, Dst::None),32
("GMT Standard Time", 0, Dst::Europe),33
("Greenwich Standard Time", 0, Dst::None),34
("W. Europe Standard Time", 60, Dst::Europe),35
("Central Europe Standard Time", 60, Dst::Europe),36
("Romance Standard Time", 60, Dst::Europe),37
("Central European Standard Time", 60, Dst::Europe),38
("W. Central Africa Standard Time", 60, Dst::None),39
("South Africa Standard Time", 120, Dst::None),40
("E. Europe Standard Time", 120, Dst::Europe),41
("GTB Standard Time", 120, Dst::Europe),42
("FLE Standard Time", 120, Dst::Europe),43
("Turkey Standard Time", 180, Dst::None),44
("Arab Standard Time", 180, Dst::None),45
("Russian Standard Time", 180, Dst::None),46
("E. Africa Standard Time", 180, Dst::None),47
("Iran Standard Time", 210, Dst::None),48
("Arabian Standard Time", 240, Dst::None),49
("Pakistan Standard Time", 300, Dst::None),50
("West Asia Standard Time", 300, Dst::None),51
("India Standard Time", 330, Dst::None),52
("Sri Lanka Standard Time", 330, Dst::None),53
("Nepal Standard Time", 345, Dst::None),54
("Central Asia Standard Time", 360, Dst::None),55
("Bangladesh Standard Time", 360, Dst::None),56
("SE Asia Standard Time", 420, Dst::None),57
("China Standard Time", 480, Dst::None),58
("Singapore Standard Time", 480, Dst::None),59
("W. Australia Standard Time", 480, Dst::None),60
("Taipei Standard Time", 480, Dst::None),61
("Tokyo Standard Time", 540, Dst::None),62
("Korea Standard Time", 540, Dst::None),63
("AUS Central Standard Time", 570, Dst::None),64
("Cen. Australia Standard Time", 570, Dst::Australia),65
("E. Australia Standard Time", 600, Dst::None),66
("AUS Eastern Standard Time", 600, Dst::Australia),67
("Tasmania Standard Time", 600, Dst::Australia),68
("New Zealand Standard Time", 720, Dst::NewZealand),69
];70
71
/// `None` for a zone outside the table.72
pub fn local_time(zone_name: &str, now: DateTime<Utc>) -> Option<DateTime<FixedOffset>> {73
let (_, standard_minutes, dst) = ZONES74
.iter()75
.find(|(name, _, _)| name.eq_ignore_ascii_case(zone_name.trim()))?;76
let saving = if is_daylight_time(*dst, *standard_minutes, now) {77
6078
} else {79
080
};81
let offset = FixedOffset::east_opt((standard_minutes + saving) * 60)?;82
Some(now.with_timezone(&offset))83
}84
85
fn is_daylight_time(rule: Dst, standard_minutes: i32, now: DateTime<Utc>) -> bool {86
let year = now.year();87
let utc = |date: NaiveDate, local_standard_minutes: i32| {88
Utc.from_utc_datetime(89
&date90
.and_hms_opt(0, 0, 0)91
.expect("midnight exists")92
.checked_add_signed(Duration::minutes(i64::from(93
local_standard_minutes - standard_minutes,94
)))95
.expect("transition is in range"),96
)97
};98
let sunday = |month: u32, nth: Option<u32>| match nth {99
Some(nth) => nth_sunday(year, month, nth),100
None => last_sunday(year, month),101
};102
match rule {103
Dst::None => false,104
Dst::Europe => {105
utc(sunday(3, None), 60 + standard_minutes) <= now106
&& now < utc(sunday(10, None), 60 + standard_minutes)107
}108
Dst::NorthAmerica => {109
utc(sunday(3, Some(2)), 120) <= now && now < utc(sunday(11, Some(1)), 60)110
}111
Dst::Australia => {112
utc(sunday(10, Some(1)), 120) <= now || now < utc(sunday(4, Some(1)), 120)113
}114
Dst::NewZealand => utc(sunday(9, None), 120) <= now || now < utc(sunday(4, Some(1)), 120),115
}116
}117
118
fn nth_sunday(year: i32, month: u32, nth: u32) -> NaiveDate {119
let first = NaiveDate::from_ymd_opt(year, month, 1).expect("month is valid");120
let to_sunday = (7 - first.weekday().num_days_from_sunday()) % 7;121
first + Duration::days(i64::from(to_sunday + 7 * (nth - 1)))122
}123
124
fn last_sunday(year: i32, month: u32) -> NaiveDate {125
let (next_year, next_month) = if month == 12 {126
(year + 1, 1)127
} else {128
(year, month + 1)129
};130
let mut day = NaiveDate::from_ymd_opt(next_year, next_month, 1).expect("month is valid")131
- Duration::days(1);132
while day.weekday() != Weekday::Sun {133
day -= Duration::days(1);134
}135
day136
}137
138
#[cfg(test)]139
mod tests {140
use chrono::TimeZone;141
142
use super::*;143
144
fn clock(145
zone: &str,146
year: i32,147
month: u32,148
day: u32,149
hour: u32,150
minute: u32,151
) -> Option<String> {152
let now = Utc153
.with_ymd_and_hms(year, month, day, hour, minute, 0)154
.unwrap();155
local_time(zone, now).map(|time| time.format("%H:%M %z").to_string())156
}157
158
#[test]159
fn europe_switches_on_the_last_sunday_at_one_utc() {160
let zone = "W. Europe Standard Time";161
assert_eq!(162
clock(zone, 2026, 1, 15, 12, 0).as_deref(),163
Some("13:00 +0100")164
);165
assert_eq!(166
clock(zone, 2026, 3, 29, 0, 59).as_deref(),167
Some("01:59 +0100")168
);169
assert_eq!(170
clock(zone, 2026, 3, 29, 1, 0).as_deref(),171
Some("03:00 +0200")172
);173
assert_eq!(174
clock(zone, 2026, 10, 9, 12, 0).as_deref(),175
Some("14:00 +0200")176
);177
assert_eq!(178
clock(zone, 2026, 10, 25, 0, 59).as_deref(),179
Some("02:59 +0200")180
);181
assert_eq!(182
clock(zone, 2026, 10, 25, 1, 0).as_deref(),183
Some("02:00 +0100")184
);185
}186
187
#[test]188
fn gmt_and_eastern_europe_follow_the_same_utc_instant() {189
assert_eq!(190
clock("GMT Standard Time", 2026, 7, 1, 12, 0).as_deref(),191
Some("13:00 +0100")192
);193
assert_eq!(194
clock("GTB Standard Time", 2026, 3, 29, 1, 0).as_deref(),195
Some("04:00 +0300")196
);197
}198
199
#[test]200
fn north_america_switches_on_the_second_sunday_of_march() {201
let zone = "Pacific Standard Time";202
assert_eq!(203
clock(zone, 2026, 3, 8, 9, 59).as_deref(),204
Some("01:59 -0800")205
);206
assert_eq!(207
clock(zone, 2026, 3, 8, 10, 0).as_deref(),208
Some("03:00 -0700")209
);210
assert_eq!(211
clock(zone, 2026, 11, 1, 8, 59).as_deref(),212
Some("01:59 -0700")213
);214
assert_eq!(215
clock(zone, 2026, 11, 1, 9, 0).as_deref(),216
Some("01:00 -0800")217
);218
}219
220
#[test]221
fn southern_zones_are_daylight_time_over_the_new_year() {222
assert_eq!(223
clock("AUS Eastern Standard Time", 2026, 1, 15, 0, 0).as_deref(),224
Some("11:00 +1100")225
);226
assert_eq!(227
clock("AUS Eastern Standard Time", 2026, 7, 15, 0, 0).as_deref(),228
Some("10:00 +1000")229
);230
assert_eq!(231
clock("New Zealand Standard Time", 2026, 12, 1, 0, 0).as_deref(),232
Some("13:00 +1300")233
);234
assert_eq!(235
clock("New Zealand Standard Time", 2026, 6, 1, 0, 0).as_deref(),236
Some("12:00 +1200")237
);238
}239
240
#[test]241
fn zones_without_daylight_time_keep_their_offset() {242
assert_eq!(243
clock("India Standard Time", 2026, 7, 1, 12, 0).as_deref(),244
Some("17:30 +0530")245
);246
assert_eq!(247
clock("UTC", 2026, 7, 1, 12, 0).as_deref(),248
Some("12:00 +0000")249
);250
}251
252
#[test]253
fn unknown_zones_have_no_clock() {254
assert_eq!(clock("Custom Zone", 2026, 7, 1, 12, 0), None);255
}256
257
#[test]258
fn zone_names_ignore_case() {259
assert!(clock("w. europe standard time", 2026, 7, 1, 12, 0).is_some());260
}261
}@@ -103,6 +103,9 @@ struct Fake {
103
103
links_put: Mutex<Vec<(String, String)>>,
104
104
link_info_calls: Mutex<usize>,
105
105
scheduled: Mutex<Vec<ScheduledCall>>,
106
own_status_answer: Mutex<chatsvc::PresenceStatus>,
107
availability_puts: Mutex<Vec<Option<chatsvc::ForcedAvailability>>>,
108
note_puts: Mutex<Vec<Option<chatsvc::StatusNote>>>,
106
109
}
107
110
108
111
impl Fake {
@@ -770,6 +773,20 @@ impl Remote for Handle {
770
773
Ok(())
771
774
}
772
775
776
async fn own_status(&self, _user_id: &str) -> Result<chatsvc::PresenceStatus> {
777
Ok(self.own_status_answer.lock().unwrap().clone())
778
}
779
780
async fn set_availability(&self, forced: Option<&chatsvc::ForcedAvailability>) -> Result<()> {
781
self.availability_puts.lock().unwrap().push(forced.copied());
782
Ok(())
783
}
784
785
async fn set_status_note(&self, note: Option<&chatsvc::StatusNote>) -> Result<()> {
786
self.note_puts.lock().unwrap().push(note.cloned());
787
Ok(())
788
}
789
773
790
async fn search_people(&self, query: &str) -> Result<Vec<User>> {
774
791
self.record(format!("search {query}"));
775
792
let configured = self.directory_users.lock().unwrap().clone();
@@ -2019,6 +2036,40 @@ async fn presence_maps_availability_and_announces_changes_once() {
2019
2036
assert!(events.try_recv().is_err());
2020
2037
}
2021
2038
2039
#[tokio::test]
2040
async fn setting_own_availability_writes_then_reads_back_and_announces() {
2041
let fake = Arc::new(Fake::default());
2042
*fake.own_status_answer.lock().unwrap() = chatsvc::PresenceStatus {
2043
availability: "Busy".into(),
2044
..chatsvc::PresenceStatus::default()
2045
};
2046
let engine = engine_with(&fake, SyncConfig::default());
2047
let mut events = engine.subscribe();
2048
let forced = chatsvc::ForcedAvailability {
2049
kind: chatsvc::ForcedKind::Busy,
2050
expires_at: None,
2051
};
2052
engine.set_own_availability(Some(forced)).await.unwrap();
2053
assert_eq!(*fake.availability_puts.lock().unwrap(), vec![Some(forced)]);
2054
assert_eq!(
2055
engine.presence(ME).unwrap().availability,
2056
Availability::Busy
2057
);
2058
assert!(matches!(
2059
events.try_recv().unwrap(),
2060
CoreEvent::PresenceStatusChanged(status) if status.availability == "Busy"
2061
));
2062
assert_eq!(events.try_recv().unwrap(), CoreEvent::PresenceChanged);
2063
}
2064
2065
#[tokio::test]
2066
async fn setting_the_own_note_forwards_the_note() {
2067
let fake = Arc::new(Fake::default());
2068
let engine = engine_with(&fake, SyncConfig::default());
2069
engine.set_own_status_note(None).await.unwrap();
2070
assert_eq!(*fake.note_puts.lock().unwrap(), vec![None]);
2071
}
2072
2022
2073
fn trouter_endpoint(endpoint_id: &str) -> chatsvc::TrouterEndpoint {
2023
2074
chatsvc::TrouterEndpoint {
2024
2075
endpoint_id: endpoint_id.to_owned(),
@@ -103,6 +103,9 @@ struct Fake {103
links_put: Mutex<Vec<(String, String)>>,103
links_put: Mutex<Vec<(String, String)>>,104
link_info_calls: Mutex<usize>,104
link_info_calls: Mutex<usize>,105
scheduled: Mutex<Vec<ScheduledCall>>,105
scheduled: Mutex<Vec<ScheduledCall>>,106
own_status_answer: Mutex<chatsvc::PresenceStatus>,107
availability_puts: Mutex<Vec<Option<chatsvc::ForcedAvailability>>>,108
note_puts: Mutex<Vec<Option<chatsvc::StatusNote>>>,106
}109
}107
110
108
impl Fake {111
impl Fake {@@ -770,6 +773,20 @@ impl Remote for Handle {770
Ok(())773
Ok(())771
}774
}772
775
776
async fn own_status(&self, _user_id: &str) -> Result<chatsvc::PresenceStatus> {777
Ok(self.own_status_answer.lock().unwrap().clone())778
}779
780
async fn set_availability(&self, forced: Option<&chatsvc::ForcedAvailability>) -> Result<()> {781
self.availability_puts.lock().unwrap().push(forced.copied());782
Ok(())783
}784
785
async fn set_status_note(&self, note: Option<&chatsvc::StatusNote>) -> Result<()> {786
self.note_puts.lock().unwrap().push(note.cloned());787
Ok(())788
}789
773
async fn search_people(&self, query: &str) -> Result<Vec<User>> {790
async fn search_people(&self, query: &str) -> Result<Vec<User>> {774
self.record(format!("search {query}"));791
self.record(format!("search {query}"));775
let configured = self.directory_users.lock().unwrap().clone();792
let configured = self.directory_users.lock().unwrap().clone();@@ -2019,6 +2036,40 @@ async fn presence_maps_availability_and_announces_changes_once() {2019
assert!(events.try_recv().is_err());2036
assert!(events.try_recv().is_err());2020
}2037
}2021
2038
2039
#[tokio::test]2040
async fn setting_own_availability_writes_then_reads_back_and_announces() {2041
let fake = Arc::new(Fake::default());2042
*fake.own_status_answer.lock().unwrap() = chatsvc::PresenceStatus {2043
availability: "Busy".into(),2044
..chatsvc::PresenceStatus::default()2045
};2046
let engine = engine_with(&fake, SyncConfig::default());2047
let mut events = engine.subscribe();2048
let forced = chatsvc::ForcedAvailability {2049
kind: chatsvc::ForcedKind::Busy,2050
expires_at: None,2051
};2052
engine.set_own_availability(Some(forced)).await.unwrap();2053
assert_eq!(*fake.availability_puts.lock().unwrap(), vec![Some(forced)]);2054
assert_eq!(2055
engine.presence(ME).unwrap().availability,2056
Availability::Busy2057
);2058
assert!(matches!(2059
events.try_recv().unwrap(),2060
CoreEvent::PresenceStatusChanged(status) if status.availability == "Busy"2061
));2062
assert_eq!(events.try_recv().unwrap(), CoreEvent::PresenceChanged);2063
}2064
2065
#[tokio::test]2066
async fn setting_the_own_note_forwards_the_note() {2067
let fake = Arc::new(Fake::default());2068
let engine = engine_with(&fake, SyncConfig::default());2069
engine.set_own_status_note(None).await.unwrap();2070
assert_eq!(*fake.note_puts.lock().unwrap(), vec![None]);2071
}2072
2022
fn trouter_endpoint(endpoint_id: &str) -> chatsvc::TrouterEndpoint {2073
fn trouter_endpoint(endpoint_id: &str) -> chatsvc::TrouterEndpoint {2023
chatsvc::TrouterEndpoint {2074
chatsvc::TrouterEndpoint {2024
endpoint_id: endpoint_id.to_owned(),2075
endpoint_id: endpoint_id.to_owned(),@@ -6,6 +6,7 @@ mod models;
6
6
mod outgoing;
7
7
mod page;
8
8
mod people;
9
mod profile;
9
10
mod target;
10
11
mod urls;
11
12
mod writes;
@@ -26,4 +27,5 @@ pub use outgoing::{
26
27
};
27
28
pub use page::Page;
28
29
pub use people::MAX_PRESENCE_IDS;
30
pub use profile::{OrgPerson, ProfileDetails, UserProfile};
29
31
pub use target::MessageTarget;
@@ -6,6 +6,7 @@ mod models;6
mod outgoing;6
mod outgoing;7
mod page;7
mod page;8
mod people;8
mod people;9
mod profile;9
mod target;10
mod target;10
mod urls;11
mod urls;11
mod writes;12
mod writes;@@ -26,4 +27,5 @@ pub use outgoing::{26
};27
};27
pub use page::Page;28
pub use page::Page;28
pub use people::MAX_PRESENCE_IDS;29
pub use people::MAX_PRESENCE_IDS;30
pub use profile::{OrgPerson, ProfileDetails, UserProfile};29
pub use target::MessageTarget;31
pub use target::MessageTarget;@@ -0,0 +1,218 @@
1
use chrono::{DateTime, Duration, SecondsFormat, Utc};
2
use serde::Deserialize;
3
use serde_json::{Value, json};
4
use session::{ApiResponse, Method, Request, Scope};
5
6
use crate::client::Graph;
7
use crate::error::Result;
8
use crate::urls;
9
10
const PROFILE_SCOPE: &str = "User.ReadBasic.All";
11
const SCHEDULE_SCOPE: &str = "Calendars.Read.Shared";
12
13
#[derive(Debug, Clone, Default, Deserialize, PartialEq, Eq)]
14
#[serde(rename_all = "camelCase", default)]
15
pub struct UserProfile {
16
pub id: String,
17
pub display_name: Option<String>,
18
pub job_title: Option<String>,
19
pub department: Option<String>,
20
pub company_name: Option<String>,
21
pub office_location: Option<String>,
22
pub mail: Option<String>,
23
pub user_principal_name: Option<String>,
24
pub business_phones: Vec<String>,
25
pub mobile_phone: Option<String>,
26
}
27
28
#[derive(Debug, Clone, Default, Deserialize, PartialEq, Eq)]
29
#[serde(rename_all = "camelCase", default)]
30
pub struct OrgPerson {
31
pub id: String,
32
pub display_name: Option<String>,
33
pub job_title: Option<String>,
34
}
35
36
#[derive(Debug, Clone, PartialEq, Eq)]
37
pub struct ProfileDetails {
38
pub user: UserProfile,
39
pub manager: Option<OrgPerson>,
40
pub direct_reports: Vec<OrgPerson>,
41
}
42
43
impl Graph {
44
pub async fn user_profile(&self, user_id: &str) -> Result<ProfileDetails> {
45
let requests = [
46
Request::get(urls::user_profile(user_id)),
47
Request::get(urls::user_manager(user_id)),
48
Request::get(urls::user_direct_reports(user_id)),
49
];
50
let mut answers = self
51
.session()
52
.batch(&requests, &Scope::graph(PROFILE_SCOPE))
53
.await?
54
.into_iter();
55
let (Some(profile), Some(manager), Some(reports)) =
56
(answers.next(), answers.next(), answers.next())
57
else {
58
return Err(session::Error::api(0, &requests[0].url, Value::Null).into());
59
};
60
parse_profile_details(&requests[0].url, profile, manager, reports)
61
}
62
63
pub async fn time_zone_name(&self, mail: &str) -> Result<Option<String>> {
64
let body = schedule_body(mail, Utc::now());
65
let answer = self
66
.session()
67
.send(
68
Request::with_body(Method::Post, urls::get_schedule(), body),
69
&Scope::graph(SCHEDULE_SCOPE),
70
)
71
.await?;
72
Ok(parse_time_zone_name(&answer.body))
73
}
74
}
75
76
fn parse_profile_details(
77
url: &str,
78
profile: ApiResponse,
79
manager: ApiResponse,
80
reports: ApiResponse,
81
) -> Result<ProfileDetails> {
82
if !profile.is_success() {
83
return Err(session::Error::api(profile.status, url, profile.body).into());
84
}
85
let manager = manager
86
.is_success()
87
.then(|| serde_json::from_value(manager.body).ok())
88
.flatten();
89
let direct_reports = reports
90
.is_success()
91
.then(|| reports.body.get("value").cloned())
92
.flatten()
93
.and_then(|value| serde_json::from_value(value).ok())
94
.unwrap_or_default();
95
Ok(ProfileDetails {
96
user: serde_json::from_value(profile.body)?,
97
manager,
98
direct_reports,
99
})
100
}
101
102
fn schedule_body(mail: &str, now: DateTime<Utc>) -> Value {
103
let stamp = |moment: DateTime<Utc>| {
104
json!({
105
"dateTime": moment.to_rfc3339_opts(SecondsFormat::Secs, true).trim_end_matches('Z'),
106
"timeZone": "UTC",
107
})
108
};
109
json!({
110
"schedules": [mail],
111
"startTime": stamp(now),
112
"endTime": stamp(now + Duration::hours(1)),
113
"availabilityViewInterval": 60,
114
})
115
}
116
117
fn parse_time_zone_name(body: &Value) -> Option<String> {
118
let name = body
119
.pointer("/value/0/workingHours/timeZone/name")?
120
.as_str()?
121
.trim();
122
(!name.is_empty()).then(|| name.to_owned())
123
}
124
125
#[cfg(test)]
126
mod tests {
127
use chrono::TimeZone;
128
129
use super::*;
130
131
fn answer(status: u16, body: Value) -> ApiResponse {
132
ApiResponse {
133
status,
134
body,
135
retry_after: None,
136
}
137
}
138
139
fn now() -> DateTime<Utc> {
140
Utc.with_ymd_and_hms(2026, 10, 9, 12, 0, 0).unwrap()
141
}
142
143
#[test]
144
fn profile_details_parse_fields_manager_and_reports() {
145
let profile = json!({
146
"id": "u1",
147
"displayName": "Ada Lovelace",
148
"jobTitle": "Engineer",
149
"department": null,
150
"mail": "ada@example.com",
151
"businessPhones": ["+49 1"],
152
"mobilePhone": null
153
});
154
let manager = json!({"id": "m1", "displayName": "Grace", "jobTitle": "Lead"});
155
let reports = json!({"value": [{"@odata.type": "#microsoft.graph.user", "id": "r1", "displayName": "Bob"}]});
156
let details = parse_profile_details(
157
"u",
158
answer(200, profile),
159
answer(200, manager),
160
answer(200, reports),
161
)
162
.unwrap();
163
assert_eq!(details.user.display_name.as_deref(), Some("Ada Lovelace"));
164
assert_eq!(details.user.department, None);
165
assert_eq!(details.user.business_phones, vec!["+49 1"]);
166
assert_eq!(details.manager.unwrap().id, "m1");
167
assert_eq!(
168
details.direct_reports[0].display_name.as_deref(),
169
Some("Bob")
170
);
171
}
172
173
#[test]
174
fn missing_manager_and_failed_reports_do_not_fail_the_profile() {
175
let details = parse_profile_details(
176
"u",
177
answer(200, json!({"id": "u1"})),
178
answer(404, json!({})),
179
answer(403, json!({})),
180
)
181
.unwrap();
182
assert!(details.manager.is_none());
183
assert!(details.direct_reports.is_empty());
184
}
185
186
#[test]
187
fn a_failed_profile_is_an_error() {
188
let failed = parse_profile_details(
189
"u",
190
answer(404, json!({})),
191
answer(200, json!({"id": "m"})),
192
answer(200, json!({"value": []})),
193
);
194
assert!(failed.is_err());
195
}
196
197
#[test]
198
fn schedule_body_asks_one_hour_in_utc() {
199
let body = schedule_body("ada@example.com", now());
200
assert_eq!(body["schedules"], json!(["ada@example.com"]));
201
assert_eq!(
202
body["startTime"],
203
json!({"dateTime": "2026-10-09T12:00:00", "timeZone": "UTC"})
204
);
205
assert_eq!(body["endTime"]["dateTime"], "2026-10-09T13:00:00");
206
}
207
208
#[test]
209
fn time_zone_comes_from_working_hours() {
210
let body =
211
json!({"value": [{"workingHours": {"timeZone": {"name": "W. Europe Standard Time"}}}]});
212
assert_eq!(
213
parse_time_zone_name(&body).as_deref(),
214
Some("W. Europe Standard Time")
215
);
216
assert_eq!(parse_time_zone_name(&json!({"value": [{}]})), None);
217
}
218
}
@@ -0,0 +1,218 @@1
use chrono::{DateTime, Duration, SecondsFormat, Utc};2
use serde::Deserialize;3
use serde_json::{Value, json};4
use session::{ApiResponse, Method, Request, Scope};5
6
use crate::client::Graph;7
use crate::error::Result;8
use crate::urls;9
10
const PROFILE_SCOPE: &str = "User.ReadBasic.All";11
const SCHEDULE_SCOPE: &str = "Calendars.Read.Shared";12
13
#[derive(Debug, Clone, Default, Deserialize, PartialEq, Eq)]14
#[serde(rename_all = "camelCase", default)]15
pub struct UserProfile {16
pub id: String,17
pub display_name: Option<String>,18
pub job_title: Option<String>,19
pub department: Option<String>,20
pub company_name: Option<String>,21
pub office_location: Option<String>,22
pub mail: Option<String>,23
pub user_principal_name: Option<String>,24
pub business_phones: Vec<String>,25
pub mobile_phone: Option<String>,26
}27
28
#[derive(Debug, Clone, Default, Deserialize, PartialEq, Eq)]29
#[serde(rename_all = "camelCase", default)]30
pub struct OrgPerson {31
pub id: String,32
pub display_name: Option<String>,33
pub job_title: Option<String>,34
}35
36
#[derive(Debug, Clone, PartialEq, Eq)]37
pub struct ProfileDetails {38
pub user: UserProfile,39
pub manager: Option<OrgPerson>,40
pub direct_reports: Vec<OrgPerson>,41
}42
43
impl Graph {44
pub async fn user_profile(&self, user_id: &str) -> Result<ProfileDetails> {45
let requests = [46
Request::get(urls::user_profile(user_id)),47
Request::get(urls::user_manager(user_id)),48
Request::get(urls::user_direct_reports(user_id)),49
];50
let mut answers = self51
.session()52
.batch(&requests, &Scope::graph(PROFILE_SCOPE))53
.await?54
.into_iter();55
let (Some(profile), Some(manager), Some(reports)) =56
(answers.next(), answers.next(), answers.next())57
else {58
return Err(session::Error::api(0, &requests[0].url, Value::Null).into());59
};60
parse_profile_details(&requests[0].url, profile, manager, reports)61
}62
63
pub async fn time_zone_name(&self, mail: &str) -> Result<Option<String>> {64
let body = schedule_body(mail, Utc::now());65
let answer = self66
.session()67
.send(68
Request::with_body(Method::Post, urls::get_schedule(), body),69
&Scope::graph(SCHEDULE_SCOPE),70
)71
.await?;72
Ok(parse_time_zone_name(&answer.body))73
}74
}75
76
fn parse_profile_details(77
url: &str,78
profile: ApiResponse,79
manager: ApiResponse,80
reports: ApiResponse,81
) -> Result<ProfileDetails> {82
if !profile.is_success() {83
return Err(session::Error::api(profile.status, url, profile.body).into());84
}85
let manager = manager86
.is_success()87
.then(|| serde_json::from_value(manager.body).ok())88
.flatten();89
let direct_reports = reports90
.is_success()91
.then(|| reports.body.get("value").cloned())92
.flatten()93
.and_then(|value| serde_json::from_value(value).ok())94
.unwrap_or_default();95
Ok(ProfileDetails {96
user: serde_json::from_value(profile.body)?,97
manager,98
direct_reports,99
})100
}101
102
fn schedule_body(mail: &str, now: DateTime<Utc>) -> Value {103
let stamp = |moment: DateTime<Utc>| {104
json!({105
"dateTime": moment.to_rfc3339_opts(SecondsFormat::Secs, true).trim_end_matches('Z'),106
"timeZone": "UTC",107
})108
};109
json!({110
"schedules": [mail],111
"startTime": stamp(now),112
"endTime": stamp(now + Duration::hours(1)),113
"availabilityViewInterval": 60,114
})115
}116
117
fn parse_time_zone_name(body: &Value) -> Option<String> {118
let name = body119
.pointer("/value/0/workingHours/timeZone/name")?120
.as_str()?121
.trim();122
(!name.is_empty()).then(|| name.to_owned())123
}124
125
#[cfg(test)]126
mod tests {127
use chrono::TimeZone;128
129
use super::*;130
131
fn answer(status: u16, body: Value) -> ApiResponse {132
ApiResponse {133
status,134
body,135
retry_after: None,136
}137
}138
139
fn now() -> DateTime<Utc> {140
Utc.with_ymd_and_hms(2026, 10, 9, 12, 0, 0).unwrap()141
}142
143
#[test]144
fn profile_details_parse_fields_manager_and_reports() {145
let profile = json!({146
"id": "u1",147
"displayName": "Ada Lovelace",148
"jobTitle": "Engineer",149
"department": null,150
"mail": "ada@example.com",151
"businessPhones": ["+49 1"],152
"mobilePhone": null153
});154
let manager = json!({"id": "m1", "displayName": "Grace", "jobTitle": "Lead"});155
let reports = json!({"value": [{"@odata.type": "#microsoft.graph.user", "id": "r1", "displayName": "Bob"}]});156
let details = parse_profile_details(157
"u",158
answer(200, profile),159
answer(200, manager),160
answer(200, reports),161
)162
.unwrap();163
assert_eq!(details.user.display_name.as_deref(), Some("Ada Lovelace"));164
assert_eq!(details.user.department, None);165
assert_eq!(details.user.business_phones, vec!["+49 1"]);166
assert_eq!(details.manager.unwrap().id, "m1");167
assert_eq!(168
details.direct_reports[0].display_name.as_deref(),169
Some("Bob")170
);171
}172
173
#[test]174
fn missing_manager_and_failed_reports_do_not_fail_the_profile() {175
let details = parse_profile_details(176
"u",177
answer(200, json!({"id": "u1"})),178
answer(404, json!({})),179
answer(403, json!({})),180
)181
.unwrap();182
assert!(details.manager.is_none());183
assert!(details.direct_reports.is_empty());184
}185
186
#[test]187
fn a_failed_profile_is_an_error() {188
let failed = parse_profile_details(189
"u",190
answer(404, json!({})),191
answer(200, json!({"id": "m"})),192
answer(200, json!({"value": []})),193
);194
assert!(failed.is_err());195
}196
197
#[test]198
fn schedule_body_asks_one_hour_in_utc() {199
let body = schedule_body("ada@example.com", now());200
assert_eq!(body["schedules"], json!(["ada@example.com"]));201
assert_eq!(202
body["startTime"],203
json!({"dateTime": "2026-10-09T12:00:00", "timeZone": "UTC"})204
);205
assert_eq!(body["endTime"]["dateTime"], "2026-10-09T13:00:00");206
}207
208
#[test]209
fn time_zone_comes_from_working_hours() {210
let body =211
json!({"value": [{"workingHours": {"timeZone": {"name": "W. Europe Standard Time"}}}]});212
assert_eq!(213
parse_time_zone_name(&body).as_deref(),214
Some("W. Europe Standard Time")215
);216
assert_eq!(parse_time_zone_name(&json!({"value": [{}]})), None);217
}218
}@@ -23,6 +23,32 @@ pub fn user_photo(user_id: &str) -> String {
23
23
)
24
24
}
25
25
26
pub fn user_profile(user_id: &str) -> String {
27
format!(
28
"{GRAPH}/v1.0/users/{}?$select=id,displayName,jobTitle,department,companyName,\
29
officeLocation,mail,userPrincipalName,businessPhones,mobilePhone",
30
segment(user_id)
31
)
32
}
33
34
pub fn user_manager(user_id: &str) -> String {
35
format!(
36
"{GRAPH}/v1.0/users/{}/manager?$select=id,displayName,jobTitle",
37
segment(user_id)
38
)
39
}
40
41
pub fn user_direct_reports(user_id: &str) -> String {
42
format!(
43
"{GRAPH}/v1.0/users/{}/directReports?$select=id,displayName,jobTitle",
44
segment(user_id)
45
)
46
}
47
48
pub fn get_schedule() -> String {
49
format!("{GRAPH}/v1.0/me/calendar/getSchedule")
50
}
51
26
52
pub fn chats(top: usize) -> String {
27
53
format!(
28
54
"{GRAPH}/v1.0/me/chats?$expand=members,lastMessagePreview\
@@ -23,6 +23,32 @@ pub fn user_photo(user_id: &str) -> String {23
)23
)24
}24
}25
25
26
pub fn user_profile(user_id: &str) -> String {27
format!(28
"{GRAPH}/v1.0/users/{}?$select=id,displayName,jobTitle,department,companyName,\29
officeLocation,mail,userPrincipalName,businessPhones,mobilePhone",30
segment(user_id)31
)32
}33
34
pub fn user_manager(user_id: &str) -> String {35
format!(36
"{GRAPH}/v1.0/users/{}/manager?$select=id,displayName,jobTitle",37
segment(user_id)38
)39
}40
41
pub fn user_direct_reports(user_id: &str) -> String {42
format!(43
"{GRAPH}/v1.0/users/{}/directReports?$select=id,displayName,jobTitle",44
segment(user_id)45
)46
}47
48
pub fn get_schedule() -> String {49
format!("{GRAPH}/v1.0/me/calendar/getSchedule")50
}51
26
pub fn chats(top: usize) -> String {52
pub fn chats(top: usize) -> String {27
format!(53
format!(28
"{GRAPH}/v1.0/me/chats?$expand=members,lastMessagePreview\54
"{GRAPH}/v1.0/me/chats?$expand=members,lastMessagePreview\