| 1 | use base64::Engine as _; |
| 2 | use base64::engine::general_purpose::STANDARD; |
| 3 | use serde::Deserialize; |
| 4 | use serde_json::{Value, json}; |
| 5 | use session::{Method, Request, Scope, Session}; |
| 6 | |
| 7 | use crate::client::Graph; |
| 8 | use crate::error::{Error, Result}; |
| 9 | use crate::outgoing::FileReference; |
| 10 | use crate::urls; |
| 11 | |
| 12 | const FILES_SCOPE: &str = "Files.ReadWrite"; |
| 13 | const CHUNK_UNIT_BYTES: u64 = 327_680; |
| 14 | pub const UPLOAD_CHUNK_BYTES: u64 = 4 * CHUNK_UNIT_BYTES; |
| 15 | const MAX_CHUNK_RETRIES: usize = 3; |
| 16 | const MAX_NAME_ATTEMPTS: usize = 50; |
| 17 | |
| 18 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 19 | pub struct DriveFolder { |
| 20 | pub drive_id: String, |
| 21 | pub item_id: String, |
| 22 | } |
| 23 | |
| 24 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 25 | pub enum UploadDestination { |
| 26 | ChatFiles, |
| 27 | Folder(DriveFolder), |
| 28 | } |
| 29 | |
| 30 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 31 | pub struct UploadedFile { |
| 32 | pub drive_id: String, |
| 33 | pub item_id: String, |
| 34 | pub name: String, |
| 35 | pub web_url: String, |
| 36 | pub web_dav_url: Option<String>, |
| 37 | pub etag: String, |
| 38 | } |
| 39 | |
| 40 | impl UploadedFile { |
| 41 | pub fn reference(&self) -> Option<FileReference> { |
| 42 | Some(FileReference { |
| 43 | attachment_id: etag_guid(&self.etag)?, |
| 44 | content_url: self |
| 45 | .web_dav_url |
| 46 | .clone() |
| 47 | .unwrap_or_else(|| self.web_url.clone()), |
| 48 | name: self.name.clone(), |
| 49 | }) |
| 50 | } |
| 51 | } |
| 52 | |
| 53 | #[derive(Debug, Deserialize)] |
| 54 | #[serde(rename_all = "camelCase")] |
| 55 | struct DriveItem { |
| 56 | id: String, |
| 57 | name: String, |
| 58 | #[serde(default)] |
| 59 | web_url: String, |
| 60 | web_dav_url: Option<String>, |
| 61 | #[serde(default)] |
| 62 | e_tag: String, |
| 63 | parent_reference: Option<ParentReference>, |
| 64 | } |
| 65 | |
| 66 | #[derive(Debug, Deserialize)] |
| 67 | #[serde(rename_all = "camelCase")] |
| 68 | struct ParentReference { |
| 69 | drive_id: Option<String>, |
| 70 | } |
| 71 | |
| 72 | impl DriveItem { |
| 73 | fn drive_id(&self) -> Option<String> { |
| 74 | self.parent_reference.as_ref()?.drive_id.clone() |
| 75 | } |
| 76 | } |
| 77 | |
| 78 | /// `"{GUID},3"` becomes `GUID`. |
| 79 | pub fn etag_guid(etag: &str) -> Option<String> { |
| 80 | let start = etag.find('{')? + 1; |
| 81 | let length = etag[start..].find('}')?; |
| 82 | let guid = &etag[start..start + length]; |
| 83 | (!guid.is_empty()).then(|| guid.to_owned()) |
| 84 | } |
| 85 | |
| 86 | /// Inclusive range of the chunk that starts at `start`; a multiple of 320 KiB long except at the end. |
| 87 | pub fn chunk_range_at(start: u64, total: u64) -> (u64, u64) { |
| 88 | (start, (start + UPLOAD_CHUNK_BYTES).min(total) - 1) |
| 89 | } |
| 90 | |
| 91 | pub fn chunk_ranges(total: u64) -> Vec<(u64, u64)> { |
| 92 | let mut ranges = Vec::new(); |
| 93 | let mut start = 0; |
| 94 | while start < total { |
| 95 | let range = chunk_range_at(start, total); |
| 96 | start = range.1 + 1; |
| 97 | ranges.push(range); |
| 98 | } |
| 99 | ranges |
| 100 | } |
| 101 | |
| 102 | /// First byte the server still wants, from `nextExpectedRanges` (`["1310720-"]`). |
| 103 | pub fn next_expected_start(body: &Value) -> Option<u64> { |
| 104 | let range = body |
| 105 | .get("nextExpectedRanges")? |
| 106 | .as_array()? |
| 107 | .first()? |
| 108 | .as_str()?; |
| 109 | range.split('-').next()?.parse().ok() |
| 110 | } |
| 111 | |
| 112 | struct SessionGuard { |
| 113 | session: Session, |
| 114 | url: String, |
| 115 | armed: bool, |
| 116 | } |
| 117 | |
| 118 | impl SessionGuard { |
| 119 | fn disarm(&mut self) { |
| 120 | self.armed = false; |
| 121 | } |
| 122 | } |
| 123 | |
| 124 | impl Drop for SessionGuard { |
| 125 | fn drop(&mut self) { |
| 126 | if !self.armed { |
| 127 | return; |
| 128 | } |
| 129 | let Ok(runtime) = tokio::runtime::Handle::try_current() else { |
| 130 | return; |
| 131 | }; |
| 132 | let session = self.session.clone(); |
| 133 | let request = Request { |
| 134 | method: Method::Delete, |
| 135 | anonymous: true, |
| 136 | ..Request::get(std::mem::take(&mut self.url)) |
| 137 | }; |
| 138 | runtime.spawn(async move { |
| 139 | let _ = session.send(request, &Scope::graph(FILES_SCOPE)).await; |
| 140 | }); |
| 141 | } |
| 142 | } |
| 143 | |
| 144 | pub fn content_range(start: u64, end: u64, total: u64) -> String { |
| 145 | format!("bytes {start}-{end}/{total}") |
| 146 | } |
| 147 | |
| 148 | pub fn percent_done(sent: u64, total: u64) -> u8 { |
| 149 | if total == 0 { |
| 150 | return 100; |
| 151 | } |
| 152 | (sent.min(total) * 100 / total) as u8 |
| 153 | } |
| 154 | |
| 155 | pub fn numbered_name(file_name: &str, number: usize) -> String { |
| 156 | if number == 0 { |
| 157 | return file_name.to_owned(); |
| 158 | } |
| 159 | match file_name.rfind('.') { |
| 160 | Some(dot) if dot > 0 => format!("{} {number}{}", &file_name[..dot], &file_name[dot..]), |
| 161 | _ => format!("{file_name} {number}"), |
| 162 | } |
| 163 | } |
| 164 | |
| 165 | impl Graph { |
| 166 | /// conflictBehavior=rename was not honored on upload sessions: a same-named upload replaced the file. |
| 167 | async fn free_name(&self, destination: &UploadDestination, file_name: &str) -> Result<String> { |
| 168 | for number in 0..MAX_NAME_ATTEMPTS { |
| 169 | let candidate = numbered_name(file_name, number); |
| 170 | let url = match destination { |
| 171 | UploadDestination::ChatFiles => urls::chat_files_item(&candidate), |
| 172 | UploadDestination::Folder(folder) => { |
| 173 | urls::folder_item(&folder.drive_id, &folder.item_id, &candidate) |
| 174 | } |
| 175 | }; |
| 176 | match self |
| 177 | .session() |
| 178 | .request(Method::Get, &url, &Scope::graph(FILES_SCOPE), None) |
| 179 | .await |
| 180 | { |
| 181 | Ok(_) => continue, |
| 182 | Err(session::Error::Api { status: 404, .. }) => return Ok(candidate), |
| 183 | Err(error) => return Err(error.into()), |
| 184 | } |
| 185 | } |
| 186 | Err(Error::Upload(format!("no free name for {file_name}"))) |
| 187 | } |
| 188 | |
| 189 | pub async fn channel_files_folder( |
| 190 | &self, |
| 191 | team_id: &str, |
| 192 | channel_id: &str, |
| 193 | ) -> Result<DriveFolder> { |
| 194 | let answer = self |
| 195 | .session() |
| 196 | .request( |
| 197 | Method::Get, |
| 198 | &urls::channel_files_folder(team_id, channel_id), |
| 199 | &Scope::graph(FILES_SCOPE), |
| 200 | None, |
| 201 | ) |
| 202 | .await?; |
| 203 | let item: DriveItem = serde_json::from_value(answer.body)?; |
| 204 | let drive_id = item |
| 205 | .drive_id() |
| 206 | .ok_or_else(|| Error::Upload("the channel folder has no drive".into()))?; |
| 207 | Ok(DriveFolder { |
| 208 | drive_id, |
| 209 | item_id: item.id, |
| 210 | }) |
| 211 | } |
| 212 | |
| 213 | pub async fn upload_file( |
| 214 | &self, |
| 215 | destination: &UploadDestination, |
| 216 | file_name: &str, |
| 217 | bytes: &[u8], |
| 218 | progress: &(dyn Fn(u8) + Send + Sync), |
| 219 | ) -> Result<UploadedFile> { |
| 220 | if bytes.is_empty() { |
| 221 | return Err(Error::EmptyUpload); |
| 222 | } |
| 223 | let scope = Scope::graph(FILES_SCOPE); |
| 224 | let shown_name = file_name; |
| 225 | let file_name = self.free_name(destination, file_name).await?; |
| 226 | let file_name = file_name.as_str(); |
| 227 | let session_url = match destination { |
| 228 | UploadDestination::ChatFiles => urls::chat_files_upload_session(file_name), |
| 229 | UploadDestination::Folder(folder) => { |
| 230 | urls::folder_upload_session(&folder.drive_id, &folder.item_id, file_name) |
| 231 | } |
| 232 | }; |
| 233 | let created = self |
| 234 | .session() |
| 235 | .request( |
| 236 | Method::Post, |
| 237 | &session_url, |
| 238 | &scope, |
| 239 | Some(json!({"item": {"@microsoft.graph.conflictBehavior": "fail"}})), |
| 240 | ) |
| 241 | .await?; |
| 242 | let upload_url = created |
| 243 | .body |
| 244 | .get("uploadUrl") |
| 245 | .and_then(Value::as_str) |
| 246 | .ok_or_else(|| Error::Upload("no upload URL in the answer".into()))? |
| 247 | .to_owned(); |
| 248 | let mut guard = SessionGuard { |
| 249 | session: self.session().clone(), |
| 250 | url: upload_url.clone(), |
| 251 | armed: true, |
| 252 | }; |
| 253 | let total = bytes.len() as u64; |
| 254 | progress(0); |
| 255 | let mut offset = 0; |
| 256 | let mut failures = 0; |
| 257 | while offset < total { |
| 258 | let (start, end) = chunk_range_at(offset, total); |
| 259 | let request = Request::anonymous_bytes( |
| 260 | Method::Put, |
| 261 | upload_url.clone(), |
| 262 | vec![("Content-Range".to_owned(), content_range(start, end, total))], |
| 263 | STANDARD.encode(&bytes[start as usize..=end as usize]), |
| 264 | ); |
| 265 | match self.session().send(request, &scope).await { |
| 266 | Ok(answer) if matches!(answer.status, 200 | 201) => { |
| 267 | guard.disarm(); |
| 268 | progress(100); |
| 269 | let mut uploaded = finished_item(answer.body)?; |
| 270 | uploaded.name = shown_name.to_owned(); |
| 271 | return Ok(uploaded); |
| 272 | } |
| 273 | Ok(_) => { |
| 274 | failures = 0; |
| 275 | offset = end + 1; |
| 276 | progress(percent_done(offset, total).min(99)); |
| 277 | } |
| 278 | Err(error) => { |
| 279 | failures += 1; |
| 280 | if failures > MAX_CHUNK_RETRIES { |
| 281 | return Err(error.into()); |
| 282 | } |
| 283 | if let Some(next) = self.resume_offset(&upload_url, &scope).await { |
| 284 | offset = next.min(total); |
| 285 | } |
| 286 | } |
| 287 | } |
| 288 | } |
| 289 | Err(Error::Upload( |
| 290 | "the last chunk did not finish the upload".into(), |
| 291 | )) |
| 292 | } |
| 293 | |
| 294 | async fn resume_offset(&self, upload_url: &str, scope: &Scope) -> Option<u64> { |
| 295 | let request = Request { |
| 296 | anonymous: true, |
| 297 | ..Request::get(upload_url) |
| 298 | }; |
| 299 | let answer = self.session().send(request, scope).await.ok()?; |
| 300 | next_expected_start(&answer.body) |
| 301 | } |
| 302 | |
| 303 | pub async fn delete_drive_item(&self, drive_id: &str, item_id: &str) -> Result<()> { |
| 304 | self.session() |
| 305 | .request( |
| 306 | Method::Delete, |
| 307 | &urls::drive_item(drive_id, item_id), |
| 308 | &Scope::graph(FILES_SCOPE), |
| 309 | None, |
| 310 | ) |
| 311 | .await?; |
| 312 | Ok(()) |
| 313 | } |
| 314 | |
| 315 | pub async fn share_item(&self, file: &UploadedFile, user_ids: &[String]) -> Result<()> { |
| 316 | if user_ids.is_empty() { |
| 317 | return Ok(()); |
| 318 | } |
| 319 | let recipients: Vec<Value> = user_ids |
| 320 | .iter() |
| 321 | .map(|user_id| json!({"objectId": user_id})) |
| 322 | .collect(); |
| 323 | self.session() |
| 324 | .request( |
| 325 | Method::Post, |
| 326 | &urls::drive_item_invite(&file.drive_id, &file.item_id), |
| 327 | &Scope::graph(FILES_SCOPE), |
| 328 | Some(json!({ |
| 329 | "recipients": recipients, |
| 330 | "roles": ["read"], |
| 331 | "requireSignIn": true, |
| 332 | "sendInvitation": false, |
| 333 | })), |
| 334 | ) |
| 335 | .await?; |
| 336 | Ok(()) |
| 337 | } |
| 338 | } |
| 339 | |
| 340 | fn finished_item(body: Value) -> Result<UploadedFile> { |
| 341 | let item: DriveItem = serde_json::from_value(body)?; |
| 342 | let drive_id = item |
| 343 | .drive_id() |
| 344 | .ok_or_else(|| Error::Upload("the uploaded file has no drive".into()))?; |
| 345 | Ok(UploadedFile { |
| 346 | drive_id, |
| 347 | item_id: item.id, |
| 348 | name: item.name, |
| 349 | web_url: item.web_url, |
| 350 | web_dav_url: item.web_dav_url, |
| 351 | etag: item.e_tag, |
| 352 | }) |
| 353 | } |
| 354 | |
| 355 | #[cfg(test)] |
| 356 | mod tests { |
| 357 | #[test] |
| 358 | fn numbered_name_goes_before_the_extension() { |
| 359 | assert_eq!(super::numbered_name("plan.pdf", 0), "plan.pdf"); |
| 360 | assert_eq!(super::numbered_name("plan.pdf", 1), "plan 1.pdf"); |
| 361 | assert_eq!( |
| 362 | super::numbered_name("archive.tar.gz", 2), |
| 363 | "archive.tar 2.gz" |
| 364 | ); |
| 365 | assert_eq!(super::numbered_name("README", 3), "README 3"); |
| 366 | assert_eq!(super::numbered_name(".env", 1), ".env 1"); |
| 367 | } |
| 368 | |
| 369 | use super::*; |
| 370 | |
| 371 | #[test] |
| 372 | fn etag_guid_is_the_part_between_braces() { |
| 373 | assert_eq!( |
| 374 | etag_guid("\"{4F2A9C1E-0B7D-4C3A-9E55-1A2B3C4D5E6F},3\""), |
| 375 | Some("4F2A9C1E-0B7D-4C3A-9E55-1A2B3C4D5E6F".to_owned()) |
| 376 | ); |
| 377 | assert_eq!(etag_guid("\"abc,3\""), None); |
| 378 | assert_eq!(etag_guid("{}"), None); |
| 379 | assert_eq!(etag_guid(""), None); |
| 380 | } |
| 381 | |
| 382 | #[test] |
| 383 | fn small_files_are_one_chunk() { |
| 384 | assert_eq!(chunk_ranges(1), vec![(0, 0)]); |
| 385 | assert_eq!( |
| 386 | chunk_ranges(UPLOAD_CHUNK_BYTES), |
| 387 | vec![(0, UPLOAD_CHUNK_BYTES - 1)] |
| 388 | ); |
| 389 | assert!(chunk_ranges(0).is_empty()); |
| 390 | } |
| 391 | |
| 392 | #[test] |
| 393 | fn chunks_are_multiples_of_320_kib_except_the_last() { |
| 394 | let total = 2 * UPLOAD_CHUNK_BYTES + 12_345; |
| 395 | let ranges = chunk_ranges(total); |
| 396 | assert_eq!(ranges.len(), 3); |
| 397 | for (start, end) in &ranges[..2] { |
| 398 | assert_eq!((end + 1 - start) % CHUNK_UNIT_BYTES, 0); |
| 399 | assert_eq!(end + 1 - start, UPLOAD_CHUNK_BYTES); |
| 400 | } |
| 401 | let (last_start, last_end) = ranges[2]; |
| 402 | assert_eq!(last_end + 1 - last_start, 12_345); |
| 403 | assert_eq!(last_end + 1, total); |
| 404 | } |
| 405 | |
| 406 | #[test] |
| 407 | fn chunks_are_contiguous_and_cover_the_file() { |
| 408 | let total = 3 * UPLOAD_CHUNK_BYTES - 7; |
| 409 | let ranges = chunk_ranges(total); |
| 410 | assert_eq!(ranges[0].0, 0); |
| 411 | for pair in ranges.windows(2) { |
| 412 | assert_eq!(pair[0].1 + 1, pair[1].0); |
| 413 | } |
| 414 | assert_eq!(ranges.last().unwrap().1 + 1, total); |
| 415 | } |
| 416 | |
| 417 | #[test] |
| 418 | fn resume_offset_comes_from_the_next_expected_range() { |
| 419 | assert_eq!( |
| 420 | next_expected_start(&json!({"nextExpectedRanges": ["1310720-"]})), |
| 421 | Some(1_310_720) |
| 422 | ); |
| 423 | assert_eq!( |
| 424 | next_expected_start(&json!({"nextExpectedRanges": ["26-100", "200-"]})), |
| 425 | Some(26) |
| 426 | ); |
| 427 | assert_eq!( |
| 428 | next_expected_start(&json!({"nextExpectedRanges": []})), |
| 429 | None |
| 430 | ); |
| 431 | assert_eq!(next_expected_start(&json!({})), None); |
| 432 | } |
| 433 | |
| 434 | #[test] |
| 435 | fn chunk_size_stays_well_under_the_evaluate_timeout() { |
| 436 | assert_eq!(UPLOAD_CHUNK_BYTES, 1_310_720); |
| 437 | assert_eq!(chunk_range_at(1_310_720, 2_000_000), (1_310_720, 1_999_999)); |
| 438 | } |
| 439 | |
| 440 | #[test] |
| 441 | fn content_range_header_matches_graph() { |
| 442 | assert_eq!( |
| 443 | content_range(0, 5_242_879, 6_000_000), |
| 444 | "bytes 0-5242879/6000000" |
| 445 | ); |
| 446 | } |
| 447 | |
| 448 | #[test] |
| 449 | fn progress_is_a_percentage() { |
| 450 | assert_eq!(percent_done(0, 200), 0); |
| 451 | assert_eq!(percent_done(50, 200), 25); |
| 452 | assert_eq!(percent_done(200, 200), 100); |
| 453 | assert_eq!(percent_done(5, 0), 100); |
| 454 | } |
| 455 | |
| 456 | #[test] |
| 457 | fn uploaded_file_reference_prefers_the_webdav_url() { |
| 458 | let mut file = UploadedFile { |
| 459 | drive_id: "d".into(), |
| 460 | item_id: "i".into(), |
| 461 | name: "a.pdf".into(), |
| 462 | web_url: "https://x/web".into(), |
| 463 | web_dav_url: Some("https://x/dav".into()), |
| 464 | etag: "\"{AAAA},1\"".into(), |
| 465 | }; |
| 466 | let reference = file.reference().unwrap(); |
| 467 | assert_eq!(reference.attachment_id, "AAAA"); |
| 468 | assert_eq!(reference.content_url, "https://x/dav"); |
| 469 | file.web_dav_url = None; |
| 470 | assert_eq!(file.reference().unwrap().content_url, "https://x/web"); |
| 471 | file.etag = "nope".into(); |
| 472 | assert!(file.reference().is_none()); |
| 473 | } |
| 474 | |
| 475 | #[test] |
| 476 | fn drive_item_answer_parses() { |
| 477 | let item = finished_item(json!({ |
| 478 | "id": "01F", "name": "a.pdf", "webUrl": "https://x/web", |
| 479 | "webDavUrl": "https://x/dav", "eTag": "\"{AAAA},2\"", |
| 480 | "parentReference": {"driveId": "b!d"} |
| 481 | })) |
| 482 | .unwrap(); |
| 483 | assert_eq!(item.drive_id, "b!d"); |
| 484 | assert_eq!(item.item_id, "01F"); |
| 485 | assert_eq!(item.web_dav_url.as_deref(), Some("https://x/dav")); |
| 486 | } |
| 487 | } |