Skip to main content

coven_storage/providers/
oauth_folders.rs

1//! Choosing provider folders through coven-held sign-in, before storage setup.
2
3use super::{
4    http::{self, Body},
5    onedrive_item::{item_kind, Kind},
6    pagination::Pagination,
7    OAuthSession,
8};
9use crate::{
10    Cooldown, DropboxAccess, DropboxLocation, OAuthAccess, StorageConfig, StorageError,
11    StorageFailure,
12};
13use reqwest::Method;
14use serde_json::{json, Value};
15use std::sync::Arc;
16
17/// A provider folder's display name and the exact location accepted by setup.
18#[derive(Clone, Debug, PartialEq, Eq)]
19pub struct StorageFolder {
20    /// The provider's current folder name; never a token or credential.
21    pub name: String,
22    /// Pass unchanged to storage setup, or as a parent when browsing OneDrive.
23    pub storage: StorageConfig,
24}
25
26/// Provider metadata calls using the same session and cooldown as store setup.
27pub(super) struct OAuthFolders {
28    session: OAuthSession,
29    access: OAuthAccess,
30    api: String,
31    cooldown: Arc<dyn Cooldown>,
32}
33
34impl OAuthFolders {
35    pub(super) fn new(
36        session: OAuthSession,
37        access: OAuthAccess,
38        api: String,
39        cooldown: Arc<dyn Cooldown>,
40    ) -> Self {
41        Self { session, access, api, cooldown }
42    }
43
44    pub(super) async fn account_label(&self) -> Result<String, StorageError> {
45        crate::cooldown::cooling(self.cooldown.as_ref())?;
46        let result = self.session.account_at(&self.api).await;
47        crate::cooldown::observed(self.cooldown.as_ref(), result).await
48    }
49
50    pub(super) async fn account_identity(&self) -> Result<crate::ProviderAccount, StorageError> {
51        crate::cooldown::cooling(self.cooldown.as_ref())?;
52        let result = self.session.identity_at(&self.api).await;
53        crate::cooldown::observed(self.cooldown.as_ref(), result).await
54    }
55
56    fn require(&self, access: OAuthAccess) -> Result<(), StorageError> {
57        if self.access != access {
58            return Err(StorageFailure::InvalidConfiguration
59                .with_source("folder selection requires the matching sign-in access"));
60        }
61        Ok(())
62    }
63
64    async fn request(&self, method: Method, url: &str, body: Body) -> Result<Value, StorageError> {
65        Ok(self.request_response(method, url, body).await?.0)
66    }
67
68    /// `request`'s answer with the response it came in, for a status whose
69    /// failure the response describes.
70    async fn request_response(
71        &self,
72        method: Method,
73        url: &str,
74        body: Body,
75    ) -> Result<(Value, http::ProviderResponse), StorageError> {
76        crate::cooldown::cooling(self.cooldown.as_ref())?;
77        http::same_origin(&self.api, url)?;
78        let result = async {
79            http::json_response(
80                self.access.provider(),
81                self.session.send(method, url, &[], body, true).await?,
82            )
83            .await
84        }
85        .await;
86        crate::cooldown::observed(self.cooldown.as_ref(), result).await
87    }
88
89    /// The signed-in person's default OneDrive root, including its actual item id.
90    pub(super) async fn onedrive_root(&self) -> Result<StorageFolder, StorageError> {
91        self.require(OAuthAccess::OneDrive)?;
92        let url = http::endpoint(&self.api, &["me", "drive", "root"], &[])?;
93        let value = self.request(Method::GET, &url, Body::Empty).await?;
94        let drive = http::string(&value["parentReference"], "driveId")?;
95        if item_kind(&value)? != Kind::Folder {
96            return Err(StorageFailure::Protocol.with_source("OneDrive did not return a folder"));
97        }
98        onedrive_folder(&value, drive, http::string(&value, "name")?)
99    }
100
101    /// The immediate child folders; every page is read, without reading file bytes.
102    pub(super) async fn onedrive_folders(
103        &self,
104        parent: &StorageConfig,
105    ) -> Result<Vec<StorageFolder>, StorageError> {
106        self.require(OAuthAccess::OneDrive)?;
107        let (drive, folder) = onedrive_parent(parent)?;
108        let mut url =
109            http::endpoint(&self.api, &["drives", drive, "items", folder, "children"], &[])?;
110        let mut pages = Pagination::new();
111        let mut folders = Vec::new();
112        loop {
113            pages.check(&url)?;
114            let value = self.request(Method::GET, &url, Body::Empty).await?;
115            for item in http::array(&value, "value")? {
116                if let Some(folder) = onedrive_child(item, drive)? {
117                    folders.push(folder);
118                }
119            }
120            match http::next_link(&value)? {
121                None => return Ok(folders),
122                Some(next) => url = next.into(),
123            }
124        }
125    }
126
127    /// Create exactly the requested name. Occupied names remain provider errors.
128    pub(super) async fn create_onedrive_folder(
129        &self,
130        parent: &StorageConfig,
131        name: &str,
132    ) -> Result<StorageFolder, StorageError> {
133        self.require(OAuthAccess::OneDrive)?;
134        let (drive, folder) = onedrive_parent(parent)?;
135        let url = http::endpoint(&self.api, &["drives", drive, "items", folder, "children"], &[])?;
136        let value = self
137            .request(
138                Method::POST,
139                &url,
140                Body::Json(crate::providers::onedrive_item::new_folder(name)),
141            )
142            .await?;
143        if item_kind(&value)? != Kind::Folder {
144            return Err(StorageFailure::Protocol.with_source("OneDrive did not return a folder"));
145        }
146        onedrive_folder(&value, drive, http::string(&value, "name")?)
147    }
148
149    /// Shared folders the signed-in Dropbox account can access, including all pages.
150    pub(super) async fn dropbox_shared_folders(&self) -> Result<Vec<StorageFolder>, StorageError> {
151        if self.access == OAuthAccess::Dropbox(DropboxAccess::AppFolder) {
152            return Err(StorageFailure::DropboxAppFolderNotShareable.into());
153        }
154        self.require(OAuthAccess::Dropbox(DropboxAccess::FullDropbox))?;
155        let mut url = http::endpoint(&self.api, &["sharing", "list_folders"], &[])?;
156        let mut body = json!({});
157        let mut pages = Pagination::new();
158        let mut folders = Vec::new();
159        loop {
160            let value = self.request(Method::POST, &url, Body::Json(body)).await?;
161            for item in http::array(&value, "entries")? {
162                folders.push(dropbox_folder(item)?);
163            }
164            match http::page_cursor(&value)? {
165                None => return Ok(folders),
166                Some(cursor) => {
167                    pages.check(cursor)?;
168                    url = http::endpoint(&self.api, &["sharing", "list_folders", "continue"], &[])?;
169                    body = json!({"cursor": cursor});
170                }
171            }
172        }
173    }
174
175    /// Make a folder named `name` at the top of the signed-in Dropbox and
176    /// share it. The name is looked up first, so a name already taken fails
177    /// with `AlreadyExists` and nothing of the person's is shared; then one
178    /// `share_folder` request makes the folder and shares it, and its job, if
179    /// Dropbox runs one, is checked until it completes.
180    pub(super) async fn create_dropbox_shared_folder(
181        &self,
182        name: &str,
183    ) -> Result<StorageFolder, StorageError> {
184        if self.access == OAuthAccess::Dropbox(DropboxAccess::AppFolder) {
185            return Err(StorageFailure::DropboxAppFolderNotShareable.into());
186        }
187        self.require(OAuthAccess::Dropbox(DropboxAccess::FullDropbox))?;
188        if name.is_empty() || name.contains('/') {
189            return Err(StorageFailure::InvalidConfiguration
190                .with_source("a Dropbox folder name is one non-empty path segment"));
191        }
192        let path = format!("/{name}");
193        let lookup = http::endpoint(&self.api, &["files", "get_metadata"], &[])?;
194        match self.request(Method::POST, &lookup, Body::Json(json!({ "path": path }))).await {
195            Ok(_) => {
196                return Err(StorageFailure::AlreadyExists
197                    .with_source("the Dropbox folder name is already taken"))
198            }
199            Err(error) if error.failure() == StorageFailure::NotFound => {}
200            Err(error) => return Err(error),
201        }
202        let share = http::endpoint(&self.api, &["sharing", "share_folder"], &[])?;
203        let launched = self
204            .request(Method::POST, &share, Body::Json(json!({"path":path,"force_async":false})))
205            .await?;
206        let shared = match http::string(&launched, ".tag")? {
207            "complete" => launched,
208            "async_job_id" => {
209                let job = http::string(&launched, "async_job_id")?;
210                let status =
211                    http::endpoint(&self.api, &["sharing", "check_share_job_status"], &[])?;
212                super::dropbox_job::completed(&self.session, "folder sharing", || {
213                    self.request_response(
214                        Method::POST,
215                        &status,
216                        Body::Json(json!({"async_job_id":job})),
217                    )
218                })
219                .await?
220            }
221            _ => return Err(StorageFailure::Protocol.with_source("invalid Dropbox share launch")),
222        };
223        dropbox_folder(&shared)
224    }
225}
226
227/// The shared folder Dropbox's metadata `item` describes, as a setup
228/// location.
229fn dropbox_folder(item: &Value) -> Result<StorageFolder, StorageError> {
230    let storage = StorageConfig::Dropbox {
231        account_label: None,
232        folder_label: None,
233        location: DropboxLocation::SharedFolder {
234            namespace_id: http::string(item, "shared_folder_id")?.into(),
235        },
236    };
237    storage.validate().map_err(|error| StorageFailure::Protocol.with_source(error))?;
238    Ok(StorageFolder { name: http::string(item, "name")?.into(), storage })
239}
240
241fn onedrive_parent(parent: &StorageConfig) -> Result<(&str, &str), StorageError> {
242    parent.validate()?;
243    match parent {
244        StorageConfig::OneDrive { drive_id, folder_id, .. } => Ok((drive_id, folder_id)),
245        _ => {
246            Err(StorageFailure::InvalidConfiguration.with_source("parent is not a OneDrive folder"))
247        }
248    }
249}
250
251fn onedrive_child(item: &Value, parent_drive: &str) -> Result<Option<StorageFolder>, StorageError> {
252    let remote = match item.get("remoteItem") {
253        None | Some(Value::Null) => None,
254        Some(value) if value.is_object() => Some(value),
255        Some(_) => return Err(StorageFailure::Protocol.with_source("invalid OneDrive remote item")),
256    };
257    let target = remote.unwrap_or(item);
258    if item_kind(target)? != Kind::Folder {
259        tracing::debug!("OneDrive folder picker skipped a non-folder item");
260        return Ok(None);
261    }
262    let drive = match remote {
263        Some(_) => http::string(&target["parentReference"], "driveId")?,
264        None => parent_drive,
265    };
266    Ok(Some(onedrive_folder(target, drive, http::string(item, "name")?)?))
267}
268
269fn onedrive_folder(value: &Value, drive: &str, name: &str) -> Result<StorageFolder, StorageError> {
270    if let Some(reference) = value.get("parentReference") {
271        if http::string(reference, "driveId")? != drive {
272            return Err(
273                StorageFailure::Protocol.with_source("OneDrive folder belongs to another drive")
274            );
275        }
276    }
277    let storage = StorageConfig::OneDrive {
278        account_label: None,
279        folder_label: None,
280        drive_id: drive.into(),
281        folder_id: http::string(value, "id")?.into(),
282    };
283    storage.validate().map_err(|error| StorageFailure::Protocol.with_source(error))?;
284    Ok(StorageFolder { name: name.into(), storage })
285}