Skip to content

armgit / ente

Public Imported from GitHub
0

πŸ’š End-to-end encrypted cloud for everything.

Scope CLI API clients by app

Manav Rathi20334a4f2632
diff --git a/mobile/apps/photos/integration_test/ente_rust_test.dart b/mobile/apps/photos/integration_test/ente_rust_test.dart
index 162232ac94..c6de7ddfc9 100644
--- a/mobile/apps/photos/integration_test/ente_rust_test.dart
+++ b/mobile/apps/photos/integration_test/ente_rust_test.dart
@@ -12,7 +12,7 @@ void main() {
test('file_download_url integration smoke test', () {
final url = fileDownloadUrl(
- apiBaseUrl: 'https://api.ente.com',
+ apiOrigin: 'https://api.ente.com',
fileId: 12345,
);
expect(url, equals('https://files.ente.com/?fileID=12345'));
diff --git a/rust/apps/cli/src/api/client.rs b/rust/apps/cli/src/api/client.rs
index 21c479efcb..7121764b1d 100644
--- a/rust/apps/cli/src/api/client.rs
+++ b/rust/apps/cli/src/api/client.rs
@@ -1,87 +1,77 @@
+use crate::models::account::App;
use crate::models::error::Result;
use ente_core::http::{self, Api, ApiConfig, Auth, Http, RetryProfile};
-use ente_core::urls::PRODUCTION_API_BASE_URL;
-use std::collections::HashMap;
-use std::sync::{Arc, RwLock};
+use ente_core::urls::PRODUCTION_API_ORIGIN;
+use std::sync::RwLock;
-const DEFAULT_CLIENT_PACKAGE: &str = "io.ente.photos";
pub(crate) const USER_AGENT: &str = concat!("ente-rs/", env!("CARGO_PKG_VERSION"));
-
-pub struct ApiClient {
- http: Http,
- pub(crate) base_url: String,
- client_package: String,
- tokens: Arc<RwLock<HashMap<String, String>>>,
+const FILES_ORIGIN: &str = "https://files.ente.com";
+const THUMBNAILS_ORIGIN: &str = "https://thumbnails.ente.com";
+
+pub struct AppClient {
+ origin: String,
+ app: App,
+ museum: Api,
+ proxies: Option<DownloadProxies>,
+ token: RwLock<Option<String>>,
}
-impl ApiClient {
- pub fn new(base_url: Option<String>) -> Result<Self> {
- Self::new_with_client_package(base_url, DEFAULT_CLIENT_PACKAGE)
- }
+struct DownloadProxies {
+ files: Api,
+ thumbnails: Api,
+}
- pub fn new_with_client_package<S>(base_url: Option<String>, client_package: S) -> Result<Self>
- where
- S: Into<String>,
- {
+impl AppClient {
+ pub fn new(origin: Option<String>, app: App) -> Result<Self> {
+ let http = Http::new()?;
+ let origin = origin.unwrap_or_else(|| PRODUCTION_API_ORIGIN.to_string());
+ let client_package = app.client_package();
+ let museum = new_api(&http, &origin, client_package);
+ let proxies = (origin == PRODUCTION_API_ORIGIN).then(|| DownloadProxies {
+ files: new_api(&http, FILES_ORIGIN, client_package),
+ thumbnails: new_api(&http, THUMBNAILS_ORIGIN, client_package),
+ });
Ok(Self {
- http: Http::new()?,
- base_url: base_url.unwrap_or_else(|| PRODUCTION_API_BASE_URL.to_string()),
- client_package: client_package.into(),
- tokens: Arc::new(RwLock::new(HashMap::new())),
+ origin,
+ app,
+ museum,
+ proxies,
+ token: RwLock::new(None),
})
}
- pub fn add_token(&self, account_id: &str, token: &str) {
- let mut tokens = self.tokens.write().unwrap();
- tokens.insert(account_id.to_string(), token.to_string());
- }
-
- pub fn remove_token(&self, account_id: &str) {
- let mut tokens = self.tokens.write().unwrap();
- tokens.remove(account_id);
- }
-
- pub fn get_token(&self, account_id: &str) -> Option<String> {
- let tokens = self.tokens.read().unwrap();
- tokens.get(account_id).cloned()
+ pub fn set_token(&self, token: &str) {
+ self.museum.set_auth(Some(Auth::User(token.to_owned())));
+ if let Some(proxies) = &self.proxies {
+ proxies.files.set_auth(Some(Auth::User(token.to_owned())));
+ proxies
+ .thumbnails
+ .set_auth(Some(Auth::User(token.to_owned())));
+ }
+ *self.token.write().unwrap() = Some(token.to_owned());
}
- pub fn base_url(&self) -> &str {
- &self.base_url
+ pub fn token(&self) -> Option<String> {
+ self.token.read().unwrap().clone()
}
- pub fn client_package(&self) -> &str {
- &self.client_package
+ pub fn origin(&self) -> &str {
+ &self.origin
}
- pub(crate) fn api(&self, account_id: Option<&str>) -> Api {
- self.api_at(&self.base_url, account_id)
+ pub fn app(&self) -> App {
+ self.app
}
- fn api_at(&self, origin: &str, account_id: Option<&str>) -> Api {
- let auth = account_id.and_then(|id| {
- let token = self.get_token(id);
- if token.is_none() {
- log::warn!("No token found for account {id}");
- }
- token.map(Auth::User)
- });
- Api::new(
- self.http.clone(),
- ApiConfig {
- origin: origin.to_owned(),
- client_package: Some(self.client_package.clone()),
- client_version: None,
- user_agent: Some(USER_AGENT.to_string()),
- auth,
- },
- )
+ pub(crate) fn api(&self) -> &Api {
+ &self.museum
}
- pub async fn download_file(&self, url: &str) -> Result<Vec<u8>> {
+ pub(crate) async fn download_file(&self, url: &str) -> Result<Vec<u8>> {
Ok(
http::retry_with_profile(RetryProfile::Background, || async {
- self.http
+ self.museum
+ .http()
.get(url)
.send()
.await?
@@ -93,26 +83,41 @@ impl ApiClient {
)
}
- pub async fn download_from_proxy(
- &self,
- origin: &str,
- account_id: &str,
- file_id: i64,
- ) -> Result<Vec<u8>> {
- let api = self.api_at(origin, Some(account_id));
- Ok(
- http::retry_with_profile(RetryProfile::Background, || async {
- api.get("/")
- .query(&[("fileID", file_id)])
- .send()
- .await?
- .error_for_status()?
- .bytes()
- .await
- })
- .await?,
- )
+ pub(crate) async fn download_file_from_proxy(&self, file_id: i64) -> Result<Vec<u8>> {
+ download_from_proxy(&self.proxies.as_ref().unwrap().files, file_id).await
}
+
+ pub(crate) async fn download_thumbnail_from_proxy(&self, file_id: i64) -> Result<Vec<u8>> {
+ download_from_proxy(&self.proxies.as_ref().unwrap().thumbnails, file_id).await
+ }
+}
+
+fn new_api(http: &Http, origin: &str, client_package: &str) -> Api {
+ Api::new(
+ http.clone(),
+ ApiConfig {
+ origin: origin.to_owned(),
+ client_package: Some(client_package.to_owned()),
+ client_version: None,
+ user_agent: Some(USER_AGENT.to_string()),
+ auth: None,
+ },
+ )
+}
+
+async fn download_from_proxy(api: &Api, file_id: i64) -> Result<Vec<u8>> {
+ Ok(
+ http::retry_with_profile(RetryProfile::Background, || async {
+ api.get("/")
+ .query(&[("fileID", file_id)])
+ .send()
+ .await?
+ .error_for_status()?
+ .bytes()
+ .await
+ })
+ .await?,
+ )
}
#[cfg(test)]
@@ -121,25 +126,35 @@ mod tests {
use mockito::{Matcher, Server};
#[tokio::test]
- async fn proxy_download_uses_api_headers() {
+ async fn app_clients_keep_auth_scoped_to_app() {
let mut server = Server::new_async().await;
- let download = server
+ let auth_download = server
.mock("GET", "/")
- .match_query(Matcher::UrlEncoded("fileID".into(), "12345".into()))
- .match_header("x-auth-token", "token")
- .match_header("x-client-package", "io.ente.locker")
- .with_body("file")
+ .match_query(Matcher::UrlEncoded("fileID".into(), "1".into()))
+ .match_header("x-auth-token", "auth-token")
+ .match_header("x-client-package", "io.ente.auth")
+ .with_body("auth")
.create_async()
.await;
- let client = ApiClient::new_with_client_package(None, "io.ente.locker").unwrap();
- client.add_token("account", "token");
-
- let bytes = client
- .download_from_proxy(&server.url(), "account", 12345)
- .await
- .unwrap();
-
- download.assert_async().await;
- assert_eq!(bytes, b"file");
+ let photos_download = server
+ .mock("GET", "/")
+ .match_query(Matcher::UrlEncoded("fileID".into(), "2".into()))
+ .match_header("x-auth-token", "photos-token")
+ .match_header("x-client-package", "io.ente.photos")
+ .with_body("photos")
+ .create_async()
+ .await;
+ let auth_client = AppClient::new(Some(server.url()), App::Auth).unwrap();
+ auth_client.set_token("auth-token");
+ let photos_client = AppClient::new(Some(server.url()), App::Photos).unwrap();
+ photos_client.set_token("photos-token");
+
+ let auth_bytes = download_from_proxy(auth_client.api(), 1).await.unwrap();
+ let photos_bytes = download_from_proxy(photos_client.api(), 2).await.unwrap();
+
+ auth_download.assert_async().await;
+ photos_download.assert_async().await;
+ assert_eq!(auth_bytes, b"auth");
+ assert_eq!(photos_bytes, b"photos");
}
}
diff --git a/rust/apps/cli/src/api/methods.rs b/rust/apps/cli/src/api/methods.rs
index 7eaca9e3fb..2028155c2d 100644
--- a/rust/apps/cli/src/api/methods.rs
+++ b/rust/apps/cli/src/api/methods.rs
@@ -1,26 +1,25 @@
-use crate::api::client::ApiClient;
+use crate::api::client::AppClient;
use crate::api::models::{
Collection, File, GetCollectionsResponse, GetDiffResponse, GetFileResponse, GetFileUrlResponse,
GetFilesResponse, GetThumbnailUrlResponse, UserDetails,
};
use crate::models::error::Result;
use ente_core::http;
-use ente_core::urls::{PRODUCTION_API_BASE_URL, file_download_url};
+use ente_core::urls::{PRODUCTION_API_ORIGIN, file_download_url};
-const FILES_ORIGIN: &str = "https://files.ente.com";
const THUMBNAILS_ORIGIN: &str = "https://thumbnails.ente.com";
pub struct ApiMethods<'a> {
- client: &'a ApiClient,
+ client: &'a AppClient,
}
impl<'a> ApiMethods<'a> {
- pub fn new(client: &'a ApiClient) -> Self {
+ pub fn new(client: &'a AppClient) -> Self {
Self { client }
}
- pub async fn get_user_details(&self, account_id: &str) -> Result<UserDetails> {
- let api = self.client.api(Some(account_id));
+ pub async fn get_user_details(&self) -> Result<UserDetails> {
+ let api = self.client.api();
Ok(http::retry(|| async {
api.get("/users/details")
.send()
@@ -33,12 +32,8 @@ impl<'a> ApiMethods<'a> {
.await?)
}
- pub async fn get_collections(
- &self,
- account_id: &str,
- since_time: i64,
- ) -> Result<Vec<Collection>> {
- let api = self.client.api(Some(account_id));
+ pub async fn get_collections(&self, since_time: i64) -> Result<Vec<Collection>> {
+ let api = self.client.api();
let response: GetCollectionsResponse = http::retry(|| async {
api.get("/collections/v2")
.query(&[("sinceTime", since_time.to_string())])
@@ -53,8 +48,8 @@ impl<'a> ApiMethods<'a> {
Ok(response.collections)
}
- pub async fn get_collection(&self, account_id: &str, collection_id: i64) -> Result<Collection> {
- let api = self.client.api(Some(account_id));
+ pub async fn get_collection(&self, collection_id: i64) -> Result<Collection> {
+ let api = self.client.api();
Ok(http::retry(|| async {
api.get(&format!("/collections/{collection_id}"))
.send()
@@ -69,11 +64,10 @@ impl<'a> ApiMethods<'a> {
pub async fn get_collection_files(
&self,
- account_id: &str,
collection_id: i64,
since_time: i64,
) -> Result<(Vec<File>, bool)> {
- let api = self.client.api(Some(account_id));
+ let api = self.client.api();
let response: GetFilesResponse = http::retry(|| async {
api.get("/collections/v2/diff")
.query(&[
@@ -91,13 +85,8 @@ impl<'a> ApiMethods<'a> {
Ok((response.diff, response.has_more))
}
- pub async fn get_file(
- &self,
- account_id: &str,
- collection_id: i64,
- file_id: i64,
- ) -> Result<File> {
- let api = self.client.api(Some(account_id));
+ pub async fn get_file(&self, collection_id: i64, file_id: i64) -> Result<File> {
+ let api = self.client.api();
let response: GetFileResponse = http::retry(|| async {
api.get("/collections/file")
.query(&[
@@ -115,13 +104,8 @@ impl<'a> ApiMethods<'a> {
Ok(response.file)
}
- pub async fn get_diff(
- &self,
- account_id: &str,
- since_time: i64,
- limit: i32,
- ) -> Result<(Vec<File>, bool)> {
- let api = self.client.api(Some(account_id));
+ pub async fn get_diff(&self, since_time: i64, limit: i32) -> Result<(Vec<File>, bool)> {
+ let api = self.client.api();
let response: GetDiffResponse = http::retry(|| async {
api.get("/diff")
.query(&[
@@ -139,11 +123,11 @@ impl<'a> ApiMethods<'a> {
Ok((response.diff, response.has_more))
}
- pub async fn get_file_url(&self, account_id: &str, file_id: i64) -> Result<String> {
- if self.client.base_url == PRODUCTION_API_BASE_URL {
- return Ok(file_download_url(&self.client.base_url, file_id));
+ pub async fn get_file_url(&self, file_id: i64) -> Result<String> {
+ if self.client.origin() == PRODUCTION_API_ORIGIN {
+ return Ok(file_download_url(self.client.origin(), file_id));
}
- let api = self.client.api(Some(account_id));
+ let api = self.client.api();
let response: GetFileUrlResponse = http::retry(|| async {
api.get(&format!("/files/download/v2/{file_id}"))
.send()
@@ -157,11 +141,11 @@ impl<'a> ApiMethods<'a> {
Ok(response.url)
}
- pub async fn get_thumbnail_url(&self, account_id: &str, file_id: i64) -> Result<String> {
- if self.client.base_url == PRODUCTION_API_BASE_URL {
+ pub async fn get_thumbnail_url(&self, file_id: i64) -> Result<String> {
+ if self.client.origin() == PRODUCTION_API_ORIGIN {
return Ok(format!("{THUMBNAILS_ORIGIN}/?fileID={file_id}"));
}
- let api = self.client.api(Some(account_id));
+ let api = self.client.api();
let response: GetThumbnailUrlResponse = http::retry(|| async {
api.get(&format!("/files/preview/v2/{file_id}"))
.send()
@@ -175,30 +159,24 @@ impl<'a> ApiMethods<'a> {
Ok(response.url)
}
- pub async fn download_file(&self, account_id: &str, file_id: i64) -> Result<Vec<u8>> {
- if self.client.base_url == PRODUCTION_API_BASE_URL {
- return self
- .client
- .download_from_proxy(FILES_ORIGIN, account_id, file_id)
- .await;
+ pub async fn download_file(&self, file_id: i64) -> Result<Vec<u8>> {
+ if self.client.origin() == PRODUCTION_API_ORIGIN {
+ return self.client.download_file_from_proxy(file_id).await;
}
- let url = self.get_file_url(account_id, file_id).await?;
+ let url = self.get_file_url(file_id).await?;
self.client.download_file(&url).await
}
- pub async fn download_thumbnail(&self, account_id: &str, file_id: i64) -> Result<Vec<u8>> {
- if self.client.base_url == PRODUCTION_API_BASE_URL {
- return self
- .client
- .download_from_proxy(THUMBNAILS_ORIGIN, account_id, file_id)
- .await;
+ pub async fn download_thumbnail(&self, file_id: i64) -> Result<Vec<u8>> {
+ if self.client.origin() == PRODUCTION_API_ORIGIN {
+ return self.client.download_thumbnail_from_proxy(file_id).await;
}
- let url = self.get_thumbnail_url(account_id, file_id).await?;
+ let url = self.get_thumbnail_url(file_id).await?;
self.client.download_file(&url).await
}
- pub async fn get_trash(&self, account_id: &str, since_time: i64) -> Result<(Vec<File>, bool)> {
- let api = self.client.api(Some(account_id));
+ pub async fn get_trash(&self, since_time: i64) -> Result<(Vec<File>, bool)> {
+ let api = self.client.api();
let response: GetDiffResponse = http::retry(|| async {
api.get("/trash/v2")
.query(&[("sinceTime", since_time.to_string())])
@@ -213,8 +191,8 @@ impl<'a> ApiMethods<'a> {
Ok((response.diff, response.has_more))
}
- pub async fn delete_from_trash(&self, account_id: &str, file_ids: &[i64]) -> Result<()> {
- let api = self.client.api(Some(account_id));
+ pub async fn delete_from_trash(&self, file_ids: &[i64]) -> Result<()> {
+ let api = self.client.api();
let body = serde_json::json!({ "fileIDs": file_ids });
http::retry(|| async {
api.post("/trash/delete")
@@ -229,8 +207,8 @@ impl<'a> ApiMethods<'a> {
Ok(())
}
- pub async fn empty_trash(&self, account_id: &str) -> Result<()> {
- let api = self.client.api(Some(account_id));
+ pub async fn empty_trash(&self) -> Result<()> {
+ let api = self.client.api();
http::retry(|| async {
api.delete("/trash/empty")
.send()
@@ -251,15 +229,15 @@ mod tests {
#[tokio::test]
async fn test_production_urls() {
- let api = ApiClient::new(None).unwrap();
+ let api = AppClient::new(None, crate::models::account::App::Photos).unwrap();
let methods = ApiMethods::new(&api);
assert_eq!(
- methods.get_file_url("test", 12345).await.unwrap(),
+ methods.get_file_url(12345).await.unwrap(),
"https://files.ente.com/?fileID=12345"
);
assert_eq!(
- methods.get_thumbnail_url("test", 12345).await.unwrap(),
+ methods.get_thumbnail_url(12345).await.unwrap(),
"https://thumbnails.ente.com/?fileID=12345"
);
}
@@ -283,13 +261,10 @@ mod tests {
.create_async()
.await;
let client =
- ApiClient::new_with_client_package(Some(server.url()), "io.ente.locker").unwrap();
- client.add_token("account", "token");
+ AppClient::new(Some(server.url()), crate::models::account::App::Locker).unwrap();
+ client.set_token("token");
- let bytes = ApiMethods::new(&client)
- .download_file("account", 12345)
- .await
- .unwrap();
+ let bytes = ApiMethods::new(&client).download_file(12345).await.unwrap();
url_mock.assert_async().await;
download_mock.assert_async().await;
diff --git a/rust/apps/cli/src/api/mod.rs b/rust/apps/cli/src/api/mod.rs
index 83308175bb..85806a665b 100644
--- a/rust/apps/cli/src/api/mod.rs
+++ b/rust/apps/cli/src/api/mod.rs
@@ -2,6 +2,6 @@ pub mod client;
pub mod methods;
pub mod models;
-pub use client::ApiClient;
+pub use client::AppClient;
pub use methods::ApiMethods;
pub use models::*;
diff --git a/rust/apps/cli/src/auth_flow.rs b/rust/apps/cli/src/auth_flow.rs
index e4719dbbdf..943db2b3d6 100644
--- a/rust/apps/cli/src/auth_flow.rs
+++ b/rust/apps/cli/src/auth_flow.rs
@@ -1,7 +1,7 @@
use crate::{
- api::{ApiClient, client::USER_AGENT, models::KeyAttributes},
+ api::{AppClient, client::USER_AGENT, models::KeyAttributes},
models::{
- account::{AccountSecrets, App},
+ account::AccountSecrets,
error::{Error, Result},
},
};
@@ -20,15 +20,11 @@ where
serde_json::from_value(serde_json::to_value(value)?).map_err(Error::from)
}
-fn shared_client(
- api_client: &ApiClient,
- app: App,
- account_id: Option<&str>,
-) -> Result<shared::AccountsClient> {
- let mut config = shared::AccountsClientConfig::new(app.client_package())
- .with_base_url(api_client.base_url().to_string())
+fn shared_client(app_client: &AppClient, authenticated: bool) -> Result<shared::AccountsClient> {
+ let mut config = shared::AccountsClientConfig::new(app_client.app().client_package())
+ .with_origin(app_client.origin().to_string())
.with_user_agent(USER_AGENT);
- if let Some(token) = account_id.and_then(|id| api_client.get_token(id)) {
+ if let Some(token) = authenticated.then(|| app_client.token()).flatten() {
config = config.with_auth_token(token);
}
shared::AccountsClient::new(config).map_err(Error::from)
@@ -216,8 +212,7 @@ fn from_shared_account(account: shared::AuthenticatedAccount) -> Result<Authenti
}
pub struct AuthFlow<'a, U> {
- api_client: &'a ApiClient,
- app: App,
+ app_client: &'a AppClient,
ui: &'a mut U,
}
@@ -225,20 +220,15 @@ impl<'a, U> AuthFlow<'a, U>
where
U: AuthFlowUi,
{
- pub fn new(api_client: &'a ApiClient, app: App, ui: &'a mut U) -> Self {
- Self {
- api_client,
- app,
- ui,
- }
+ pub fn new(app_client: &'a AppClient, ui: &'a mut U) -> Self {
+ Self { app_client, ui }
}
pub async fn create_account(
&mut self,
params: CreateAccountParams,
) -> Result<AuthenticatedAccount> {
- let email = params.email.clone();
- let client = shared_client(self.api_client, self.app, None)?;
+ let client = shared_client(self.app_client, false)?;
let mut ui = UiAdapter { inner: self.ui };
let mut flow = shared::AuthFlow::new(&client, &mut ui);
let account = from_shared_account(
@@ -250,13 +240,13 @@ where
.await
.map_err(Error::from)?,
)?;
- self.api_client
- .add_token(&email, &URL_SAFE.encode(&account.secrets.token));
+ self.app_client
+ .set_token(&URL_SAFE.encode(&account.secrets.token));
Ok(account)
}
pub async fn login(&mut self, params: LoginParams) -> Result<AuthenticatedAccount> {
- let client = shared_client(self.api_client, self.app, None)?;
+ let client = shared_client(self.app_client, false)?;
let mut ui = UiAdapter { inner: self.ui };
let mut flow = shared::AuthFlow::new(&client, &mut ui);
from_shared_account(
@@ -273,7 +263,7 @@ where
&mut self,
params: SetupTwoFactorParams,
) -> Result<SetupTwoFactorResult> {
- let client = shared_client(self.api_client, self.app, Some(&params.account_id))?;
+ let client = shared_client(self.app_client, true)?;
let mut ui = UiAdapter { inner: self.ui };
let mut flow = shared::AuthFlow::new(&client, &mut ui);
let result = flow
@@ -294,6 +284,7 @@ where
#[cfg(test)]
mod tests {
use super::*;
+ use crate::models::account::App;
use mockito::{Matcher, Server};
use serde::{Deserialize, de::DeserializeOwned};
use sha2::{Digest, Sha256};
@@ -631,8 +622,8 @@ mod tests {
.create_async()
.await;
- let api_client = ApiClient::new(Some(server.url())).unwrap();
- let mut flow = AuthFlow::new(&api_client, App::Photos, &mut ui);
+ let app_client = AppClient::new(Some(server.url()), App::Photos).unwrap();
+ let mut flow = AuthFlow::new(&app_client, &mut ui);
let created = flow
.create_account(CreateAccountParams {
@@ -643,10 +634,7 @@ mod tests {
.await
.unwrap();
- assert_eq!(
- api_client.get_token(email).as_deref(),
- Some(signup_token.as_str())
- );
+ assert_eq!(app_client.token().as_deref(), Some(signup_token.as_str()));
let (uploaded_key_attributes, remote_srp_attributes) = {
let state = signup_state.lock().unwrap();
diff --git a/rust/apps/cli/src/commands/account.rs b/rust/apps/cli/src/commands/account.rs
index 97f2cb4b9b..385002983c 100644
--- a/rust/apps/cli/src/commands/account.rs
+++ b/rust/apps/cli/src/commands/account.rs
@@ -15,7 +15,7 @@ use ente_accounts::{
SecondFactorMethod, SetupTwoFactorParams, TotpPurpose,
};
use ente_core::crypto::SecretVec;
-use ente_core::urls::PRODUCTION_API_BASE_URL;
+use ente_core::urls::PRODUCTION_API_ORIGIN;
use std::{path::PathBuf, str::FromStr};
use zeroize::Zeroizing;
@@ -229,7 +229,7 @@ async fn list_accounts(storage: &Storage) -> Result<()> {
println!("{}", "-".repeat(110));
for account in accounts {
- let endpoint_display = if account.endpoint == PRODUCTION_API_BASE_URL {
+ let endpoint_display = if account.endpoint == PRODUCTION_API_ORIGIN {
"api.ente.com (prod)".to_string()
} else if account.endpoint.starts_with("http://localhost") {
format!(
@@ -575,7 +575,7 @@ fn parse_second_factor(second_factor: Option<&str>) -> Result<Option<SecondFacto
fn new_accounts_client(endpoint: &str, app: App) -> Result<AccountsClient> {
AccountsClient::new(
AccountsClientConfig::new(app.client_package())
- .with_base_url(endpoint.to_string())
+ .with_origin(endpoint.to_string())
.with_user_agent(USER_AGENT),
)
.map_err(Error::from)
diff --git a/rust/apps/cli/src/commands/export.rs b/rust/apps/cli/src/commands/export.rs
index 443a58f77e..5c0ece8444 100644
--- a/rust/apps/cli/src/commands/export.rs
+++ b/rust/apps/cli/src/commands/export.rs
@@ -1,5 +1,5 @@
use crate::Result;
-use crate::api::client::ApiClient;
+use crate::api::AppClient;
use crate::api::methods::ApiMethods;
use crate::models::{
account::Account,
@@ -197,14 +197,11 @@ async fn sync_account_before_export(storage: &Storage, account: &Account) -> Res
.ok_or_else(|| crate::Error::NotFound("Account secrets not found".into()))?;
// Create API client with account's endpoint
- let api_client = ApiClient::new_with_client_package(
- Some(account.endpoint.clone()),
- account.app.client_package(),
- )?;
+ let api_client = AppClient::new(Some(account.endpoint.clone()), account.app)?;
// Store token for this account
let token = base64::engine::general_purpose::URL_SAFE.encode(&secrets.token);
- api_client.add_token(&account.email, &token);
+ api_client.set_token(&token);
// Get the database path to create a new Storage instance
let db_path = storage
@@ -261,16 +258,13 @@ async fn export_account(storage: &Storage, account: &Account, filter: &ExportFil
.ok_or_else(|| crate::Error::NotFound("Account secrets not found".into()))?;
// Create API client with account's endpoint
- let api_client = ApiClient::new_with_client_package(
- Some(account.endpoint.clone()),
- account.app.client_package(),
- )?;
+ let api_client = AppClient::new(Some(account.endpoint.clone()), account.app)?;
// Store token for this account
// Token is stored as raw bytes from sealed_box_open
// The Go CLI encodes it as base64 URL-encoded string WITH padding for the API
let token = base64::engine::general_purpose::URL_SAFE.encode(&secrets.token);
- api_client.add_token(&account.email, &token);
+ api_client.set_token(&token);
let api = ApiMethods::new(&api_client);
@@ -283,7 +277,7 @@ async fn export_account(storage: &Storage, account: &Account, filter: &ExportFil
// Step 1: Fetch all collections and create a map of collection IDs to collections
println!("\nFetching collections...");
- let collections = api.get_collections(&account.email, 0).await?;
+ let collections = api.get_collections(0).await?;
println!("Found {} collections", collections.len());
// Create collection ID to collection map and decrypt collection keys
@@ -390,9 +384,7 @@ async fn export_account(storage: &Storage, account: &Account, filter: &ExportFil
let mut since_time = 0i64;
while has_more {
- let (files, more) = api
- .get_collection_files(&account.email, *collection_id, since_time)
- .await?;
+ let (files, more) = api.get_collection_files(*collection_id, since_time).await?;
has_more = more;
if files.is_empty() {
@@ -703,7 +695,7 @@ async fn export_account(storage: &Storage, account: &Account, filter: &ExportFil
}
// Download encrypted file
- let encrypted_data = api.download_file(&account.email, file.id).await?;
+ let encrypted_data = api.download_file(file.id).await?;
// The file nonce/header is stored separately in the API response
let file_nonce = match base64::engine::general_purpose::STANDARD
diff --git a/rust/apps/cli/src/commands/sync.rs b/rust/apps/cli/src/commands/sync.rs
index 126f447476..70d6531e36 100644
--- a/rust/apps/cli/src/commands/sync.rs
+++ b/rust/apps/cli/src/commands/sync.rs
@@ -1,5 +1,5 @@
use crate::Result;
-use crate::api::client::ApiClient;
+use crate::api::AppClient;
use crate::api::methods::ApiMethods;
use crate::models::{account::Account, metadata::FileMetadata};
use crate::storage::Storage;
@@ -73,12 +73,11 @@ async fn sync_account(
.ok_or_else(|| crate::Error::NotFound("Account secrets not found".into()))?;
// Create API client with account's endpoint
- let api_client =
- ApiClient::new_with_client_package(Some(account.endpoint.clone()), account.app.client_package())?;
+ let api_client = AppClient::new(Some(account.endpoint.clone()), account.app)?;
// Store token for this account
let token = base64::engine::general_purpose::URL_SAFE.encode(&secrets.token);
- api_client.add_token(&account.email, &token);
+ api_client.set_token(&token);
// Clear sync state if full sync requested
if full_sync {
@@ -92,9 +91,8 @@ async fn sync_account(
.ok_or_else(|| crate::Error::Generic("Database path not available".into()))?;
// Create API client for sync engine
- let sync_api_client =
- ApiClient::new_with_client_package(Some(account.endpoint.clone()), account.app.client_package())?;
- sync_api_client.add_token(&account.email, &token);
+ let sync_api_client = AppClient::new(Some(account.endpoint.clone()), account.app)?;
+ sync_api_client.set_token(&token);
let sync_storage = Storage::new(db_path)?;
let sync_engine = SyncEngine::new(sync_api_client, sync_storage, account.clone());
@@ -117,7 +115,7 @@ async fn sync_account(
// Get collections to decrypt collection keys
// Need to fetch from API to get the api::models::Collection type with encrypted_key
let api = ApiMethods::new(&api_client);
- let api_collections = api.get_collections(&account.email, 0).await?;
+ let api_collections = api.get_collections(0).await?;
// Decrypt collection keys
let collection_keys = decrypt_collection_keys(
@@ -128,11 +126,9 @@ async fn sync_account(
// Create download manager
// Create a new API client for the download manager
- let download_api_client = ApiClient::new_with_client_package(
- Some(account.endpoint.clone()),
- account.app.client_package(),
- )?;
- download_api_client.add_token(&account.email, &token);
+ let download_api_client =
+ AppClient::new(Some(account.endpoint.clone()), account.app)?;
+ download_api_client.set_token(&token);
let mut download_manager = DownloadManager::new(download_api_client)?;
download_manager.set_collection_keys(collection_keys);
@@ -177,9 +173,7 @@ async fn sync_account(
println!("πŸ“₯ Downloading {} new files", to_download.len());
// Download files with progress bar
- let download_stats = download_manager
- .download_files(&account.email, to_download)
- .await?;
+ let download_stats = download_manager.download_files(to_download).await?;
// Update local paths in database for newly downloaded files
for (file, path) in &download_stats.successful_downloads {
diff --git a/rust/apps/cli/src/sync/download.rs b/rust/apps/cli/src/sync/download.rs
index e44cb5e6c4..be1df4d1e4 100644
--- a/rust/apps/cli/src/sync/download.rs
+++ b/rust/apps/cli/src/sync/download.rs
@@ -1,5 +1,5 @@
use crate::Result;
-use crate::api::client::ApiClient;
+use crate::api::client::AppClient;
use crate::api::methods::ApiMethods;
use crate::models::file::RemoteFile;
use base64::{Engine, engine::general_purpose::STANDARD as BASE64};
@@ -14,7 +14,7 @@ use tokio::io::AsyncWriteExt;
/// Manages file downloads with parallel processing and error recovery
pub struct DownloadManager {
- api_client: ApiClient,
+ api_client: AppClient,
temp_dir: PathBuf,
pub collection_keys: HashMap<i64, Vec<u8>>,
concurrent_downloads: usize,
@@ -23,7 +23,7 @@ pub struct DownloadManager {
impl DownloadManager {
/// Create a new download manager
- pub fn new(api_client: ApiClient) -> Result<Self> {
+ pub fn new(api_client: AppClient) -> Result<Self> {
let temp_dir = std::env::temp_dir().join("ente-downloads");
std::fs::create_dir_all(&temp_dir)?;
@@ -52,20 +52,14 @@ impl DownloadManager {
}
/// Download a single file
- pub async fn download_file(
- &self,
- account_id: &str,
- file: &RemoteFile,
- destination: &Path,
- ) -> Result<()> {
- self.download_file_with_progress(account_id, file, destination, None)
+ pub async fn download_file(&self, file: &RemoteFile, destination: &Path) -> Result<()> {
+ self.download_file_with_progress(file, destination, None)
.await
}
/// Download a single file with optional progress bar
async fn download_file_with_progress(
&self,
- account_id: &str,
file: &RemoteFile,
destination: &Path,
progress: Option<Arc<ProgressBar>>,
@@ -92,7 +86,7 @@ impl DownloadManager {
// Get file data
let api = ApiMethods::new(&self.api_client);
- let encrypted_data = api.download_file(account_id, file.id).await?;
+ let encrypted_data = api.download_file(file.id).await?;
// Decrypt file
let decrypted_data = self.decrypt_file_data(file, &encrypted_data)?;
@@ -145,11 +139,7 @@ impl DownloadManager {
}
/// Download multiple files with concurrency control
- pub async fn download_files(
- &self,
- account_id: &str,
- files: Vec<(RemoteFile, PathBuf)>,
- ) -> Result<DownloadStats> {
+ pub async fn download_files(&self, files: Vec<(RemoteFile, PathBuf)>) -> Result<DownloadStats> {
use futures::stream::{self, StreamExt};
let total = files.len();
@@ -180,14 +170,11 @@ impl DownloadManager {
let pb_clone = progress_bar.clone();
let results: Vec<_> = stream::iter(files)
.map(|(file, path)| {
- let account_id = account_id.to_string();
let file_clone = file.clone();
let path_clone = path.clone();
let pb = pb_clone.clone();
async move {
- let result = self
- .download_file_with_progress(&account_id, &file, &path, pb)
- .await;
+ let result = self.download_file_with_progress(&file, &path, pb).await;
(file_clone, path_clone, result)
}
})
@@ -223,12 +210,7 @@ impl DownloadManager {
}
/// Download thumbnail for a file
- pub async fn download_thumbnail(
- &self,
- account_id: &str,
- file: &RemoteFile,
- destination: &Path,
- ) -> Result<()> {
+ pub async fn download_thumbnail(&self, file: &RemoteFile, destination: &Path) -> Result<()> {
log::debug!(
"Downloading thumbnail for file {} to {:?}",
file.id,
@@ -242,7 +224,7 @@ impl DownloadManager {
// Get thumbnail data
let api = ApiMethods::new(&self.api_client);
- let encrypted_data = api.download_thumbnail(account_id, file.id).await?;
+ let encrypted_data = api.download_thumbnail(file.id).await?;
// Decrypt thumbnail
let decrypted_data = self.decrypt_file_data(file, &encrypted_data)?;
@@ -291,7 +273,6 @@ impl DownloadManager {
/// Resume a partial download (for future implementation)
pub async fn resume_download(
&self,
- _account_id: &str,
_file: &RemoteFile,
_destination: &Path,
_offset: u64,
diff --git a/rust/apps/cli/src/sync/engine.rs b/rust/apps/cli/src/sync/engine.rs
index 53494c9021..df3aebb1ae 100644
--- a/rust/apps/cli/src/sync/engine.rs
+++ b/rust/apps/cli/src/sync/engine.rs
@@ -1,19 +1,19 @@
use crate::Result;
-use crate::api::client::ApiClient;
+use crate::api::client::AppClient;
use crate::api::methods::ApiMethods;
use crate::models::{account::Account, file::RemoteFile};
use crate::storage::Storage;
/// Core sync engine responsible for fetching and tracking remote changes
pub struct SyncEngine {
- api_client: ApiClient,
+ api_client: AppClient,
storage: Storage,
account: Account,
}
impl SyncEngine {
/// Create a new sync engine for an account
- pub fn new(api_client: ApiClient, storage: Storage, account: Account) -> Self {
+ pub fn new(api_client: AppClient, storage: Storage, account: Account) -> Self {
Self {
api_client,
storage,
@@ -25,23 +25,17 @@ impl SyncEngine {
pub async fn sync(&self) -> Result<SyncStats> {
log::info!("Starting sync for account: {}", self.account.email);
- let mut stats = SyncStats::default();
-
- // Get account ID for auth - use email as account identifier
- let account_id = &self.account.email;
-
- // Sync collections first
- stats.collections = self.sync_collections(account_id).await?;
-
- // Then sync files
- stats.files = self.sync_files(account_id).await?;
+ let stats = SyncStats {
+ collections: self.sync_collections().await?,
+ files: self.sync_files().await?,
+ };
log::info!("Sync completed: {stats:?}");
Ok(stats)
}
/// Sync collections (albums)
- async fn sync_collections(&self, account_id: &str) -> Result<SyncResult> {
+ async fn sync_collections(&self) -> Result<SyncResult> {
log::debug!("Syncing collections...");
let sync_store = self.storage.sync();
@@ -52,7 +46,7 @@ impl SyncEngine {
.unwrap_or(0);
let api = ApiMethods::new(&self.api_client);
- let collections = api.get_collections(account_id, last_sync).await?;
+ let collections = api.get_collections(last_sync).await?;
let mut result = SyncResult {
total: collections.len(),
@@ -120,7 +114,7 @@ impl SyncEngine {
}
/// Sync files incrementally
- async fn sync_files(&self, account_id: &str) -> Result<SyncResult> {
+ async fn sync_files(&self) -> Result<SyncResult> {
log::debug!("Syncing files...");
let sync_store = self.storage.sync();
@@ -182,9 +176,7 @@ impl SyncEngine {
last_sync
);
- let (files, more) = api
- .get_collection_files(account_id, collection.id, last_sync)
- .await?;
+ let (files, more) = api.get_collection_files(collection.id, last_sync).await?;
has_more = more;
batch_count += 1;
diff --git a/rust/bindings/frb/ente-rust/src/api/urls.rs b/rust/bindings/frb/ente-rust/src/api/urls.rs
index 01a75e82d5..4570c57883 100644
--- a/rust/bindings/frb/ente-rust/src/api/urls.rs
+++ b/rust/bindings/frb/ente-rust/src/api/urls.rs
@@ -4,6 +4,6 @@ use flutter_rust_bridge::frb;
/// Generate the download URL for a file.
#[frb(sync)]
-pub fn file_download_url(api_base_url: String, file_id: i64) -> String {
- ente_core::urls::file_download_url(&api_base_url, file_id)
+pub fn file_download_url(api_origin: String, file_id: i64) -> String {
+ ente_core::urls::file_download_url(&api_origin, file_id)
}
diff --git a/rust/bindings/wasm/ente-wasm/src/urls.rs b/rust/bindings/wasm/ente-wasm/src/urls.rs
index c051ffe0e1..05ef11291d 100644
--- a/rust/bindings/wasm/ente-wasm/src/urls.rs
+++ b/rust/bindings/wasm/ente-wasm/src/urls.rs
@@ -4,6 +4,6 @@ use wasm_bindgen::prelude::*;
/// Generate the download URL for a file.
#[wasm_bindgen]
-pub fn file_download_url(api_base_url: &str, file_id: i64) -> String {
- ente_core::urls::file_download_url(api_base_url, file_id)
+pub fn file_download_url(api_origin: &str, file_id: i64) -> String {
+ ente_core::urls::file_download_url(api_origin, file_id)
}
diff --git a/rust/crates/accounts/src/client.rs b/rust/crates/accounts/src/client.rs
index 11a6c04e31..58a322e695 100644
--- a/rust/crates/accounts/src/client.rs
+++ b/rust/crates/accounts/src/client.rs
@@ -54,7 +54,7 @@ impl AccountsClient {
let api = Api::new(
Http::new()?,
ApiConfig {
- origin: config.base_url,
+ origin: config.origin,
client_package: Some(config.client_package.clone()),
client_version: config.client_version,
user_agent: config.user_agent,
@@ -553,10 +553,10 @@ mod tests {
use crate::types::AccountsClientConfig;
use mockito::Server;
- fn make_client(base_url: String) -> AccountsClient {
+ fn make_client(origin: String) -> AccountsClient {
AccountsClient::new(
AccountsClientConfig::new("io.ente.photos")
- .with_base_url(base_url)
+ .with_origin(origin)
.with_user_agent("ente-accounts-test"),
)
.unwrap()
diff --git a/rust/crates/accounts/src/flow.rs b/rust/crates/accounts/src/flow.rs
index 53eea00fd6..33be6f08cc 100644
--- a/rust/crates/accounts/src/flow.rs
+++ b/rust/crates/accounts/src/flow.rs
@@ -1206,10 +1206,10 @@ mod tests {
}
}
- fn make_client(base_url: String) -> AccountsClient {
+ fn make_client(origin: String) -> AccountsClient {
AccountsClient::new(
AccountsClientConfig::new("io.ente.photos")
- .with_base_url(base_url)
+ .with_origin(origin)
.with_user_agent("ente-accounts-test"),
)
.unwrap()
diff --git a/rust/crates/accounts/src/types.rs b/rust/crates/accounts/src/types.rs
index ef2607d927..e3e5bfe49b 100644
--- a/rust/crates/accounts/src/types.rs
+++ b/rust/crates/accounts/src/types.rs
@@ -1,17 +1,17 @@
//! Shared reusable types for account clients.
-use ente_core::urls::PRODUCTION_API_BASE_URL;
+use ente_core::urls::PRODUCTION_API_ORIGIN;
use serde::{Deserialize, Serialize};
use zeroize::Zeroize;
-/// Default base URL for Ente's public API.
-pub const DEFAULT_API_BASE_URL: &str = PRODUCTION_API_BASE_URL;
+/// Default origin for Ente's public API.
+pub const DEFAULT_API_ORIGIN: &str = PRODUCTION_API_ORIGIN;
/// Configuration for constructing an [`crate::client::AccountsClient`].
#[derive(Clone)]
pub struct AccountsClientConfig {
- /// Base Ente API URL.
- pub base_url: String,
+ /// Ente API origin.
+ pub origin: String,
/// Optional auth token for authenticated requests.
pub auth_token: Option<String>,
/// Concrete client package header value.
@@ -25,7 +25,7 @@ pub struct AccountsClientConfig {
impl std::fmt::Debug for AccountsClientConfig {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("AccountsClientConfig")
- .field("base_url", &self.base_url)
+ .field("origin", &self.origin)
.field(
"auth_token",
&self.auth_token.as_ref().map(|_| "<redacted>"),
@@ -41,7 +41,7 @@ impl AccountsClientConfig {
/// Create a config for the given client package.
pub fn new(client_package: impl Into<String>) -> Self {
Self {
- base_url: DEFAULT_API_BASE_URL.to_string(),
+ origin: DEFAULT_API_ORIGIN.to_string(),
auth_token: None,
client_package: client_package.into(),
client_version: None,
@@ -49,9 +49,9 @@ impl AccountsClientConfig {
}
}
- /// Override the API base URL.
- pub fn with_base_url(mut self, base_url: impl Into<String>) -> Self {
- self.base_url = base_url.into();
+ /// Override the API origin.
+ pub fn with_origin(mut self, origin: impl Into<String>) -> Self {
+ self.origin = origin.into();
self
}
diff --git a/rust/crates/core/src/urls.rs b/rust/crates/core/src/urls.rs
index ac1ac78c5e..e584c05717 100644
--- a/rust/crates/core/src/urls.rs
+++ b/rust/crates/core/src/urls.rs
@@ -1,14 +1,14 @@
//! URL construction utilities.
-/// Production API base URL.
-pub const PRODUCTION_API_BASE_URL: &str = "https://api.ente.com";
+/// Production API origin.
+pub const PRODUCTION_API_ORIGIN: &str = "https://api.ente.com";
/// Generate the download URL for a file.
-pub fn file_download_url(api_base_url: &str, file_id: i64) -> String {
- if api_base_url == PRODUCTION_API_BASE_URL {
+pub fn file_download_url(api_origin: &str, file_id: i64) -> String {
+ if api_origin == PRODUCTION_API_ORIGIN {
format!("https://files.ente.com/?fileID={}", file_id)
} else {
- format!("{}/files/download/{}", api_base_url, file_id)
+ format!("{}/files/download/{}", api_origin, file_id)
}
}
@@ -18,7 +18,7 @@ mod tests {
#[test]
fn test_production_url() {
- let url = file_download_url(PRODUCTION_API_BASE_URL, 12345);
+ let url = file_download_url(PRODUCTION_API_ORIGIN, 12345);
assert_eq!(url, "https://files.ente.com/?fileID=12345");
}
diff --git a/rust/e2e/tests/support/auth.rs b/rust/e2e/tests/support/auth.rs
index 92949c2ffa..d3c0fdc8da 100644
--- a/rust/e2e/tests/support/auth.rs
+++ b/rust/e2e/tests/support/auth.rs
@@ -279,7 +279,7 @@ fn decode_base32(secret: &str) -> Vec<u8> {
fn accounts_client(endpoint: &str) -> CliResult<AccountsClient> {
AccountsClient::new(
AccountsClientConfig::new(App::Photos.client_package())
- .with_base_url(endpoint.to_string())
+ .with_origin(endpoint.to_string())
.with_user_agent("ente-e2e"),
)
}