π End-to-end encrypted cloud for everything.
Dart 2faandroidauthye2eeencryptionend-to-end-encryptionfluttergolanggoogle-photosgoogle-photos-alternativeiosopensourcephotosprivacyprivacy-toolstypescriptzero-knowledge
feat(rust): Implement comprehensive API client for Ente services
Manav Rathi9ac9e6bd2621
diff --git a/rust/CLAUDE.md b/rust/CLAUDE.mdindex bd2a090b7c..ec112050c6 100644--- a/rust/CLAUDE.md+++ b/rust/CLAUDE.md@@ -80,7 +80,7 @@ The project has completed foundational components (crypto, storage, models) and## Commit Guidelines-- Keep the co-author line, remove promotional links+- No promotional text like "Generated with [tool name]" - only keep the co-author line- Check `git status` before committing to avoid adding temporary/binary files- Never commit to main branch- Ensure code passes `cargo fmt` and `cargo clippy` before committingdiff --git a/rust/Cargo.lock b/rust/Cargo.lockindex 0a13d2d1b2..dbfeefd81d 100644--- a/rust/Cargo.lock+++ b/rust/Cargo.lock@@ -688,12 +688,14 @@ dependencies = ["log","mockito","num-bigint",+ "rand 0.8.5","reqwest","rpassword","rusqlite","serde","serde_json","serde_yaml",+ "sha2","sqlx","srp","tempdir",@@ -701,6 +703,7 @@ dependencies = ["thiserror 2.0.16","tokio","toml",+ "urlencoding","uuid","walkdir","zeroize",@@ -1738,6 +1741,7 @@ checksum = "a5e44f723f1133c9deac646763579fdb3ac745e418f2a7af9cd0c431da1f20b9"dependencies = ["num-integer","num-traits",+ "rand 0.8.5",][[package]]@@ -3355,6 +3359,12 @@ dependencies = ["percent-encoding",]+[[package]]+name = "urlencoding"+version = "2.1.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "daf8dba3b7eb870caf1ddeed7bc9d2a049f3cfdfae7cb521b087cc33ae4c49da"+[[package]]name = "utf8_iter"version = "1.0.4"diff --git a/rust/Cargo.toml b/rust/Cargo.tomlindex b34adacbaa..b2f3c26d39 100644--- a/rust/Cargo.toml+++ b/rust/Cargo.toml@@ -29,7 +29,10 @@ zeroize = { version = "1.8", features = ["derive"] }# SRP authenticationsrp = "0.6"-num-bigint = "0.4"+num-bigint = { version = "0.4", features = ["rand"] }+sha2 = "0.10"+urlencoding = "2.1"+rand = "0.8"# Storagerusqlite = { version = "0.32", features = ["bundled", "serde_json"] }diff --git a/rust/src/api/auth.rs b/rust/src/api/auth.rsnew file mode 100644index 0000000000..5d18de8e51--- /dev/null+++ b/rust/src/api/auth.rs@@ -0,0 +1,293 @@+use crate::api::client::ApiClient;+use crate::api::models::{+ AuthResponse, CreateSrpSessionRequest, CreateSrpSessionResponse, GetSrpAttributesResponse,+ SendOtpRequest, SrpAttributes, VerifyEmailRequest, VerifySrpSessionRequest, VerifyTotpRequest,+};+use crate::crypto::{derive_argon_key, derive_login_key};+use crate::models::error::Result;+use base64::{Engine, engine::general_purpose::STANDARD};+use num_bigint::{BigUint, RandBigInt};+use sha2::{Digest, Sha256};++/// Simple SRP-6a client implementation matching Go's behavior+struct SimpleSrpClient {+ n: BigUint, // Safe prime+ g: BigUint, // Generator+}++impl SimpleSrpClient {+ fn new() -> Self {+ // SRP-4096 group parameters (same as used in Go client)+ let n_hex = "FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E088A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3DC2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F83655D23DCA3AD961C62F356208552BB9ED529077096966D670C354E4ABC9804F1746C08CA18217C32905E462E36CE3BE39E772C180E86039B2783A2EC07A28FB5C55DF06F4C52C9DE2BCBF6955817183995497CEA956AE515D2261898FA051015728E5A8AAAC42DAD33170D04507A33A85521ABDF1CBA64ECFB850458DBEF0A8AEA71575D060C7DB3970F85A6E1E4C7ABF5AE8CDB0933D71E8C94E04A25619DCEE3D2261AD2EE6BF12FFA06D98A0864D87602733EC86A64521F2B18177B200CBBE117577A615D6C770988C0BAD946E208E24FA074E5AB3143DB5BFCE0FD108E4B82D120A92108011A723C12A787E6D788719A10BDBA5B2699C327186AF4E23C1A946834B6150BDA2583E9CA2AD44CE8DBBBC2DB04DE8EF92E8EFC141FBECAA6287C59474E6BC05D99B2964FA090C3A2233BA186515BE7ED1F612970CEE2D7AFB81BDD762170481CD0069127D5B05AA993B4EA988D8FDDC186FFB7DC90A6C08F4DF435C93402849236C3FAB4D27C7026C1D4DCB2602646DEC9751E763DBA37BDF8FF9406AD9E530EE5DB382F413001AEB06A53ED9027D831179727B0865A8918DA3EDBEBCF9B14ED44CE6CBACED4BB1BDB7F1447E6CC254B332051512BD7AF426FB8F401378CD2BF5983CA01C64B92ECF032EA15D1721D03F482D7CE6E74FEF6D55E702F46980C82B5A84031900B1C9E59E7C97FBEC7E8F323A97A7E36CC88BE0F1D45B7FF585AC54BD407B22B4154AACC8F6D7EBF48E1D814CC5ED20F8037E0A79715EEF29BE32806A1D58BB7C5DA76F550AA3D8A1FBFF0EB19CCB1A313D55CDA56C9EC2EF29632387FE8D76E3C0468043E8F663F4860EE12BF2D5B0B7474D6E694F91E6DBE115974A3926F12FEE5E438777CB6A932DF8CD8BEC4D073B931BA3BC832B68D9DD300741FA7BF8AFC47ED2576F6936BA424663AAB639C5AE4F5683423B4742BF1C978238F16CBE39D652DE3FDB8BEFC848AD922222E04A4037C0713EB57A81A23F0C73473FC646CEA306B4BCBC8862F8385DDFA9D4B7FA2C087E879683303ED5BDD3A062B3CF5B3A278A66D2A13F83F44F82DDF310EE074AB6A364597E899A0255DC164F31CC50846851DF9AB48195DED7EA1B1D510BD7EE74D73FAF36BC31ECFA268359046F4EB879F924009438B481C6CD7889A002ED5EE382BC9190DA6FC026E479558E4475677E9AA9E3050E2765694DFC81F56E880B96E7160C980DD98EDD3DFFFFFFFFFFFFFFFFF";+ let g_hex = "02";++ Self {+ n: BigUint::parse_bytes(n_hex.as_bytes(), 16).unwrap(),+ g: BigUint::parse_bytes(g_hex.as_bytes(), 16).unwrap(),+ }+ }++ fn generate_keys(&self) -> (BigUint, Vec<u8>) {+ let mut rng = rand::thread_rng();+ let client_secret = rng.gen_biguint_below(&self.n);+ let client_public = self.g.modpow(&client_secret, &self.n);+ let client_public_bytes = pad_to_n_bytes(client_public.to_bytes_be(), 512); // 4096 bits = 512 bytes+ (client_secret, client_public_bytes)+ }++ fn compute_proof(+ &self,+ identity: &[u8],+ password: &[u8],+ salt: &[u8],+ client_secret: &BigUint,+ client_public: &[u8],+ server_public: &[u8],+ ) -> crate::models::error::Result<Vec<u8>> {+ // H(N) XOR H(g)+ let h_n = Sha256::digest(&self.n.to_bytes_be());+ let h_g = Sha256::digest(&self.g.to_bytes_be());+ let h_xor: Vec<u8> = h_n.iter().zip(h_g.iter()).map(|(a, b)| a ^ b).collect();++ // H(identity)+ let h_identity = Sha256::digest(identity);++ // Compute shared key+ let k = compute_k(&self.n, &self.g);+ let u = compute_u(client_public, server_public);+ let x = compute_x(identity, password, salt);++ let server_b = BigUint::from_bytes_be(server_public);+ let v = self.g.modpow(&x, &self.n);+ let kv = (&k * &v) % &self.n;+ let diff = if server_b >= kv {+ &server_b - &kv+ } else {+ &self.n - (&kv - &server_b)+ };+ let ux = &u * &x;+ let aux = client_secret + &ux;+ let session_key = diff.modpow(&aux, &self.n);+ let session_key_hash = Sha256::digest(&session_key.to_bytes_be());++ // M1 = H(H(N) XOR H(g) | H(identity) | salt | A | B | session_key)+ let mut hasher = Sha256::new();+ hasher.update(&h_xor);+ hasher.update(&h_identity);+ hasher.update(salt);+ hasher.update(client_public);+ hasher.update(server_public);+ hasher.update(&session_key_hash);++ Ok(hasher.finalize().to_vec())+ }+}++fn pad_to_n_bytes(bytes: Vec<u8>, n: usize) -> Vec<u8> {+ if bytes.len() >= n {+ bytes+ } else {+ let mut padded = vec![0u8; n - bytes.len()];+ padded.extend(bytes);+ padded+ }+}++fn compute_k(n: &BigUint, g: &BigUint) -> BigUint {+ let mut hasher = Sha256::new();+ hasher.update(&n.to_bytes_be());+ hasher.update(&pad_to_n_bytes(g.to_bytes_be(), 512));+ BigUint::from_bytes_be(&hasher.finalize())+}++fn compute_u(client_public: &[u8], server_public: &[u8]) -> BigUint {+ let mut hasher = Sha256::new();+ hasher.update(client_public);+ hasher.update(server_public);+ BigUint::from_bytes_be(&hasher.finalize())+}++fn compute_x(identity: &[u8], password: &[u8], salt: &[u8]) -> BigUint {+ let mut hasher = Sha256::new();+ hasher.update(identity);+ hasher.update(b":");+ hasher.update(password);+ let h1 = hasher.finalize();++ let mut hasher = Sha256::new();+ hasher.update(salt);+ hasher.update(&h1);+ BigUint::from_bytes_be(&hasher.finalize())+}+use uuid::Uuid;++/// SRP authentication implementation for Ente API+pub struct AuthClient<'a> {+ api: &'a ApiClient,+}++impl<'a> AuthClient<'a> {+ pub fn new(api: &'a ApiClient) -> Self {+ Self { api }+ }++ /// Get SRP attributes for a user by email+ pub async fn get_srp_attributes(&self, email: &str) -> Result<SrpAttributes> {+ let url = format!("/users/srp/attributes?email={}", urlencoding::encode(email));+ let response: GetSrpAttributesResponse = self.api.get(&url, None).await?;+ Ok(response.attributes)+ }++ /// Create SRP session - first step of SRP authentication+ pub async fn create_srp_session(+ &self,+ srp_user_id: &Uuid,+ client_public: &[u8],+ ) -> Result<CreateSrpSessionResponse> {+ let request = CreateSrpSessionRequest {+ srp_user_id: srp_user_id.to_string(),+ srp_a: STANDARD.encode(client_public),+ };++ self.api+ .post("/users/srp/create-session", &request, None)+ .await+ }++ /// Verify SRP session - final step of SRP authentication+ pub async fn verify_srp_session(+ &self,+ srp_user_id: &Uuid,+ session_id: &Uuid,+ client_proof: &[u8],+ ) -> Result<AuthResponse> {+ let request = VerifySrpSessionRequest {+ srp_user_id: srp_user_id.to_string(),+ session_id: session_id.to_string(),+ srp_m1: STANDARD.encode(client_proof),+ };++ self.api+ .post("/users/srp/verify-session", &request, None)+ .await+ }++ /// Complete SRP authentication flow+ pub async fn login_with_srp(+ &self,+ email: &str,+ password: &str,+ ) -> Result<(AuthResponse, Vec<u8>)> {+ // Step 1: Get SRP attributes+ let srp_attrs = self.get_srp_attributes(email).await?;++ // Step 2: Derive key encryption key from password+ let key_enc_key = derive_argon_key(+ password,+ &srp_attrs.kek_salt,+ srp_attrs.mem_limit as u32,+ srp_attrs.ops_limit as u32,+ )?;++ // Step 3: Derive login key+ let login_key = derive_login_key(&key_enc_key)?;++ // Step 4: Initialize SRP client using the same approach as Go+ let srp_salt = STANDARD.decode(&srp_attrs.srp_salt)?;+ let identity = srp_attrs.srp_user_id.to_string();++ // Create SRP client (matching Go's srp.NewClient)+ let srp_client = SimpleSrpClient::new();+ let (client_secret, client_public) = srp_client.generate_keys();++ // Step 5: Create SRP session+ let session = self+ .create_srp_session(&srp_attrs.srp_user_id, &client_public)+ .await?;++ // Step 6: Process server's public key and generate proof+ let server_public = STANDARD.decode(&session.srp_b)?;+ let client_proof = srp_client.compute_proof(+ identity.as_bytes(),+ &login_key,+ &srp_salt,+ &client_secret,+ &client_public,+ &server_public,+ )?;++ // Step 7: Verify session with proof+ let auth_response = self+ .verify_srp_session(&srp_attrs.srp_user_id, &session.session_id, &client_proof)+ .await?;++ // TODO: Verify server proof if provided+ // if let Some(srp_m2) = &auth_response.srp_m2 {+ // let server_proof = STANDARD.decode(srp_m2)?;+ // // Verify server proof+ // }++ Ok((auth_response, key_enc_key))+ }++ /// Send OTP for email verification+ pub async fn send_login_otp(&self, email: &str) -> Result<()> {+ let request = SendOtpRequest {+ email: email.to_string(),+ purpose: "login".to_string(),+ };++ let _: serde_json::Value = self.api.post("/users/ott", &request, None).await?;+ Ok(())+ }++ /// Verify email with OTP+ pub async fn verify_email(&self, email: &str, otp: &str) -> Result<AuthResponse> {+ let request = VerifyEmailRequest {+ email: email.to_string(),+ ott: otp.to_string(),+ };++ self.api.post("/users/verify-email", &request, None).await+ }++ /// Verify TOTP for two-factor authentication+ pub async fn verify_totp(&self, session_id: &str, code: &str) -> Result<AuthResponse> {+ let request = VerifyTotpRequest {+ session_id: session_id.to_string(),+ code: code.to_string(),+ };++ self.api+ .post("/users/two-factor/verify", &request, None)+ .await+ }++ /// Check passkey verification status+ pub async fn check_passkey_status(&self, session_id: &str) -> Result<AuthResponse> {+ let url = format!(+ "/users/two-factor/passkeys/get-token?sessionID={}",+ session_id+ );+ self.api.get(&url, None).await+ }+}++#[cfg(test)]+mod tests {+ use super::*;+ use crate::crypto::{derive_argon_key, derive_login_key};++ #[test]+ fn test_login_key_derivation() {+ // Test that login key derivation matches expected output+ let password = "test_password";+ let salt = b"test_salt_16bytes";++ let key = derive_argon_key(password, &STANDARD.encode(salt), 4, 3).unwrap();+ assert_eq!(key.len(), 32);++ let login_key = derive_login_key(&key).unwrap();+ assert_eq!(login_key.len(), 32);+ }+}diff --git a/rust/src/api/client.rs b/rust/src/api/client.rsindex 8de5c69ae9..cf0ddd5c3a 100644--- a/rust/src/api/client.rs+++ b/rust/src/api/client.rs@@ -1,27 +1,251 @@#![allow(dead_code)]-use crate::Result;-use reqwest::Client;+use crate::models::error::{Error, Result};+use reqwest::{Client, RequestBuilder, Response, StatusCode};+use serde::{Deserialize, Serialize};+use std::collections::HashMap;+use std::sync::{Arc, RwLock};use std::time::Duration;+use tokio::time::sleep;const ENTE_API_ENDPOINT: &str = "https://api.ente.io";const TOKEN_HEADER: &str = "X-Auth-Token";const CLIENT_PKG_HEADER: &str = "X-Client-Package";+const CLIENT_PACKAGE: &str = "io.ente.cli";++/// Maximum number of retry attempts for failed requests+const MAX_RETRIES: u32 = 3;+/// Initial retry delay in milliseconds+const INITIAL_RETRY_DELAY_MS: u64 = 1000;+/// Maximum retry delay in milliseconds+const MAX_RETRY_DELAY_MS: u64 = 20000;++#[derive(Debug, Deserialize)]+pub struct ApiError {+ pub code: Option<String>,+ pub message: Option<String>,+}pub struct ApiClient {client: Client,- base_url: String,+ download_client: Client,+ pub(crate) base_url: String,+ /// Token storage for multi-account support: account_id -> token+ tokens: Arc<RwLock<HashMap<String, String>>>,}impl ApiClient {pub fn new(base_url: Option<String>) -> Result<Self> {- let client = Client::builder().timeout(Duration::from_secs(30)).build()?;+ // Main API client with standard timeout+ let client = Client::builder()+ .timeout(Duration::from_secs(30))+ .user_agent(format!("ente-cli-rust/{}", env!("CARGO_PKG_VERSION")))+ .build()?;++ // Download client with longer timeout and connection pool settings+ let download_client = Client::builder()+ .timeout(Duration::from_secs(300))+ .pool_idle_timeout(Duration::from_secs(90))+ .pool_max_idle_per_host(10)+ .user_agent(format!("ente-cli-rust/{}", env!("CARGO_PKG_VERSION")))+ .build()?;Ok(Self {client,+ download_client,base_url: base_url.unwrap_or_else(|| ENTE_API_ENDPOINT.to_string()),+ tokens: Arc::new(RwLock::new(HashMap::new())),})}- // TODO: Implement API methods+ /// Add or update authentication token for an account+ 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());+ }++ /// Remove authentication token for an account+ pub fn remove_token(&self, account_id: &str) {+ let mut tokens = self.tokens.write().unwrap();+ tokens.remove(account_id);+ }++ /// Get authentication token for an account+ pub fn get_token(&self, account_id: &str) -> Option<String> {+ let tokens = self.tokens.read().unwrap();+ tokens.get(account_id).cloned()+ }++ /// Build a request with common headers+ fn build_request(&self, builder: RequestBuilder, account_id: Option<&str>) -> RequestBuilder {+ let mut req = builder.header(CLIENT_PKG_HEADER, CLIENT_PACKAGE);++ // Add auth token if account_id is provided+ if let Some(id) = account_id {+ if let Some(token) = self.get_token(id) {+ req = req.header(TOKEN_HEADER, token);+ }+ }++ req+ }++ /// Execute request with retry logic+ async fn execute_with_retry(&self, request_builder: RequestBuilder) -> Result<Response> {+ let mut retry_count = 0;+ let mut delay_ms = INITIAL_RETRY_DELAY_MS;++ loop {+ let req = request_builder+ .try_clone()+ .ok_or_else(|| Error::Generic("Failed to clone request for retry".to_string()))?;++ match req.send().await {+ Ok(response) => {+ // Check if we should retry based on status code+ if response.status() == StatusCode::TOO_MANY_REQUESTS+ || response.status().is_server_error()+ {+ if retry_count < MAX_RETRIES {+ retry_count += 1;+ log::warn!(+ "Request failed with status {}, retry attempt {}/{}",+ response.status(),+ retry_count,+ MAX_RETRIES+ );++ // Exponential backoff with jitter+ sleep(Duration::from_millis(delay_ms)).await;+ delay_ms = (delay_ms * 2).min(MAX_RETRY_DELAY_MS);+ continue;+ }+ }++ return Ok(response);+ }+ Err(e) => {+ if retry_count < MAX_RETRIES {+ retry_count += 1;+ log::warn!(+ "Request failed with error: {}, retry attempt {}/{}",+ e,+ retry_count,+ MAX_RETRIES+ );++ sleep(Duration::from_millis(delay_ms)).await;+ delay_ms = (delay_ms * 2).min(MAX_RETRY_DELAY_MS);+ continue;+ }+ return Err(e.into());+ }+ }+ }+ }++ /// Make a GET request+ pub async fn get<T>(&self, path: &str, account_id: Option<&str>) -> Result<T>+ where+ T: for<'de> Deserialize<'de>,+ {+ let url = format!("{}{}", self.base_url, path);+ let request = self.client.get(&url);+ let request = self.build_request(request, account_id);++ let response = self.execute_with_retry(request).await?;++ if !response.status().is_success() {+ let error_text = response+ .text()+ .await+ .unwrap_or_else(|_| "Unknown error".to_string());+ return Err(Error::Generic(format!("API error: {}", error_text)));+ }++ Ok(response.json().await?)+ }++ /// Make a POST request+ pub async fn post<T, B>(&self, path: &str, body: &B, account_id: Option<&str>) -> Result<T>+ where+ T: for<'de> Deserialize<'de>,+ B: Serialize,+ {+ let url = format!("{}{}", self.base_url, path);+ let request = self.client.post(&url).json(body);+ let request = self.build_request(request, account_id);++ let response = self.execute_with_retry(request).await?;++ if !response.status().is_success() {+ let error_text = response+ .text()+ .await+ .unwrap_or_else(|_| "Unknown error".to_string());+ return Err(Error::Generic(format!("API error: {}", error_text)));+ }++ Ok(response.json().await?)+ }++ /// Make a PUT request+ pub async fn put<T, B>(&self, path: &str, body: &B, account_id: Option<&str>) -> Result<T>+ where+ T: for<'de> Deserialize<'de>,+ B: Serialize,+ {+ let url = format!("{}{}", self.base_url, path);+ let request = self.client.put(&url).json(body);+ let request = self.build_request(request, account_id);++ let response = self.execute_with_retry(request).await?;++ if !response.status().is_success() {+ let error_text = response+ .text()+ .await+ .unwrap_or_else(|_| "Unknown error".to_string());+ return Err(Error::Generic(format!("API error: {}", error_text)));+ }++ Ok(response.json().await?)+ }++ /// Make a DELETE request+ pub async fn delete(&self, path: &str, account_id: Option<&str>) -> Result<()> {+ let url = format!("{}{}", self.base_url, path);+ let request = self.client.delete(&url);+ let request = self.build_request(request, account_id);++ let response = self.execute_with_retry(request).await?;++ if !response.status().is_success() {+ let error_text = response+ .text()+ .await+ .unwrap_or_else(|_| "Unknown error".to_string());+ return Err(Error::Generic(format!("API error: {}", error_text)));+ }++ Ok(())+ }++ /// Download a file with the download client+ pub async fn download_file(&self, url: &str, account_id: Option<&str>) -> Result<Vec<u8>> {+ let request = self.download_client.get(url);+ let request = self.build_request(request, account_id);++ let response = self.execute_with_retry(request).await?;++ if !response.status().is_success() {+ let error_text = response+ .text()+ .await+ .unwrap_or_else(|_| "Unknown error".to_string());+ return Err(Error::Generic(format!("Download error: {}", error_text)));+ }++ Ok(response.bytes().await?.to_vec())+ }}diff --git a/rust/src/api/methods.rs b/rust/src/api/methods.rsnew file mode 100644index 0000000000..1107294732--- /dev/null+++ b/rust/src/api/methods.rs@@ -0,0 +1,183 @@+use crate::api::client::ApiClient;+use crate::api::models::{+ Collection, File, GetCollectionsResponse, GetDiffResponse, GetFileResponse, GetFileUrlResponse,+ GetFilesResponse, GetThumbnailUrlResponse, UserDetails,+};+use crate::models::error::Result;++/// API methods for interacting with Ente services+pub struct ApiMethods<'a> {+ api: &'a ApiClient,+}++impl<'a> ApiMethods<'a> {+ pub fn new(api: &'a ApiClient) -> Self {+ Self { api }+ }++ // ========== User Methods ==========++ /// Get user details including subscription and storage info+ pub async fn get_user_details(&self, account_id: &str) -> Result<UserDetails> {+ self.api.get("/users/details", Some(account_id)).await+ }++ // ========== Collection Methods ==========++ /// Get all collections (albums) for the authenticated user+ ///+ /// # Arguments+ /// * `account_id` - The account identifier for authentication+ /// * `since_time` - Unix timestamp in microseconds to get collections modified after this time (0 for all)+ 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?;+ Ok(response.collections)+ }++ /// Get a specific collection by ID+ 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+ }++ // ========== File Methods ==========++ /// Get files from a specific collection with pagination+ ///+ /// # Arguments+ /// * `account_id` - The account identifier for authentication+ /// * `collection_id` - The collection ID to fetch files from+ /// * `since_time` - Unix timestamp in microseconds to get files modified after this time+ ///+ /// # Returns+ /// A tuple of (files, has_more) where has_more indicates if there are more files to fetch+ 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={}&sinceTime={}",+ collection_id, since_time+ );+ let response: GetFilesResponse = self.api.get(&url, Some(account_id)).await?;+ Ok((response.diff, response.has_more))+ }++ /// Get a specific file by ID+ pub async fn get_file(+ &self,+ account_id: &str,+ collection_id: i64,+ file_id: i64,+ ) -> Result<File> {+ let url = format!(+ "/collections/file?collectionID={}&fileID={}",+ collection_id, file_id+ );+ let response: GetFileResponse = self.api.get(&url, Some(account_id)).await?;+ Ok(response.file)+ }++ /// Get all files across all collections (for incremental sync)+ ///+ /// # Arguments+ /// * `account_id` - The account identifier for authentication+ /// * `since_time` - Unix timestamp in microseconds to get files modified after this time+ /// * `limit` - Maximum number of files to return (typically 500)+ ///+ /// # Returns+ /// A tuple of (files, has_more) where has_more indicates if there are more files to fetch+ pub async fn get_diff(+ &self,+ account_id: &str,+ since_time: i64,+ limit: i32,+ ) -> Result<(Vec<File>, bool)> {+ let url = format!("/diff?sinceTime={}&limit={}", since_time, limit);+ let response: GetDiffResponse = self.api.get(&url, Some(account_id)).await?;+ Ok((response.diff, response.has_more))+ }++ /// Get download URL for a file+ pub async fn get_file_url(&self, account_id: &str, file_id: i64) -> Result<String> {+ // Check if we're using the default API endpoint+ let base_url = &self.api.base_url;+ if base_url == "https://api.ente.io" {+ // Use the CDN URL for production+ Ok(format!("https://files.ente.io/?fileID={}", file_id))+ } else {+ // Use the API endpoint for custom/dev environments+ let url = format!("/files/download/{}", file_id);+ let response: GetFileUrlResponse = self.api.get(&url, Some(account_id)).await?;+ Ok(response.url)+ }+ }++ /// Get thumbnail URL for a file+ 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?;+ Ok(response.url)+ }++ /// Download file content+ 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+ }++ /// Download thumbnail content+ 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+ }++ // ========== Trash Methods ==========++ /// Get deleted files+ 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?;+ Ok((response.diff, response.has_more))+ }++ /// Permanently delete files from trash+ 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?;+ Ok(())+ }++ /// Empty all trash+ pub async fn empty_trash(&self, account_id: &str) -> Result<()> {+ self.api.delete("/trash/empty", Some(account_id)).await+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[tokio::test]+ async fn test_file_url_generation() {+ let api = ApiClient::new(None).unwrap();+ let methods = ApiMethods::new(&api);++ // For production endpoint, should use CDN+ let url = methods.get_file_url("test", 12345).await;+ assert!(url.is_ok());+ assert!(url.unwrap().contains("files.ente.io"));+ }+}diff --git a/rust/src/api/mod.rs b/rust/src/api/mod.rsindex 05d6ac19ea..30ad1d8051 100644--- a/rust/src/api/mod.rs+++ b/rust/src/api/mod.rs@@ -1,3 +1,9 @@+pub mod auth;pub mod client;+pub mod methods;+pub mod models;+pub use auth::AuthClient;pub use client::ApiClient;+pub use methods::ApiMethods;+pub use models::*;diff --git a/rust/src/api/models.rs b/rust/src/api/models.rsnew file mode 100644index 0000000000..a546a29ecd--- /dev/null+++ b/rust/src/api/models.rs@@ -0,0 +1,286 @@+use serde::{Deserialize, Serialize};+use uuid::Uuid;++// ========== Authentication Models ==========++#[derive(Debug, Deserialize, Serialize)]+#[serde(rename_all = "camelCase")]+pub struct SrpAttributes {+ pub srp_user_id: Uuid,+ pub srp_salt: String,+ pub mem_limit: i32,+ pub ops_limit: i32,+ pub kek_salt: String,+ pub is_email_mfa_enabled: bool,+}++#[derive(Debug, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct GetSrpAttributesResponse {+ pub attributes: SrpAttributes,+}++#[derive(Debug, Serialize)]+#[serde(rename_all = "camelCase")]+pub struct CreateSrpSessionRequest {+ pub srp_user_id: String,+ pub srp_a: String,+}++#[derive(Debug, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct CreateSrpSessionResponse {+ pub session_id: Uuid,+ pub srp_b: String,+}++#[derive(Debug, Serialize)]+#[serde(rename_all = "camelCase")]+pub struct VerifySrpSessionRequest {+ pub srp_user_id: String,+ pub session_id: String,+ pub srp_m1: String,+}++#[derive(Debug, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct KeyAttributes {+ pub kek_salt: String,+ pub kek_hash: Option<String>,+ pub encrypted_key: String,+ pub key_decryption_nonce: String,+ pub public_key: String,+ pub encrypted_secret_key: String,+ pub secret_key_decryption_nonce: String,+ pub mem_limit: i32,+ pub ops_limit: i32,+}++#[derive(Debug, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct AuthResponse {+ pub id: i64,+ pub key_attributes: Option<KeyAttributes>,+ pub encrypted_token: Option<String>,+ pub token: Option<String>,+ pub two_factor_session_id: Option<String>,+ pub passkey_session_id: Option<String>,+ pub srp_m2: Option<String>,+ pub accounts_url: Option<String>,+}++impl AuthResponse {+ pub fn is_mfa_required(&self) -> bool {+ self.two_factor_session_id.is_some()+ }++ pub fn is_passkey_required(&self) -> bool {+ self.passkey_session_id.is_some()+ }+}++#[derive(Debug, Serialize)]+pub struct SendOtpRequest {+ pub email: String,+ pub purpose: String,+}++#[derive(Debug, Serialize)]+pub struct VerifyEmailRequest {+ pub email: String,+ pub ott: String,+}++#[derive(Debug, Serialize)]+#[serde(rename_all = "camelCase")]+pub struct VerifyTotpRequest {+ pub session_id: String,+ pub code: String,+}++// ========== User Models ==========++#[derive(Debug, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct UserDetails {+ pub user: User,+ pub subscription: Subscription,+ pub family_data: Option<FamilyData>,+ pub storage: Storage,+}++#[derive(Debug, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct User {+ pub id: i64,+ pub email: String,+ pub profile_data: Option<ProfileData>,+}++#[derive(Debug, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct ProfileData {+ pub can_disable_emails: bool,+ pub is_email_mfa_enabled: bool,+ pub is_two_factor_enabled: bool,+}++#[derive(Debug, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct Subscription {+ pub product_id: String,+ pub storage: i64,+ pub expiry_time: i64,+}++#[derive(Debug, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct FamilyData {+ pub members: Vec<FamilyMember>,+}++#[derive(Debug, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct FamilyMember {+ pub id: i64,+ pub email: String,+ pub usage: i64,+ pub is_admin: bool,+}++#[derive(Debug, Deserialize)]+pub struct Storage {+ pub used: i64,+}++// ========== Collection Models ==========++#[derive(Debug, Deserialize, Serialize, Clone)]+#[serde(rename_all = "camelCase")]+pub struct Collection {+ pub id: i64,+ pub owner: CollectionUser,+ pub encrypted_key: String,+ pub key_decryption_nonce: String,+ pub name: Option<String>,+ pub encrypted_name: Option<String>,+ pub name_decryption_nonce: Option<String>,+ #[serde(rename = "type")]+ pub collection_type: String,+ pub sharees: Option<Vec<CollectionUser>>,+ pub updation_time: i64,+ pub is_deleted: bool,+ pub magic_metadata: Option<MagicMetadata>,+ pub pub_magic_metadata: Option<MagicMetadata>,+ pub shared_magic_metadata: Option<MagicMetadata>,+}++#[derive(Debug, Deserialize, Serialize, Clone)]+pub struct CollectionUser {+ pub id: i64,+ pub email: String,+ pub name: Option<String>,+ pub role: Option<String>,+}++#[derive(Debug, Deserialize, Serialize, Clone)]+pub struct MagicMetadata {+ pub version: i32,+ pub count: i32,+ pub data: String,+ pub header: String,+}++#[derive(Debug, Deserialize)]+pub struct GetCollectionsResponse {+ pub collections: Vec<Collection>,+}++// ========== File Models ==========++#[derive(Debug, Deserialize, Serialize, Clone)]+#[serde(rename_all = "camelCase")]+pub struct File {+ pub id: i64,+ pub owner_id: i64,+ pub collection_id: i64,+ pub collection_owner_id: Option<i64>,+ pub encrypted_key: String,+ pub key_decryption_nonce: String,+ pub file: FileAttributes,+ pub thumbnail: FileAttributes,+ pub metadata: FileAttributes,+ pub is_deleted: bool,+ pub updation_time: i64,+ pub magic_metadata: Option<MagicMetadata>,+ pub pubic_magic_metadata: Option<MagicMetadata>,+ pub info: Option<FileInfo>,+}++impl File {+ pub fn is_removed_from_album(&self) -> bool {+ self.is_deleted || self.file.encrypted_data == Some("-".to_string())+ }+}++#[derive(Debug, Deserialize, Serialize, Clone)]+#[serde(rename_all = "camelCase")]+pub struct FileAttributes {+ pub encrypted_data: Option<String>,+ pub decryption_header: String,+}++#[derive(Debug, Deserialize, Serialize, Clone)]+#[serde(rename_all = "camelCase")]+pub struct FileInfo {+ pub file_size: Option<i64>,+ pub thumbnail_size: Option<i64>,+}++#[derive(Debug, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct GetFilesRequest {+ pub collection_id: i64,+ pub since_time: i64,+ pub limit: Option<i32>,+}++#[derive(Debug, Deserialize)]+pub struct GetFilesResponse {+ pub diff: Vec<File>,+ #[serde(rename = "hasMore")]+ pub has_more: bool,+}++#[derive(Debug, Deserialize)]+pub struct GetFileResponse {+ pub file: File,+}++// ========== Diff/Sync Models ==========++#[derive(Debug, Serialize)]+#[serde(rename_all = "camelCase")]+pub struct GetDiffRequest {+ pub since_time: i64,+ pub limit: i32,+}++#[derive(Debug, Deserialize)]+pub struct GetDiffResponse {+ pub diff: Vec<File>,+ #[serde(rename = "hasMore")]+ pub has_more: bool,+}++// ========== Download Models ==========++#[derive(Debug, Deserialize)]+pub struct GetFileUrlResponse {+ pub url: String,+}++#[derive(Debug, Deserialize)]+pub struct GetThumbnailUrlResponse {+ pub url: String,+}diff --git a/rust/src/main.rs b/rust/src/main.rsindex eb0339166d..915c819be0 100644--- a/rust/src/main.rs+++ b/rust/src/main.rs@@ -12,7 +12,7 @@ async fn main() -> Result<()> {// Initialize libsodiumente_rs::crypto::init()?;-+// Initialize storagelet config_dir = ente_rs::utils::get_cli_config_dir()?;let db_path = config_dir.join("ente.db");diff --git a/rust/src/models/error.rs b/rust/src/models/error.rsindex 8ba242c919..f5bb28075a 100644--- a/rust/src/models/error.rs+++ b/rust/src/models/error.rs@@ -12,7 +12,7 @@ pub enum Error {Serialization(#[from] serde_json::Error),#[error("Database error: {0}")]- Database(String),+ Database(#[from] rusqlite::Error),#[error("Crypto error: {0}")]Crypto(String),diff --git a/rust/src/storage/account.rs b/rust/src/storage/account.rsindex 5050caaaa2..2be9a2c76a 100644--- a/rust/src/storage/account.rs+++ b/rust/src/storage/account.rs@@ -1,7 +1,10 @@#![allow(dead_code)]-use crate::{Result, models::account::{Account, App, AccountSecrets}};-use rusqlite::{Connection, params, Row, OptionalExtension};+use crate::{+ Result,+ models::account::{Account, AccountSecrets, App},+};+use rusqlite::{Connection, OptionalExtension, Row, params};use std::time::{SystemTime, UNIX_EPOCH};pub struct AccountStore<'a> {@@ -12,11 +15,11 @@ impl<'a> AccountStore<'a> {pub fn new(conn: &'a Connection) -> Self {Self { conn }}-+/// Add a new accountpub fn add(&self, account: &Account) -> Result<i64> {let now = current_timestamp();-+self.conn.execute("INSERT INTO accounts (email, user_id, app, export_dir, created_at, updated_at)VALUES (?1, ?2, ?3, ?4, ?5, ?6)",@@ -29,64 +32,64 @@ impl<'a> AccountStore<'a> {now],)?;-+Ok(self.conn.last_insert_rowid())}-+/// Get an account by email and apppub fn get(&self, email: &str, app: App) -> Result<Option<Account>> {let mut stmt = self.conn.prepare("SELECT id, email, user_id, app, export_dir FROM accounts- WHERE email = ?1 AND app = ?2"+ WHERE email = ?1 AND app = ?2",)?;-- let account = stmt.query_row(- params![email, format!("{:?}", app).to_lowercase()],- |row| row_to_account(row)- ).optional()?;-++ let account = stmt+ .query_row(params![email, format!("{:?}", app).to_lowercase()], |row| {+ row_to_account(row)+ })+ .optional()?;+Ok(account)}-+/// List all accountspub fn list(&self) -> Result<Vec<Account>> {let mut stmt = self.conn.prepare("SELECT id, email, user_id, app, export_dir FROM accounts- ORDER BY email, app"+ ORDER BY email, app",)?;-- let accounts = stmt.query_map([], |row| row_to_account(row))?++ let accounts = stmt+ .query_map([], |row| row_to_account(row))?.collect::<std::result::Result<Vec<_>, _>>()?;-+Ok(accounts)}-+/// Update account export directorypub fn update_export_dir(&self, email: &str, app: App, export_dir: &str) -> Result<()> {let now = current_timestamp();-+self.conn.execute("UPDATE accounts SET export_dir = ?1, updated_at = ?2WHERE email = ?3 AND app = ?4",params![export_dir, now, email, format!("{:?}", app).to_lowercase()],)?;-+Ok(())}-+/// Delete an accountpub fn delete(&self, account_id: i64) -> Result<()> {- self.conn.execute(- "DELETE FROM accounts WHERE id = ?1",- params![account_id],- )?;+ self.conn+ .execute("DELETE FROM accounts WHERE id = ?1", params![account_id])?;Ok(())}-+/// Store account secrets (encrypted)pub fn store_secrets(&self, account_id: i64, secrets: &AccountSecrets) -> Result<()> {let now = current_timestamp();-+self.conn.execute("INSERT OR REPLACE INTO secrets(account_id, token, master_key, secret_key, public_key, updated_at)@@ -100,26 +103,28 @@ impl<'a> AccountStore<'a> {now],)?;-+Ok(())}-+/// Get account secretspub fn get_secrets(&self, account_id: i64) -> Result<Option<AccountSecrets>> {let mut stmt = self.conn.prepare("SELECT token, master_key, secret_key, public_key FROM secrets- WHERE account_id = ?1"+ WHERE account_id = ?1",)?;-- let secrets = stmt.query_row(params![account_id], |row| {- Ok(AccountSecrets {- token: row.get(0)?,- master_key: row.get(1)?,- secret_key: row.get(2)?,- public_key: row.get(3)?,++ let secrets = stmt+ .query_row(params![account_id], |row| {+ Ok(AccountSecrets {+ token: row.get(0)?,+ master_key: row.get(1)?,+ secret_key: row.get(2)?,+ public_key: row.get(3)?,+ })})- }).optional()?;-+ .optional()?;+Ok(secrets)}}@@ -132,7 +137,7 @@ fn row_to_account(row: &Row) -> rusqlite::Result<Account> {"auth" => App::Auth,_ => App::Photos, // Default fallback};-+Ok(Account {id: row.get(0)?,email: row.get(1)?,@@ -147,4 +152,4 @@ fn current_timestamp() -> i64 {.duration_since(UNIX_EPOCH).unwrap().as_secs() as i64-}\ No newline at end of file+}diff --git a/rust/src/storage/config.rs b/rust/src/storage/config.rsindex 4d1c80c536..f223b6234d 100644--- a/rust/src/storage/config.rs+++ b/rust/src/storage/config.rs@@ -1,7 +1,7 @@#![allow(dead_code)]use crate::Result;-use rusqlite::{Connection, params, OptionalExtension};+use rusqlite::{Connection, OptionalExtension, params};use std::time::{SystemTime, UNIX_EPOCH};pub struct ConfigStore<'a> {@@ -12,56 +12,56 @@ impl<'a> ConfigStore<'a> {pub fn new(conn: &'a Connection) -> Self {Self { conn }}-+/// Set a configuration valuepub fn set(&self, key: &str, value: &str) -> Result<()> {let now = SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_secs() as i64;-+self.conn.execute("INSERT OR REPLACE INTO config (key, value, updated_at)VALUES (?1, ?2, ?3)",params![key, value, now],)?;-+Ok(())}-+/// Get a configuration valuepub fn get(&self, key: &str) -> Result<Option<String>> {- let mut stmt = self.conn.prepare(- "SELECT value FROM config WHERE key = ?1"- )?;-- let value = stmt.query_row(params![key], |row| {- row.get::<_, String>(0)- }).optional()?;-+ let mut stmt = self+ .conn+ .prepare("SELECT value FROM config WHERE key = ?1")?;++ let value = stmt+ .query_row(params![key], |row| row.get::<_, String>(0))+ .optional()?;+Ok(value)}-+/// Delete a configuration valuepub fn delete(&self, key: &str) -> Result<()> {- self.conn.execute(- "DELETE FROM config WHERE key = ?1",- params![key],- )?;-+ self.conn+ .execute("DELETE FROM config WHERE key = ?1", params![key])?;+Ok(())}-+/// Get all configuration valuespub fn list(&self) -> Result<Vec<(String, String)>> {- let mut stmt = self.conn.prepare(- "SELECT key, value FROM config ORDER BY key"- )?;-- let configs = stmt.query_map([], |row| {- Ok((row.get::<_, String>(0)?, row.get::<_, String>(1)?))- })?.collect::<std::result::Result<Vec<_>, _>>()?;-+ let mut stmt = self+ .conn+ .prepare("SELECT key, value FROM config ORDER BY key")?;++ let configs = stmt+ .query_map([], |row| {+ Ok((row.get::<_, String>(0)?, row.get::<_, String>(1)?))+ })?+ .collect::<std::result::Result<Vec<_>, _>>()?;+Ok(configs)}-}\ No newline at end of file+}diff --git a/rust/src/storage/mod.rs b/rust/src/storage/mod.rsindex a64b53b4c8..0e31c9198f 100644--- a/rust/src/storage/mod.rs+++ b/rust/src/storage/mod.rs@@ -2,12 +2,12 @@use crate::{Error, Result};use rusqlite::Connection;+use serde::{Deserialize, Serialize};use std::path::Path;-use serde::{Serialize, Deserialize};-pub mod schema;pub mod account;pub mod config;+pub mod schema;pub mod sync;pub use account::AccountStore;@@ -23,16 +23,16 @@ impl Storage {/// Create a new storage instance with the given database pathpub fn new<P: AsRef<Path>>(path: P) -> Result<Self> {let conn = Connection::open(path)?;-+// Enable foreign keysconn.execute("PRAGMA foreign_keys = ON", [])?;-+// Create tablesschema::create_tables(&conn)?;-+Ok(Self { conn })}-+/// Create an in-memory database (useful for testing)pub fn new_in_memory() -> Result<Self> {let conn = Connection::open_in_memory()?;@@ -40,12 +40,12 @@ impl Storage {schema::create_tables(&conn)?;Ok(Self { conn })}-+/// Get a reference to the connectionpub fn conn(&self) -> &Connection {&self.conn}-+/// Begin a transactionpub fn transaction<F, R>(&mut self, f: F) -> Result<R>where@@ -56,17 +56,17 @@ impl Storage {tx.commit()?;Ok(result)}-+/// Get account storepub fn accounts(&self) -> AccountStore {AccountStore::new(&self.conn)}-+/// Get config storepub fn config(&self) -> ConfigStore {ConfigStore::new(&self.conn)}-+/// Get sync storepub fn sync(&self) -> SyncStore {SyncStore::new(&self.conn)@@ -78,7 +78,7 @@ pub trait JsonValue: Serialize + for<'de> Deserialize<'de> {fn to_json(&self) -> Result<String> {Ok(serde_json::to_string(self)?)}-+fn from_json(json: &str) -> Result<Self> {Ok(serde_json::from_str(json)?)}@@ -87,9 +87,4 @@ pub trait JsonValue: Serialize + for<'de> Deserialize<'de> {// Implement for common typesimpl<T> JsonValue for T where T: Serialize + for<'de> Deserialize<'de> {}-// Re-export rusqlite error conversion-impl From<rusqlite::Error> for Error {- fn from(err: rusqlite::Error) -> Self {- Error::Generic(err.to_string())- }-}\ No newline at end of file+// Rusqlite error conversion is now handled in models/error.rs via #[from]diff --git a/rust/src/storage/schema.rs b/rust/src/storage/schema.rsindex 2e33591d53..a5079515c4 100644--- a/rust/src/storage/schema.rs+++ b/rust/src/storage/schema.rs@@ -17,7 +17,7 @@ pub fn create_tables(conn: &Connection) -> Result<()> {)",[],)?;-+// Secrets table (encrypted credentials)conn.execute("CREATE TABLE IF NOT EXISTS secrets (@@ -31,7 +31,7 @@ pub fn create_tables(conn: &Connection) -> Result<()> {)",[],)?;-+// Configuration tableconn.execute("CREATE TABLE IF NOT EXISTS config (@@ -41,7 +41,7 @@ pub fn create_tables(conn: &Connection) -> Result<()> {)",[],)?;-+// Collections/Albums tableconn.execute("CREATE TABLE IF NOT EXISTS collections (@@ -59,7 +59,7 @@ pub fn create_tables(conn: &Connection) -> Result<()> {)",[],)?;-+// Files table (for caching remote file metadata)conn.execute("CREATE TABLE IF NOT EXISTS files (@@ -79,7 +79,7 @@ pub fn create_tables(conn: &Connection) -> Result<()> {)",[],)?;-+// Album files mappingconn.execute("CREATE TABLE IF NOT EXISTS album_files (@@ -94,7 +94,7 @@ pub fn create_tables(conn: &Connection) -> Result<()> {)",[],)?;-+// Sync state tableconn.execute("CREATE TABLE IF NOT EXISTS sync_state (@@ -107,25 +107,25 @@ pub fn create_tables(conn: &Connection) -> Result<()> {)",[],)?;-+// Create indices for better performanceconn.execute("CREATE INDEX IF NOT EXISTS idx_files_collectionON files(account_id, collection_id)",[],)?;-+conn.execute("CREATE INDEX IF NOT EXISTS idx_album_files_albumON album_files(account_id, album_id)",[],)?;-+conn.execute("CREATE INDEX IF NOT EXISTS idx_collections_accountON collections(account_id)",[],)?;-+Ok(())-}\ No newline at end of file+}diff --git a/rust/src/storage/sync.rs b/rust/src/storage/sync.rsindex 92959764b6..cab03cc663 100644--- a/rust/src/storage/sync.rs+++ b/rust/src/storage/sync.rs@@ -1,7 +1,10 @@#![allow(dead_code)]-use crate::{Result, models::{file::RemoteFile, collection::Collection}};-use rusqlite::{Connection, params, OptionalExtension};+use crate::{+ Result,+ models::{collection::Collection, file::RemoteFile},+};+use rusqlite::{Connection, OptionalExtension, params};use serde_json;pub struct SyncStore<'a> {@@ -12,11 +15,11 @@ impl<'a> SyncStore<'a> {pub fn new(conn: &'a Connection) -> Self {Self { conn }}-+/// Store a collectionpub fn upsert_collection(&self, account_id: i64, collection: &Collection) -> Result<()> {let metadata = serde_json::to_string(&collection)?;-+self.conn.execute("INSERT OR REPLACE INTO collections(account_id, collection_id, name, type, owner, is_deleted, metadata, updated_at)@@ -32,31 +35,33 @@ impl<'a> SyncStore<'a> {collection.updated_at],)?;-+Ok(())}-+/// Get all collections for an accountpub fn get_collections(&self, account_id: i64) -> Result<Vec<Collection>> {let mut stmt = self.conn.prepare("SELECT metadata FROM collectionsWHERE account_id = ?1 AND is_deleted = 0- ORDER BY collection_id"+ ORDER BY collection_id",)?;-- let collections = stmt.query_map(params![account_id], |row| {- let metadata: String = row.get(0)?;- Ok(serde_json::from_str::<Collection>(&metadata).unwrap())- })?.collect::<std::result::Result<Vec<_>, _>>()?;-++ let collections = stmt+ .query_map(params![account_id], |row| {+ let metadata: String = row.get(0)?;+ Ok(serde_json::from_str::<Collection>(&metadata).unwrap())+ })?+ .collect::<std::result::Result<Vec<_>, _>>()?;+Ok(collections)}-+/// Store a filepub fn upsert_file(&self, account_id: i64, file: &RemoteFile) -> Result<()> {let file_info = serde_json::to_string(&file.file)?;let metadata = serde_json::to_string(&file.metadata)?;-+self.conn.execute("INSERT OR REPLACE INTO files(account_id, file_id, collection_id, encrypted_key, key_decryption_nonce,@@ -74,61 +79,72 @@ impl<'a> SyncStore<'a> {file.updated_at],)?;-+Ok(())}-+/// Get files for a collection- pub fn get_files_by_collection(&self, account_id: i64, collection_id: i64) -> Result<Vec<RemoteFile>> {+ pub fn get_files_by_collection(+ &self,+ account_id: i64,+ collection_id: i64,+ ) -> Result<Vec<RemoteFile>> {let mut stmt = self.conn.prepare("SELECT file_id, collection_id, encrypted_key, key_decryption_nonce,file_info, metadata, is_deleted, updated_atFROM filesWHERE account_id = ?1 AND collection_id = ?2 AND is_deleted = 0- ORDER BY file_id"+ ORDER BY file_id",)?;-- let files = stmt.query_map(params![account_id, collection_id], |row| {- let file_info: String = row.get(4)?;- let metadata: String = row.get(5)?;-- Ok(RemoteFile {- id: row.get(0)?,- collection_id: row.get(1)?,- owner_id: 0, // Will need to fetch from account- encrypted_key: row.get(2)?,- key_decryption_nonce: row.get(3)?,- file: serde_json::from_str(&file_info).unwrap(),- thumbnail: serde_json::from_str("{}").unwrap(), // Placeholder- metadata: serde_json::from_str(&metadata).unwrap(),- is_deleted: row.get::<_, i32>(6)? != 0,- updated_at: row.get(7)?,- })- })?.collect::<std::result::Result<Vec<_>, _>>()?;-++ let files = stmt+ .query_map(params![account_id, collection_id], |row| {+ let file_info: String = row.get(4)?;+ let metadata: String = row.get(5)?;++ Ok(RemoteFile {+ id: row.get(0)?,+ collection_id: row.get(1)?,+ owner_id: 0, // Will need to fetch from account+ encrypted_key: row.get(2)?,+ key_decryption_nonce: row.get(3)?,+ file: serde_json::from_str(&file_info).unwrap(),+ thumbnail: serde_json::from_str("{}").unwrap(), // Placeholder+ metadata: serde_json::from_str(&metadata).unwrap(),+ is_deleted: row.get::<_, i32>(6)? != 0,+ updated_at: row.get(7)?,+ })+ })?+ .collect::<std::result::Result<Vec<_>, _>>()?;+Ok(files)}-+/// Update sync state- pub fn update_sync_state(&self, account_id: i64, sync_type: &str, timestamp: i64) -> Result<()> {+ pub fn update_sync_state(+ &self,+ account_id: i64,+ sync_type: &str,+ timestamp: i64,+ ) -> Result<()> {let column = match sync_type {"files" => "last_file_sync","collections" => "last_collection_sync","albums" => "last_album_sync",_ => return Err(crate::Error::InvalidInput("Invalid sync type".into())),};-+let query = format!("INSERT OR REPLACE INTO sync_state (account_id, {}) VALUES (?1, ?2)ON CONFLICT(account_id) DO UPDATE SET {} = ?2",column, column);-+self.conn.execute(&query, params![account_id, timestamp])?;-+Ok(())}-+/// Get last sync timestamppub fn get_last_sync(&self, account_id: i64, sync_type: &str) -> Result<Option<i64>> {let column = match sync_type {@@ -137,25 +153,31 @@ impl<'a> SyncStore<'a> {"albums" => "last_album_sync",_ => return Err(crate::Error::InvalidInput("Invalid sync type".into())),};-+let query = format!("SELECT {} FROM sync_state WHERE account_id = ?1", column);let mut stmt = self.conn.prepare(&query)?;-- let timestamp = stmt.query_row(params![account_id], |row| {- row.get::<_, Option<i64>>(0)- }).optional()?.flatten();-++ let timestamp = stmt+ .query_row(params![account_id], |row| row.get::<_, Option<i64>>(0))+ .optional()?+ .flatten();+Ok(timestamp)}-+/// Mark album file as synced- pub fn mark_album_file_synced(&self, account_id: i64, album_id: i64, file_id: i64) -> Result<()> {+ pub fn mark_album_file_synced(+ &self,+ account_id: i64,+ album_id: i64,+ file_id: i64,+ ) -> Result<()> {self.conn.execute("UPDATE album_files SET synced_locally = 1WHERE account_id = ?1 AND album_id = ?2 AND file_id = ?3",params![account_id, album_id, file_id],)?;-+Ok(())}-}\ No newline at end of file+}