π End-to-end encrypted cloud for everything.
Dart 2faandroidauthye2eeencryptionend-to-end-encryptionfluttergolanggoogle-photosgoogle-photos-alternativeiosopensourcephotosprivacyprivacy-toolstypescriptzero-knowledge
Dissolve the CLI verb wrappers, fix query params
Manav Rathi9baa1be09fb8
diff --git a/rust/apps/cli/Cargo.toml b/rust/apps/cli/Cargo.tomlindex fded86fce6..dfb3041566 100644--- a/rust/apps/cli/Cargo.toml+++ b/rust/apps/cli/Cargo.toml@@ -14,6 +14,10 @@ museum = []name = "paste"required-features = ["museum"]+[[test]]+name = "sync"+required-features = ["museum"]+[dependencies]# CLIclap = { version = "4.5", features = ["derive", "env"] }diff --git a/rust/apps/cli/src/api/client.rs b/rust/apps/cli/src/api/client.rsindex fac27bfd99..723d23c0f2 100644--- a/rust/apps/cli/src/api/client.rs+++ b/rust/apps/cli/src/api/client.rs@@ -1,8 +1,6 @@use crate::models::error::Result;use ente_core::http::{self, Api, ApiConfig, Auth, Http, RetryProfile};use ente_core::urls::PRODUCTION_API_BASE_URL;-use serde::Serialize;-use serde::de::DeserializeOwned;use std::collections::HashMap;use std::sync::{Arc, RwLock};@@ -56,7 +54,7 @@ impl ApiClient {&self.client_package}- fn api(&self, account_id: Option<&str>) -> Api {+ pub(crate) fn api(&self, account_id: Option<&str>) -> Api {let auth = account_id.and_then(|id| {let token = self.get_token(id);if token.is_none() {@@ -76,108 +74,6 @@ impl ApiClient {)}- pub async fn get<T: DeserializeOwned>(- &self,- path: &str,- account_id: Option<&str>,- ) -> Result<T> {- let api = self.api(account_id);- Ok(http::retry(|| async {- api.get(path)- .send()- .await?- .error_for_code()- .await?- .json()- .await- })- .await?)- }-- pub async fn post<T, B>(&self, path: &str, body: &B, account_id: Option<&str>) -> Result<T>- where- T: DeserializeOwned,- B: Serialize,- {- let api = self.api(account_id);- Ok(http::retry(|| async {- api.post(path)- .json(body)- .send()- .await?- .error_for_code()- .await?- .json()- .await- })- .await?)- }-- pub async fn post_empty<B>(&self, path: &str, body: &B, account_id: Option<&str>) -> Result<()>- where- B: Serialize,- {- let api = self.api(account_id);- http::retry(|| async {- api.post(path)- .json(body)- .send()- .await?- .error_for_code()- .await?;- Ok(())- })- .await?;- Ok(())- }-- pub async fn put<T, B>(&self, path: &str, body: &B, account_id: Option<&str>) -> Result<T>- where- T: DeserializeOwned,- B: Serialize,- {- let api = self.api(account_id);- Ok(http::retry(|| async {- api.put(path)- .json(body)- .send()- .await?- .error_for_code()- .await?- .json()- .await- })- .await?)- }-- pub async fn put_empty<B>(&self, path: &str, body: &B, account_id: Option<&str>) -> Result<()>- where- B: Serialize,- {- let api = self.api(account_id);- http::retry(|| async {- api.put(path)- .json(body)- .send()- .await?- .error_for_code()- .await?;- Ok(())- })- .await?;- Ok(())- }-- pub async fn delete(&self, path: &str, account_id: Option<&str>) -> Result<()> {- let api = self.api(account_id);- http::retry(|| async {- api.delete(path).send().await?.error_for_code().await?;- Ok(())- })- .await?;- Ok(())- }-pub async fn download_file(&self, url: &str, account_id: Option<&str>) -> Result<Vec<u8>> {let token = account_id.and_then(|id| self.get_token(id));Ok(diff --git a/rust/apps/cli/src/api/methods.rs b/rust/apps/cli/src/api/methods.rsindex b2f52fde1a..5d65ee6789 100644--- a/rust/apps/cli/src/api/methods.rs+++ b/rust/apps/cli/src/api/methods.rs@@ -4,51 +4,87 @@ use crate::api::models::{GetThumbnailUrlResponse, UserDetails,};use crate::models::error::Result;+use ente_core::http;use ente_core::urls::file_download_url;pub struct ApiMethods<'a> {- api: &'a ApiClient,+ client: &'a ApiClient,}impl<'a> ApiMethods<'a> {- pub fn new(api: &'a ApiClient) -> Self {- Self { api }+ pub fn new(client: &'a ApiClient) -> Self {+ Self { client }}- // ========== User Methods ==========-pub async fn get_user_details(&self, account_id: &str) -> Result<UserDetails> {- self.api.get("/users/details", Some(account_id)).await+ let api = self.client.api(Some(account_id));+ Ok(http::retry(|| async {+ api.get("/users/details")+ .send()+ .await?+ .error_for_code()+ .await?+ .json()+ .await+ })+ .await?)}- // ========== Collection Methods ==========-pub async fn get_collections(&self,account_id: &str,since_time: i64,) -> Result<Vec<Collection>> {- let url = format!("/collections/v2?sinceTime={since_time}");- let response: GetCollectionsResponse = self.api.get(&url, Some(account_id)).await?;+ let api = self.client.api(Some(account_id));+ let response: GetCollectionsResponse = http::retry(|| async {+ api.get("/collections/v2")+ .query(&[("sinceTime", since_time.to_string())])+ .send()+ .await?+ .error_for_code()+ .await?+ .json()+ .await+ })+ .await?;Ok(response.collections)}pub async fn get_collection(&self, account_id: &str, collection_id: i64) -> Result<Collection> {- let url = format!("/collections/{collection_id}");- self.api.get(&url, Some(account_id)).await+ let api = self.client.api(Some(account_id));+ Ok(http::retry(|| async {+ api.get(&format!("/collections/{collection_id}"))+ .send()+ .await?+ .error_for_code()+ .await?+ .json()+ .await+ })+ .await?)}- // ========== File Methods ==========-pub async fn get_collection_files(&self,account_id: &str,collection_id: i64,since_time: i64,) -> Result<(Vec<File>, bool)> {- let url =- format!("/collections/v2/diff?collectionID={collection_id}&sinceTime={since_time}");- let response: GetFilesResponse = self.api.get(&url, Some(account_id)).await?;+ let api = self.client.api(Some(account_id));+ let response: GetFilesResponse = http::retry(|| async {+ api.get("/collections/v2/diff")+ .query(&[+ ("collectionID", collection_id.to_string()),+ ("sinceTime", since_time.to_string()),+ ])+ .send()+ .await?+ .error_for_code()+ .await?+ .json()+ .await+ })+ .await?;Ok((response.diff, response.has_more))}@@ -58,8 +94,21 @@ impl<'a> ApiMethods<'a> {collection_id: i64,file_id: i64,) -> Result<File> {- let url = format!("/collections/file?collectionID={collection_id}&fileID={file_id}");- let response: GetFileResponse = self.api.get(&url, Some(account_id)).await?;+ let api = self.client.api(Some(account_id));+ let response: GetFileResponse = http::retry(|| async {+ api.get("/collections/file")+ .query(&[+ ("collectionID", collection_id.to_string()),+ ("fileID", file_id.to_string()),+ ])+ .send()+ .await?+ .error_for_code()+ .await?+ .json()+ .await+ })+ .await?;Ok(response.file)}@@ -69,52 +118,97 @@ impl<'a> ApiMethods<'a> {since_time: i64,limit: i32,) -> Result<(Vec<File>, bool)> {- let url = format!("/diff?sinceTime={since_time}&limit={limit}");- let response: GetDiffResponse = self.api.get(&url, Some(account_id)).await?;+ let api = self.client.api(Some(account_id));+ let response: GetDiffResponse = http::retry(|| async {+ api.get("/diff")+ .query(&[+ ("sinceTime", since_time.to_string()),+ ("limit", limit.to_string()),+ ])+ .send()+ .await?+ .error_for_code()+ .await?+ .json()+ .await+ })+ .await?;Ok((response.diff, response.has_more))}pub async fn get_file_url(&self, _account_id: &str, file_id: i64) -> Result<String> {- Ok(file_download_url(&self.api.base_url, file_id))+ Ok(file_download_url(&self.client.base_url, file_id))}pub async fn get_thumbnail_url(&self, account_id: &str, file_id: i64) -> Result<String> {- let url = format!("/files/preview/{file_id}");- let response: GetThumbnailUrlResponse = self.api.get(&url, Some(account_id)).await?;+ let api = self.client.api(Some(account_id));+ let response: GetThumbnailUrlResponse = http::retry(|| async {+ api.get(&format!("/files/preview/{file_id}"))+ .send()+ .await?+ .error_for_code()+ .await?+ .json()+ .await+ })+ .await?;Ok(response.url)}pub async fn download_file(&self, account_id: &str, file_id: i64) -> Result<Vec<u8>> {let url = self.get_file_url(account_id, file_id).await?;- self.api.download_file(&url, Some(account_id)).await+ self.client.download_file(&url, Some(account_id)).await}pub async fn download_thumbnail(&self, account_id: &str, file_id: i64) -> Result<Vec<u8>> {let url = self.get_thumbnail_url(account_id, file_id).await?;- self.api.download_file(&url, Some(account_id)).await+ self.client.download_file(&url, Some(account_id)).await}- // ========== Trash Methods ==========-pub async fn get_trash(&self, account_id: &str, since_time: i64) -> Result<(Vec<File>, bool)> {- let url = format!("/trash/v2?sinceTime={since_time}");- let response: GetDiffResponse = self.api.get(&url, Some(account_id)).await?;+ let api = self.client.api(Some(account_id));+ let response: GetDiffResponse = http::retry(|| async {+ api.get("/trash/v2")+ .query(&[("sinceTime", since_time.to_string())])+ .send()+ .await?+ .error_for_code()+ .await?+ .json()+ .await+ })+ .await?;Ok((response.diff, response.has_more))}pub async fn delete_from_trash(&self, account_id: &str, file_ids: &[i64]) -> Result<()> {- let body = serde_json::json!({- "fileIDs": file_ids- });- let _: serde_json::Value = self- .api- .post("/trash/delete", &body, Some(account_id))- .await?;+ let api = self.client.api(Some(account_id));+ let body = serde_json::json!({ "fileIDs": file_ids });+ http::retry(|| async {+ api.post("/trash/delete")+ .json(&body)+ .send()+ .await?+ .error_for_code()+ .await?;+ Ok(())+ })+ .await?;Ok(())}pub async fn empty_trash(&self, account_id: &str) -> Result<()> {- self.api.delete("/trash/empty", Some(account_id)).await+ let api = self.client.api(Some(account_id));+ http::retry(|| async {+ api.delete("/trash/empty")+ .send()+ .await?+ .error_for_code()+ .await?;+ Ok(())+ })+ .await?;+ Ok(())}}diff --git a/rust/apps/cli/src/commands/export.rs b/rust/apps/cli/src/commands/export.rsindex 857bc82b77..443a58f77e 100644--- a/rust/apps/cli/src/commands/export.rs+++ b/rust/apps/cli/src/commands/export.rs@@ -158,6 +158,7 @@ pub async fn run_export(account_email: Option<String>, filter: ExportFilter) ->}// Export each account+ let mut failures = 0;for account in accounts_to_export {println!("\n=== Exporting account: {} ===", account.email);@@ -166,6 +167,7 @@ pub async fn run_export(account_email: Option<String>, filter: ExportFilter) ->if let Err(e) = sync_account_before_export(&storage, &account).await {log::error!("Failed to sync account {}: {}", account.email, e);println!("β Sync failed: {e}");+ failures += 1;continue;}println!("β Sync completed!");@@ -173,11 +175,17 @@ pub async fn run_export(account_email: Option<String>, filter: ExportFilter) ->if let Err(e) = export_account(&storage, &account, &filter).await {log::error!("Failed to export account {}: {}", account.email, e);println!("β Export failed: {e}");+ failures += 1;} else {println!("β Export completed successfully!");}}+ if failures > 0 {+ return Err(crate::Error::Generic(format!(+ "export failed for {failures} account(s)"+ )));+ }Ok(())}diff --git a/rust/apps/cli/src/models/error.rs b/rust/apps/cli/src/models/error.rsindex f30b15a081..b456c060e4 100644--- a/rust/apps/cli/src/models/error.rs+++ b/rust/apps/cli/src/models/error.rs@@ -53,7 +53,7 @@ pub enum Error {impl From<ente_core::http::Error> for Error {fn from(error: ente_core::http::Error) -> Self {- let message = error.to_string();+ let message = ente_core::error::chain(&error);match error {ente_core::http::Error::Http { status, .. } => Error::ApiError {status,diff --git a/rust/apps/cli/tests/support/cli.rs b/rust/apps/cli/tests/support/cli.rsindex 4955d08339..db60bf1382 100644--- a/rust/apps/cli/tests/support/cli.rs+++ b/rust/apps/cli/tests/support/cli.rs@@ -1,3 +1,6 @@+// https://github.com/rust-lang/rust/issues/46379+#![allow(dead_code)]+use std::{io::Write,path::{Path, PathBuf},diff --git a/rust/apps/cli/tests/sync.rs b/rust/apps/cli/tests/sync.rsnew file mode 100644index 0000000000..bacb366b9d--- /dev/null+++ b/rust/apps/cli/tests/sync.rs@@ -0,0 +1,36 @@+mod support;++use ente_test_support::HARDCODED_OTT;+use support::{Museum, TestResult};++#[test]+fn sync() -> TestResult {+ Museum::run(|museum| {+ let cli = support::cli_session(museum, "sync")?;+ let export_dir = museum.temp_dir().join("export");+ std::fs::create_dir_all(&export_dir)?;++ cli.run_ok(&[+ "account",+ "create",+ "--email",+ "[email protected]",+ "--password",+ "sync-test-password",+ "--endpoint",+ museum.endpoint(),+ "--export-dir",+ export_dir.to_str().unwrap(),+ "--otp",+ HARDCODED_OTT,+ ])?;++ let output = cli.run_ok(&["export"])?;+ assert!(+ output.contains("Sync completed"),+ "export did not sync: {output}"+ );++ Ok(())+ })+}