BlueGit

ict rusty-teams

Files

rusty-teams / crates / graph / src / cloud_files.rs

cloud_files.rs

cloud_files.rs 3.7 KiB Download Raw
1use chrono::{DateTime, Utc};
2use serde_json::Value;
3use session::{Method, Scope};
4
5use crate::client::Graph;
6use crate::error::Result;
7use crate::files::{FILES_SCOPE, UploadedFile, finished_item, share_id};
8use crate::urls;
9
10/// A file in OneDrive or SharePoint that can be attached by reference, without uploading it again.
11#[derive(Debug, Clone, PartialEq, Eq)]
12pub struct CloudFile {
13 pub name: String,
14 pub size: u64,
15 pub web_url: String,
16 pub drive_id: Option<String>,
17 pub item_id: Option<String>,
18 pub last_opened: Option<DateTime<Utc>>,
19}
20
21fn time(value: &Value) -> Option<DateTime<Utc>> {
22 DateTime::parse_from_rfc3339(value.as_str()?)
23 .ok()
24 .map(|time| time.with_timezone(&Utc))
25}
26
27fn recent_file(item: &Value) -> Option<CloudFile> {
28 let remote = item.get("remoteItem").filter(|remote| remote.is_object()).unwrap_or(item);
29 item.get("file")?;
30 let opened = |source: &Value| time(&source["fileSystemInfo"]["lastAccessedDateTime"]);
31 Some(CloudFile {
32 name: item["name"].as_str()?.to_owned(),
33 size: item["size"].as_u64().or_else(|| remote["size"].as_u64()).unwrap_or(0),
34 web_url: item["webUrl"].as_str().or_else(|| remote["webUrl"].as_str())?.to_owned(),
35 drive_id: remote["parentReference"]["driveId"].as_str().map(str::to_owned),
36 item_id: remote["id"].as_str().map(str::to_owned),
37 last_opened: opened(remote).or_else(|| opened(item)),
38 })
39}
40
41pub fn parse_recent_files(body: &Value) -> Vec<CloudFile> {
42 body["value"]
43 .as_array()
44 .into_iter()
45 .flatten()
46 .filter_map(recent_file)
47 .collect()
48}
49
50impl Graph {
51 pub async fn recent_files(&self, top: usize) -> Result<Vec<CloudFile>> {
52 let answer = self
53 .session()
54 .request(Method::Get, &urls::recent_drive_items(top), &Scope::graph(FILES_SCOPE), None)
55 .await?;
56 Ok(parse_recent_files(&answer.body))
57 }
58
59 /// The reference a message needs to carry `file`: its drive item, found by id or else by its link.
60 pub async fn cloud_file_reference(&self, file: &CloudFile) -> Result<UploadedFile> {
61 let url = match (&file.drive_id, &file.item_id) {
62 (Some(drive_id), Some(item_id)) => urls::drive_item(drive_id, item_id),
63 _ => urls::shared_drive_item(&share_id(&file.web_url)),
64 };
65 let answer = self
66 .session()
67 .request(Method::Get, &url, &Scope::graph(FILES_SCOPE), None)
68 .await?;
69 finished_item(answer.body)
70 }
71}
72
73#[cfg(test)]
74mod tests {
75 use serde_json::json;
76
77 use super::*;
78
79 #[test]
80 fn recent_files_take_ids_and_open_time_from_the_remote_item() {
81 let body = json!({"value": [
82 {"name": "plan.pdf", "size": 12, "webUrl": "https://x/plan.pdf", "file": {},
83 "fileSystemInfo": {"lastAccessedDateTime": "2026-11-09T10:00:00Z"},
84 "remoteItem": {"id": "item-1", "parentReference": {"driveId": "drive-1"},
85 "fileSystemInfo": {"lastAccessedDateTime": "2026-11-09T12:00:00Z"}}},
86 {"name": "Folder", "webUrl": "https://x/folder", "folder": {}},
87 {"name": "notes.docx", "webUrl": "https://x/notes.docx", "file": {}, "id": "item-2",
88 "parentReference": {"driveId": "drive-2"}}
89 ]});
90 let files = parse_recent_files(&body);
91 assert_eq!(files.len(), 2);
92 assert_eq!(files[0].item_id.as_deref(), Some("item-1"));
93 assert_eq!(files[0].drive_id.as_deref(), Some("drive-1"));
94 assert_eq!(files[0].last_opened.unwrap().to_rfc3339(), "2026-11-09T12:00:00+00:00");
95 assert_eq!((files[1].item_id.as_deref(), files[1].size), (Some("item-2"), 0));
96 assert!(files[1].last_opened.is_none());
97 }
98}