feat(composer): attach cloud files from a OneDrive picker
- attach menu row "Attach cloud files" opens a picker like the Teams OneDrive picker: Home (Opened, Owner), My files, Shared with you (Date shared, Shared by), Quick access sites with their Documents library, folders with a breadcrumb - multi-select with checkboxes, Attach (disabled until a selection) and Cancel; Escape or a click outside closes - graph: shared with me, site and drive roots, owners of recent files; probe prints counts only - deviation: Favorites, Browse by, More places, the Activity column, New folder and Upload are left out - deviation: Quick access comes from the sites of recently opened files, /me/followedSites answers 403 with the web token Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@@ -32,6 +32,7 @@ use teams_core::{
32
32
33
33
pub(crate) mod delivery;
34
34
mod attach_menu;
35
mod cloud_picker;
35
36
mod drafts;
36
37
mod format_menus;
37
38
pub(crate) mod plus_menu;
@@ -264,6 +265,7 @@ pub struct Composer {
264
265
importance: store::MessageImportance,
265
266
rewrite: rewrite::RewritePanel,
266
267
attach_menu: attach_menu::AttachMenu,
268
cloud_picker: Option<(Entity<cloud_picker::CloudPicker>, Subscription)>,
267
269
delivery_menu: bool,
268
270
plus_menu: bool,
269
271
_subscriptions: [Subscription; 4],
@@ -538,6 +540,7 @@ impl Composer {
538
540
importance: store::MessageImportance::Normal,
539
541
rewrite: rewrite::RewritePanel::default(),
540
542
attach_menu: attach_menu::AttachMenu::default(),
543
cloud_picker: None,
541
544
delivery_menu: false,
542
545
plus_menu: false,
543
546
_subscriptions: [subscription, observer, image_observer, picker_subscription],
@@ -3464,6 +3467,7 @@ impl Render for Composer {
3464
3467
.children(self.render_delivery_menu(cx))
3465
3468
.children(self.render_plus_menu(cx))
3466
3469
.children(self.render_attach_menu(cx))
3470
.children(self.cloud_picker.as_ref().map(|(picker, _)| picker.clone()))
3467
3471
.children(self.render_rewrite_panel(cx))
3468
3472
.child(
3469
3473
v_flex()
@@ -32,6 +32,7 @@ use teams_core::{32
32
33
pub(crate) mod delivery;33
pub(crate) mod delivery;34
mod attach_menu;34
mod attach_menu;35
mod cloud_picker;35
mod drafts;36
mod drafts;36
mod format_menus;37
mod format_menus;37
pub(crate) mod plus_menu;38
pub(crate) mod plus_menu;@@ -264,6 +265,7 @@ pub struct Composer {264
importance: store::MessageImportance,265
importance: store::MessageImportance,265
rewrite: rewrite::RewritePanel,266
rewrite: rewrite::RewritePanel,266
attach_menu: attach_menu::AttachMenu,267
attach_menu: attach_menu::AttachMenu,268
cloud_picker: Option<(Entity<cloud_picker::CloudPicker>, Subscription)>,267
delivery_menu: bool,269
delivery_menu: bool,268
plus_menu: bool,270
plus_menu: bool,269
_subscriptions: [Subscription; 4],271
_subscriptions: [Subscription; 4],@@ -538,6 +540,7 @@ impl Composer {538
importance: store::MessageImportance::Normal,540
importance: store::MessageImportance::Normal,539
rewrite: rewrite::RewritePanel::default(),541
rewrite: rewrite::RewritePanel::default(),540
attach_menu: attach_menu::AttachMenu::default(),542
attach_menu: attach_menu::AttachMenu::default(),543
cloud_picker: None,541
delivery_menu: false,544
delivery_menu: false,542
plus_menu: false,545
plus_menu: false,543
_subscriptions: [subscription, observer, image_observer, picker_subscription],546
_subscriptions: [subscription, observer, image_observer, picker_subscription],@@ -3464,6 +3467,7 @@ impl Render for Composer {3464
.children(self.render_delivery_menu(cx))3467
.children(self.render_delivery_menu(cx))3465
.children(self.render_plus_menu(cx))3468
.children(self.render_plus_menu(cx))3466
.children(self.render_attach_menu(cx))3469
.children(self.render_attach_menu(cx))3470
.children(self.cloud_picker.as_ref().map(|(picker, _)| picker.clone()))3467
.children(self.render_rewrite_panel(cx))3471
.children(self.render_rewrite_panel(cx))3468
.child(3472
.child(3469
v_flex()3473
v_flex()@@ -0,0 +1,565 @@
1
use chrono::{DateTime, Utc};
2
use gpui_kit::component::button::{Button, ButtonVariants as _};
3
use gpui_kit::component::checkbox::Checkbox;
4
use gpui_kit::component::scroll::ScrollableElement as _;
5
use gpui_kit::component::{Disableable as _, h_flex, v_flex};
6
use gpui_kit::prelude::FluentBuilder as _;
7
use gpui_kit::*;
8
use teams_core::{CloudFile, DriveEntry, DriveFolder, QuickSite};
9
10
use crate::app_state::AppState;
11
use crate::runtime;
12
use crate::theme::{self, ElevatedSurface as _};
13
use crate::views::shared_tab::{entry_badge, modified_text};
14
use crate::views::widgets::symbol;
15
16
pub const CLOUD_PICKER_TAG: &str = "composer/cloud-picker";
17
pub const ATTACH_CLOUD_LABEL: &str = "Attach cloud files";
18
const PANEL_WIDTH: f32 = 1052.;
19
const PANEL_HEIGHT: f32 = 742.;
20
const PANEL_MARGIN: f32 = 32.;
21
const NAV_WIDTH: f32 = 210.;
22
const NAV_ROW_HEIGHT: f32 = 32.;
23
const ROW_HEIGHT: f32 = 48.;
24
const WHEN_WIDTH: f32 = 150.;
25
const WHO_WIDTH: f32 = 170.;
26
const CHECK_WIDTH: f32 = 32.;
27
const PADDING: f32 = 24.;
28
const BACKDROP_OPACITY: f32 = 0.55;
29
30
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
31
enum Place {
32
Home,
33
MyFiles,
34
Shared,
35
Site(usize),
36
}
37
38
impl Place {
39
fn columns(self) -> [&'static str; 3] {
40
match self {
41
Place::Home => ["Name", "Opened", "Owner"],
42
Place::Shared => ["Name", "Date shared", "Shared by"],
43
Place::MyFiles | Place::Site(_) => ["Name", "Modified", "Modified By"],
44
}
45
}
46
}
47
48
struct Crumb {
49
name: String,
50
folder: DriveFolder,
51
}
52
53
enum Rows {
54
Loading,
55
Failed,
56
Ready(Vec<DriveEntry>),
57
}
58
59
pub enum CloudPickerEvent {
60
Attach(Vec<CloudFile>),
61
Close,
62
}
63
64
pub struct CloudPicker {
65
app: Entity<AppState>,
66
place: Place,
67
sites: Vec<QuickSite>,
68
crumbs: Vec<Crumb>,
69
rows: Rows,
70
selected: Vec<DriveEntry>,
71
generation: u64,
72
focus_handle: FocusHandle,
73
}
74
75
impl EventEmitter<CloudPickerEvent> for CloudPicker {}
76
77
impl Focusable for CloudPicker {
78
fn focus_handle(&self, _: &App) -> FocusHandle {
79
self.focus_handle.clone()
80
}
81
}
82
83
fn recent_row((file, owner): (CloudFile, Option<String>)) -> Option<DriveEntry> {
84
Some(DriveEntry {
85
drive_id: file.drive_id?,
86
id: file.item_id?,
87
name: file.name,
88
web_url: file.web_url,
89
size: file.size,
90
modified_at: file.last_opened,
91
modified_by: owner,
92
child_count: None,
93
download_url: None,
94
})
95
}
96
97
fn demo_rows() -> Vec<DriveEntry> {
98
let now = Utc::now();
99
["Q4 planning.pptx", "Budget 2027.xlsx", "Release notes.docx"]
100
.iter()
101
.enumerate()
102
.map(|(index, name)| DriveEntry {
103
drive_id: "demo-drive".into(),
104
id: format!("demo-{index}"),
105
name: (*name).into(),
106
web_url: format!("https://contoso.sharepoint.com/demo/{index}"),
107
size: 20_000,
108
modified_at: Some(now - chrono::Duration::hours(3 * index as i64 + 1)),
109
modified_by: Some("Megan Bowen".into()),
110
child_count: None,
111
download_url: None,
112
})
113
.collect()
114
}
115
116
pub fn opened_ago(time: DateTime<Utc>, now: DateTime<Utc>) -> Option<String> {
117
let minutes = (now - time).num_minutes().max(0);
118
match minutes {
119
0 => Some("Just now".into()),
120
1..60 => Some(format!("{minutes}m ago")),
121
60..1440 => Some(format!("{}h ago", minutes / 60)),
122
_ => None,
123
}
124
}
125
126
impl CloudPicker {
127
pub fn new(app: Entity<AppState>, cx: &mut Context<Self>) -> Self {
128
let mut picker = CloudPicker {
129
app,
130
place: Place::Home,
131
sites: Vec::new(),
132
crumbs: Vec::new(),
133
rows: Rows::Loading,
134
selected: Vec::new(),
135
generation: 0,
136
focus_handle: cx.focus_handle(),
137
};
138
picker.load_sites(cx);
139
picker.open_place(Place::Home, cx);
140
picker
141
}
142
143
fn load_sites(&mut self, cx: &mut Context<Self>) {
144
let Some(engine) = self.app.read(cx).engine.clone() else {
145
return;
146
};
147
let receiver = runtime::spawn(async move { engine.picker_sites().await });
148
cx.spawn(async move |this, cx| {
149
if let Ok(Ok(sites)) = receiver.await {
150
this.update(cx, |this, cx| {
151
this.sites = sites;
152
cx.notify();
153
})
154
.ok();
155
}
156
})
157
.detach();
158
}
159
160
fn open_place(&mut self, place: Place, cx: &mut Context<Self>) {
161
self.place = place;
162
self.crumbs.clear();
163
self.generation += 1;
164
let generation = self.generation;
165
self.rows = Rows::Loading;
166
cx.notify();
167
if self.app.read(cx).mode.demo {
168
self.rows = Rows::Ready(if place == Place::Home { demo_rows() } else { Vec::new() });
169
return;
170
}
171
let Some(engine) = self.app.read(cx).engine.clone() else {
172
self.rows = Rows::Failed;
173
return;
174
};
175
let site = match place {
176
Place::Site(index) => self.sites.get(index).map(|site| site.id.clone()),
177
_ => None,
178
};
179
let receiver = runtime::spawn(async move {
180
match place {
181
Place::Home => Ok((None, engine.picker_recent().await?.into_iter().filter_map(recent_row).collect())),
182
Place::Shared => Ok((None, engine.picker_shared().await?)),
183
Place::MyFiles | Place::Site(_) => {
184
let root = engine.picker_root(site.as_deref()).await?;
185
let entries = engine.picker_folder(&root).await?;
186
Ok((Some(root), entries))
187
}
188
}
189
});
190
cx.spawn(async move |this, cx| {
191
let result: Option<teams_core::Result<(Option<DriveFolder>, Vec<DriveEntry>)>> = receiver.await.ok();
192
this.update(cx, |this, cx| {
193
if this.generation != generation {
194
return;
195
}
196
match result {
197
Some(Ok((root, entries))) => {
198
if let Some(folder) = root {
199
this.crumbs.push(Crumb { name: this.root_name(), folder });
200
}
201
this.rows = Rows::Ready(entries);
202
}
203
_ => this.rows = Rows::Failed,
204
}
205
cx.notify();
206
})
207
.ok();
208
})
209
.detach();
210
}
211
212
fn root_name(&self) -> String {
213
match self.place {
214
Place::Site(_) => "Documents".into(),
215
_ => "My files".into(),
216
}
217
}
218
219
fn open_folder(&mut self, name: String, folder: DriveFolder, cx: &mut Context<Self>) {
220
self.crumbs.push(Crumb { name, folder: folder.clone() });
221
self.list_folder(folder, cx);
222
}
223
224
fn back_to(&mut self, depth: usize, cx: &mut Context<Self>) {
225
self.crumbs.truncate(depth + 1);
226
if let Some(crumb) = self.crumbs.last() {
227
let folder = crumb.folder.clone();
228
self.list_folder(folder, cx);
229
}
230
}
231
232
fn list_folder(&mut self, folder: DriveFolder, cx: &mut Context<Self>) {
233
self.generation += 1;
234
let generation = self.generation;
235
self.rows = Rows::Loading;
236
cx.notify();
237
let Some(engine) = self.app.read(cx).engine.clone() else {
238
self.rows = Rows::Failed;
239
return;
240
};
241
let receiver = runtime::spawn(async move { engine.picker_folder(&folder).await });
242
cx.spawn(async move |this, cx| {
243
let result = receiver.await;
244
this.update(cx, |this, cx| {
245
if this.generation == generation {
246
this.rows = match result {
247
Ok(Ok(entries)) => Rows::Ready(entries),
248
_ => Rows::Failed,
249
};
250
cx.notify();
251
}
252
})
253
.ok();
254
})
255
.detach();
256
}
257
258
fn click_row(&mut self, entry: DriveEntry, cx: &mut Context<Self>) {
259
if entry.is_folder() {
260
self.open_folder(entry.name.clone(), entry.folder(), cx);
261
return;
262
}
263
match self.selected.iter().position(|picked| picked.id == entry.id) {
264
Some(index) => {
265
self.selected.remove(index);
266
}
267
None => self.selected.push(entry),
268
}
269
cx.notify();
270
}
271
272
fn attach(&mut self, cx: &mut Context<Self>) {
273
let files = self.selected.iter().map(CloudFile::from).collect::<Vec<_>>();
274
if !files.is_empty() {
275
cx.emit(CloudPickerEvent::Attach(files));
276
}
277
}
278
279
fn title(&self) -> String {
280
match self.place {
281
Place::Home => "Home".into(),
282
Place::Shared => "Shared with you".into(),
283
Place::MyFiles | Place::Site(_) => self.crumbs.last().map_or_else(|| self.root_name(), |crumb| crumb.name.clone()),
284
}
285
}
286
287
fn nav_row(&self, id: impl Into<ElementId>, glyph: &'static str, label: String, place: Place, cx: &mut Context<Self>) -> Stateful<Div> {
288
let active = self.place == place;
289
h_flex()
290
.id(id)
291
.h(px(NAV_ROW_HEIGHT))
292
.flex_none()
293
.px(px(10.))
294
.gap(px(10.))
295
.items_center()
296
.rounded(px(6.))
297
.cursor_pointer()
298
.text_size(px(13.))
299
.text_color(if active { theme::text_strong() } else { theme::text() })
300
.when(active, |row| row.bg(theme::selection()).font_weight(FontWeight::SEMIBOLD))
301
.hover(|row| row.bg(theme::row_hover()))
302
.child(symbol(glyph, 18., if active { theme::accent_text() } else { theme::text_soft() }))
303
.child(div().flex_1().min_w_0().truncate().child(label))
304
.on_click(cx.listener(move |this, _, _, cx| this.open_place(place, cx)))
305
}
306
307
fn navigation(&self, cx: &mut Context<Self>) -> Div {
308
let section = |label: &'static str| {
309
div()
310
.pt(px(20.))
311
.pb(px(6.))
312
.px(px(10.))
313
.text_size(px(13.))
314
.font_weight(FontWeight::SEMIBOLD)
315
.text_color(theme::text())
316
.child(label)
317
};
318
let mut sites = Vec::with_capacity(self.sites.len());
319
for (index, site) in self.sites.iter().enumerate() {
320
sites.push(self.nav_row(("cloud-picker-site", index), "domain", site.name.clone(), Place::Site(index), cx));
321
}
322
v_flex()
323
.w(px(NAV_WIDTH))
324
.flex_none()
325
.h_full()
326
.px(px(8.))
327
.py(px(PADDING))
328
.child(
329
div()
330
.px(px(10.))
331
.pb(px(16.))
332
.text_size(px(20.))
333
.font_weight(FontWeight::SEMIBOLD)
334
.text_color(theme::text_strong())
335
.child("OneDrive"),
336
)
337
.child(self.nav_row("cloud-picker-home", "home", "Home".into(), Place::Home, cx))
338
.child(self.nav_row("cloud-picker-mine", "folder", "My files".into(), Place::MyFiles, cx))
339
.child(self.nav_row("cloud-picker-shared", "group", "Shared".into(), Place::Shared, cx))
340
.when(!self.sites.is_empty(), |nav| {
341
nav.child(section("Quick access"))
342
.child(v_flex().id("cloud-picker-sites").flex_1().min_h_0().overflow_y_scrollbar().children(sites))
343
})
344
}
345
346
fn breadcrumb(&self, cx: &mut Context<Self>) -> Div {
347
let last = self.crumbs.len().saturating_sub(1);
348
let mut trail = h_flex().gap(px(4.)).items_center().min_w_0();
349
for (depth, crumb) in self.crumbs.iter().enumerate() {
350
if depth > 0 {
351
trail = trail.child(symbol("chevron_right", 16., theme::text_soft()));
352
}
353
let current = depth == last;
354
trail = trail.child(
355
div()
356
.id(("cloud-picker-crumb", depth))
357
.truncate()
358
.text_size(px(if current { 20. } else { 14. }))
359
.font_weight(if current { FontWeight::SEMIBOLD } else { FontWeight::NORMAL })
360
.text_color(if current { theme::text_strong() } else { theme::text_soft() })
361
.when(!current, |crumb| {
362
crumb.cursor_pointer().hover(|crumb| crumb.text_color(theme::text())).on_click(cx.listener(move |this, _, _, cx| this.back_to(depth, cx)))
363
})
364
.child(crumb.name.clone()),
365
);
366
}
367
trail
368
}
369
370
fn header(&self, cx: &mut Context<Self>) -> Div {
371
let site = match self.place {
372
Place::Site(index) => self.sites.get(index).map(|site| site.name.clone()),
373
_ => None,
374
};
375
let title = if self.crumbs.len() > 1 {
376
self.breadcrumb(cx)
377
} else {
378
h_flex().child(
379
div().text_size(px(20.)).font_weight(FontWeight::SEMIBOLD).text_color(theme::text_strong()).child(self.title()),
380
)
381
};
382
v_flex()
383
.gap(px(2.))
384
.children(site.map(|name| div().text_size(px(13.)).text_color(theme::text_soft()).child(name)))
385
.child(title)
386
}
387
388
fn column_header(&self) -> Div {
389
let [name, when, who] = self.place.columns();
390
h_flex()
391
.h(px(40.))
392
.flex_none()
393
.px(px(12.))
394
.gap(px(12.))
395
.items_center()
396
.border_b_1()
397
.border_color(theme::border())
398
.text_size(px(12.5))
399
.font_weight(FontWeight::SEMIBOLD)
400
.text_color(theme::text_soft())
401
.child(div().w(px(CHECK_WIDTH)).flex_none())
402
.child(div().flex_1().min_w_0().child(name))
403
.child(div().w(px(WHEN_WIDTH)).flex_none().child(when))
404
.child(div().w(px(WHO_WIDTH)).flex_none().child(who))
405
}
406
407
fn when_text(&self, entry: &DriveEntry, now: DateTime<Utc>) -> String {
408
match (self.place, entry.modified_at) {
409
(Place::Home, Some(opened)) => opened_ago(opened, now).unwrap_or_else(|| modified_text(entry)),
410
_ => modified_text(entry),
411
}
412
}
413
414
fn row(&self, index: usize, entry: &DriveEntry, now: DateTime<Utc>, cx: &mut Context<Self>) -> Stateful<Div> {
415
let picked = self.selected.iter().any(|selected| selected.id == entry.id);
416
let folder = entry.is_folder();
417
let clicked = entry.clone();
418
h_flex()
419
.id(("cloud-picker-row", index))
420
.h(px(ROW_HEIGHT))
421
.flex_none()
422
.px(px(12.))
423
.gap(px(12.))
424
.items_center()
425
.border_b_1()
426
.border_color(theme::border())
427
.cursor_pointer()
428
.text_size(px(13.))
429
.text_color(theme::text_soft())
430
.when(picked, |row| row.bg(theme::selection()))
431
.hover(|row| row.bg(theme::row_hover()))
432
.child(
433
div().w(px(CHECK_WIDTH)).flex_none().when(!folder, |cell| {
434
cell.child(Checkbox::new(("cloud-picker-check", index)).checked(picked))
435
}),
436
)
437
.child(
438
h_flex()
439
.flex_1()
440
.min_w_0()
441
.gap(px(10.))
442
.items_center()
443
.child(entry_badge(entry))
444
.child(div().truncate().text_color(theme::text()).child(entry.name.clone())),
445
)
446
.child(div().w(px(WHEN_WIDTH)).flex_none().truncate().child(self.when_text(entry, now)))
447
.child(div().w(px(WHO_WIDTH)).flex_none().truncate().child(entry.modified_by.clone().unwrap_or_default()))
448
.on_click(cx.listener(move |this, _, _, cx| this.click_row(clicked.clone(), cx)))
449
}
450
451
fn table(&self, cx: &mut Context<Self>) -> AnyElement {
452
let note = |text: &'static str| {
453
div().p(px(16.)).text_size(px(13.)).text_color(theme::text_soft()).child(text).into_any_element()
454
};
455
let now = Utc::now();
456
let body: Vec<AnyElement> = match &self.rows {
457
Rows::Loading => vec![note("Loading ...")],
458
Rows::Failed => vec![note("Couldn't load files.")],
459
Rows::Ready(entries) if entries.is_empty() => vec![note("This folder is empty.")],
460
Rows::Ready(entries) => {
461
entries.iter().enumerate().map(|(index, entry)| self.row(index, entry, now, cx).into_any_element()).collect()
462
}
463
};
464
v_flex()
465
.flex_1()
466
.min_h_0()
467
.rounded(px(10.))
468
.bg(theme::surface_raised())
469
.overflow_hidden()
470
.child(self.column_header())
471
.child(v_flex().id("cloud-picker-rows").flex_1().min_h_0().overflow_y_scrollbar().children(body))
472
.into_any_element()
473
}
474
}
475
476
impl Render for CloudPicker {
477
fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
478
let viewport = window.viewport_size();
479
let width = px(PANEL_WIDTH).min(viewport.width - px(2. * PANEL_MARGIN));
480
let height = px(PANEL_HEIGHT).min(viewport.height - px(2. * PANEL_MARGIN));
481
let can_attach = !self.selected.is_empty();
482
let panel = h_flex()
483
.id(CLOUD_PICKER_TAG)
484
.debug_selector(|| CLOUD_PICKER_TAG.into())
485
.w(width)
486
.h(height)
487
.rounded(px(12.))
488
.dialog_surface()
489
.text_color(theme::text())
490
.occlude()
491
.on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
492
.child(self.navigation(cx))
493
.child(
494
v_flex()
495
.flex_1()
496
.min_w_0()
497
.h_full()
498
.p(px(PADDING))
499
.gap(px(16.))
500
.child(self.header(cx))
501
.child(self.table(cx))
502
.child(
503
h_flex()
504
.justify_end()
505
.gap(px(8.))
506
.child(
507
Button::new("cloud-picker-attach")
508
.primary()
509
.label("Attach")
510
.disabled(!can_attach)
511
.on_click(cx.listener(|this, _, _, cx| this.attach(cx))),
512
)
513
.child(
514
Button::new("cloud-picker-cancel")
515
.label("Cancel")
516
.on_click(cx.listener(|_, _, _, cx| cx.emit(CloudPickerEvent::Close))),
517
),
518
),
519
);
520
deferred(
521
anchored().position(point(px(0.), px(0.))).child(
522
div()
523
.id("cloud-picker-backdrop")
524
.track_focus(&self.focus_handle)
525
.w(viewport.width)
526
.h(viewport.height)
527
.flex()
528
.items_center()
529
.justify_center()
530
.bg(black().opacity(BACKDROP_OPACITY))
531
.occlude()
532
.on_key_down(cx.listener(|_, event: &KeyDownEvent, _, cx| {
533
if event.keystroke.key == "escape" {
534
cx.emit(CloudPickerEvent::Close);
535
}
536
}))
537
.on_mouse_down(MouseButton::Left, cx.listener(|_, _, _, cx| cx.emit(CloudPickerEvent::Close)))
538
.child(panel),
539
),
540
)
541
.with_priority(3)
542
}
543
}
544
545
#[cfg(test)]
546
mod tests {
547
use chrono::{TimeZone as _, Utc};
548
549
use super::{Place, opened_ago};
550
551
#[test]
552
fn home_shows_hours_ago_like_the_onedrive_picker() {
553
let now = Utc.with_ymd_and_hms(2026, 11, 10, 22, 0, 0).unwrap();
554
assert_eq!(opened_ago(now - chrono::Duration::hours(9), now).as_deref(), Some("9h ago"));
555
assert_eq!(opened_ago(now - chrono::Duration::minutes(5), now).as_deref(), Some("5m ago"));
556
assert_eq!(opened_ago(now - chrono::Duration::days(3), now), None);
557
}
558
559
#[test]
560
fn each_place_has_the_picker_columns() {
561
assert_eq!(Place::Home.columns(), ["Name", "Opened", "Owner"]);
562
assert_eq!(Place::Shared.columns(), ["Name", "Date shared", "Shared by"]);
563
assert_eq!(Place::Site(0).columns(), ["Name", "Modified", "Modified By"]);
564
}
565
}
@@ -0,0 +1,565 @@1
use chrono::{DateTime, Utc};2
use gpui_kit::component::button::{Button, ButtonVariants as _};3
use gpui_kit::component::checkbox::Checkbox;4
use gpui_kit::component::scroll::ScrollableElement as _;5
use gpui_kit::component::{Disableable as _, h_flex, v_flex};6
use gpui_kit::prelude::FluentBuilder as _;7
use gpui_kit::*;8
use teams_core::{CloudFile, DriveEntry, DriveFolder, QuickSite};9
10
use crate::app_state::AppState;11
use crate::runtime;12
use crate::theme::{self, ElevatedSurface as _};13
use crate::views::shared_tab::{entry_badge, modified_text};14
use crate::views::widgets::symbol;15
16
pub const CLOUD_PICKER_TAG: &str = "composer/cloud-picker";17
pub const ATTACH_CLOUD_LABEL: &str = "Attach cloud files";18
const PANEL_WIDTH: f32 = 1052.;19
const PANEL_HEIGHT: f32 = 742.;20
const PANEL_MARGIN: f32 = 32.;21
const NAV_WIDTH: f32 = 210.;22
const NAV_ROW_HEIGHT: f32 = 32.;23
const ROW_HEIGHT: f32 = 48.;24
const WHEN_WIDTH: f32 = 150.;25
const WHO_WIDTH: f32 = 170.;26
const CHECK_WIDTH: f32 = 32.;27
const PADDING: f32 = 24.;28
const BACKDROP_OPACITY: f32 = 0.55;29
30
#[derive(Debug, Clone, Copy, PartialEq, Eq)]31
enum Place {32
Home,33
MyFiles,34
Shared,35
Site(usize),36
}37
38
impl Place {39
fn columns(self) -> [&'static str; 3] {40
match self {41
Place::Home => ["Name", "Opened", "Owner"],42
Place::Shared => ["Name", "Date shared", "Shared by"],43
Place::MyFiles | Place::Site(_) => ["Name", "Modified", "Modified By"],44
}45
}46
}47
48
struct Crumb {49
name: String,50
folder: DriveFolder,51
}52
53
enum Rows {54
Loading,55
Failed,56
Ready(Vec<DriveEntry>),57
}58
59
pub enum CloudPickerEvent {60
Attach(Vec<CloudFile>),61
Close,62
}63
64
pub struct CloudPicker {65
app: Entity<AppState>,66
place: Place,67
sites: Vec<QuickSite>,68
crumbs: Vec<Crumb>,69
rows: Rows,70
selected: Vec<DriveEntry>,71
generation: u64,72
focus_handle: FocusHandle,73
}74
75
impl EventEmitter<CloudPickerEvent> for CloudPicker {}76
77
impl Focusable for CloudPicker {78
fn focus_handle(&self, _: &App) -> FocusHandle {79
self.focus_handle.clone()80
}81
}82
83
fn recent_row((file, owner): (CloudFile, Option<String>)) -> Option<DriveEntry> {84
Some(DriveEntry {85
drive_id: file.drive_id?,86
id: file.item_id?,87
name: file.name,88
web_url: file.web_url,89
size: file.size,90
modified_at: file.last_opened,91
modified_by: owner,92
child_count: None,93
download_url: None,94
})95
}96
97
fn demo_rows() -> Vec<DriveEntry> {98
let now = Utc::now();99
["Q4 planning.pptx", "Budget 2027.xlsx", "Release notes.docx"]100
.iter()101
.enumerate()102
.map(|(index, name)| DriveEntry {103
drive_id: "demo-drive".into(),104
id: format!("demo-{index}"),105
name: (*name).into(),106
web_url: format!("https://contoso.sharepoint.com/demo/{index}"),107
size: 20_000,108
modified_at: Some(now - chrono::Duration::hours(3 * index as i64 + 1)),109
modified_by: Some("Megan Bowen".into()),110
child_count: None,111
download_url: None,112
})113
.collect()114
}115
116
pub fn opened_ago(time: DateTime<Utc>, now: DateTime<Utc>) -> Option<String> {117
let minutes = (now - time).num_minutes().max(0);118
match minutes {119
0 => Some("Just now".into()),120
1..60 => Some(format!("{minutes}m ago")),121
60..1440 => Some(format!("{}h ago", minutes / 60)),122
_ => None,123
}124
}125
126
impl CloudPicker {127
pub fn new(app: Entity<AppState>, cx: &mut Context<Self>) -> Self {128
let mut picker = CloudPicker {129
app,130
place: Place::Home,131
sites: Vec::new(),132
crumbs: Vec::new(),133
rows: Rows::Loading,134
selected: Vec::new(),135
generation: 0,136
focus_handle: cx.focus_handle(),137
};138
picker.load_sites(cx);139
picker.open_place(Place::Home, cx);140
picker141
}142
143
fn load_sites(&mut self, cx: &mut Context<Self>) {144
let Some(engine) = self.app.read(cx).engine.clone() else {145
return;146
};147
let receiver = runtime::spawn(async move { engine.picker_sites().await });148
cx.spawn(async move |this, cx| {149
if let Ok(Ok(sites)) = receiver.await {150
this.update(cx, |this, cx| {151
this.sites = sites;152
cx.notify();153
})154
.ok();155
}156
})157
.detach();158
}159
160
fn open_place(&mut self, place: Place, cx: &mut Context<Self>) {161
self.place = place;162
self.crumbs.clear();163
self.generation += 1;164
let generation = self.generation;165
self.rows = Rows::Loading;166
cx.notify();167
if self.app.read(cx).mode.demo {168
self.rows = Rows::Ready(if place == Place::Home { demo_rows() } else { Vec::new() });169
return;170
}171
let Some(engine) = self.app.read(cx).engine.clone() else {172
self.rows = Rows::Failed;173
return;174
};175
let site = match place {176
Place::Site(index) => self.sites.get(index).map(|site| site.id.clone()),177
_ => None,178
};179
let receiver = runtime::spawn(async move {180
match place {181
Place::Home => Ok((None, engine.picker_recent().await?.into_iter().filter_map(recent_row).collect())),182
Place::Shared => Ok((None, engine.picker_shared().await?)),183
Place::MyFiles | Place::Site(_) => {184
let root = engine.picker_root(site.as_deref()).await?;185
let entries = engine.picker_folder(&root).await?;186
Ok((Some(root), entries))187
}188
}189
});190
cx.spawn(async move |this, cx| {191
let result: Option<teams_core::Result<(Option<DriveFolder>, Vec<DriveEntry>)>> = receiver.await.ok();192
this.update(cx, |this, cx| {193
if this.generation != generation {194
return;195
}196
match result {197
Some(Ok((root, entries))) => {198
if let Some(folder) = root {199
this.crumbs.push(Crumb { name: this.root_name(), folder });200
}201
this.rows = Rows::Ready(entries);202
}203
_ => this.rows = Rows::Failed,204
}205
cx.notify();206
})207
.ok();208
})209
.detach();210
}211
212
fn root_name(&self) -> String {213
match self.place {214
Place::Site(_) => "Documents".into(),215
_ => "My files".into(),216
}217
}218
219
fn open_folder(&mut self, name: String, folder: DriveFolder, cx: &mut Context<Self>) {220
self.crumbs.push(Crumb { name, folder: folder.clone() });221
self.list_folder(folder, cx);222
}223
224
fn back_to(&mut self, depth: usize, cx: &mut Context<Self>) {225
self.crumbs.truncate(depth + 1);226
if let Some(crumb) = self.crumbs.last() {227
let folder = crumb.folder.clone();228
self.list_folder(folder, cx);229
}230
}231
232
fn list_folder(&mut self, folder: DriveFolder, cx: &mut Context<Self>) {233
self.generation += 1;234
let generation = self.generation;235
self.rows = Rows::Loading;236
cx.notify();237
let Some(engine) = self.app.read(cx).engine.clone() else {238
self.rows = Rows::Failed;239
return;240
};241
let receiver = runtime::spawn(async move { engine.picker_folder(&folder).await });242
cx.spawn(async move |this, cx| {243
let result = receiver.await;244
this.update(cx, |this, cx| {245
if this.generation == generation {246
this.rows = match result {247
Ok(Ok(entries)) => Rows::Ready(entries),248
_ => Rows::Failed,249
};250
cx.notify();251
}252
})253
.ok();254
})255
.detach();256
}257
258
fn click_row(&mut self, entry: DriveEntry, cx: &mut Context<Self>) {259
if entry.is_folder() {260
self.open_folder(entry.name.clone(), entry.folder(), cx);261
return;262
}263
match self.selected.iter().position(|picked| picked.id == entry.id) {264
Some(index) => {265
self.selected.remove(index);266
}267
None => self.selected.push(entry),268
}269
cx.notify();270
}271
272
fn attach(&mut self, cx: &mut Context<Self>) {273
let files = self.selected.iter().map(CloudFile::from).collect::<Vec<_>>();274
if !files.is_empty() {275
cx.emit(CloudPickerEvent::Attach(files));276
}277
}278
279
fn title(&self) -> String {280
match self.place {281
Place::Home => "Home".into(),282
Place::Shared => "Shared with you".into(),283
Place::MyFiles | Place::Site(_) => self.crumbs.last().map_or_else(|| self.root_name(), |crumb| crumb.name.clone()),284
}285
}286
287
fn nav_row(&self, id: impl Into<ElementId>, glyph: &'static str, label: String, place: Place, cx: &mut Context<Self>) -> Stateful<Div> {288
let active = self.place == place;289
h_flex()290
.id(id)291
.h(px(NAV_ROW_HEIGHT))292
.flex_none()293
.px(px(10.))294
.gap(px(10.))295
.items_center()296
.rounded(px(6.))297
.cursor_pointer()298
.text_size(px(13.))299
.text_color(if active { theme::text_strong() } else { theme::text() })300
.when(active, |row| row.bg(theme::selection()).font_weight(FontWeight::SEMIBOLD))301
.hover(|row| row.bg(theme::row_hover()))302
.child(symbol(glyph, 18., if active { theme::accent_text() } else { theme::text_soft() }))303
.child(div().flex_1().min_w_0().truncate().child(label))304
.on_click(cx.listener(move |this, _, _, cx| this.open_place(place, cx)))305
}306
307
fn navigation(&self, cx: &mut Context<Self>) -> Div {308
let section = |label: &'static str| {309
div()310
.pt(px(20.))311
.pb(px(6.))312
.px(px(10.))313
.text_size(px(13.))314
.font_weight(FontWeight::SEMIBOLD)315
.text_color(theme::text())316
.child(label)317
};318
let mut sites = Vec::with_capacity(self.sites.len());319
for (index, site) in self.sites.iter().enumerate() {320
sites.push(self.nav_row(("cloud-picker-site", index), "domain", site.name.clone(), Place::Site(index), cx));321
}322
v_flex()323
.w(px(NAV_WIDTH))324
.flex_none()325
.h_full()326
.px(px(8.))327
.py(px(PADDING))328
.child(329
div()330
.px(px(10.))331
.pb(px(16.))332
.text_size(px(20.))333
.font_weight(FontWeight::SEMIBOLD)334
.text_color(theme::text_strong())335
.child("OneDrive"),336
)337
.child(self.nav_row("cloud-picker-home", "home", "Home".into(), Place::Home, cx))338
.child(self.nav_row("cloud-picker-mine", "folder", "My files".into(), Place::MyFiles, cx))339
.child(self.nav_row("cloud-picker-shared", "group", "Shared".into(), Place::Shared, cx))340
.when(!self.sites.is_empty(), |nav| {341
nav.child(section("Quick access"))342
.child(v_flex().id("cloud-picker-sites").flex_1().min_h_0().overflow_y_scrollbar().children(sites))343
})344
}345
346
fn breadcrumb(&self, cx: &mut Context<Self>) -> Div {347
let last = self.crumbs.len().saturating_sub(1);348
let mut trail = h_flex().gap(px(4.)).items_center().min_w_0();349
for (depth, crumb) in self.crumbs.iter().enumerate() {350
if depth > 0 {351
trail = trail.child(symbol("chevron_right", 16., theme::text_soft()));352
}353
let current = depth == last;354
trail = trail.child(355
div()356
.id(("cloud-picker-crumb", depth))357
.truncate()358
.text_size(px(if current { 20. } else { 14. }))359
.font_weight(if current { FontWeight::SEMIBOLD } else { FontWeight::NORMAL })360
.text_color(if current { theme::text_strong() } else { theme::text_soft() })361
.when(!current, |crumb| {362
crumb.cursor_pointer().hover(|crumb| crumb.text_color(theme::text())).on_click(cx.listener(move |this, _, _, cx| this.back_to(depth, cx)))363
})364
.child(crumb.name.clone()),365
);366
}367
trail368
}369
370
fn header(&self, cx: &mut Context<Self>) -> Div {371
let site = match self.place {372
Place::Site(index) => self.sites.get(index).map(|site| site.name.clone()),373
_ => None,374
};375
let title = if self.crumbs.len() > 1 {376
self.breadcrumb(cx)377
} else {378
h_flex().child(379
div().text_size(px(20.)).font_weight(FontWeight::SEMIBOLD).text_color(theme::text_strong()).child(self.title()),380
)381
};382
v_flex()383
.gap(px(2.))384
.children(site.map(|name| div().text_size(px(13.)).text_color(theme::text_soft()).child(name)))385
.child(title)386
}387
388
fn column_header(&self) -> Div {389
let [name, when, who] = self.place.columns();390
h_flex()391
.h(px(40.))392
.flex_none()393
.px(px(12.))394
.gap(px(12.))395
.items_center()396
.border_b_1()397
.border_color(theme::border())398
.text_size(px(12.5))399
.font_weight(FontWeight::SEMIBOLD)400
.text_color(theme::text_soft())401
.child(div().w(px(CHECK_WIDTH)).flex_none())402
.child(div().flex_1().min_w_0().child(name))403
.child(div().w(px(WHEN_WIDTH)).flex_none().child(when))404
.child(div().w(px(WHO_WIDTH)).flex_none().child(who))405
}406
407
fn when_text(&self, entry: &DriveEntry, now: DateTime<Utc>) -> String {408
match (self.place, entry.modified_at) {409
(Place::Home, Some(opened)) => opened_ago(opened, now).unwrap_or_else(|| modified_text(entry)),410
_ => modified_text(entry),411
}412
}413
414
fn row(&self, index: usize, entry: &DriveEntry, now: DateTime<Utc>, cx: &mut Context<Self>) -> Stateful<Div> {415
let picked = self.selected.iter().any(|selected| selected.id == entry.id);416
let folder = entry.is_folder();417
let clicked = entry.clone();418
h_flex()419
.id(("cloud-picker-row", index))420
.h(px(ROW_HEIGHT))421
.flex_none()422
.px(px(12.))423
.gap(px(12.))424
.items_center()425
.border_b_1()426
.border_color(theme::border())427
.cursor_pointer()428
.text_size(px(13.))429
.text_color(theme::text_soft())430
.when(picked, |row| row.bg(theme::selection()))431
.hover(|row| row.bg(theme::row_hover()))432
.child(433
div().w(px(CHECK_WIDTH)).flex_none().when(!folder, |cell| {434
cell.child(Checkbox::new(("cloud-picker-check", index)).checked(picked))435
}),436
)437
.child(438
h_flex()439
.flex_1()440
.min_w_0()441
.gap(px(10.))442
.items_center()443
.child(entry_badge(entry))444
.child(div().truncate().text_color(theme::text()).child(entry.name.clone())),445
)446
.child(div().w(px(WHEN_WIDTH)).flex_none().truncate().child(self.when_text(entry, now)))447
.child(div().w(px(WHO_WIDTH)).flex_none().truncate().child(entry.modified_by.clone().unwrap_or_default()))448
.on_click(cx.listener(move |this, _, _, cx| this.click_row(clicked.clone(), cx)))449
}450
451
fn table(&self, cx: &mut Context<Self>) -> AnyElement {452
let note = |text: &'static str| {453
div().p(px(16.)).text_size(px(13.)).text_color(theme::text_soft()).child(text).into_any_element()454
};455
let now = Utc::now();456
let body: Vec<AnyElement> = match &self.rows {457
Rows::Loading => vec![note("Loading ...")],458
Rows::Failed => vec![note("Couldn't load files.")],459
Rows::Ready(entries) if entries.is_empty() => vec![note("This folder is empty.")],460
Rows::Ready(entries) => {461
entries.iter().enumerate().map(|(index, entry)| self.row(index, entry, now, cx).into_any_element()).collect()462
}463
};464
v_flex()465
.flex_1()466
.min_h_0()467
.rounded(px(10.))468
.bg(theme::surface_raised())469
.overflow_hidden()470
.child(self.column_header())471
.child(v_flex().id("cloud-picker-rows").flex_1().min_h_0().overflow_y_scrollbar().children(body))472
.into_any_element()473
}474
}475
476
impl Render for CloudPicker {477
fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {478
let viewport = window.viewport_size();479
let width = px(PANEL_WIDTH).min(viewport.width - px(2. * PANEL_MARGIN));480
let height = px(PANEL_HEIGHT).min(viewport.height - px(2. * PANEL_MARGIN));481
let can_attach = !self.selected.is_empty();482
let panel = h_flex()483
.id(CLOUD_PICKER_TAG)484
.debug_selector(|| CLOUD_PICKER_TAG.into())485
.w(width)486
.h(height)487
.rounded(px(12.))488
.dialog_surface()489
.text_color(theme::text())490
.occlude()491
.on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())492
.child(self.navigation(cx))493
.child(494
v_flex()495
.flex_1()496
.min_w_0()497
.h_full()498
.p(px(PADDING))499
.gap(px(16.))500
.child(self.header(cx))501
.child(self.table(cx))502
.child(503
h_flex()504
.justify_end()505
.gap(px(8.))506
.child(507
Button::new("cloud-picker-attach")508
.primary()509
.label("Attach")510
.disabled(!can_attach)511
.on_click(cx.listener(|this, _, _, cx| this.attach(cx))),512
)513
.child(514
Button::new("cloud-picker-cancel")515
.label("Cancel")516
.on_click(cx.listener(|_, _, _, cx| cx.emit(CloudPickerEvent::Close))),517
),518
),519
);520
deferred(521
anchored().position(point(px(0.), px(0.))).child(522
div()523
.id("cloud-picker-backdrop")524
.track_focus(&self.focus_handle)525
.w(viewport.width)526
.h(viewport.height)527
.flex()528
.items_center()529
.justify_center()530
.bg(black().opacity(BACKDROP_OPACITY))531
.occlude()532
.on_key_down(cx.listener(|_, event: &KeyDownEvent, _, cx| {533
if event.keystroke.key == "escape" {534
cx.emit(CloudPickerEvent::Close);535
}536
}))537
.on_mouse_down(MouseButton::Left, cx.listener(|_, _, _, cx| cx.emit(CloudPickerEvent::Close)))538
.child(panel),539
),540
)541
.with_priority(3)542
}543
}544
545
#[cfg(test)]546
mod tests {547
use chrono::{TimeZone as _, Utc};548
549
use super::{Place, opened_ago};550
551
#[test]552
fn home_shows_hours_ago_like_the_onedrive_picker() {553
let now = Utc.with_ymd_and_hms(2026, 11, 10, 22, 0, 0).unwrap();554
assert_eq!(opened_ago(now - chrono::Duration::hours(9), now).as_deref(), Some("9h ago"));555
assert_eq!(opened_ago(now - chrono::Duration::minutes(5), now).as_deref(), Some("5m ago"));556
assert_eq!(opened_ago(now - chrono::Duration::days(3), now), None);557
}558
559
#[test]560
fn each_place_has_the_picker_columns() {561
assert_eq!(Place::Home.columns(), ["Name", "Opened", "Owner"]);562
assert_eq!(Place::Shared.columns(), ["Name", "Date shared", "Shared by"]);563
assert_eq!(Place::Site(0).columns(), ["Name", "Modified", "Modified By"]);564
}565
}@@ -1,5 +1,5 @@
1
1
use chatsvc::substrate_search::{QueryRequest, QueryScope, SearchFile, SearchSession};
2
use graph::{CloudFile, FileReference};
2
use graph::{CloudFile, DriveEntry, DriveFolder, FileReference, QuickSite};
3
3
4
4
use crate::engine::SyncEngine;
5
5
use crate::error::{Error, Result};
@@ -35,6 +35,39 @@ impl<R: Remote> SyncEngine<R> {
35
35
Ok(recent_documents(self.remote.recent_files(RECENT_FETCH).await?))
36
36
}
37
37
38
/// The picker's Home list: every recently opened file with its owner, newest first.
39
pub async fn picker_recent(&self) -> Result<Vec<(CloudFile, Option<String>)>> {
40
let (files, owners) = self.remote.recent_files_with_owners(RECENT_FETCH).await?;
41
Ok(files
42
.into_iter()
43
.map(|file| {
44
let owner = owners.iter().find(|(id, _)| file.item_id.as_deref() == Some(id)).map(|(_, owner)| owner.clone());
45
(file, owner)
46
})
47
.collect())
48
}
49
50
pub async fn picker_shared(&self) -> Result<Vec<DriveEntry>> {
51
self.remote.shared_with_me().await
52
}
53
54
pub async fn picker_sites(&self) -> Result<Vec<QuickSite>> {
55
self.remote.quick_access_sites().await
56
}
57
58
/// The root of the user's OneDrive, or of a site's document library, as a folder to list.
59
pub async fn picker_root(&self, site_id: Option<&str>) -> Result<DriveFolder> {
60
self.remote.drive_root(site_id).await
61
}
62
63
pub async fn picker_folder(&self, folder: &DriveFolder) -> Result<Vec<DriveEntry>> {
64
let mut entries = self.remote.list_children(folder).await?;
65
entries.sort_by(|first, second| {
66
second.is_folder().cmp(&first.is_folder()).then_with(|| first.name.to_lowercase().cmp(&second.name.to_lowercase()))
67
});
68
Ok(entries)
69
}
70
38
71
pub async fn search_cloud_files(&self, search_session: &SearchSession, text: &str) -> Result<Vec<CloudFile>> {
39
72
let request = QueryRequest {
40
73
size: SEARCH_SIZE,
@@ -1,5 +1,5 @@1
use chatsvc::substrate_search::{QueryRequest, QueryScope, SearchFile, SearchSession};1
use chatsvc::substrate_search::{QueryRequest, QueryScope, SearchFile, SearchSession};2
use graph::{CloudFile, FileReference};2
use graph::{CloudFile, DriveEntry, DriveFolder, FileReference, QuickSite};3
3
4
use crate::engine::SyncEngine;4
use crate::engine::SyncEngine;5
use crate::error::{Error, Result};5
use crate::error::{Error, Result};@@ -35,6 +35,39 @@ impl<R: Remote> SyncEngine<R> {35
Ok(recent_documents(self.remote.recent_files(RECENT_FETCH).await?))35
Ok(recent_documents(self.remote.recent_files(RECENT_FETCH).await?))36
}36
}37
37
38
/// The picker's Home list: every recently opened file with its owner, newest first.39
pub async fn picker_recent(&self) -> Result<Vec<(CloudFile, Option<String>)>> {40
let (files, owners) = self.remote.recent_files_with_owners(RECENT_FETCH).await?;41
Ok(files42
.into_iter()43
.map(|file| {44
let owner = owners.iter().find(|(id, _)| file.item_id.as_deref() == Some(id)).map(|(_, owner)| owner.clone());45
(file, owner)46
})47
.collect())48
}49
50
pub async fn picker_shared(&self) -> Result<Vec<DriveEntry>> {51
self.remote.shared_with_me().await52
}53
54
pub async fn picker_sites(&self) -> Result<Vec<QuickSite>> {55
self.remote.quick_access_sites().await56
}57
58
/// The root of the user's OneDrive, or of a site's document library, as a folder to list.59
pub async fn picker_root(&self, site_id: Option<&str>) -> Result<DriveFolder> {60
self.remote.drive_root(site_id).await61
}62
63
pub async fn picker_folder(&self, folder: &DriveFolder) -> Result<Vec<DriveEntry>> {64
let mut entries = self.remote.list_children(folder).await?;65
entries.sort_by(|first, second| {66
second.is_folder().cmp(&first.is_folder()).then_with(|| first.name.to_lowercase().cmp(&second.name.to_lowercase()))67
});68
Ok(entries)69
}70
38
pub async fn search_cloud_files(&self, search_session: &SearchSession, text: &str) -> Result<Vec<CloudFile>> {71
pub async fn search_cloud_files(&self, search_session: &SearchSession, text: &str) -> Result<Vec<CloudFile>> {39
let request = QueryRequest {72
let request = QueryRequest {40
size: SEARCH_SIZE,73
size: SEARCH_SIZE,@@ -157,7 +157,7 @@ pub use forwarded::{
157
157
ForwardInfo, ForwardState, forwarded_texts, forwards, is_forwarded,
158
158
};
159
159
pub use graph::{
160
CloudFile, DriveEntry, DriveFolder, FileReference, HostedImage, KeptAttachment, MentionTarget,
160
CloudFile, DriveEntry, DriveFolder, FileReference, HostedImage, KeptAttachment, MentionTarget, QuickSite,
161
161
MessageExtras, SharedFile, UploadedFile,
162
162
};
163
163
pub use images::StoredImage;
@@ -157,7 +157,7 @@ pub use forwarded::{157
ForwardInfo, ForwardState, forwarded_texts, forwards, is_forwarded,157
ForwardInfo, ForwardState, forwarded_texts, forwards, is_forwarded,158
};158
};159
pub use graph::{159
pub use graph::{160
CloudFile, DriveEntry, DriveFolder, FileReference, HostedImage, KeptAttachment, MentionTarget,160
CloudFile, DriveEntry, DriveFolder, FileReference, HostedImage, KeptAttachment, MentionTarget, QuickSite,161
MessageExtras, SharedFile, UploadedFile,161
MessageExtras, SharedFile, UploadedFile,162
};162
};163
pub use images::StoredImage;163
pub use images::StoredImage;@@ -23,7 +23,7 @@ use chatsvc::{
23
23
};
24
24
use chrono::{DateTime, Utc};
25
25
use graph::{
26
CloudFile,
26
CloudFile, QuickSite,
27
27
Channel, Chat, DriveEntry, DriveFolder, Graph, Member, Message, MessageExtras, MessageTarget,
28
28
OutgoingMention, Photo, Presence, SharedFile, Tag, Team, UploadDestination, UploadedFile, User,
29
29
};
@@ -271,6 +271,22 @@ pub trait Remote {
271
271
Err(Error::Unsupported("recent files"))
272
272
}
273
273
274
async fn recent_files_with_owners(&self, _top: usize) -> Result<(Vec<CloudFile>, Vec<(String, String)>)> {
275
Err(Error::Unsupported("recent files"))
276
}
277
278
async fn shared_with_me(&self) -> Result<Vec<DriveEntry>> {
279
Err(Error::Unsupported("shared files"))
280
}
281
282
async fn quick_access_sites(&self) -> Result<Vec<QuickSite>> {
283
Err(Error::Unsupported("sites"))
284
}
285
286
async fn drive_root(&self, _site_id: Option<&str>) -> Result<DriveFolder> {
287
Err(Error::Unsupported("drive root"))
288
}
289
274
290
async fn cloud_file_reference(&self, _file: &CloudFile) -> Result<UploadedFile> {
275
291
Err(Error::Unsupported("cloud files"))
276
292
}
@@ -1106,6 +1122,22 @@ impl Remote for Graph {
1106
1122
Ok(Graph::recent_files(self, top).await?)
1107
1123
}
1108
1124
1125
async fn recent_files_with_owners(&self, top: usize) -> Result<(Vec<CloudFile>, Vec<(String, String)>)> {
1126
Ok(Graph::recent_files_with_owners(self, top).await?)
1127
}
1128
1129
async fn shared_with_me(&self) -> Result<Vec<DriveEntry>> {
1130
Ok(Graph::shared_with_me(self).await?)
1131
}
1132
1133
async fn quick_access_sites(&self) -> Result<Vec<QuickSite>> {
1134
Ok(Graph::quick_access_sites(self).await?)
1135
}
1136
1137
async fn drive_root(&self, site_id: Option<&str>) -> Result<DriveFolder> {
1138
Ok(Graph::drive_root(self, site_id).await?)
1139
}
1140
1109
1141
async fn cloud_file_reference(&self, file: &CloudFile) -> Result<UploadedFile> {
1110
1142
Ok(Graph::cloud_file_reference(self, file).await?)
1111
1143
}
@@ -23,7 +23,7 @@ use chatsvc::{23
};23
};24
use chrono::{DateTime, Utc};24
use chrono::{DateTime, Utc};25
use graph::{25
use graph::{26
CloudFile,26
CloudFile, QuickSite,27
Channel, Chat, DriveEntry, DriveFolder, Graph, Member, Message, MessageExtras, MessageTarget,27
Channel, Chat, DriveEntry, DriveFolder, Graph, Member, Message, MessageExtras, MessageTarget,28
OutgoingMention, Photo, Presence, SharedFile, Tag, Team, UploadDestination, UploadedFile, User,28
OutgoingMention, Photo, Presence, SharedFile, Tag, Team, UploadDestination, UploadedFile, User,29
};29
};@@ -271,6 +271,22 @@ pub trait Remote {271
Err(Error::Unsupported("recent files"))271
Err(Error::Unsupported("recent files"))272
}272
}273
273
274
async fn recent_files_with_owners(&self, _top: usize) -> Result<(Vec<CloudFile>, Vec<(String, String)>)> {275
Err(Error::Unsupported("recent files"))276
}277
278
async fn shared_with_me(&self) -> Result<Vec<DriveEntry>> {279
Err(Error::Unsupported("shared files"))280
}281
282
async fn quick_access_sites(&self) -> Result<Vec<QuickSite>> {283
Err(Error::Unsupported("sites"))284
}285
286
async fn drive_root(&self, _site_id: Option<&str>) -> Result<DriveFolder> {287
Err(Error::Unsupported("drive root"))288
}289
274
async fn cloud_file_reference(&self, _file: &CloudFile) -> Result<UploadedFile> {290
async fn cloud_file_reference(&self, _file: &CloudFile) -> Result<UploadedFile> {275
Err(Error::Unsupported("cloud files"))291
Err(Error::Unsupported("cloud files"))276
}292
}@@ -1106,6 +1122,22 @@ impl Remote for Graph {1106
Ok(Graph::recent_files(self, top).await?)1122
Ok(Graph::recent_files(self, top).await?)1107
}1123
}1108
1124
1125
async fn recent_files_with_owners(&self, top: usize) -> Result<(Vec<CloudFile>, Vec<(String, String)>)> {1126
Ok(Graph::recent_files_with_owners(self, top).await?)1127
}1128
1129
async fn shared_with_me(&self) -> Result<Vec<DriveEntry>> {1130
Ok(Graph::shared_with_me(self).await?)1131
}1132
1133
async fn quick_access_sites(&self) -> Result<Vec<QuickSite>> {1134
Ok(Graph::quick_access_sites(self).await?)1135
}1136
1137
async fn drive_root(&self, site_id: Option<&str>) -> Result<DriveFolder> {1138
Ok(Graph::drive_root(self, site_id).await?)1139
}1140
1109
async fn cloud_file_reference(&self, file: &CloudFile) -> Result<UploadedFile> {1141
async fn cloud_file_reference(&self, file: &CloudFile) -> Result<UploadedFile> {1110
Ok(Graph::cloud_file_reference(self, file).await?)1142
Ok(Graph::cloud_file_reference(self, file).await?)1111
}1143
}@@ -0,0 +1,48 @@
1
use graph::Graph;
2
use session::{DEFAULT_ENDPOINT, Session};
3
4
#[tokio::main]
5
async fn main() {
6
let endpoint = std::env::var("CDP_ENDPOINT").unwrap_or_else(|_| DEFAULT_ENDPOINT.to_owned());
7
let graph = Graph::new(Session::connect(&endpoint).await.expect("browser"));
8
match graph.recent_files_with_owners(40).await {
9
Ok((files, owners)) => println!("recent {} files, {} owners", files.len(), owners.len()),
10
Err(error) => println!("recent error: {error}"),
11
}
12
match graph.drive_root(None).await {
13
Ok(root) => match graph.list_children(&root).await {
14
Ok(children) => println!(
15
"my files {} entries, {} folders, {} with modifier",
16
children.len(),
17
children.iter().filter(|entry| entry.is_folder()).count(),
18
children.iter().filter(|entry| entry.modified_by.is_some()).count()
19
),
20
Err(error) => println!("my files error: {error}"),
21
},
22
Err(error) => println!("drive root error: {error}"),
23
}
24
match graph.shared_with_me().await {
25
Ok(shared) => println!(
26
"shared {} entries, {} with sharer, {} with date",
27
shared.len(),
28
shared.iter().filter(|entry| entry.modified_by.is_some()).count(),
29
shared.iter().filter(|entry| entry.modified_at.is_some()).count()
30
),
31
Err(error) => println!("shared error: {error}"),
32
}
33
match graph.quick_access_sites().await {
34
Ok(sites) => {
35
println!("sites {}", sites.len());
36
for site in &sites {
37
match graph.drive_root(Some(&site.id)).await {
38
Ok(root) => match graph.list_children(&root).await {
39
Ok(children) => println!("first site library: {} entries", children.len()),
40
Err(error) => println!("site library error: {error}"),
41
},
42
Err(error) => println!("site root error: {error}"),
43
}
44
}
45
}
46
Err(error) => println!("sites error: {error}"),
47
}
48
}
@@ -0,0 +1,48 @@1
use graph::Graph;2
use session::{DEFAULT_ENDPOINT, Session};3
4
#[tokio::main]5
async fn main() {6
let endpoint = std::env::var("CDP_ENDPOINT").unwrap_or_else(|_| DEFAULT_ENDPOINT.to_owned());7
let graph = Graph::new(Session::connect(&endpoint).await.expect("browser"));8
match graph.recent_files_with_owners(40).await {9
Ok((files, owners)) => println!("recent {} files, {} owners", files.len(), owners.len()),10
Err(error) => println!("recent error: {error}"),11
}12
match graph.drive_root(None).await {13
Ok(root) => match graph.list_children(&root).await {14
Ok(children) => println!(15
"my files {} entries, {} folders, {} with modifier",16
children.len(),17
children.iter().filter(|entry| entry.is_folder()).count(),18
children.iter().filter(|entry| entry.modified_by.is_some()).count()19
),20
Err(error) => println!("my files error: {error}"),21
},22
Err(error) => println!("drive root error: {error}"),23
}24
match graph.shared_with_me().await {25
Ok(shared) => println!(26
"shared {} entries, {} with sharer, {} with date",27
shared.len(),28
shared.iter().filter(|entry| entry.modified_by.is_some()).count(),29
shared.iter().filter(|entry| entry.modified_at.is_some()).count()30
),31
Err(error) => println!("shared error: {error}"),32
}33
match graph.quick_access_sites().await {34
Ok(sites) => {35
println!("sites {}", sites.len());36
for site in &sites {37
match graph.drive_root(Some(&site.id)).await {38
Ok(root) => match graph.list_children(&root).await {39
Ok(children) => println!("first site library: {} entries", children.len()),40
Err(error) => println!("site library error: {error}"),41
},42
Err(error) => println!("site root error: {error}"),43
}44
}45
}46
Err(error) => println!("sites error: {error}"),47
}48
}@@ -3,8 +3,9 @@ use serde_json::Value;
3
3
use session::{Method, Scope};
4
4
5
5
use crate::client::Graph;
6
use crate::error::Result;
7
use crate::files::{FILES_SCOPE, UploadedFile, finished_item, share_id};
6
use crate::error::{Error, Result};
7
use crate::files::{DriveFolder, FILES_SCOPE, UploadedFile, finished_item, share_id};
8
use crate::library::DriveEntry;
8
9
use crate::urls;
9
10
10
11
/// A file in OneDrive or SharePoint that can be attached by reference, without uploading it again.
@@ -38,6 +39,91 @@ fn recent_file(item: &Value) -> Option<CloudFile> {
38
39
})
39
40
}
40
41
42
const RECENT_FOR_SITES: usize = 100;
43
const SHARED_SHOWN: usize = 100;
44
const ROOT_ITEM: &str = "root";
45
const QUICK_ACCESS_SITES: usize = 8;
46
47
/// A SharePoint site under "Quick access".
48
#[derive(Debug, Clone, PartialEq, Eq)]
49
pub struct QuickSite {
50
pub id: String,
51
pub name: String,
52
}
53
54
impl From<&DriveEntry> for CloudFile {
55
fn from(entry: &DriveEntry) -> Self {
56
CloudFile {
57
name: entry.name.clone(),
58
size: entry.size,
59
web_url: entry.web_url.clone(),
60
drive_id: Some(entry.drive_id.clone()).filter(|id| !id.is_empty()),
61
item_id: Some(entry.id.clone()),
62
last_opened: None,
63
}
64
}
65
}
66
67
fn user_name(value: &Value) -> Option<String> {
68
value["user"]["displayName"].as_str().filter(|name| !name.is_empty()).map(str::to_owned)
69
}
70
71
/// A file someone shared, as a picker row: `modified_at` holds the share date, `modified_by` who shared it.
72
fn shared_entry(item: &Value) -> Option<DriveEntry> {
73
let remote = item.get("remoteItem").filter(|remote| remote.is_object())?;
74
let shared = &remote["shared"];
75
Some(DriveEntry {
76
drive_id: remote["parentReference"]["driveId"].as_str()?.to_owned(),
77
id: remote["id"].as_str()?.to_owned(),
78
name: item["name"].as_str()?.to_owned(),
79
web_url: item["webUrl"].as_str().or_else(|| remote["webUrl"].as_str())?.to_owned(),
80
size: remote["size"].as_u64().unwrap_or(0),
81
modified_at: time(&shared["sharedDateTime"]),
82
modified_by: user_name(&shared["sharedBy"]).or_else(|| user_name(&shared["owner"])),
83
child_count: remote.get("folder").map(|folder| folder["childCount"].as_u64().unwrap_or(0)),
84
download_url: None,
85
})
86
}
87
88
pub fn parse_shared(body: &Value) -> Vec<DriveEntry> {
89
let mut shared: Vec<DriveEntry> = body["value"].as_array().into_iter().flatten().filter_map(shared_entry).collect();
90
shared.sort_by(|first, second| second.modified_at.cmp(&first.modified_at));
91
shared.truncate(SHARED_SHOWN);
92
shared
93
}
94
95
/// The owner of each recent file, by item id, for the "Owner" column.
96
pub fn parse_recent_owners(body: &Value) -> Vec<(String, String)> {
97
body["value"]
98
.as_array()
99
.into_iter()
100
.flatten()
101
.filter_map(|item| {
102
let remote = item.get("remoteItem").filter(|remote| remote.is_object()).unwrap_or(item);
103
let owner = user_name(&remote["shared"]["owner"]).or_else(|| user_name(&remote["createdBy"]))?;
104
Some((remote["id"].as_str()?.to_owned(), owner))
105
})
106
.collect()
107
}
108
109
/// The SharePoint sites of recently opened files, most recent first, without personal OneDrives.
110
pub fn recent_site_ids(body: &Value, limit: usize) -> Vec<String> {
111
let mut sites: Vec<String> = Vec::new();
112
for item in body["value"].as_array().into_iter().flatten() {
113
let remote = item.get("remoteItem").filter(|remote| remote.is_object()).unwrap_or(item);
114
let web_url = remote["webUrl"].as_str().or_else(|| item["webUrl"].as_str()).unwrap_or_default();
115
let site = remote["parentReference"]["siteId"].as_str().or_else(|| remote["sharepointIds"]["siteId"].as_str());
116
if let Some(site) = site
117
&& !web_url.contains("/personal/")
118
&& !sites.iter().any(|known| known == site)
119
{
120
sites.push(site.to_owned());
121
}
122
}
123
sites.truncate(limit);
124
sites
125
}
126
41
127
pub fn parse_recent_files(body: &Value) -> Vec<CloudFile> {
42
128
body["value"]
43
129
.as_array()
@@ -49,11 +135,38 @@ pub fn parse_recent_files(body: &Value) -> Vec<CloudFile> {
49
135
50
136
impl Graph {
51
137
pub async fn recent_files(&self, top: usize) -> Result<Vec<CloudFile>> {
52
let answer = self
53
.session()
54
.request(Method::Get, &urls::recent_drive_items(top), &Scope::graph(FILES_SCOPE), None)
55
.await?;
56
Ok(parse_recent_files(&answer.body))
138
Ok(self.recent_files_with_owners(top).await?.0)
139
}
140
141
pub async fn recent_files_with_owners(&self, top: usize) -> Result<(Vec<CloudFile>, Vec<(String, String)>)> {
142
let body = self.get(&urls::recent_drive_items(top), &Scope::graph(FILES_SCOPE)).await?;
143
Ok((parse_recent_files(&body), parse_recent_owners(&body)))
144
}
145
146
pub async fn shared_with_me(&self) -> Result<Vec<DriveEntry>> {
147
Ok(parse_shared(&self.get(&urls::shared_with_me(), &Scope::graph(FILES_SCOPE)).await?))
148
}
149
150
pub async fn quick_access_sites(&self) -> Result<Vec<QuickSite>> {
151
let scope = Scope::graph(FILES_SCOPE);
152
let recent = self.get(&urls::recent_drive_items(RECENT_FOR_SITES), &scope).await?;
153
let mut sites = Vec::new();
154
for site_id in recent_site_ids(&recent, QUICK_ACCESS_SITES) {
155
if let Ok(site) = self.get(&urls::site(&site_id), &scope).await
156
&& let Some(name) = site["displayName"].as_str()
157
{
158
sites.push(QuickSite { id: site_id, name: name.to_owned() });
159
}
160
}
161
Ok(sites)
162
}
163
164
/// The root folder of the user's OneDrive, or of a site's document library.
165
pub async fn drive_root(&self, site_id: Option<&str>) -> Result<DriveFolder> {
166
let url = site_id.map_or_else(urls::my_drive, urls::site_drive);
167
let drive = self.get(&url, &Scope::graph(FILES_SCOPE)).await?;
168
let drive_id = drive["id"].as_str().ok_or_else(|| Error::Decode("a drive without an id".into()))?;
169
Ok(DriveFolder { drive_id: drive_id.to_owned(), item_id: ROOT_ITEM.to_owned() })
57
170
}
58
171
59
172
/// The reference a message needs to carry `file`: its drive item, found by id or else by its link.
@@ -95,4 +208,34 @@ mod tests {
95
208
assert_eq!((files[1].item_id.as_deref(), files[1].size), (Some("item-2"), 0));
96
209
assert!(files[1].last_opened.is_none());
97
210
}
211
212
#[test]
213
fn shared_files_carry_the_sharer_and_date_newest_first() {
214
let body = json!({"value": [
215
{"name": "old.pdf", "webUrl": "https://x/o", "remoteItem": {"id": "o", "file": {}, "parentReference": {"driveId": "d"},
216
"shared": {"sharedDateTime": "2026-10-01T10:00:00Z", "sharedBy": {"user": {"displayName": "Anna"}}}}},
217
{"name": "Team", "webUrl": "https://x/t", "remoteItem": {"id": "t", "folder": {"childCount": 2}, "parentReference": {"driveId": "d"},
218
"shared": {"sharedDateTime": "2026-11-01T10:00:00Z", "owner": {"user": {"displayName": "Ben"}}}}}
219
]});
220
let shared = parse_shared(&body);
221
assert_eq!(shared[0].name, "Team");
222
assert!(shared[0].is_folder());
223
assert_eq!(shared[0].modified_by.as_deref(), Some("Ben"));
224
assert_eq!(shared[1].modified_by.as_deref(), Some("Anna"));
225
assert_eq!(CloudFile::from(&shared[1]).item_id.as_deref(), Some("o"));
226
}
227
228
#[test]
229
fn recent_owners_and_sites() {
230
let recent = json!({"value": [
231
{"name": "a", "remoteItem": {"id": "1", "createdBy": {"user": {"displayName": "Cara"}},
232
"webUrl": "https://t.sharepoint.com/sites/dev/a", "parentReference": {"siteId": "dev"}}},
233
{"name": "b", "remoteItem": {"id": "2", "webUrl": "https://t-my.sharepoint.com/personal/x/b", "parentReference": {"siteId": "me"}}},
234
{"name": "c", "remoteItem": {"id": "3", "webUrl": "https://t.sharepoint.com/sites/dev/c", "parentReference": {"siteId": "dev"}}},
235
{"name": "d", "remoteItem": {"id": "4", "webUrl": "https://t.sharepoint.com/sites/ops/d", "sharepointIds": {"siteId": "ops"}}}
236
]});
237
assert_eq!(parse_recent_owners(&recent), vec![("1".to_owned(), "Cara".to_owned())]);
238
assert_eq!(recent_site_ids(&recent, 8), ["dev", "ops"]);
239
assert_eq!(recent_site_ids(&recent, 1), ["dev"]);
240
}
98
241
}
@@ -3,8 +3,9 @@ use serde_json::Value;3
use session::{Method, Scope};3
use session::{Method, Scope};4
4
5
use crate::client::Graph;5
use crate::client::Graph;6
use crate::error::Result;6
use crate::error::{Error, Result};7
use crate::files::{FILES_SCOPE, UploadedFile, finished_item, share_id};7
use crate::files::{DriveFolder, FILES_SCOPE, UploadedFile, finished_item, share_id};8
use crate::library::DriveEntry;8
use crate::urls;9
use crate::urls;9
10
10
/// A file in OneDrive or SharePoint that can be attached by reference, without uploading it again.11
/// A file in OneDrive or SharePoint that can be attached by reference, without uploading it again.@@ -38,6 +39,91 @@ fn recent_file(item: &Value) -> Option<CloudFile> {38
})39
})39
}40
}40
41
42
const RECENT_FOR_SITES: usize = 100;43
const SHARED_SHOWN: usize = 100;44
const ROOT_ITEM: &str = "root";45
const QUICK_ACCESS_SITES: usize = 8;46
47
/// A SharePoint site under "Quick access".48
#[derive(Debug, Clone, PartialEq, Eq)]49
pub struct QuickSite {50
pub id: String,51
pub name: String,52
}53
54
impl From<&DriveEntry> for CloudFile {55
fn from(entry: &DriveEntry) -> Self {56
CloudFile {57
name: entry.name.clone(),58
size: entry.size,59
web_url: entry.web_url.clone(),60
drive_id: Some(entry.drive_id.clone()).filter(|id| !id.is_empty()),61
item_id: Some(entry.id.clone()),62
last_opened: None,63
}64
}65
}66
67
fn user_name(value: &Value) -> Option<String> {68
value["user"]["displayName"].as_str().filter(|name| !name.is_empty()).map(str::to_owned)69
}70
71
/// A file someone shared, as a picker row: `modified_at` holds the share date, `modified_by` who shared it.72
fn shared_entry(item: &Value) -> Option<DriveEntry> {73
let remote = item.get("remoteItem").filter(|remote| remote.is_object())?;74
let shared = &remote["shared"];75
Some(DriveEntry {76
drive_id: remote["parentReference"]["driveId"].as_str()?.to_owned(),77
id: remote["id"].as_str()?.to_owned(),78
name: item["name"].as_str()?.to_owned(),79
web_url: item["webUrl"].as_str().or_else(|| remote["webUrl"].as_str())?.to_owned(),80
size: remote["size"].as_u64().unwrap_or(0),81
modified_at: time(&shared["sharedDateTime"]),82
modified_by: user_name(&shared["sharedBy"]).or_else(|| user_name(&shared["owner"])),83
child_count: remote.get("folder").map(|folder| folder["childCount"].as_u64().unwrap_or(0)),84
download_url: None,85
})86
}87
88
pub fn parse_shared(body: &Value) -> Vec<DriveEntry> {89
let mut shared: Vec<DriveEntry> = body["value"].as_array().into_iter().flatten().filter_map(shared_entry).collect();90
shared.sort_by(|first, second| second.modified_at.cmp(&first.modified_at));91
shared.truncate(SHARED_SHOWN);92
shared93
}94
95
/// The owner of each recent file, by item id, for the "Owner" column.96
pub fn parse_recent_owners(body: &Value) -> Vec<(String, String)> {97
body["value"]98
.as_array()99
.into_iter()100
.flatten()101
.filter_map(|item| {102
let remote = item.get("remoteItem").filter(|remote| remote.is_object()).unwrap_or(item);103
let owner = user_name(&remote["shared"]["owner"]).or_else(|| user_name(&remote["createdBy"]))?;104
Some((remote["id"].as_str()?.to_owned(), owner))105
})106
.collect()107
}108
109
/// The SharePoint sites of recently opened files, most recent first, without personal OneDrives.110
pub fn recent_site_ids(body: &Value, limit: usize) -> Vec<String> {111
let mut sites: Vec<String> = Vec::new();112
for item in body["value"].as_array().into_iter().flatten() {113
let remote = item.get("remoteItem").filter(|remote| remote.is_object()).unwrap_or(item);114
let web_url = remote["webUrl"].as_str().or_else(|| item["webUrl"].as_str()).unwrap_or_default();115
let site = remote["parentReference"]["siteId"].as_str().or_else(|| remote["sharepointIds"]["siteId"].as_str());116
if let Some(site) = site117
&& !web_url.contains("/personal/")118
&& !sites.iter().any(|known| known == site)119
{120
sites.push(site.to_owned());121
}122
}123
sites.truncate(limit);124
sites125
}126
41
pub fn parse_recent_files(body: &Value) -> Vec<CloudFile> {127
pub fn parse_recent_files(body: &Value) -> Vec<CloudFile> {42
body["value"]128
body["value"]43
.as_array()129
.as_array()@@ -49,11 +135,38 @@ pub fn parse_recent_files(body: &Value) -> Vec<CloudFile> {49
135
50
impl Graph {136
impl Graph {51
pub async fn recent_files(&self, top: usize) -> Result<Vec<CloudFile>> {137
pub async fn recent_files(&self, top: usize) -> Result<Vec<CloudFile>> {52
let answer = self138
Ok(self.recent_files_with_owners(top).await?.0)53
.session()139
}54
.request(Method::Get, &urls::recent_drive_items(top), &Scope::graph(FILES_SCOPE), None)140
55
.await?;141
pub async fn recent_files_with_owners(&self, top: usize) -> Result<(Vec<CloudFile>, Vec<(String, String)>)> {56
Ok(parse_recent_files(&answer.body))142
let body = self.get(&urls::recent_drive_items(top), &Scope::graph(FILES_SCOPE)).await?;143
Ok((parse_recent_files(&body), parse_recent_owners(&body)))144
}145
146
pub async fn shared_with_me(&self) -> Result<Vec<DriveEntry>> {147
Ok(parse_shared(&self.get(&urls::shared_with_me(), &Scope::graph(FILES_SCOPE)).await?))148
}149
150
pub async fn quick_access_sites(&self) -> Result<Vec<QuickSite>> {151
let scope = Scope::graph(FILES_SCOPE);152
let recent = self.get(&urls::recent_drive_items(RECENT_FOR_SITES), &scope).await?;153
let mut sites = Vec::new();154
for site_id in recent_site_ids(&recent, QUICK_ACCESS_SITES) {155
if let Ok(site) = self.get(&urls::site(&site_id), &scope).await156
&& let Some(name) = site["displayName"].as_str()157
{158
sites.push(QuickSite { id: site_id, name: name.to_owned() });159
}160
}161
Ok(sites)162
}163
164
/// The root folder of the user's OneDrive, or of a site's document library.165
pub async fn drive_root(&self, site_id: Option<&str>) -> Result<DriveFolder> {166
let url = site_id.map_or_else(urls::my_drive, urls::site_drive);167
let drive = self.get(&url, &Scope::graph(FILES_SCOPE)).await?;168
let drive_id = drive["id"].as_str().ok_or_else(|| Error::Decode("a drive without an id".into()))?;169
Ok(DriveFolder { drive_id: drive_id.to_owned(), item_id: ROOT_ITEM.to_owned() })57
}170
}58
171
59
/// The reference a message needs to carry `file`: its drive item, found by id or else by its link.172
/// The reference a message needs to carry `file`: its drive item, found by id or else by its link.@@ -95,4 +208,34 @@ mod tests {95
assert_eq!((files[1].item_id.as_deref(), files[1].size), (Some("item-2"), 0));208
assert_eq!((files[1].item_id.as_deref(), files[1].size), (Some("item-2"), 0));96
assert!(files[1].last_opened.is_none());209
assert!(files[1].last_opened.is_none());97
}210
}211
212
#[test]213
fn shared_files_carry_the_sharer_and_date_newest_first() {214
let body = json!({"value": [215
{"name": "old.pdf", "webUrl": "https://x/o", "remoteItem": {"id": "o", "file": {}, "parentReference": {"driveId": "d"},216
"shared": {"sharedDateTime": "2026-10-01T10:00:00Z", "sharedBy": {"user": {"displayName": "Anna"}}}}},217
{"name": "Team", "webUrl": "https://x/t", "remoteItem": {"id": "t", "folder": {"childCount": 2}, "parentReference": {"driveId": "d"},218
"shared": {"sharedDateTime": "2026-11-01T10:00:00Z", "owner": {"user": {"displayName": "Ben"}}}}}219
]});220
let shared = parse_shared(&body);221
assert_eq!(shared[0].name, "Team");222
assert!(shared[0].is_folder());223
assert_eq!(shared[0].modified_by.as_deref(), Some("Ben"));224
assert_eq!(shared[1].modified_by.as_deref(), Some("Anna"));225
assert_eq!(CloudFile::from(&shared[1]).item_id.as_deref(), Some("o"));226
}227
228
#[test]229
fn recent_owners_and_sites() {230
let recent = json!({"value": [231
{"name": "a", "remoteItem": {"id": "1", "createdBy": {"user": {"displayName": "Cara"}},232
"webUrl": "https://t.sharepoint.com/sites/dev/a", "parentReference": {"siteId": "dev"}}},233
{"name": "b", "remoteItem": {"id": "2", "webUrl": "https://t-my.sharepoint.com/personal/x/b", "parentReference": {"siteId": "me"}}},234
{"name": "c", "remoteItem": {"id": "3", "webUrl": "https://t.sharepoint.com/sites/dev/c", "parentReference": {"siteId": "dev"}}},235
{"name": "d", "remoteItem": {"id": "4", "webUrl": "https://t.sharepoint.com/sites/ops/d", "sharepointIds": {"siteId": "ops"}}}236
]});237
assert_eq!(parse_recent_owners(&recent), vec![("1".to_owned(), "Cara".to_owned())]);238
assert_eq!(recent_site_ids(&recent, 8), ["dev", "ops"]);239
assert_eq!(recent_site_ids(&recent, 1), ["dev"]);240
}98
}241
}@@ -14,7 +14,7 @@ mod target;
14
14
mod urls;
15
15
mod writes;
16
16
17
pub use cloud_files::CloudFile;
17
pub use cloud_files::{CloudFile, QuickSite};
18
18
pub use client::{BATCH_SIZE, CHAT_PAGE_SIZE, Graph, MESSAGE_PAGE_SIZE};
19
19
pub use error::{Error, Result};
20
20
pub use files::{
@@ -14,7 +14,7 @@ mod target;14
mod urls;14
mod urls;15
mod writes;15
mod writes;16
16
17
pub use cloud_files::CloudFile;17
pub use cloud_files::{CloudFile, QuickSite};18
pub use client::{BATCH_SIZE, CHAT_PAGE_SIZE, Graph, MESSAGE_PAGE_SIZE};18
pub use client::{BATCH_SIZE, CHAT_PAGE_SIZE, Graph, MESSAGE_PAGE_SIZE};19
pub use error::{Error, Result};19
pub use error::{Error, Result};20
pub use files::{20
pub use files::{@@ -235,6 +235,22 @@ pub fn recent_drive_items(top: usize) -> String {
235
235
format!("{GRAPH}/v1.0/me/drive/recent?$top={top}")
236
236
}
237
237
238
pub fn my_drive() -> String {
239
format!("{GRAPH}/v1.0/me/drive?$select=id")
240
}
241
242
pub fn site_drive(site_id: &str) -> String {
243
format!("{GRAPH}/v1.0/sites/{}/drive?$select=id", segment(site_id))
244
}
245
246
pub fn shared_with_me() -> String {
247
format!("{GRAPH}/v1.0/me/drive/sharedWithMe?$top=100")
248
}
249
250
pub fn site(site_id: &str) -> String {
251
format!("{GRAPH}/v1.0/sites/{}?$select=id,displayName,webUrl", segment(site_id))
252
}
253
238
254
pub fn shared_drive_item(share_id: &str) -> String {
239
255
format!("{GRAPH}/v1.0/shares/{}/driveItem", segment(share_id))
240
256
}
@@ -235,6 +235,22 @@ pub fn recent_drive_items(top: usize) -> String {235
format!("{GRAPH}/v1.0/me/drive/recent?$top={top}")235
format!("{GRAPH}/v1.0/me/drive/recent?$top={top}")236
}236
}237
237
238
pub fn my_drive() -> String {239
format!("{GRAPH}/v1.0/me/drive?$select=id")240
}241
242
pub fn site_drive(site_id: &str) -> String {243
format!("{GRAPH}/v1.0/sites/{}/drive?$select=id", segment(site_id))244
}245
246
pub fn shared_with_me() -> String {247
format!("{GRAPH}/v1.0/me/drive/sharedWithMe?$top=100")248
}249
250
pub fn site(site_id: &str) -> String {251
format!("{GRAPH}/v1.0/sites/{}?$select=id,displayName,webUrl", segment(site_id))252
}253
238
pub fn shared_drive_item(share_id: &str) -> String {254
pub fn shared_drive_item(share_id: &str) -> String {239
format!("{GRAPH}/v1.0/shares/{}/driveItem", segment(share_id))255
format!("{GRAPH}/v1.0/shares/{}/driveItem", segment(share_id))240
}256
}