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