| 1 | use chrono::{DateTime, Utc}; |
| 2 | use serde_json::Value; |
| 3 | use session::{Method, Scope}; |
| 4 | |
| 5 | use crate::client::Graph; |
| 6 | use crate::error::{Error, Result}; |
| 7 | use crate::files::{DriveFolder, FILES_SCOPE, UploadedFile, finished_item, share_id}; |
| 8 | use crate::library::DriveEntry; |
| 9 | use crate::urls; |
| 10 | |
| 11 | /// A file in OneDrive or SharePoint that can be attached by reference, without uploading it again. |
| 12 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 13 | pub struct CloudFile { |
| 14 | pub name: String, |
| 15 | pub size: u64, |
| 16 | pub web_url: String, |
| 17 | pub drive_id: Option<String>, |
| 18 | pub item_id: Option<String>, |
| 19 | pub last_opened: Option<DateTime<Utc>>, |
| 20 | } |
| 21 | |
| 22 | fn time(value: &Value) -> Option<DateTime<Utc>> { |
| 23 | DateTime::parse_from_rfc3339(value.as_str()?) |
| 24 | .ok() |
| 25 | .map(|time| time.with_timezone(&Utc)) |
| 26 | } |
| 27 | |
| 28 | fn recent_file(item: &Value) -> Option<CloudFile> { |
| 29 | let remote = item |
| 30 | .get("remoteItem") |
| 31 | .filter(|remote| remote.is_object()) |
| 32 | .unwrap_or(item); |
| 33 | item.get("file")?; |
| 34 | let opened = |source: &Value| time(&source["fileSystemInfo"]["lastAccessedDateTime"]); |
| 35 | Some(CloudFile { |
| 36 | name: item["name"].as_str()?.to_owned(), |
| 37 | size: item["size"] |
| 38 | .as_u64() |
| 39 | .or_else(|| remote["size"].as_u64()) |
| 40 | .unwrap_or(0), |
| 41 | web_url: item["webUrl"] |
| 42 | .as_str() |
| 43 | .or_else(|| remote["webUrl"].as_str())? |
| 44 | .to_owned(), |
| 45 | drive_id: remote["parentReference"]["driveId"] |
| 46 | .as_str() |
| 47 | .map(str::to_owned), |
| 48 | item_id: remote["id"].as_str().map(str::to_owned), |
| 49 | last_opened: opened(remote).or_else(|| opened(item)), |
| 50 | }) |
| 51 | } |
| 52 | |
| 53 | const RECENT_FOR_SITES: usize = 100; |
| 54 | const SHARED_SHOWN: usize = 100; |
| 55 | const ROOT_ITEM: &str = "root"; |
| 56 | const QUICK_ACCESS_SITES: usize = 8; |
| 57 | |
| 58 | /// A SharePoint site under "Quick access". |
| 59 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 60 | pub struct QuickSite { |
| 61 | pub id: String, |
| 62 | pub name: String, |
| 63 | } |
| 64 | |
| 65 | impl From<&DriveEntry> for CloudFile { |
| 66 | fn from(entry: &DriveEntry) -> Self { |
| 67 | CloudFile { |
| 68 | name: entry.name.clone(), |
| 69 | size: entry.size, |
| 70 | web_url: entry.web_url.clone(), |
| 71 | drive_id: Some(entry.drive_id.clone()).filter(|id| !id.is_empty()), |
| 72 | item_id: Some(entry.id.clone()), |
| 73 | last_opened: None, |
| 74 | } |
| 75 | } |
| 76 | } |
| 77 | |
| 78 | fn user_name(value: &Value) -> Option<String> { |
| 79 | value["user"]["displayName"] |
| 80 | .as_str() |
| 81 | .filter(|name| !name.is_empty()) |
| 82 | .map(str::to_owned) |
| 83 | } |
| 84 | |
| 85 | /// A file someone shared, as a picker row: `modified_at` holds the share date, `modified_by` who shared it. |
| 86 | fn shared_entry(item: &Value) -> Option<DriveEntry> { |
| 87 | let remote = item.get("remoteItem").filter(|remote| remote.is_object())?; |
| 88 | let shared = &remote["shared"]; |
| 89 | Some(DriveEntry { |
| 90 | drive_id: remote["parentReference"]["driveId"].as_str()?.to_owned(), |
| 91 | id: remote["id"].as_str()?.to_owned(), |
| 92 | name: item["name"].as_str()?.to_owned(), |
| 93 | web_url: item["webUrl"] |
| 94 | .as_str() |
| 95 | .or_else(|| remote["webUrl"].as_str())? |
| 96 | .to_owned(), |
| 97 | size: remote["size"].as_u64().unwrap_or(0), |
| 98 | modified_at: time(&shared["sharedDateTime"]), |
| 99 | modified_by: user_name(&shared["sharedBy"]).or_else(|| user_name(&shared["owner"])), |
| 100 | child_count: remote |
| 101 | .get("folder") |
| 102 | .map(|folder| folder["childCount"].as_u64().unwrap_or(0)), |
| 103 | download_url: None, |
| 104 | }) |
| 105 | } |
| 106 | |
| 107 | pub fn parse_shared(body: &Value) -> Vec<DriveEntry> { |
| 108 | let mut shared: Vec<DriveEntry> = body["value"] |
| 109 | .as_array() |
| 110 | .into_iter() |
| 111 | .flatten() |
| 112 | .filter_map(shared_entry) |
| 113 | .collect(); |
| 114 | shared.sort_by(|first, second| second.modified_at.cmp(&first.modified_at)); |
| 115 | shared.truncate(SHARED_SHOWN); |
| 116 | shared |
| 117 | } |
| 118 | |
| 119 | /// The owner of each recent file, by item id, for the "Owner" column. |
| 120 | pub fn parse_recent_owners(body: &Value) -> Vec<(String, String)> { |
| 121 | body["value"] |
| 122 | .as_array() |
| 123 | .into_iter() |
| 124 | .flatten() |
| 125 | .filter_map(|item| { |
| 126 | let remote = item |
| 127 | .get("remoteItem") |
| 128 | .filter(|remote| remote.is_object()) |
| 129 | .unwrap_or(item); |
| 130 | let owner = user_name(&remote["shared"]["owner"]) |
| 131 | .or_else(|| user_name(&remote["createdBy"]))?; |
| 132 | Some((remote["id"].as_str()?.to_owned(), owner)) |
| 133 | }) |
| 134 | .collect() |
| 135 | } |
| 136 | |
| 137 | /// The SharePoint sites of recently opened files, most recent first, without personal OneDrives. |
| 138 | pub fn recent_site_ids(body: &Value, limit: usize) -> Vec<String> { |
| 139 | let mut sites: Vec<String> = Vec::new(); |
| 140 | for item in body["value"].as_array().into_iter().flatten() { |
| 141 | let remote = item |
| 142 | .get("remoteItem") |
| 143 | .filter(|remote| remote.is_object()) |
| 144 | .unwrap_or(item); |
| 145 | let web_url = remote["webUrl"] |
| 146 | .as_str() |
| 147 | .or_else(|| item["webUrl"].as_str()) |
| 148 | .unwrap_or_default(); |
| 149 | let site = remote["parentReference"]["siteId"] |
| 150 | .as_str() |
| 151 | .or_else(|| remote["sharepointIds"]["siteId"].as_str()); |
| 152 | if let Some(site) = site |
| 153 | && !web_url.contains("/personal/") |
| 154 | && !sites.iter().any(|known| known == site) |
| 155 | { |
| 156 | sites.push(site.to_owned()); |
| 157 | } |
| 158 | } |
| 159 | sites.truncate(limit); |
| 160 | sites |
| 161 | } |
| 162 | |
| 163 | pub fn parse_recent_files(body: &Value) -> Vec<CloudFile> { |
| 164 | body["value"] |
| 165 | .as_array() |
| 166 | .into_iter() |
| 167 | .flatten() |
| 168 | .filter_map(recent_file) |
| 169 | .collect() |
| 170 | } |
| 171 | |
| 172 | impl Graph { |
| 173 | pub async fn recent_files(&self, top: usize) -> Result<Vec<CloudFile>> { |
| 174 | Ok(self.recent_files_with_owners(top).await?.0) |
| 175 | } |
| 176 | |
| 177 | pub async fn recent_files_with_owners( |
| 178 | &self, |
| 179 | top: usize, |
| 180 | ) -> Result<(Vec<CloudFile>, Vec<(String, String)>)> { |
| 181 | let body = self |
| 182 | .get(&urls::recent_drive_items(top), &Scope::graph(FILES_SCOPE)) |
| 183 | .await?; |
| 184 | Ok((parse_recent_files(&body), parse_recent_owners(&body))) |
| 185 | } |
| 186 | |
| 187 | pub async fn shared_with_me(&self) -> Result<Vec<DriveEntry>> { |
| 188 | Ok(parse_shared( |
| 189 | &self |
| 190 | .get(&urls::shared_with_me(), &Scope::graph(FILES_SCOPE)) |
| 191 | .await?, |
| 192 | )) |
| 193 | } |
| 194 | |
| 195 | pub async fn quick_access_sites(&self) -> Result<Vec<QuickSite>> { |
| 196 | let scope = Scope::graph(FILES_SCOPE); |
| 197 | let recent = self |
| 198 | .get(&urls::recent_drive_items(RECENT_FOR_SITES), &scope) |
| 199 | .await?; |
| 200 | let mut sites = Vec::new(); |
| 201 | for site_id in recent_site_ids(&recent, QUICK_ACCESS_SITES) { |
| 202 | if let Ok(site) = self.get(&urls::site(&site_id), &scope).await |
| 203 | && let Some(name) = site["displayName"].as_str() |
| 204 | { |
| 205 | sites.push(QuickSite { |
| 206 | id: site_id, |
| 207 | name: name.to_owned(), |
| 208 | }); |
| 209 | } |
| 210 | } |
| 211 | Ok(sites) |
| 212 | } |
| 213 | |
| 214 | /// The root folder of the user's OneDrive, or of a site's document library. |
| 215 | pub async fn drive_root(&self, site_id: Option<&str>) -> Result<DriveFolder> { |
| 216 | let url = site_id.map_or_else(urls::my_drive, urls::site_drive); |
| 217 | let drive = self.get(&url, &Scope::graph(FILES_SCOPE)).await?; |
| 218 | let drive_id = drive["id"] |
| 219 | .as_str() |
| 220 | .ok_or_else(|| Error::Decode("a drive without an id".into()))?; |
| 221 | Ok(DriveFolder { |
| 222 | drive_id: drive_id.to_owned(), |
| 223 | item_id: ROOT_ITEM.to_owned(), |
| 224 | }) |
| 225 | } |
| 226 | |
| 227 | /// The reference a message needs to carry `file`: its drive item, found by id or else by its link. |
| 228 | pub async fn cloud_file_reference(&self, file: &CloudFile) -> Result<UploadedFile> { |
| 229 | let url = match (&file.drive_id, &file.item_id) { |
| 230 | (Some(drive_id), Some(item_id)) => urls::drive_item(drive_id, item_id), |
| 231 | _ => urls::shared_drive_item(&share_id(&file.web_url)), |
| 232 | }; |
| 233 | let answer = self |
| 234 | .session() |
| 235 | .request(Method::Get, &url, &Scope::graph(FILES_SCOPE), None) |
| 236 | .await?; |
| 237 | finished_item(answer.body) |
| 238 | } |
| 239 | } |
| 240 | |
| 241 | #[cfg(test)] |
| 242 | mod tests { |
| 243 | use serde_json::json; |
| 244 | |
| 245 | use super::*; |
| 246 | |
| 247 | #[test] |
| 248 | fn recent_files_take_ids_and_open_time_from_the_remote_item() { |
| 249 | let body = json!({"value": [ |
| 250 | {"name": "plan.pdf", "size": 12, "webUrl": "https://x/plan.pdf", "file": {}, |
| 251 | "fileSystemInfo": {"lastAccessedDateTime": "2026-11-09T10:00:00Z"}, |
| 252 | "remoteItem": {"id": "item-1", "parentReference": {"driveId": "drive-1"}, |
| 253 | "fileSystemInfo": {"lastAccessedDateTime": "2026-11-09T12:00:00Z"}}}, |
| 254 | {"name": "Folder", "webUrl": "https://x/folder", "folder": {}}, |
| 255 | {"name": "notes.docx", "webUrl": "https://x/notes.docx", "file": {}, "id": "item-2", |
| 256 | "parentReference": {"driveId": "drive-2"}} |
| 257 | ]}); |
| 258 | let files = parse_recent_files(&body); |
| 259 | assert_eq!(files.len(), 2); |
| 260 | assert_eq!(files[0].item_id.as_deref(), Some("item-1")); |
| 261 | assert_eq!(files[0].drive_id.as_deref(), Some("drive-1")); |
| 262 | assert_eq!( |
| 263 | files[0].last_opened.unwrap().to_rfc3339(), |
| 264 | "2026-11-09T12:00:00+00:00" |
| 265 | ); |
| 266 | assert_eq!( |
| 267 | (files[1].item_id.as_deref(), files[1].size), |
| 268 | (Some("item-2"), 0) |
| 269 | ); |
| 270 | assert!(files[1].last_opened.is_none()); |
| 271 | } |
| 272 | |
| 273 | #[test] |
| 274 | fn shared_files_carry_the_sharer_and_date_newest_first() { |
| 275 | let body = json!({"value": [ |
| 276 | {"name": "old.pdf", "webUrl": "https://x/o", "remoteItem": {"id": "o", "file": {}, "parentReference": {"driveId": "d"}, |
| 277 | "shared": {"sharedDateTime": "2026-10-01T10:00:00Z", "sharedBy": {"user": {"displayName": "Anna"}}}}}, |
| 278 | {"name": "Team", "webUrl": "https://x/t", "remoteItem": {"id": "t", "folder": {"childCount": 2}, "parentReference": {"driveId": "d"}, |
| 279 | "shared": {"sharedDateTime": "2026-11-01T10:00:00Z", "owner": {"user": {"displayName": "Ben"}}}}} |
| 280 | ]}); |
| 281 | let shared = parse_shared(&body); |
| 282 | assert_eq!(shared[0].name, "Team"); |
| 283 | assert!(shared[0].is_folder()); |
| 284 | assert_eq!(shared[0].modified_by.as_deref(), Some("Ben")); |
| 285 | assert_eq!(shared[1].modified_by.as_deref(), Some("Anna")); |
| 286 | assert_eq!(CloudFile::from(&shared[1]).item_id.as_deref(), Some("o")); |
| 287 | } |
| 288 | |
| 289 | #[test] |
| 290 | fn recent_owners_and_sites() { |
| 291 | let recent = json!({"value": [ |
| 292 | {"name": "a", "remoteItem": {"id": "1", "createdBy": {"user": {"displayName": "Cara"}}, |
| 293 | "webUrl": "https://t.sharepoint.com/sites/dev/a", "parentReference": {"siteId": "dev"}}}, |
| 294 | {"name": "b", "remoteItem": {"id": "2", "webUrl": "https://t-my.sharepoint.com/personal/x/b", "parentReference": {"siteId": "me"}}}, |
| 295 | {"name": "c", "remoteItem": {"id": "3", "webUrl": "https://t.sharepoint.com/sites/dev/c", "parentReference": {"siteId": "dev"}}}, |
| 296 | {"name": "d", "remoteItem": {"id": "4", "webUrl": "https://t.sharepoint.com/sites/ops/d", "sharepointIds": {"siteId": "ops"}}} |
| 297 | ]}); |
| 298 | assert_eq!( |
| 299 | parse_recent_owners(&recent), |
| 300 | vec![("1".to_owned(), "Cara".to_owned())] |
| 301 | ); |
| 302 | assert_eq!(recent_site_ids(&recent, 8), ["dev", "ops"]); |
| 303 | assert_eq!(recent_site_ids(&recent, 1), ["dev"]); |
| 304 | } |
| 305 | } |