BlueGit

ict rusty-teams

fix(chat): guests can attach files in chats of a guest org (#76)

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Joachim Mild <joe@root-files.net>

metis Michael Wallner · pushed by metis

Authored 2026-11-25 · 6 days ago

Hash
8794b4c6b333ae79c3d27cd82fccd423f02243ec
Parent
35c95470
12 files changed +452 −99
crates/app-state/src/backend.rs +10 −4
@@ -189,12 +189,18 @@ async fn supervise(
189 189 };
190 190 tokio::spawn(org_list(home.clone(), guest_tenant.clone(), events.clone()));
191 191 // Calls stay on the home tenant's registration, like rings for the home org while a guest org is open.
192 let session = match &guest_tenant {
193 Some(tenant) => home.in_tenant(tenant),
194 None => home.clone(),
192 // Chat files of a guest org go to the home OneDrive: the guest tenant has none.
193 let (session, home_drive) = match &guest_tenant {
194 Some(tenant) => (home.in_tenant(tenant), Some(home.clone())),
195 None => (home.clone(), None),
195 196 };
196 197 let build = || {
197 SyncEngine::new(Graph::new(session.clone()), store.clone())
198 let graph = Graph::new(session.clone());
199 let graph = match &home_drive {
200 Some(home) => graph.with_home_drive(home.clone()),
201 None => graph,
202 };
203 SyncEngine::new(graph, store.clone())
198 204 .with_folder_source(Arc::new(ChatsvcFolderSource::new(&session)))
199 205 };
200 206 let engine = image_directory()
@@ -189,12 +189,18 @@ async fn supervise(
189 };
189 };
190 tokio::spawn(org_list(home.clone(), guest_tenant.clone(), events.clone()));
190 tokio::spawn(org_list(home.clone(), guest_tenant.clone(), events.clone()));
191 // Calls stay on the home tenant's registration, like rings for the home org while a guest org is open.
191 // Calls stay on the home tenant's registration, like rings for the home org while a guest org is open.
192 let session = match &guest_tenant {
192 // Chat files of a guest org go to the home OneDrive: the guest tenant has none.
193 Some(tenant) => home.in_tenant(tenant),
193 let (session, home_drive) = match &guest_tenant {
194 None => home.clone(),
194 Some(tenant) => (home.in_tenant(tenant), Some(home.clone())),
195 None => (home.clone(), None),
195 };
196 };
196 let build = || {
197 let build = || {
197 SyncEngine::new(Graph::new(session.clone()), store.clone())
198 let graph = Graph::new(session.clone());
199 let graph = match &home_drive {
200 Some(home) => graph.with_home_drive(home.clone()),
201 None => graph,
202 };
203 SyncEngine::new(graph, store.clone())
198 .with_folder_source(Arc::new(ChatsvcFolderSource::new(&session)))
204 .with_folder_source(Arc::new(ChatsvcFolderSource::new(&session)))
199 };
205 };
200 let engine = image_directory()
206 let engine = image_directory()
crates/app/src/views/attachment_tray.rs +76 −6
@@ -22,6 +22,8 @@ pub const INLINE_IMAGE_MAX_BYTES: u64 = 1024 * 1024;
22 22 pub const INLINE_TOTAL_MAX_BYTES: u64 = 5 * 512 * 1024;
23 23 pub const MAX_FILE_BYTES: u64 = 250 * 1024 * 1024;
24 24 pub const FILES_LATER_NOTICE: &str = "Files can be added once the chat exists.";
25 pub const NOT_SHARED_NOTICE: &str =
26 "Your organization does not allow sharing with this chat. People may need to request access.";
25 27 const PASTED_IMAGE_STEM: &str = "pasted-image";
26 28 const PREVIEW_HEIGHT: f32 = 120.;
27 29 const PREVIEW_GAP: f32 = 4.;
@@ -94,10 +96,43 @@ pub struct DoneFile {
94 96 #[derive(Debug, Clone, PartialEq, Eq)]
95 97 pub enum UploadResult {
96 98 Done(DoneFile),
99 /// Sent without access for the chat members, like Teams does for a guest's file that the
100 /// home tenant may not share outside.
101 NotShared(DoneFile),
97 102 ShareFailed(UploadedFile),
98 103 Failed,
99 104 }
100 105
106 /// How a share ended, separate from the Graph error so the tray can be tested without a session.
107 pub(crate) enum ShareEnd {
108 Linked(Option<String>),
109 Denied,
110 Failed,
111 }
112
113 pub(crate) fn result_of_share(
114 uploaded: UploadedFile,
115 mut reference: FileReference,
116 end: ShareEnd,
117 ) -> UploadResult {
118 match end {
119 ShareEnd::Linked(link) => {
120 if let Some(link) = link.filter(|link| !link.is_empty()) {
121 reference.content_url = link;
122 }
123 UploadResult::Done(DoneFile {
124 reference,
125 uploaded: Some(uploaded),
126 })
127 }
128 ShareEnd::Denied => UploadResult::NotShared(DoneFile {
129 reference,
130 uploaded: Some(uploaded),
131 }),
132 ShareEnd::Failed => UploadResult::ShareFailed(uploaded),
133 }
134 }
135
101 136 impl UploadState {
102 137 fn uploaded(&self) -> Option<UploadedFile> {
103 138 match self {
@@ -389,19 +424,23 @@ impl AttachmentTray {
389 424 pub fn finish_upload(&mut self, id: u64, result: UploadResult) -> Option<UploadedFile> {
390 425 if !self.items.iter().any(|item| item.id == id) {
391 426 return match result {
392 UploadResult::Done(done) => done.uploaded,
427 UploadResult::Done(done) | UploadResult::NotShared(done) => done.uploaded,
393 428 UploadResult::ShareFailed(uploaded) => Some(uploaded),
394 429 UploadResult::Failed => None,
395 430 };
396 431 }
432 let not_shared = matches!(result, UploadResult::NotShared(_));
397 433 if let Some(ItemKind::File { upload, .. }) = self.kind_of_mut(id)
398 434 && matches!(upload, UploadState::Uploading(_) | UploadState::Sharing(_))
399 435 {
400 436 *upload = match result {
401 UploadResult::Done(done) => UploadState::Done(done),
437 UploadResult::Done(done) | UploadResult::NotShared(done) => UploadState::Done(done),
402 438 UploadResult::ShareFailed(uploaded) => UploadState::ShareFailed(uploaded),
403 439 UploadResult::Failed => UploadState::Failed,
404 440 };
441 if not_shared {
442 self.notice = Some(NOT_SHARED_NOTICE.to_owned());
443 }
405 444 }
406 445 None
407 446 }
@@ -950,10 +989,10 @@ mod tests {
950 989
951 990 use super::{
952 991 AttachmentTray, Classification, DoneFile, FILES_LATER_NOTICE, INLINE_IMAGE_MAX_BYTES,
953 INLINE_TOTAL_MAX_BYTES, InlineFormat, ItemKind, LoadedFile, MAX_ATTACHMENTS, OutgoingImage,
954 PasteAction, PreviewImage, RemoteImage, Tone, UploadResult, chip_state, classify,
955 limit_notice, paste_action, pasted_image_name, prepare_pasted_image, preview_size,
956 read_attachment, sniff_inline_format,
992 INLINE_TOTAL_MAX_BYTES, InlineFormat, ItemKind, LoadedFile, MAX_ATTACHMENTS,
993 NOT_SHARED_NOTICE, OutgoingImage, PasteAction, PreviewImage, RemoteImage, ShareEnd, Tone,
994 UploadResult, chip_state, classify, limit_notice, paste_action, pasted_image_name,
995 prepare_pasted_image, preview_size, read_attachment, result_of_share, sniff_inline_format,
957 996 };
958 997 use crate::remote_image::RemoteKind;
959 998
@@ -995,6 +1034,7 @@ mod tests {
995 1034 web_url: "https://x".into(),
996 1035 web_dav_url: None,
997 1036 etag: "\"{G},1\"".into(),
1037 home_drive: false,
998 1038 }
999 1039 }
1000 1040
@@ -1312,6 +1352,36 @@ mod tests {
1312 1352 assert!(!tray.blocks_send());
1313 1353 }
1314 1354
1355 #[test]
1356 fn only_a_denied_share_sends_the_file_with_the_notice() {
1357 let uploaded = sample_upload();
1358 let reference = reference("plan.pdf");
1359 let denied = result_of_share(uploaded.clone(), reference.clone(), ShareEnd::Denied);
1360 assert!(matches!(denied, UploadResult::NotShared(_)));
1361 let failed = result_of_share(uploaded.clone(), reference.clone(), ShareEnd::Failed);
1362 assert!(matches!(failed, UploadResult::ShareFailed(_)));
1363 let UploadResult::Done(done) = result_of_share(
1364 uploaded,
1365 reference,
1366 ShareEnd::Linked(Some("https://files.example/share".into())),
1367 ) else {
1368 panic!("a sharing link finishes the upload");
1369 };
1370 assert_eq!(done.reference.content_url, "https://files.example/share");
1371 }
1372
1373 #[test]
1374 fn a_file_that_could_not_be_shared_still_goes_out_with_a_notice() {
1375 let (mut tray, id) = tray_with_file();
1376 let UploadResult::Done(done) = done("plan.pdf") else {
1377 unreachable!()
1378 };
1379 tray.finish_upload(id, UploadResult::NotShared(done));
1380 assert!(!tray.blocks_send());
1381 assert_eq!(tray.outgoing_files().len(), 1);
1382 assert_eq!(tray.notice(), Some(NOT_SHARED_NOTICE));
1383 }
1384
1315 1385 #[test]
1316 1386 fn a_failed_upload_blocks_sending_until_it_is_retried_or_removed() {
1317 1387 let (mut tray, id) = tray_with_file();
@@ -22,6 +22,8 @@ pub const INLINE_IMAGE_MAX_BYTES: u64 = 1024 * 1024;
22pub const INLINE_TOTAL_MAX_BYTES: u64 = 5 * 512 * 1024;
22pub const INLINE_TOTAL_MAX_BYTES: u64 = 5 * 512 * 1024;
23pub const MAX_FILE_BYTES: u64 = 250 * 1024 * 1024;
23pub const MAX_FILE_BYTES: u64 = 250 * 1024 * 1024;
24pub const FILES_LATER_NOTICE: &str = "Files can be added once the chat exists.";
24pub const FILES_LATER_NOTICE: &str = "Files can be added once the chat exists.";
25pub const NOT_SHARED_NOTICE: &str =
26 "Your organization does not allow sharing with this chat. People may need to request access.";
25const PASTED_IMAGE_STEM: &str = "pasted-image";
27const PASTED_IMAGE_STEM: &str = "pasted-image";
26const PREVIEW_HEIGHT: f32 = 120.;
28const PREVIEW_HEIGHT: f32 = 120.;
27const PREVIEW_GAP: f32 = 4.;
29const PREVIEW_GAP: f32 = 4.;
@@ -94,10 +96,43 @@ pub struct DoneFile {
94#[derive(Debug, Clone, PartialEq, Eq)]
96#[derive(Debug, Clone, PartialEq, Eq)]
95pub enum UploadResult {
97pub enum UploadResult {
96 Done(DoneFile),
98 Done(DoneFile),
99 /// Sent without access for the chat members, like Teams does for a guest's file that the
100 /// home tenant may not share outside.
101 NotShared(DoneFile),
97 ShareFailed(UploadedFile),
102 ShareFailed(UploadedFile),
98 Failed,
103 Failed,
99}
104}
100
105
106/// How a share ended, separate from the Graph error so the tray can be tested without a session.
107pub(crate) enum ShareEnd {
108 Linked(Option<String>),
109 Denied,
110 Failed,
111}
112
113pub(crate) fn result_of_share(
114 uploaded: UploadedFile,
115 mut reference: FileReference,
116 end: ShareEnd,
117) -> UploadResult {
118 match end {
119 ShareEnd::Linked(link) => {
120 if let Some(link) = link.filter(|link| !link.is_empty()) {
121 reference.content_url = link;
122 }
123 UploadResult::Done(DoneFile {
124 reference,
125 uploaded: Some(uploaded),
126 })
127 }
128 ShareEnd::Denied => UploadResult::NotShared(DoneFile {
129 reference,
130 uploaded: Some(uploaded),
131 }),
132 ShareEnd::Failed => UploadResult::ShareFailed(uploaded),
133 }
134}
135
101impl UploadState {
136impl UploadState {
102 fn uploaded(&self) -> Option<UploadedFile> {
137 fn uploaded(&self) -> Option<UploadedFile> {
103 match self {
138 match self {
@@ -389,19 +424,23 @@ impl AttachmentTray {
389 pub fn finish_upload(&mut self, id: u64, result: UploadResult) -> Option<UploadedFile> {
424 pub fn finish_upload(&mut self, id: u64, result: UploadResult) -> Option<UploadedFile> {
390 if !self.items.iter().any(|item| item.id == id) {
425 if !self.items.iter().any(|item| item.id == id) {
391 return match result {
426 return match result {
392 UploadResult::Done(done) => done.uploaded,
427 UploadResult::Done(done) | UploadResult::NotShared(done) => done.uploaded,
393 UploadResult::ShareFailed(uploaded) => Some(uploaded),
428 UploadResult::ShareFailed(uploaded) => Some(uploaded),
394 UploadResult::Failed => None,
429 UploadResult::Failed => None,
395 };
430 };
396 }
431 }
432 let not_shared = matches!(result, UploadResult::NotShared(_));
397 if let Some(ItemKind::File { upload, .. }) = self.kind_of_mut(id)
433 if let Some(ItemKind::File { upload, .. }) = self.kind_of_mut(id)
398 && matches!(upload, UploadState::Uploading(_) | UploadState::Sharing(_))
434 && matches!(upload, UploadState::Uploading(_) | UploadState::Sharing(_))
399 {
435 {
400 *upload = match result {
436 *upload = match result {
401 UploadResult::Done(done) => UploadState::Done(done),
437 UploadResult::Done(done) | UploadResult::NotShared(done) => UploadState::Done(done),
402 UploadResult::ShareFailed(uploaded) => UploadState::ShareFailed(uploaded),
438 UploadResult::ShareFailed(uploaded) => UploadState::ShareFailed(uploaded),
403 UploadResult::Failed => UploadState::Failed,
439 UploadResult::Failed => UploadState::Failed,
404 };
440 };
441 if not_shared {
442 self.notice = Some(NOT_SHARED_NOTICE.to_owned());
443 }
405 }
444 }
406 None
445 None
407 }
446 }
@@ -950,10 +989,10 @@ mod tests {
950
989
951 use super::{
990 use super::{
952 AttachmentTray, Classification, DoneFile, FILES_LATER_NOTICE, INLINE_IMAGE_MAX_BYTES,
991 AttachmentTray, Classification, DoneFile, FILES_LATER_NOTICE, INLINE_IMAGE_MAX_BYTES,
953 INLINE_TOTAL_MAX_BYTES, InlineFormat, ItemKind, LoadedFile, MAX_ATTACHMENTS, OutgoingImage,
992 INLINE_TOTAL_MAX_BYTES, InlineFormat, ItemKind, LoadedFile, MAX_ATTACHMENTS,
954 PasteAction, PreviewImage, RemoteImage, Tone, UploadResult, chip_state, classify,
993 NOT_SHARED_NOTICE, OutgoingImage, PasteAction, PreviewImage, RemoteImage, ShareEnd, Tone,
955 limit_notice, paste_action, pasted_image_name, prepare_pasted_image, preview_size,
994 UploadResult, chip_state, classify, limit_notice, paste_action, pasted_image_name,
956 read_attachment, sniff_inline_format,
995 prepare_pasted_image, preview_size, read_attachment, result_of_share, sniff_inline_format,
957 };
996 };
958 use crate::remote_image::RemoteKind;
997 use crate::remote_image::RemoteKind;
959
998
@@ -995,6 +1034,7 @@ mod tests {
995 web_url: "https://x".into(),
1034 web_url: "https://x".into(),
996 web_dav_url: None,
1035 web_dav_url: None,
997 etag: "\"{G},1\"".into(),
1036 etag: "\"{G},1\"".into(),
1037 home_drive: false,
998 }
1038 }
999 }
1039 }
1000
1040
@@ -1312,6 +1352,36 @@ mod tests {
1312 assert!(!tray.blocks_send());
1352 assert!(!tray.blocks_send());
1313 }
1353 }
1314
1354
1355 #[test]
1356 fn only_a_denied_share_sends_the_file_with_the_notice() {
1357 let uploaded = sample_upload();
1358 let reference = reference("plan.pdf");
1359 let denied = result_of_share(uploaded.clone(), reference.clone(), ShareEnd::Denied);
1360 assert!(matches!(denied, UploadResult::NotShared(_)));
1361 let failed = result_of_share(uploaded.clone(), reference.clone(), ShareEnd::Failed);
1362 assert!(matches!(failed, UploadResult::ShareFailed(_)));
1363 let UploadResult::Done(done) = result_of_share(
1364 uploaded,
1365 reference,
1366 ShareEnd::Linked(Some("https://files.example/share".into())),
1367 ) else {
1368 panic!("a sharing link finishes the upload");
1369 };
1370 assert_eq!(done.reference.content_url, "https://files.example/share");
1371 }
1372
1373 #[test]
1374 fn a_file_that_could_not_be_shared_still_goes_out_with_a_notice() {
1375 let (mut tray, id) = tray_with_file();
1376 let UploadResult::Done(done) = done("plan.pdf") else {
1377 unreachable!()
1378 };
1379 tray.finish_upload(id, UploadResult::NotShared(done));
1380 assert!(!tray.blocks_send());
1381 assert_eq!(tray.outgoing_files().len(), 1);
1382 assert_eq!(tray.notice(), Some(NOT_SHARED_NOTICE));
1383 }
1384
1315 #[test]
1385 #[test]
1316 fn a_failed_upload_blocks_sending_until_it_is_retried_or_removed() {
1386 fn a_failed_upload_blocks_sending_until_it_is_retried_or_removed() {
1317 let (mut tray, id) = tray_with_file();
1387 let (mut tray, id) = tray_with_file();
crates/app/src/views/composer.rs +23 −8
@@ -2296,7 +2296,12 @@ impl Composer {
2296 2296 let _ = event_sender.send(UploadEvent::Uploaded(uploaded.clone()));
2297 2297 uploaded
2298 2298 }
2299 Err(_) => return UploadResult::Failed,
2299 Err(error) => {
2300 app_base::diagnostics::record(format!(
2301 "attachments: upload failed: {error}"
2302 ));
2303 return UploadResult::Failed;
2304 }
2300 2305 }
2301 2306 }
2302 2307 JobKind::Share(uploaded) => uploaded,
@@ -2304,13 +2309,23 @@ impl Composer {
2304 2309 let Some(reference) = uploaded.reference() else {
2305 2310 return UploadResult::Failed;
2306 2311 };
2307 match engine.share_attachment(&conversation_id, &uploaded).await {
2308 Ok(()) => UploadResult::Done(DoneFile {
2309 reference,
2310 uploaded: Some(uploaded),
2311 }),
2312 Err(_) => UploadResult::ShareFailed(uploaded),
2313 }
2312 let end = match engine.share_attachment(&conversation_id, &uploaded).await {
2313 Ok(link) => super::attachment_tray::ShareEnd::Linked(link),
2314 Err(error) => {
2315 app_base::diagnostics::record(format!(
2316 "attachments: share failed: {error}"
2317 ));
2318 if matches!(
2319 error,
2320 teams_core::Error::Graph(graph::Error::SharingDenied(_))
2321 ) {
2322 super::attachment_tray::ShareEnd::Denied
2323 } else {
2324 super::attachment_tray::ShareEnd::Failed
2325 }
2326 }
2327 };
2328 super::attachment_tray::result_of_share(uploaded, reference, end)
2314 2329 }
2315 2330 .await;
2316 2331 let _ = finished_sender.send(UploadEvent::Finished(result));
@@ -2296,7 +2296,12 @@ impl Composer {
2296 let _ = event_sender.send(UploadEvent::Uploaded(uploaded.clone()));
2296 let _ = event_sender.send(UploadEvent::Uploaded(uploaded.clone()));
2297 uploaded
2297 uploaded
2298 }
2298 }
2299 Err(_) => return UploadResult::Failed,
2299 Err(error) => {
2300 app_base::diagnostics::record(format!(
2301 "attachments: upload failed: {error}"
2302 ));
2303 return UploadResult::Failed;
2304 }
2300 }
2305 }
2301 }
2306 }
2302 JobKind::Share(uploaded) => uploaded,
2307 JobKind::Share(uploaded) => uploaded,
@@ -2304,13 +2309,23 @@ impl Composer {
2304 let Some(reference) = uploaded.reference() else {
2309 let Some(reference) = uploaded.reference() else {
2305 return UploadResult::Failed;
2310 return UploadResult::Failed;
2306 };
2311 };
2307 match engine.share_attachment(&conversation_id, &uploaded).await {
2312 let end = match engine.share_attachment(&conversation_id, &uploaded).await {
2308 Ok(()) => UploadResult::Done(DoneFile {
2313 Ok(link) => super::attachment_tray::ShareEnd::Linked(link),
2309 reference,
2314 Err(error) => {
2310 uploaded: Some(uploaded),
2315 app_base::diagnostics::record(format!(
2311 }),
2316 "attachments: share failed: {error}"
2312 Err(_) => UploadResult::ShareFailed(uploaded),
2317 ));
2313 }
2318 if matches!(
2319 error,
2320 teams_core::Error::Graph(graph::Error::SharingDenied(_))
2321 ) {
2322 super::attachment_tray::ShareEnd::Denied
2323 } else {
2324 super::attachment_tray::ShareEnd::Failed
2325 }
2326 }
2327 };
2328 super::attachment_tray::result_of_share(uploaded, reference, end)
2314 }
2329 }
2315 .await;
2330 .await;
2316 let _ = finished_sender.send(UploadEvent::Finished(result));
2331 let _ = finished_sender.send(UploadEvent::Finished(result));
crates/core/src/actions.rs +42 −7
@@ -1,8 +1,8 @@
1 1 use chatsvc::{ConversationRef, read_horizon};
2 2 use chrono::{DateTime, Duration, Utc};
3 3 use graph::{
4 FileReference, MessageExtras, MessageTarget, OutgoingMention, UploadDestination, UploadedFile,
5 hosted_image_order,
4 FileReference, MessageExtras, MessageTarget, OutgoingMention, Recipient, UploadDestination,
5 UploadedFile, hosted_image_order,
6 6 };
7 7 use store::MessageRecord;
8 8
@@ -264,8 +264,12 @@ impl<R: Remote> SyncEngine<R> {
264 264 let uploaded = self
265 265 .upload_attachment_file(conversation_id, file_name, bytes, progress)
266 266 .await?;
267 self.share_attachment(conversation_id, &uploaded).await?;
268 uploaded.reference().ok_or_else(missing_attachment_id)
267 let link = self.share_attachment(conversation_id, &uploaded).await?;
268 let mut reference = uploaded.reference().ok_or_else(missing_attachment_id)?;
269 if let Some(link) = link.filter(|link| !link.is_empty()) {
270 reference.content_url = link;
271 }
272 Ok(reference)
269 273 }
270 274
271 275 /// Chat files go to the sender's "Microsoft Teams Chat Files", channel files to the channel's folder.
@@ -294,16 +298,47 @@ impl<R: Remote> SyncEngine<R> {
294 298 }
295 299
296 300 /// Read-only for the other chat members; channels need nothing.
301 /// `Some` is a sharing link that the chat message should carry instead of the item URL.
297 302 pub async fn share_attachment(
298 303 &self,
299 304 conversation_id: &str,
300 305 uploaded: &UploadedFile,
301 ) -> Result<()> {
306 ) -> Result<Option<String>> {
302 307 if !matches!(self.resolve(conversation_id).await?, Conversation::Chat) {
303 return Ok(());
308 return Ok(None);
304 309 }
305 310 let other_members = self.other_member_ids(conversation_id).await?;
306 self.remote.share_file(uploaded, &other_members).await
311 let recipients = if uploaded.home_drive {
312 let emails = self.member_emails(conversation_id, &other_members).await?;
313 // Bots and members Graph lists without an email cannot be invited in the home
314 // tenant. Sending then would post a file nobody can open, with no notice.
315 if emails.is_empty() && !other_members.is_empty() {
316 return Err(graph::Error::SharingDenied(
317 "no chat member has an email the home tenant can invite".into(),
318 )
319 .into());
320 }
321 emails
322 } else {
323 other_members.into_iter().map(Recipient::ObjectId).collect()
324 };
325 self.remote.share_file(uploaded, &recipients).await
326 }
327
328 /// The home tenant does not know the guest org's user ids, so a file there is shared by email.
329 /// Members without an email, such as bots, cannot be invited and are left out.
330 async fn member_emails(&self, chat_id: &str, user_ids: &[String]) -> Result<Vec<Recipient>> {
331 let members = self.remote.chat_members(chat_id).await?;
332 Ok(members
333 .into_iter()
334 .filter(|member| {
335 member
336 .user_id
337 .as_ref()
338 .is_some_and(|user_id| user_ids.contains(user_id))
339 })
340 .filter_map(|member| member.email.map(Recipient::Email))
341 .collect())
307 342 }
308 343
309 344 pub async fn discard_attachment(&self, uploaded: &UploadedFile) -> Result<()> {
@@ -1,8 +1,8 @@
1use chatsvc::{ConversationRef, read_horizon};
1use chatsvc::{ConversationRef, read_horizon};
2use chrono::{DateTime, Duration, Utc};
2use chrono::{DateTime, Duration, Utc};
3use graph::{
3use graph::{
4 FileReference, MessageExtras, MessageTarget, OutgoingMention, UploadDestination, UploadedFile,
4 FileReference, MessageExtras, MessageTarget, OutgoingMention, Recipient, UploadDestination,
5 hosted_image_order,
5 UploadedFile, hosted_image_order,
6};
6};
7use store::MessageRecord;
7use store::MessageRecord;
8
8
@@ -264,8 +264,12 @@ impl<R: Remote> SyncEngine<R> {
264 let uploaded = self
264 let uploaded = self
265 .upload_attachment_file(conversation_id, file_name, bytes, progress)
265 .upload_attachment_file(conversation_id, file_name, bytes, progress)
266 .await?;
266 .await?;
267 self.share_attachment(conversation_id, &uploaded).await?;
267 let link = self.share_attachment(conversation_id, &uploaded).await?;
268 uploaded.reference().ok_or_else(missing_attachment_id)
268 let mut reference = uploaded.reference().ok_or_else(missing_attachment_id)?;
269 if let Some(link) = link.filter(|link| !link.is_empty()) {
270 reference.content_url = link;
271 }
272 Ok(reference)
269 }
273 }
270
274
271 /// Chat files go to the sender's "Microsoft Teams Chat Files", channel files to the channel's folder.
275 /// Chat files go to the sender's "Microsoft Teams Chat Files", channel files to the channel's folder.
@@ -294,16 +298,47 @@ impl<R: Remote> SyncEngine<R> {
294 }
298 }
295
299
296 /// Read-only for the other chat members; channels need nothing.
300 /// Read-only for the other chat members; channels need nothing.
301 /// `Some` is a sharing link that the chat message should carry instead of the item URL.
297 pub async fn share_attachment(
302 pub async fn share_attachment(
298 &self,
303 &self,
299 conversation_id: &str,
304 conversation_id: &str,
300 uploaded: &UploadedFile,
305 uploaded: &UploadedFile,
301 ) -> Result<()> {
306 ) -> Result<Option<String>> {
302 if !matches!(self.resolve(conversation_id).await?, Conversation::Chat) {
307 if !matches!(self.resolve(conversation_id).await?, Conversation::Chat) {
303 return Ok(());
308 return Ok(None);
304 }
309 }
305 let other_members = self.other_member_ids(conversation_id).await?;
310 let other_members = self.other_member_ids(conversation_id).await?;
306 self.remote.share_file(uploaded, &other_members).await
311 let recipients = if uploaded.home_drive {
312 let emails = self.member_emails(conversation_id, &other_members).await?;
313 // Bots and members Graph lists without an email cannot be invited in the home
314 // tenant. Sending then would post a file nobody can open, with no notice.
315 if emails.is_empty() && !other_members.is_empty() {
316 return Err(graph::Error::SharingDenied(
317 "no chat member has an email the home tenant can invite".into(),
318 )
319 .into());
320 }
321 emails
322 } else {
323 other_members.into_iter().map(Recipient::ObjectId).collect()
324 };
325 self.remote.share_file(uploaded, &recipients).await
326 }
327
328 /// The home tenant does not know the guest org's user ids, so a file there is shared by email.
329 /// Members without an email, such as bots, cannot be invited and are left out.
330 async fn member_emails(&self, chat_id: &str, user_ids: &[String]) -> Result<Vec<Recipient>> {
331 let members = self.remote.chat_members(chat_id).await?;
332 Ok(members
333 .into_iter()
334 .filter(|member| {
335 member
336 .user_id
337 .as_ref()
338 .is_some_and(|user_id| user_ids.contains(user_id))
339 })
340 .filter_map(|member| member.email.map(Recipient::Email))
341 .collect())
307 }
342 }
308
343
309 pub async fn discard_attachment(&self, uploaded: &UploadedFile) -> Result<()> {
344 pub async fn discard_attachment(&self, uploaded: &UploadedFile) -> Result<()> {
crates/core/src/lib.rs +1 −1
@@ -162,7 +162,7 @@ pub use forwarded::{
162 162 };
163 163 pub use graph::{
164 164 CloudFile, DriveEntry, DriveFolder, FileReference, HostedImage, KeptAttachment, MentionTarget,
165 MessageExtras, QuickSite, SharedFile, UploadedFile,
165 MessageExtras, QuickSite, Recipient, SharedFile, UploadedFile,
166 166 };
167 167 pub use images::StoredImage;
168 168 pub use jumbo::{JumboEmoji, MAX_JUMBO_EMOJI, jumbo_emoji};
@@ -162,7 +162,7 @@ pub use forwarded::{
162};
162};
163pub use graph::{
163pub use graph::{
164 CloudFile, DriveEntry, DriveFolder, FileReference, HostedImage, KeptAttachment, MentionTarget,
164 CloudFile, DriveEntry, DriveFolder, FileReference, HostedImage, KeptAttachment, MentionTarget,
165 MessageExtras, QuickSite, SharedFile, UploadedFile,
165 MessageExtras, QuickSite, Recipient, SharedFile, UploadedFile,
166};
166};
167pub use images::StoredImage;
167pub use images::StoredImage;
168pub use jumbo::{JumboEmoji, MAX_JUMBO_EMOJI, jumbo_emoji};
168pub use jumbo::{JumboEmoji, MAX_JUMBO_EMOJI, jumbo_emoji};
crates/core/src/remote.rs +13 −5
@@ -24,7 +24,7 @@ use chatsvc::{
24 24 use chrono::{DateTime, Utc};
25 25 use graph::{
26 26 Channel, Chat, CloudFile, DriveEntry, DriveFolder, Graph, Member, Message, MessageExtras,
27 MessageTarget, OutgoingMention, Photo, Presence, QuickSite, SharedFile, Tag, Team,
27 MessageTarget, OutgoingMention, Photo, Presence, QuickSite, Recipient, SharedFile, Tag, Team,
28 28 UploadDestination, UploadedFile, User,
29 29 };
30 30
@@ -245,7 +245,11 @@ pub trait Remote {
245 245 Err(Error::Unsupported("a file upload"))
246 246 }
247 247
248 async fn share_file(&self, _file: &UploadedFile, _user_ids: &[String]) -> Result<()> {
248 async fn share_file(
249 &self,
250 _file: &UploadedFile,
251 _recipients: &[Recipient],
252 ) -> Result<Option<String>> {
249 253 Err(Error::Unsupported("sharing a file"))
250 254 }
251 255
@@ -1121,8 +1125,12 @@ impl Remote for Graph {
1121 1125 Ok(Graph::upload_file(self, destination, file_name, bytes, progress).await?)
1122 1126 }
1123 1127
1124 async fn share_file(&self, file: &UploadedFile, user_ids: &[String]) -> Result<()> {
1125 Ok(Graph::share_item(self, file, user_ids).await?)
1128 async fn share_file(
1129 &self,
1130 file: &UploadedFile,
1131 recipients: &[Recipient],
1132 ) -> Result<Option<String>> {
1133 Ok(Graph::share_item(self, file, recipients).await?)
1126 1134 }
1127 1135
1128 1136 async fn recent_files(&self, top: usize) -> Result<Vec<CloudFile>> {
@@ -1153,7 +1161,7 @@ impl Remote for Graph {
1153 1161 }
1154 1162
1155 1163 async fn delete_file(&self, file: &UploadedFile) -> Result<()> {
1156 Ok(Graph::delete_drive_item(self, &file.drive_id, &file.item_id).await?)
1164 Ok(Graph::delete_uploaded(self, file).await?)
1157 1165 }
1158 1166
1159 1167 async fn resolve_share(&self, open_url: &str) -> Result<SharedFile> {
@@ -24,7 +24,7 @@ use chatsvc::{
24use chrono::{DateTime, Utc};
24use chrono::{DateTime, Utc};
25use graph::{
25use graph::{
26 Channel, Chat, CloudFile, DriveEntry, DriveFolder, Graph, Member, Message, MessageExtras,
26 Channel, Chat, CloudFile, DriveEntry, DriveFolder, Graph, Member, Message, MessageExtras,
27 MessageTarget, OutgoingMention, Photo, Presence, QuickSite, SharedFile, Tag, Team,
27 MessageTarget, OutgoingMention, Photo, Presence, QuickSite, Recipient, SharedFile, Tag, Team,
28 UploadDestination, UploadedFile, User,
28 UploadDestination, UploadedFile, User,
29};
29};
30
30
@@ -245,7 +245,11 @@ pub trait Remote {
245 Err(Error::Unsupported("a file upload"))
245 Err(Error::Unsupported("a file upload"))
246 }
246 }
247
247
248 async fn share_file(&self, _file: &UploadedFile, _user_ids: &[String]) -> Result<()> {
248 async fn share_file(
249 &self,
250 _file: &UploadedFile,
251 _recipients: &[Recipient],
252 ) -> Result<Option<String>> {
249 Err(Error::Unsupported("sharing a file"))
253 Err(Error::Unsupported("sharing a file"))
250 }
254 }
251
255
@@ -1121,8 +1125,12 @@ impl Remote for Graph {
1121 Ok(Graph::upload_file(self, destination, file_name, bytes, progress).await?)
1125 Ok(Graph::upload_file(self, destination, file_name, bytes, progress).await?)
1122 }
1126 }
1123
1127
1124 async fn share_file(&self, file: &UploadedFile, user_ids: &[String]) -> Result<()> {
1128 async fn share_file(
1125 Ok(Graph::share_item(self, file, user_ids).await?)
1129 &self,
1130 file: &UploadedFile,
1131 recipients: &[Recipient],
1132 ) -> Result<Option<String>> {
1133 Ok(Graph::share_item(self, file, recipients).await?)
1126 }
1134 }
1127
1135
1128 async fn recent_files(&self, top: usize) -> Result<Vec<CloudFile>> {
1136 async fn recent_files(&self, top: usize) -> Result<Vec<CloudFile>> {
@@ -1153,7 +1161,7 @@ impl Remote for Graph {
1153 }
1161 }
1154
1162
1155 async fn delete_file(&self, file: &UploadedFile) -> Result<()> {
1163 async fn delete_file(&self, file: &UploadedFile) -> Result<()> {
1156 Ok(Graph::delete_drive_item(self, &file.drive_id, &file.item_id).await?)
1164 Ok(Graph::delete_uploaded(self, file).await?)
1157 }
1165 }
1158
1166
1159 async fn resolve_share(&self, open_url: &str) -> Result<SharedFile> {
1167 async fn resolve_share(&self, open_url: &str) -> Result<SharedFile> {
crates/core/tests/engine.rs +63 −4
@@ -5,7 +5,8 @@ use chatsvc::ConversationRef;
5 5 use chrono::{DateTime, Duration, TimeZone, Utc};
6 6 use graph::{
7 7 Channel, Chat, DriveFolder, HostedImage, Member, Message, MessageExtras, MessageTarget,
8 OutgoingMention, Photo, Presence, SharedFile, Team, UploadDestination, UploadedFile, User,
8 OutgoingMention, Photo, Presence, Recipient, SharedFile, Team, UploadDestination, UploadedFile,
9 User,
9 10 };
10 11 use serde_json::json;
11 12 use store::{
@@ -137,6 +138,7 @@ struct Fake {
137 138 window_requests: Mutex<Vec<(String, chatsvc::WindowDirection)>>,
138 139 search_identities: Mutex<Vec<substrate_search::SearchIdentity>>,
139 140 member_requests: Mutex<Vec<String>>,
141 omit_member_email: Mutex<bool>,
140 142 activity_feed: Mutex<chatsvc::ActivitySnapshot>,
141 143 app_channel_horizon_ms: Mutex<i64>,
142 144 }
@@ -268,11 +270,20 @@ impl Remote for Handle {
268 270 .lock()
269 271 .unwrap()
270 272 .push(chat_id.to_owned());
273 let ada = if *self.omit_member_email.lock().unwrap() {
274 json!({"userId": "user-ada", "tenantId": "tenant-1", "displayName": "Ada Example"})
275 } else {
276 json!({
277 "userId": "user-ada", "tenantId": "tenant-1", "displayName": "Ada Example",
278 "email": "ada@example.com"
279 })
280 };
271 281 Ok(vec![
272 282 serde_json::from_value(
273 283 json!({"userId": ME, "tenantId": "tenant-1", "displayName": "Me Myself"}),
274 284 )
275 285 .unwrap(),
286 serde_json::from_value(ada).unwrap(),
276 287 ])
277 288 }
278 289
@@ -768,6 +779,7 @@ impl Remote for Handle {
768 779 web_url: "https://files.example/web".into(),
769 780 web_dav_url: Some("https://files.example/dav".into()),
770 781 etag: "\"{GUID-1},2\"".into(),
782 home_drive: false,
771 783 })
772 784 }
773 785
@@ -813,9 +825,21 @@ impl Remote for Handle {
813 825 Ok(vec![7; length as usize])
814 826 }
815 827
816 async fn share_file(&self, file: &UploadedFile, user_ids: &[String]) -> Result<()> {
817 self.record(format!("share {} {}", file.item_id, user_ids.join(",")));
818 Ok(())
828 async fn share_file(
829 &self,
830 file: &UploadedFile,
831 recipients: &[Recipient],
832 ) -> Result<Option<String>> {
833 let recipients: Vec<&str> = recipients
834 .iter()
835 .map(|recipient| match recipient {
836 Recipient::ObjectId(id) | Recipient::Email(id) => id.as_str(),
837 })
838 .collect();
839 self.record(format!("share {} {}", file.item_id, recipients.join(",")));
840 Ok(file
841 .home_drive
842 .then(|| "https://files.example/share".to_owned()))
819 843 }
820 844
821 845 async fn external_image(&self, url: &str) -> Result<Photo> {
@@ -2265,9 +2289,44 @@ fn uploaded() -> UploadedFile {
2265 2289 web_url: "https://files.example/web".into(),
2266 2290 web_dav_url: None,
2267 2291 etag: "\"{GUID-1},2\"".into(),
2292 home_drive: false,
2268 2293 }
2269 2294 }
2270 2295
2296 #[tokio::test]
2297 async fn a_file_in_the_home_drive_is_shared_by_email() {
2298 let fake = Arc::new(Fake::default());
2299 let engine = chat_engine(&fake, small_pages()).await;
2300 let file = UploadedFile {
2301 home_drive: true,
2302 ..uploaded()
2303 };
2304 let link = engine.share_attachment(CHAT, &file).await.unwrap();
2305 assert_eq!(link.as_deref(), Some("https://files.example/share"));
2306 assert!(
2307 fake.calls()
2308 .contains(&"share item-1 ada@example.com".to_owned())
2309 );
2310 }
2311
2312 #[tokio::test]
2313 async fn a_home_drive_file_is_not_sent_as_shared_when_nobody_has_an_email() {
2314 let fake = Arc::new(Fake::default());
2315 *fake.omit_member_email.lock().unwrap() = true;
2316 let engine = chat_engine(&fake, small_pages()).await;
2317 let file = UploadedFile {
2318 home_drive: true,
2319 ..uploaded()
2320 };
2321
2322 let error = engine.share_attachment(CHAT, &file).await.unwrap_err();
2323 assert!(matches!(
2324 error,
2325 Error::Graph(graph::Error::SharingDenied(_))
2326 ));
2327 assert!(fake.calls().iter().all(|call| !call.starts_with("share")));
2328 }
2329
2271 2330 #[tokio::test]
2272 2331 async fn sharing_fails_loudly_when_the_chat_members_are_unknown() {
2273 2332 let fake = Arc::new(Fake::default());
@@ -5,7 +5,8 @@ use chatsvc::ConversationRef;
5use chrono::{DateTime, Duration, TimeZone, Utc};
5use chrono::{DateTime, Duration, TimeZone, Utc};
6use graph::{
6use graph::{
7 Channel, Chat, DriveFolder, HostedImage, Member, Message, MessageExtras, MessageTarget,
7 Channel, Chat, DriveFolder, HostedImage, Member, Message, MessageExtras, MessageTarget,
8 OutgoingMention, Photo, Presence, SharedFile, Team, UploadDestination, UploadedFile, User,
8 OutgoingMention, Photo, Presence, Recipient, SharedFile, Team, UploadDestination, UploadedFile,
9 User,
9};
10};
10use serde_json::json;
11use serde_json::json;
11use store::{
12use store::{
@@ -137,6 +138,7 @@ struct Fake {
137 window_requests: Mutex<Vec<(String, chatsvc::WindowDirection)>>,
138 window_requests: Mutex<Vec<(String, chatsvc::WindowDirection)>>,
138 search_identities: Mutex<Vec<substrate_search::SearchIdentity>>,
139 search_identities: Mutex<Vec<substrate_search::SearchIdentity>>,
139 member_requests: Mutex<Vec<String>>,
140 member_requests: Mutex<Vec<String>>,
141 omit_member_email: Mutex<bool>,
140 activity_feed: Mutex<chatsvc::ActivitySnapshot>,
142 activity_feed: Mutex<chatsvc::ActivitySnapshot>,
141 app_channel_horizon_ms: Mutex<i64>,
143 app_channel_horizon_ms: Mutex<i64>,
142}
144}
@@ -268,11 +270,20 @@ impl Remote for Handle {
268 .lock()
270 .lock()
269 .unwrap()
271 .unwrap()
270 .push(chat_id.to_owned());
272 .push(chat_id.to_owned());
273 let ada = if *self.omit_member_email.lock().unwrap() {
274 json!({"userId": "user-ada", "tenantId": "tenant-1", "displayName": "Ada Example"})
275 } else {
276 json!({
277 "userId": "user-ada", "tenantId": "tenant-1", "displayName": "Ada Example",
278 "email": "ada@example.com"
279 })
280 };
271 Ok(vec![
281 Ok(vec![
272 serde_json::from_value(
282 serde_json::from_value(
273 json!({"userId": ME, "tenantId": "tenant-1", "displayName": "Me Myself"}),
283 json!({"userId": ME, "tenantId": "tenant-1", "displayName": "Me Myself"}),
274 )
284 )
275 .unwrap(),
285 .unwrap(),
286 serde_json::from_value(ada).unwrap(),
276 ])
287 ])
277 }
288 }
278
289
@@ -768,6 +779,7 @@ impl Remote for Handle {
768 web_url: "https://files.example/web".into(),
779 web_url: "https://files.example/web".into(),
769 web_dav_url: Some("https://files.example/dav".into()),
780 web_dav_url: Some("https://files.example/dav".into()),
770 etag: "\"{GUID-1},2\"".into(),
781 etag: "\"{GUID-1},2\"".into(),
782 home_drive: false,
771 })
783 })
772 }
784 }
773
785
@@ -813,9 +825,21 @@ impl Remote for Handle {
813 Ok(vec![7; length as usize])
825 Ok(vec![7; length as usize])
814 }
826 }
815
827
816 async fn share_file(&self, file: &UploadedFile, user_ids: &[String]) -> Result<()> {
828 async fn share_file(
817 self.record(format!("share {} {}", file.item_id, user_ids.join(",")));
829 &self,
818 Ok(())
830 file: &UploadedFile,
831 recipients: &[Recipient],
832 ) -> Result<Option<String>> {
833 let recipients: Vec<&str> = recipients
834 .iter()
835 .map(|recipient| match recipient {
836 Recipient::ObjectId(id) | Recipient::Email(id) => id.as_str(),
837 })
838 .collect();
839 self.record(format!("share {} {}", file.item_id, recipients.join(",")));
840 Ok(file
841 .home_drive
842 .then(|| "https://files.example/share".to_owned()))
819 }
843 }
820
844
821 async fn external_image(&self, url: &str) -> Result<Photo> {
845 async fn external_image(&self, url: &str) -> Result<Photo> {
@@ -2265,9 +2289,44 @@ fn uploaded() -> UploadedFile {
2265 web_url: "https://files.example/web".into(),
2289 web_url: "https://files.example/web".into(),
2266 web_dav_url: None,
2290 web_dav_url: None,
2267 etag: "\"{GUID-1},2\"".into(),
2291 etag: "\"{GUID-1},2\"".into(),
2292 home_drive: false,
2268 }
2293 }
2269}
2294}
2270
2295
2296#[tokio::test]
2297async fn a_file_in_the_home_drive_is_shared_by_email() {
2298 let fake = Arc::new(Fake::default());
2299 let engine = chat_engine(&fake, small_pages()).await;
2300 let file = UploadedFile {
2301 home_drive: true,
2302 ..uploaded()
2303 };
2304 let link = engine.share_attachment(CHAT, &file).await.unwrap();
2305 assert_eq!(link.as_deref(), Some("https://files.example/share"));
2306 assert!(
2307 fake.calls()
2308 .contains(&"share item-1 ada@example.com".to_owned())
2309 );
2310}
2311
2312#[tokio::test]
2313async fn a_home_drive_file_is_not_sent_as_shared_when_nobody_has_an_email() {
2314 let fake = Arc::new(Fake::default());
2315 *fake.omit_member_email.lock().unwrap() = true;
2316 let engine = chat_engine(&fake, small_pages()).await;
2317 let file = UploadedFile {
2318 home_drive: true,
2319 ..uploaded()
2320 };
2321
2322 let error = engine.share_attachment(CHAT, &file).await.unwrap_err();
2323 assert!(matches!(
2324 error,
2325 Error::Graph(graph::Error::SharingDenied(_))
2326 ));
2327 assert!(fake.calls().iter().all(|call| !call.starts_with("share")));
2328}
2329
2271#[tokio::test]
2330#[tokio::test]
2272async fn sharing_fails_loudly_when_the_chat_members_are_unknown() {
2331async fn sharing_fails_loudly_when_the_chat_members_are_unknown() {
2273 let fake = Arc::new(Fake::default());
2332 let fake = Arc::new(Fake::default());
crates/graph/src/client.rs +29 −1
@@ -15,17 +15,45 @@ const PEOPLE_PAGE_SIZE: usize = 10;
15 15
16 16 pub struct Graph {
17 17 session: Session,
18 home_drive: Option<Session>,
18 19 }
19 20
20 21 impl Graph {
21 22 pub fn new(session: Session) -> Self {
22 Graph { session }
23 Graph {
24 session,
25 home_drive: None,
26 }
27 }
28
29 /// Chat files go to the OneDrive of `home`, the account's home tenant.
30 /// For a guest org, where the account has no OneDrive.
31 pub fn with_home_drive(mut self, home: Session) -> Self {
32 self.home_drive = Some(home);
33 self
23 34 }
24 35
25 36 pub fn session(&self) -> &Session {
26 37 &self.session
27 38 }
28 39
40 /// The session that owns the file. A home-drive file with no home session is an error:
41 /// falling back to the guest session would delete or share it in the wrong tenant.
42 pub(crate) fn drive_session(&self, home: bool) -> Result<&Session> {
43 if !home {
44 return Ok(&self.session);
45 }
46 self.home_drive.as_ref().ok_or_else(|| {
47 Error::Upload(
48 "the file is in the home drive, but this session has no home tenant".into(),
49 )
50 })
51 }
52
53 pub(crate) fn has_home_drive(&self) -> bool {
54 self.home_drive.is_some()
55 }
56
29 57 pub async fn me(&self) -> Result<User> {
30 58 let body = self
31 59 .get(&urls::me(), &Scope::graph("User.ReadBasic.All"))
@@ -15,17 +15,45 @@ const PEOPLE_PAGE_SIZE: usize = 10;
15
15
16pub struct Graph {
16pub struct Graph {
17 session: Session,
17 session: Session,
18 home_drive: Option<Session>,
18}
19}
19
20
20impl Graph {
21impl Graph {
21 pub fn new(session: Session) -> Self {
22 pub fn new(session: Session) -> Self {
22 Graph { session }
23 Graph {
24 session,
25 home_drive: None,
26 }
27 }
28
29 /// Chat files go to the OneDrive of `home`, the account's home tenant.
30 /// For a guest org, where the account has no OneDrive.
31 pub fn with_home_drive(mut self, home: Session) -> Self {
32 self.home_drive = Some(home);
33 self
23 }
34 }
24
35
25 pub fn session(&self) -> &Session {
36 pub fn session(&self) -> &Session {
26 &self.session
37 &self.session
27 }
38 }
28
39
40 /// The session that owns the file. A home-drive file with no home session is an error:
41 /// falling back to the guest session would delete or share it in the wrong tenant.
42 pub(crate) fn drive_session(&self, home: bool) -> Result<&Session> {
43 if !home {
44 return Ok(&self.session);
45 }
46 self.home_drive.as_ref().ok_or_else(|| {
47 Error::Upload(
48 "the file is in the home drive, but this session has no home tenant".into(),
49 )
50 })
51 }
52
53 pub(crate) fn has_home_drive(&self) -> bool {
54 self.home_drive.is_some()
55 }
56
29 pub async fn me(&self) -> Result<User> {
57 pub async fn me(&self) -> Result<User> {
30 let body = self
58 let body = self
31 .get(&urls::me(), &Scope::graph("User.ReadBasic.All"))
59 .get(&urls::me(), &Scope::graph("User.ReadBasic.All"))
crates/graph/src/error.rs +4 −0
@@ -16,6 +16,10 @@ pub enum Error {
16 16 EmptyUpload,
17 17 #[error("upload failed: {0}")]
18 18 Upload(String),
19 /// The file is in the drive, but the organization refused the share (`sharingFailed`)
20 /// or nobody in the chat could be invited.
21 #[error("sharing denied: {0}")]
22 SharingDenied(String),
19 23 #[error("download failed: {0}")]
20 24 Download(String),
21 25 }
@@ -16,6 +16,10 @@ pub enum Error {
16 EmptyUpload,
16 EmptyUpload,
17 #[error("upload failed: {0}")]
17 #[error("upload failed: {0}")]
18 Upload(String),
18 Upload(String),
19 /// The file is in the drive, but the organization refused the share (`sharingFailed`)
20 /// or nobody in the chat could be invited.
21 #[error("sharing denied: {0}")]
22 SharingDenied(String),
19 #[error("download failed: {0}")]
23 #[error("download failed: {0}")]
20 Download(String),
24 Download(String),
21}
25}
crates/graph/src/files.rs +180 −60
@@ -44,6 +44,17 @@ pub struct UploadedFile {
44 44 pub web_url: String,
45 45 pub web_dav_url: Option<String>,
46 46 pub etag: String,
47 /// Stored in the home tenant's OneDrive while a guest org is open.
48 #[serde(default)]
49 pub home_drive: bool,
50 }
51
52 /// Who gets access to a shared file. A file in the home drive of a guest org takes emails,
53 /// because the guest org's user ids do not exist in the home tenant.
54 #[derive(Debug, Clone, PartialEq, Eq)]
55 pub enum Recipient {
56 ObjectId(String),
57 Email(String),
47 58 }
48 59
49 60 impl UploadedFile {
@@ -221,7 +232,12 @@ pub fn numbered_name(file_name: &str, number: usize) -> String {
221 232
222 233 impl Graph {
223 234 /// conflictBehavior=rename was not honored on upload sessions: a same-named upload replaced the file.
224 async fn free_name(&self, destination: &UploadDestination, file_name: &str) -> Result<String> {
235 async fn free_name(
236 &self,
237 session: &Session,
238 destination: &UploadDestination,
239 file_name: &str,
240 ) -> Result<String> {
225 241 for number in 0..MAX_NAME_ATTEMPTS {
226 242 let candidate = numbered_name(file_name, number);
227 243 let url = match destination {
@@ -230,8 +246,7 @@ impl Graph {
230 246 urls::folder_item(&folder.drive_id, &folder.item_id, &candidate)
231 247 }
232 248 };
233 match self
234 .session()
249 match session
235 250 .request(Method::Get, &url, &Scope::graph(FILES_SCOPE), None)
236 251 .await
237 252 {
@@ -278,8 +293,11 @@ impl Graph {
278 293 return Err(Error::EmptyUpload);
279 294 }
280 295 let scope = Scope::graph(FILES_SCOPE);
296 let home_drive =
297 matches!(destination, UploadDestination::ChatFiles) && self.has_home_drive();
298 let session = self.drive_session(home_drive)?;
281 299 let shown_name = file_name;
282 let file_name = self.free_name(destination, file_name).await?;
300 let file_name = self.free_name(session, destination, file_name).await?;
283 301 let file_name = file_name.as_str();
284 302 let session_url = match destination {
285 303 UploadDestination::ChatFiles => urls::chat_files_upload_session(file_name),
@@ -287,8 +305,7 @@ impl Graph {
287 305 urls::folder_upload_session(&folder.drive_id, &folder.item_id, file_name)
288 306 }
289 307 };
290 let created = self
291 .session()
308 let created = session
292 309 .request(
293 310 Method::Post,
294 311 &session_url,
@@ -303,7 +320,7 @@ impl Graph {
303 320 .ok_or_else(|| Error::Upload("no upload URL in the answer".into()))?
304 321 .to_owned();
305 322 let mut guard = SessionGuard {
306 session: self.session().clone(),
323 session: session.clone(),
307 324 url: upload_url.clone(),
308 325 armed: true,
309 326 };
@@ -319,12 +336,13 @@ impl Graph {
319 336 vec![("Content-Range".to_owned(), content_range(start, end, total))],
320 337 STANDARD.encode(&bytes[start as usize..=end as usize]),
321 338 );
322 match self.session().send(request, &scope).await {
339 match session.send(request, &scope).await {
323 340 Ok(answer) if matches!(answer.status, 200 | 201) => {
324 341 guard.disarm();
325 342 progress(100);
326 343 let mut uploaded = finished_item(answer.body)?;
327 344 uploaded.name = shown_name.to_owned();
345 uploaded.home_drive = home_drive;
328 346 return Ok(uploaded);
329 347 }
330 348 Ok(_) => {
@@ -337,7 +355,7 @@ impl Graph {
337 355 if failures > MAX_CHUNK_RETRIES {
338 356 return Err(error.into());
339 357 }
340 if let Some(next) = self.resume_offset(&upload_url, &scope).await {
358 if let Some(next) = resume_offset(session, &upload_url, &scope).await {
341 359 offset = next.min(total);
342 360 }
343 361 }
@@ -348,37 +366,30 @@ impl Graph {
348 366 ))
349 367 }
350 368
351 async fn resume_offset(&self, upload_url: &str, scope: &Scope) -> Option<u64> {
352 let request = Request {
353 anonymous: true,
354 ..Request::get(upload_url)
355 };
356 let answer = self.session().send(request, scope).await.ok()?;
357 next_expected_start(&answer.body)
358 }
359
360 369 pub async fn resolve_share(&self, open_url: &str) -> Result<SharedFile> {
361 let answer = self
362 .session()
363 .request(
364 Method::Get,
365 &urls::shared_drive_item(&share_id(open_url)),
366 &Scope::graph(FILES_SCOPE),
367 None,
368 )
369 .await?;
370 shared_file(answer.body)
370 let url = urls::shared_drive_item(&share_id(open_url));
371 self.drive_item_request(&url).await
371 372 }
372 373
373 374 pub async fn resolve_drive_item(&self, drive_id: &str, item_id: &str) -> Result<SharedFile> {
374 let answer = self
375 .session()
376 .request(
377 Method::Get,
378 &urls::drive_item(drive_id, item_id),
379 &Scope::graph(FILES_SCOPE),
380 None,
381 )
375 let url = urls::drive_item(drive_id, item_id);
376 self.drive_item_request(&url).await
377 }
378
379 /// A guest-org session cannot see a file that lives in the home OneDrive.
380 /// A 401 there is retried with the home session.
381 async fn drive_item_request(&self, url: &str) -> Result<SharedFile> {
382 match self.item_request(self.session(), url).await {
383 Err(error) if unauthorized(&error) && self.has_home_drive() => {
384 self.item_request(self.drive_session(true)?, url).await
385 }
386 other => other,
387 }
388 }
389
390 async fn item_request(&self, session: &Session, url: &str) -> Result<SharedFile> {
391 let answer = session
392 .request(Method::Get, url, &Scope::graph(FILES_SCOPE), None)
382 393 .await?;
383 394 shared_file(answer.body)
384 395 }
@@ -406,11 +417,11 @@ impl Graph {
406 417 Ok(decode_binary(download_url, answer)?.bytes)
407 418 }
408 419
409 pub async fn delete_drive_item(&self, drive_id: &str, item_id: &str) -> Result<()> {
410 self.session()
420 pub async fn delete_uploaded(&self, file: &UploadedFile) -> Result<()> {
421 self.drive_session(file.home_drive)?
411 422 .request(
412 423 Method::Delete,
413 &urls::drive_item(drive_id, item_id),
424 &urls::drive_item(&file.drive_id, &file.item_id),
414 425 &Scope::graph(FILES_SCOPE),
415 426 None,
416 427 )
@@ -418,29 +429,84 @@ impl Graph {
418 429 Ok(())
419 430 }
420 431
421 pub async fn share_item(&self, file: &UploadedFile, user_ids: &[String]) -> Result<()> {
422 if user_ids.is_empty() {
423 return Ok(());
432 /// `Some` is the sharing-link URL when Graph returned one. The chat message should
433 /// carry that link: a specific-people grant is redeemed through it, not the item URL.
434 pub async fn share_item(
435 &self,
436 file: &UploadedFile,
437 recipients: &[Recipient],
438 ) -> Result<Option<String>> {
439 if recipients.is_empty() {
440 return Ok(None);
424 441 }
425 let recipients: Vec<Value> = user_ids
426 .iter()
427 .map(|user_id| json!({"objectId": user_id}))
428 .collect();
429 self.session()
430 .request(
431 Method::Post,
432 &urls::drive_item_invite(&file.drive_id, &file.item_id),
433 &Scope::graph(FILES_SCOPE),
434 Some(json!({
435 "recipients": recipients,
436 "roles": ["read"],
437 "requireSignIn": true,
438 "sendInvitation": false,
439 })),
440 )
441 .await?;
442 Ok(())
442 let (url, body) = share_request(file, recipients);
443 let answer = self
444 .drive_session(file.home_drive)?
445 .request(Method::Post, &url, &Scope::graph(FILES_SCOPE), Some(body))
446 .await
447 .map_err(share_error)?;
448 Ok(answer
449 .body
450 .pointer("/link/webUrl")
451 .and_then(Value::as_str)
452 .map(str::to_owned))
453 }
454 }
455
456 fn unauthorized(error: &Error) -> bool {
457 matches!(
458 error,
459 Error::Session(session::Error::Api { status: 401, .. })
460 )
461 }
462
463 /// Sharing errors carry a generic message; the code and inner error in the body name the cause.
464 fn share_error(error: session::Error) -> Error {
465 match error {
466 session::Error::Api { status, body, .. } => {
467 let code = body
468 .pointer("/error/code")
469 .and_then(Value::as_str)
470 .unwrap_or("");
471 let detail = format!("HTTP {status}: {}", body.pointer("/error").unwrap_or(&body));
472 // Only the organization's sharing policy. A 401 or a network error stays a failure
473 // the user can retry, instead of the "does not allow sharing" notice.
474 if code.eq_ignore_ascii_case("sharingFailed") {
475 Error::SharingDenied(detail)
476 } else {
477 Error::Upload(format!("sharing answered {detail}"))
478 }
479 }
480 other => other.into(),
481 }
482 }
483
484 /// A file in the home drive gets a specific-people link like Teams creates for a guest's chat
485 /// files: an invite fails there because the other org's people are not guests of the home tenant
486 /// yet, while a link lets them in when they open it.
487 fn share_request(file: &UploadedFile, recipients: &[Recipient]) -> (String, Value) {
488 let recipients: Vec<Value> = recipients
489 .iter()
490 .map(|recipient| match recipient {
491 Recipient::ObjectId(id) => json!({"objectId": id}),
492 Recipient::Email(email) => json!({"email": email}),
493 })
494 .collect();
495 if file.home_drive {
496 return (
497 urls::drive_item_create_link(&file.drive_id, &file.item_id),
498 json!({"type": "view", "scope": "users", "recipients": recipients}),
499 );
443 500 }
501 (
502 urls::drive_item_invite(&file.drive_id, &file.item_id),
503 json!({
504 "recipients": recipients,
505 "roles": ["read"],
506 "requireSignIn": true,
507 "sendInvitation": false,
508 }),
509 )
444 510 }
445 511
446 512 pub(crate) fn finished_item(body: Value) -> Result<UploadedFile> {
@@ -455,9 +521,19 @@ pub(crate) fn finished_item(body: Value) -> Result<UploadedFile> {
455 521 web_url: item.web_url,
456 522 web_dav_url: item.web_dav_url,
457 523 etag: item.e_tag,
524 home_drive: false,
458 525 })
459 526 }
460 527
528 async fn resume_offset(session: &Session, upload_url: &str, scope: &Scope) -> Option<u64> {
529 let request = Request {
530 anonymous: true,
531 ..Request::get(upload_url)
532 };
533 let answer = session.send(request, scope).await.ok()?;
534 next_expected_start(&answer.body)
535 }
536
461 537 #[cfg(test)]
462 538 mod tests {
463 539 #[test]
@@ -619,6 +695,49 @@ mod tests {
619 695 assert_eq!(percent_done(5, 0), 100);
620 696 }
621 697
698 #[test]
699 fn only_sharing_failed_is_a_denied_share() {
700 let denied = share_error(session::Error::api(
701 403,
702 "https://graph.microsoft.com/createLink",
703 json!({"error": {"code": "sharingFailed", "message": "blocked"}}),
704 ));
705 assert!(matches!(denied, Error::SharingDenied(_)));
706 let unauthorized = share_error(session::Error::api(
707 401,
708 "https://graph.microsoft.com/createLink",
709 json!({"error": {"code": "InvalidAuthenticationToken", "message": "no"}}),
710 ));
711 assert!(matches!(unauthorized, Error::Upload(_)));
712 }
713
714 #[test]
715 fn a_home_drive_file_is_shared_with_a_specific_people_link() {
716 let file = UploadedFile {
717 drive_id: "d".into(),
718 item_id: "i".into(),
719 name: "a.xlsx".into(),
720 web_url: "https://x/web".into(),
721 web_dav_url: None,
722 etag: "\"{AAAA},1\"".into(),
723 home_drive: true,
724 };
725 let (url, body) = share_request(&file, &[Recipient::Email("ada@example.com".into())]);
726 assert!(url.ends_with("/drives/d/items/i/createLink"));
727 assert_eq!(
728 body,
729 json!({"type": "view", "scope": "users", "recipients": [{"email": "ada@example.com"}]})
730 );
731 let (url, _) = share_request(
732 &UploadedFile {
733 home_drive: false,
734 ..file
735 },
736 &[Recipient::ObjectId("u".into())],
737 );
738 assert!(url.ends_with("/drives/d/items/i/invite"));
739 }
740
622 741 #[test]
623 742 fn uploaded_file_reference_prefers_the_webdav_url() {
624 743 let mut file = UploadedFile {
@@ -628,6 +747,7 @@ mod tests {
628 747 web_url: "https://x/web".into(),
629 748 web_dav_url: Some("https://x/dav".into()),
630 749 etag: "\"{AAAA},1\"".into(),
750 home_drive: false,
631 751 };
632 752 let reference = file.reference().unwrap();
633 753 assert_eq!(reference.attachment_id, "AAAA");
@@ -44,6 +44,17 @@ pub struct UploadedFile {
44 pub web_url: String,
44 pub web_url: String,
45 pub web_dav_url: Option<String>,
45 pub web_dav_url: Option<String>,
46 pub etag: String,
46 pub etag: String,
47 /// Stored in the home tenant's OneDrive while a guest org is open.
48 #[serde(default)]
49 pub home_drive: bool,
50}
51
52/// Who gets access to a shared file. A file in the home drive of a guest org takes emails,
53/// because the guest org's user ids do not exist in the home tenant.
54#[derive(Debug, Clone, PartialEq, Eq)]
55pub enum Recipient {
56 ObjectId(String),
57 Email(String),
47}
58}
48
59
49impl UploadedFile {
60impl UploadedFile {
@@ -221,7 +232,12 @@ pub fn numbered_name(file_name: &str, number: usize) -> String {
221
232
222impl Graph {
233impl Graph {
223 /// conflictBehavior=rename was not honored on upload sessions: a same-named upload replaced the file.
234 /// conflictBehavior=rename was not honored on upload sessions: a same-named upload replaced the file.
224 async fn free_name(&self, destination: &UploadDestination, file_name: &str) -> Result<String> {
235 async fn free_name(
236 &self,
237 session: &Session,
238 destination: &UploadDestination,
239 file_name: &str,
240 ) -> Result<String> {
225 for number in 0..MAX_NAME_ATTEMPTS {
241 for number in 0..MAX_NAME_ATTEMPTS {
226 let candidate = numbered_name(file_name, number);
242 let candidate = numbered_name(file_name, number);
227 let url = match destination {
243 let url = match destination {
@@ -230,8 +246,7 @@ impl Graph {
230 urls::folder_item(&folder.drive_id, &folder.item_id, &candidate)
246 urls::folder_item(&folder.drive_id, &folder.item_id, &candidate)
231 }
247 }
232 };
248 };
233 match self
249 match session
234 .session()
235 .request(Method::Get, &url, &Scope::graph(FILES_SCOPE), None)
250 .request(Method::Get, &url, &Scope::graph(FILES_SCOPE), None)
236 .await
251 .await
237 {
252 {
@@ -278,8 +293,11 @@ impl Graph {
278 return Err(Error::EmptyUpload);
293 return Err(Error::EmptyUpload);
279 }
294 }
280 let scope = Scope::graph(FILES_SCOPE);
295 let scope = Scope::graph(FILES_SCOPE);
296 let home_drive =
297 matches!(destination, UploadDestination::ChatFiles) && self.has_home_drive();
298 let session = self.drive_session(home_drive)?;
281 let shown_name = file_name;
299 let shown_name = file_name;
282 let file_name = self.free_name(destination, file_name).await?;
300 let file_name = self.free_name(session, destination, file_name).await?;
283 let file_name = file_name.as_str();
301 let file_name = file_name.as_str();
284 let session_url = match destination {
302 let session_url = match destination {
285 UploadDestination::ChatFiles => urls::chat_files_upload_session(file_name),
303 UploadDestination::ChatFiles => urls::chat_files_upload_session(file_name),
@@ -287,8 +305,7 @@ impl Graph {
287 urls::folder_upload_session(&folder.drive_id, &folder.item_id, file_name)
305 urls::folder_upload_session(&folder.drive_id, &folder.item_id, file_name)
288 }
306 }
289 };
307 };
290 let created = self
308 let created = session
291 .session()
292 .request(
309 .request(
293 Method::Post,
310 Method::Post,
294 &session_url,
311 &session_url,
@@ -303,7 +320,7 @@ impl Graph {
303 .ok_or_else(|| Error::Upload("no upload URL in the answer".into()))?
320 .ok_or_else(|| Error::Upload("no upload URL in the answer".into()))?
304 .to_owned();
321 .to_owned();
305 let mut guard = SessionGuard {
322 let mut guard = SessionGuard {
306 session: self.session().clone(),
323 session: session.clone(),
307 url: upload_url.clone(),
324 url: upload_url.clone(),
308 armed: true,
325 armed: true,
309 };
326 };
@@ -319,12 +336,13 @@ impl Graph {
319 vec![("Content-Range".to_owned(), content_range(start, end, total))],
336 vec![("Content-Range".to_owned(), content_range(start, end, total))],
320 STANDARD.encode(&bytes[start as usize..=end as usize]),
337 STANDARD.encode(&bytes[start as usize..=end as usize]),
321 );
338 );
322 match self.session().send(request, &scope).await {
339 match session.send(request, &scope).await {
323 Ok(answer) if matches!(answer.status, 200 | 201) => {
340 Ok(answer) if matches!(answer.status, 200 | 201) => {
324 guard.disarm();
341 guard.disarm();
325 progress(100);
342 progress(100);
326 let mut uploaded = finished_item(answer.body)?;
343 let mut uploaded = finished_item(answer.body)?;
327 uploaded.name = shown_name.to_owned();
344 uploaded.name = shown_name.to_owned();
345 uploaded.home_drive = home_drive;
328 return Ok(uploaded);
346 return Ok(uploaded);
329 }
347 }
330 Ok(_) => {
348 Ok(_) => {
@@ -337,7 +355,7 @@ impl Graph {
337 if failures > MAX_CHUNK_RETRIES {
355 if failures > MAX_CHUNK_RETRIES {
338 return Err(error.into());
356 return Err(error.into());
339 }
357 }
340 if let Some(next) = self.resume_offset(&upload_url, &scope).await {
358 if let Some(next) = resume_offset(session, &upload_url, &scope).await {
341 offset = next.min(total);
359 offset = next.min(total);
342 }
360 }
343 }
361 }
@@ -348,37 +366,30 @@ impl Graph {
348 ))
366 ))
349 }
367 }
350
368
351 async fn resume_offset(&self, upload_url: &str, scope: &Scope) -> Option<u64> {
352 let request = Request {
353 anonymous: true,
354 ..Request::get(upload_url)
355 };
356 let answer = self.session().send(request, scope).await.ok()?;
357 next_expected_start(&answer.body)
358 }
359
360 pub async fn resolve_share(&self, open_url: &str) -> Result<SharedFile> {
369 pub async fn resolve_share(&self, open_url: &str) -> Result<SharedFile> {
361 let answer = self
370 let url = urls::shared_drive_item(&share_id(open_url));
362 .session()
371 self.drive_item_request(&url).await
363 .request(
364 Method::Get,
365 &urls::shared_drive_item(&share_id(open_url)),
366 &Scope::graph(FILES_SCOPE),
367 None,
368 )
369 .await?;
370 shared_file(answer.body)
371 }
372 }
372
373
373 pub async fn resolve_drive_item(&self, drive_id: &str, item_id: &str) -> Result<SharedFile> {
374 pub async fn resolve_drive_item(&self, drive_id: &str, item_id: &str) -> Result<SharedFile> {
374 let answer = self
375 let url = urls::drive_item(drive_id, item_id);
375 .session()
376 self.drive_item_request(&url).await
376 .request(
377 }
377 Method::Get,
378
378 &urls::drive_item(drive_id, item_id),
379 /// A guest-org session cannot see a file that lives in the home OneDrive.
379 &Scope::graph(FILES_SCOPE),
380 /// A 401 there is retried with the home session.
380 None,
381 async fn drive_item_request(&self, url: &str) -> Result<SharedFile> {
381 )
382 match self.item_request(self.session(), url).await {
383 Err(error) if unauthorized(&error) && self.has_home_drive() => {
384 self.item_request(self.drive_session(true)?, url).await
385 }
386 other => other,
387 }
388 }
389
390 async fn item_request(&self, session: &Session, url: &str) -> Result<SharedFile> {
391 let answer = session
392 .request(Method::Get, url, &Scope::graph(FILES_SCOPE), None)
382 .await?;
393 .await?;
383 shared_file(answer.body)
394 shared_file(answer.body)
384 }
395 }
@@ -406,11 +417,11 @@ impl Graph {
406 Ok(decode_binary(download_url, answer)?.bytes)
417 Ok(decode_binary(download_url, answer)?.bytes)
407 }
418 }
408
419
409 pub async fn delete_drive_item(&self, drive_id: &str, item_id: &str) -> Result<()> {
420 pub async fn delete_uploaded(&self, file: &UploadedFile) -> Result<()> {
410 self.session()
421 self.drive_session(file.home_drive)?
411 .request(
422 .request(
412 Method::Delete,
423 Method::Delete,
413 &urls::drive_item(drive_id, item_id),
424 &urls::drive_item(&file.drive_id, &file.item_id),
414 &Scope::graph(FILES_SCOPE),
425 &Scope::graph(FILES_SCOPE),
415 None,
426 None,
416 )
427 )
@@ -418,29 +429,84 @@ impl Graph {
418 Ok(())
429 Ok(())
419 }
430 }
420
431
421 pub async fn share_item(&self, file: &UploadedFile, user_ids: &[String]) -> Result<()> {
432 /// `Some` is the sharing-link URL when Graph returned one. The chat message should
422 if user_ids.is_empty() {
433 /// carry that link: a specific-people grant is redeemed through it, not the item URL.
423 return Ok(());
434 pub async fn share_item(
435 &self,
436 file: &UploadedFile,
437 recipients: &[Recipient],
438 ) -> Result<Option<String>> {
439 if recipients.is_empty() {
440 return Ok(None);
424 }
441 }
425 let recipients: Vec<Value> = user_ids
442 let (url, body) = share_request(file, recipients);
426 .iter()
443 let answer = self
427 .map(|user_id| json!({"objectId": user_id}))
444 .drive_session(file.home_drive)?
428 .collect();
445 .request(Method::Post, &url, &Scope::graph(FILES_SCOPE), Some(body))
429 self.session()
446 .await
430 .request(
447 .map_err(share_error)?;
431 Method::Post,
448 Ok(answer
432 &urls::drive_item_invite(&file.drive_id, &file.item_id),
449 .body
433 &Scope::graph(FILES_SCOPE),
450 .pointer("/link/webUrl")
434 Some(json!({
451 .and_then(Value::as_str)
435 "recipients": recipients,
452 .map(str::to_owned))
436 "roles": ["read"],
453 }
437 "requireSignIn": true,
454}
438 "sendInvitation": false,
455
439 })),
456fn unauthorized(error: &Error) -> bool {
440 )
457 matches!(
441 .await?;
458 error,
442 Ok(())
459 Error::Session(session::Error::Api { status: 401, .. })
460 )
461}
462
463/// Sharing errors carry a generic message; the code and inner error in the body name the cause.
464fn share_error(error: session::Error) -> Error {
465 match error {
466 session::Error::Api { status, body, .. } => {
467 let code = body
468 .pointer("/error/code")
469 .and_then(Value::as_str)
470 .unwrap_or("");
471 let detail = format!("HTTP {status}: {}", body.pointer("/error").unwrap_or(&body));
472 // Only the organization's sharing policy. A 401 or a network error stays a failure
473 // the user can retry, instead of the "does not allow sharing" notice.
474 if code.eq_ignore_ascii_case("sharingFailed") {
475 Error::SharingDenied(detail)
476 } else {
477 Error::Upload(format!("sharing answered {detail}"))
478 }
479 }
480 other => other.into(),
481 }
482}
483
484/// A file in the home drive gets a specific-people link like Teams creates for a guest's chat
485/// files: an invite fails there because the other org's people are not guests of the home tenant
486/// yet, while a link lets them in when they open it.
487fn share_request(file: &UploadedFile, recipients: &[Recipient]) -> (String, Value) {
488 let recipients: Vec<Value> = recipients
489 .iter()
490 .map(|recipient| match recipient {
491 Recipient::ObjectId(id) => json!({"objectId": id}),
492 Recipient::Email(email) => json!({"email": email}),
493 })
494 .collect();
495 if file.home_drive {
496 return (
497 urls::drive_item_create_link(&file.drive_id, &file.item_id),
498 json!({"type": "view", "scope": "users", "recipients": recipients}),
499 );
443 }
500 }
501 (
502 urls::drive_item_invite(&file.drive_id, &file.item_id),
503 json!({
504 "recipients": recipients,
505 "roles": ["read"],
506 "requireSignIn": true,
507 "sendInvitation": false,
508 }),
509 )
444}
510}
445
511
446pub(crate) fn finished_item(body: Value) -> Result<UploadedFile> {
512pub(crate) fn finished_item(body: Value) -> Result<UploadedFile> {
@@ -455,9 +521,19 @@ pub(crate) fn finished_item(body: Value) -> Result<UploadedFile> {
455 web_url: item.web_url,
521 web_url: item.web_url,
456 web_dav_url: item.web_dav_url,
522 web_dav_url: item.web_dav_url,
457 etag: item.e_tag,
523 etag: item.e_tag,
524 home_drive: false,
458 })
525 })
459}
526}
460
527
528async fn resume_offset(session: &Session, upload_url: &str, scope: &Scope) -> Option<u64> {
529 let request = Request {
530 anonymous: true,
531 ..Request::get(upload_url)
532 };
533 let answer = session.send(request, scope).await.ok()?;
534 next_expected_start(&answer.body)
535}
536
461#[cfg(test)]
537#[cfg(test)]
462mod tests {
538mod tests {
463 #[test]
539 #[test]
@@ -619,6 +695,49 @@ mod tests {
619 assert_eq!(percent_done(5, 0), 100);
695 assert_eq!(percent_done(5, 0), 100);
620 }
696 }
621
697
698 #[test]
699 fn only_sharing_failed_is_a_denied_share() {
700 let denied = share_error(session::Error::api(
701 403,
702 "https://graph.microsoft.com/createLink",
703 json!({"error": {"code": "sharingFailed", "message": "blocked"}}),
704 ));
705 assert!(matches!(denied, Error::SharingDenied(_)));
706 let unauthorized = share_error(session::Error::api(
707 401,
708 "https://graph.microsoft.com/createLink",
709 json!({"error": {"code": "InvalidAuthenticationToken", "message": "no"}}),
710 ));
711 assert!(matches!(unauthorized, Error::Upload(_)));
712 }
713
714 #[test]
715 fn a_home_drive_file_is_shared_with_a_specific_people_link() {
716 let file = UploadedFile {
717 drive_id: "d".into(),
718 item_id: "i".into(),
719 name: "a.xlsx".into(),
720 web_url: "https://x/web".into(),
721 web_dav_url: None,
722 etag: "\"{AAAA},1\"".into(),
723 home_drive: true,
724 };
725 let (url, body) = share_request(&file, &[Recipient::Email("ada@example.com".into())]);
726 assert!(url.ends_with("/drives/d/items/i/createLink"));
727 assert_eq!(
728 body,
729 json!({"type": "view", "scope": "users", "recipients": [{"email": "ada@example.com"}]})
730 );
731 let (url, _) = share_request(
732 &UploadedFile {
733 home_drive: false,
734 ..file
735 },
736 &[Recipient::ObjectId("u".into())],
737 );
738 assert!(url.ends_with("/drives/d/items/i/invite"));
739 }
740
622 #[test]
741 #[test]
623 fn uploaded_file_reference_prefers_the_webdav_url() {
742 fn uploaded_file_reference_prefers_the_webdav_url() {
624 let mut file = UploadedFile {
743 let mut file = UploadedFile {
@@ -628,6 +747,7 @@ mod tests {
628 web_url: "https://x/web".into(),
747 web_url: "https://x/web".into(),
629 web_dav_url: Some("https://x/dav".into()),
748 web_dav_url: Some("https://x/dav".into()),
630 etag: "\"{AAAA},1\"".into(),
749 etag: "\"{AAAA},1\"".into(),
750 home_drive: false,
631 };
751 };
632 let reference = file.reference().unwrap();
752 let reference = file.reference().unwrap();
633 assert_eq!(reference.attachment_id, "AAAA");
753 assert_eq!(reference.attachment_id, "AAAA");
crates/graph/src/lib.rs +3 −3
@@ -19,9 +19,9 @@ pub use client::{BATCH_SIZE, CHAT_PAGE_SIZE, Graph, MESSAGE_PAGE_SIZE};
19 19 pub use cloud_files::{CloudFile, QuickSite};
20 20 pub use error::{Error, Result};
21 21 pub use files::{
22 DOWNLOAD_CHUNK_BYTES, DriveFolder, SharedFile, UPLOAD_CHUNK_BYTES, UploadDestination,
23 UploadedFile, chunk_range_at, chunk_ranges, download_ranges, etag_guid, next_expected_start,
24 percent_done, share_id,
22 DOWNLOAD_CHUNK_BYTES, DriveFolder, Recipient, SharedFile, UPLOAD_CHUNK_BYTES,
23 UploadDestination, UploadedFile, chunk_range_at, chunk_ranges, download_ranges, etag_guid,
24 next_expected_start, percent_done, share_id,
25 25 };
26 26 pub use library::DriveEntry;
27 27 pub use mailbox::{MailboxWorkingHours, parse_working_hours, working_hours_body};
@@ -19,9 +19,9 @@ pub use client::{BATCH_SIZE, CHAT_PAGE_SIZE, Graph, MESSAGE_PAGE_SIZE};
19pub use cloud_files::{CloudFile, QuickSite};
19pub use cloud_files::{CloudFile, QuickSite};
20pub use error::{Error, Result};
20pub use error::{Error, Result};
21pub use files::{
21pub use files::{
22 DOWNLOAD_CHUNK_BYTES, DriveFolder, SharedFile, UPLOAD_CHUNK_BYTES, UploadDestination,
22 DOWNLOAD_CHUNK_BYTES, DriveFolder, Recipient, SharedFile, UPLOAD_CHUNK_BYTES,
23 UploadedFile, chunk_range_at, chunk_ranges, download_ranges, etag_guid, next_expected_start,
23 UploadDestination, UploadedFile, chunk_range_at, chunk_ranges, download_ranges, etag_guid,
24 percent_done, share_id,
24 next_expected_start, percent_done, share_id,
25};
25};
26pub use library::DriveEntry;
26pub use library::DriveEntry;
27pub use mailbox::{MailboxWorkingHours, parse_working_hours, working_hours_body};
27pub use mailbox::{MailboxWorkingHours, parse_working_hours, working_hours_body};
crates/graph/src/urls.rs +8 −0
@@ -230,6 +230,14 @@ pub fn drive_item_invite(drive_id: &str, item_id: &str) -> String {
230 230 )
231 231 }
232 232
233 pub fn drive_item_create_link(drive_id: &str, item_id: &str) -> String {
234 format!(
235 "{GRAPH}/v1.0/drives/{}/items/{}/createLink",
236 segment(drive_id),
237 segment(item_id)
238 )
239 }
240
233 241 pub fn joined_teams() -> String {
234 242 format!("{GRAPH}/v1.0/me/joinedTeams?$select=id,displayName")
235 243 }
@@ -230,6 +230,14 @@ pub fn drive_item_invite(drive_id: &str, item_id: &str) -> String {
230 )
230 )
231}
231}
232
232
233pub fn drive_item_create_link(drive_id: &str, item_id: &str) -> String {
234 format!(
235 "{GRAPH}/v1.0/drives/{}/items/{}/createLink",
236 segment(drive_id),
237 segment(item_id)
238 )
239}
240
233pub fn joined_teams() -> String {
241pub fn joined_teams() -> String {
234 format!("{GRAPH}/v1.0/me/joinedTeams?$select=id,displayName")
242 format!("{GRAPH}/v1.0/me/joinedTeams?$select=id,displayName")
235}
243}