π End-to-end encrypted cloud for everything.
Dart 2faandroidauthye2eeencryptionend-to-end-encryptionfluttergolanggoogle-photosgoogle-photos-alternativeiosopensourcephotosprivacyprivacy-toolstypescriptzero-knowledge
feat(rust): Implement export command with collection-based file fetching
Manav Rathi618753cb1a7f
diff --git a/rust/src/api/client.rs b/rust/src/api/client.rsindex 4db015f1bb..49acc2cf6d 100644--- a/rust/src/api/client.rs+++ b/rust/src/api/client.rs@@ -83,7 +83,10 @@ impl ApiClient {// Add auth token if account_id is providedif let Some(id) = account_id {if let Some(token) = self.get_token(id) {+ log::debug!("Adding auth token for account {}: {}", id, token);req = req.header(TOKEN_HEADER, token);+ } else {+ log::warn!("No token found for account {}", id);}}@@ -174,7 +177,12 @@ impl ApiClient {)));}- Ok(response.json().await?)+ let text = response.text().await?;+ serde_json::from_str(&text).map_err(|e| {+ log::error!("Failed to deserialize response: {}", e);+ log::error!("Response text (first 1000 chars): {}", &text[..1000.min(text.len())]);+ Error::Generic(format!("Deserialization failed: {}", e))+ })}/// Make a POST request@@ -222,7 +230,12 @@ impl ApiClient {)));}- Ok(response.json().await?)+ let text = response.text().await?;+ serde_json::from_str(&text).map_err(|e| {+ log::error!("Failed to deserialize response: {}", e);+ log::error!("Response text (first 1000 chars): {}", &text[..1000.min(text.len())]);+ Error::Generic(format!("Deserialization failed: {}", e))+ })}/// Make a PUT request@@ -260,7 +273,12 @@ impl ApiClient {)));}- Ok(response.json().await?)+ let text = response.text().await?;+ serde_json::from_str(&text).map_err(|e| {+ log::error!("Failed to deserialize response: {}", e);+ log::error!("Response text (first 1000 chars): {}", &text[..1000.min(text.len())]);+ Error::Generic(format!("Deserialization failed: {}", e))+ })}/// Make a DELETE requestdiff --git a/rust/src/api/methods.rs b/rust/src/api/methods.rsindex 210e9f687c..e7049b4714 100644--- a/rust/src/api/methods.rs+++ b/rust/src/api/methods.rs@@ -1,6 +1,6 @@use crate::api::client::ApiClient;use crate::api::models::{- Collection, File, GetCollectionsResponse, GetDiffResponse, GetFileResponse, GetFileUrlResponse,+ Collection, File, GetCollectionsResponse, GetDiffResponse, GetFileResponse,GetFilesResponse, GetThumbnailUrlResponse, UserDetails,};use crate::models::error::Result;@@ -101,17 +101,16 @@ impl<'a> ApiMethods<'a> {}/// Get download URL for a file- pub async fn get_file_url(&self, account_id: &str, file_id: i64) -> Result<String> {+ pub async fn get_file_url(&self, _account_id: &str, file_id: i64) -> Result<String> {// Check if we're using the default API endpointlet base_url = &self.api.base_url;if base_url == "https://api.ente.io" {// Use the CDN URL for productionOk(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)+ // For custom/dev environments, use direct download URL+ // The Go implementation shows this is the pattern+ Ok(format!("{}/files/download/{}", base_url, file_id))}}diff --git a/rust/src/api/models.rs b/rust/src/api/models.rsindex 7986ce7609..2985269923 100644--- a/rust/src/api/models.rs+++ b/rust/src/api/models.rs@@ -176,17 +176,40 @@ pub struct Collection {pub name_decryption_nonce: Option<String>,#[serde(rename = "type")]pub collection_type: String,+ pub attributes: Option<CollectionAttributes>,pub sharees: Option<Vec<CollectionUser>>,+ #[serde(rename = "publicURLs")]+ pub public_urls: Option<Vec<PublicUrl>>,pub updation_time: i64,+ #[serde(default)]pub is_deleted: bool,pub magic_metadata: Option<MagicMetadata>,pub pub_magic_metadata: Option<MagicMetadata>,pub shared_magic_metadata: Option<MagicMetadata>,+ pub app: Option<String>,+}++#[derive(Debug, Deserialize, Serialize, Clone)]+pub struct CollectionAttributes {+ pub version: i32,+}++#[derive(Debug, Deserialize, Serialize, Clone)]+#[serde(rename_all = "camelCase")]+pub struct PublicUrl {+ pub url: String,+ pub device_limit: i32,+ pub valid_till: i64,+ pub enable_download: bool,+ pub enable_collect: bool,+ pub password_enabled: bool,+ pub enable_join: bool,}#[derive(Debug, Deserialize, Serialize, Clone)]pub struct CollectionUser {pub id: i64,+ #[serde(default)]pub email: String,pub name: Option<String>,pub role: Option<String>,@@ -211,8 +234,11 @@ pub struct GetCollectionsResponse {#[serde(rename_all = "camelCase")]pub struct File {pub id: i64,+ #[serde(rename = "ownerID")]pub owner_id: i64,+ #[serde(rename = "collectionID")]pub collection_id: i64,+ #[serde(rename = "collectionOwnerID")]pub collection_owner_id: Option<i64>,pub encrypted_key: String,pub key_decryption_nonce: String,@@ -222,7 +248,8 @@ pub struct File {pub is_deleted: bool,pub updation_time: i64,pub magic_metadata: Option<MagicMetadata>,- pub pubic_magic_metadata: Option<MagicMetadata>,+ #[serde(rename = "pubMagicMetadata")]+ pub pub_magic_metadata: Option<MagicMetadata>,pub info: Option<FileInfo>,}@@ -237,6 +264,7 @@ impl File {pub struct FileAttributes {pub encrypted_data: Option<String>,pub decryption_header: String,+ pub size: Option<i64>,}#[derive(Debug, Deserialize, Serialize, Clone)]diff --git a/rust/src/cli/export.rs b/rust/src/cli/export.rsindex 4a96e9fc17..014675ecac 100644--- a/rust/src/cli/export.rs+++ b/rust/src/cli/export.rs@@ -2,6 +2,10 @@ use clap::Args;#[derive(Args)]pub struct ExportCommand {+ /// Email of specific account to export (exports all if not specified)+ #[arg(long)]+ pub account: Option<String>,+/// Include shared albums (pass --shared=false to exclude)#[arg(long, default_value = "true")]pub shared: bool,diff --git a/rust/src/commands/account.rs b/rust/src/commands/account.rsindex 234b2146e7..6206db1ea2 100644--- a/rust/src/commands/account.rs+++ b/rust/src/commands/account.rs@@ -8,6 +8,7 @@ use crate::{},storage::Storage,};+use base64::Engine;use dialoguer::{Input, Password, Select};use std::path::PathBuf;@@ -212,6 +213,7 @@ async fn add_account(&decode_base64(&key_attributes.key_decryption_nonce)?,&key_enc_key,)?;+ log::info!("Master key decrypted, length: {}", master_key.len());// Decrypt secret keylet secret_key = secret_box_open(@@ -219,13 +221,38 @@ async fn add_account(&decode_base64(&key_attributes.secret_key_decryption_nonce)?,&master_key,)?;+ log::info!("Secret key decrypted, length: {}", secret_key.len());+ log::info!("Secret key hex (first 16 bytes): {}", hex::encode(&secret_key[..16.min(secret_key.len())]));// Get public keylet public_key = decode_base64(&key_attributes.public_key)?;// Decrypt token if encryptedlet token = if let Some(encrypted_token) = &auth_response.encrypted_token {- sealed_box_open(&decode_base64(encrypted_token)?, &public_key, &secret_key)?+ log::info!("Encrypted token from server (base64): {}", encrypted_token);+ log::info!("Public key (base64): {}", key_attributes.public_key);++ let encrypted_bytes = decode_base64(encrypted_token)?;+ log::info!("Encrypted token bytes length: {}", encrypted_bytes.len());++ let decrypted = sealed_box_open(&encrypted_bytes, &public_key, &secret_key)?;+ log::info!("Decrypted token bytes length: {}", decrypted.len());+ log::info!("Decrypted token hex: {}", hex::encode(&decrypted));++ // Try to interpret as UTF-8 string first+ match String::from_utf8(decrypted.clone()) {+ Ok(token_str) => {+ log::info!("Decrypted token is UTF-8 string: {}", token_str);+ // If it's a string, use it as bytes+ token_str.into_bytes()+ }+ Err(_) => {+ log::info!("Token is not UTF-8, using raw bytes");+ log::info!("Token as base64 URL: {}", base64::engine::general_purpose::URL_SAFE.encode(&decrypted));+ // If not UTF-8, use raw bytes+ decrypted+ }+ }} else if let Some(plain_token) = &auth_response.token {plain_token.as_bytes().to_vec()} else {@@ -317,10 +344,9 @@ async fn get_token(storage: &Storage, email: &str, app_str: &str) -> Result<()>crate::models::error::Error::NotFound(format!("Secrets not found for account {email}"))})?;- // Convert token to string (assuming it's UTF-8)- let token_str = String::from_utf8(secrets.token.clone()).map_err(|_| {- crate::models::error::Error::Generic("Token is not valid UTF-8".to_string())- })?;+ // Token is stored as raw bytes from sealed_box_open+ // The Go CLI returns it as base64 URL-encoded string WITH padding (matching TokenStr() in Go)+ let token_str = base64::engine::general_purpose::URL_SAFE.encode(&secrets.token);println!("{token_str}");diff --git a/rust/src/commands/export.rs b/rust/src/commands/export.rsnew file mode 100644index 0000000000..66ab557754--- /dev/null+++ b/rust/src/commands/export.rs@@ -0,0 +1,230 @@+use crate::api::client::ApiClient;+use crate::api::methods::ApiMethods;+use crate::crypto::init as crypto_init;+use crate::models::account::Account;+use crate::storage::Storage;+use crate::Result;+use base64::Engine;+use std::path::{Path, PathBuf};+use tokio::fs;+use tokio::io::AsyncWriteExt;++pub async fn run_export(account_email: Option<String>) -> Result<()> {+ // Initialize crypto+ crypto_init()?;++ // Open database+ let config_dir = crate::utils::get_cli_config_dir()?;+ let db_path = config_dir.join("ente.db");+ let storage = Storage::new(&db_path)?;++ // Get accounts to export+ let accounts = if let Some(email) = account_email {+ // Export specific account - try to find it with any app+ let all_accounts = storage.accounts().list()?;+ log::debug!("Found {} total accounts", all_accounts.len());+ for acc in &all_accounts {+ log::debug!("Account: email='{}', id={}", acc.email, acc.id);+ }+ let matching: Vec<Account> = all_accounts.into_iter()+ .filter(|a| {+ let matches = a.email == email;+ log::debug!("Comparing '{}' == '{}': {}", a.email, email, matches);+ matches+ })+ .collect();++ if matching.is_empty() {+ return Err(crate::Error::NotFound(format!("Account not found: {email}")));+ }+ matching+ } else {+ // Export all accounts+ storage.accounts().list()?+ };++ if accounts.is_empty() {+ println!("No accounts configured. Use 'ente-rs account add' first.");+ return Ok(());+ }++ // Export each account+ for account in accounts {+ println!("\n=== Exporting account: {} ===", account.email);++ if let Err(e) = export_account(&storage, &account).await {+ log::error!("Failed to export account {}: {}", account.email, e);+ println!("β Export failed: {}", e);+ } else {+ println!("β Export completed successfully!");+ }+ }++ Ok(())+}++async fn export_account(storage: &Storage, account: &Account) -> Result<()> {+ // Get export directory+ let export_dir = account.export_dir.as_ref()+ .ok_or_else(|| crate::Error::InvalidInput("No export directory configured".into()))?;+ let export_path = Path::new(export_dir);++ println!("Export directory: {}", export_dir);++ // Create export directory if needed+ fs::create_dir_all(export_path).await?;++ // Get stored secrets+ let secrets = storage.accounts().get_secrets(account.id)?+ .ok_or_else(|| crate::Error::NotFound("Account secrets not found".into()))?;++ // Create API client with account's endpoint+ let api_client = ApiClient::new(Some(account.endpoint.clone()))?;++ // 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);++ let api = ApiMethods::new(&api_client);++ // Fetch collections+ println!("\nFetching collections...");+ let collections = api.get_collections(&account.email, 0).await?;+ println!("Found {} collections", collections.len());++ // Master key is already raw bytes, no need to decode+ let _master_key = &secrets.master_key;++ // Fetch and export files for each collection+ println!("\nFetching files...");+ let mut total_files = 0;+ let mut exported_files = 0;++ for collection in &collections {+ // Skip deleted collections+ if collection.is_deleted {+ continue;+ }++ println!("Processing collection: {}", collection.id);++ let mut has_more = true;+ let mut since_time = 0i64;++ while has_more {+ let (files, more) = api.get_collection_files(&account.email, collection.id, since_time).await?;+ has_more = more;++ if files.is_empty() {+ break;+ }++ total_files += files.len();++ for file in files {+ // Skip deleted files+ if file.is_deleted {+ continue;+ }++ // Update since_time for next batch+ if file.updation_time > since_time {+ since_time = file.updation_time;+ }++ // Generate export path+ let file_path = generate_export_path(+ export_path,+ &file,+ Some(collection),+ )?;++ // Skip if file already exists+ if file_path.exists() {+ log::debug!("File already exists: {:?}", file_path);+ continue;+ }++ // Download and save file+ log::debug!("Downloading file {} to {:?}", file.id, file_path);++ // Ensure directory exists+ if let Some(parent) = file_path.parent() {+ fs::create_dir_all(parent).await?;+ }++ // Download encrypted file+ let encrypted_data = api.download_file(&account.email, file.id).await?;++ // Decrypt file (simplified - would need proper key management)+ // For now, just save the encrypted file+ let mut file_handle = fs::File::create(&file_path).await?;+ file_handle.write_all(&encrypted_data).await?;+ file_handle.sync_all().await?;++ exported_files += 1;++ // Progress indicator+ if exported_files % 10 == 0 {+ println!("Exported {} files...", exported_files);+ }+ }+ }+ }++ println!("\nExport summary:");+ println!(" Total files: {}", total_files);+ println!(" Exported: {}", exported_files);+ println!(" Skipped (already exists or deleted): {}", total_files - exported_files);++ Ok(())+}++fn generate_export_path(+ export_dir: &Path,+ file: &crate::api::models::File,+ collection: Option<&crate::api::models::Collection>,+) -> Result<PathBuf> {+ use chrono::{Utc, TimeZone};++ // Start with export directory+ let mut path = export_dir.to_path_buf();++ // Add date-based directory structure (YYYY/MM-MonthName)+ // Use updation_time as creation time proxy+ let datetime = Utc.timestamp_micros(file.updation_time).single()+ .ok_or_else(|| crate::Error::Generic("Invalid timestamp".into()))?;++ let year = datetime.format("%Y").to_string();+ let month = datetime.format("%m-%B").to_string(); // e.g., "01-January"++ path.push(year);+ path.push(month);++ // Add collection name if available+ if let Some(col) = collection {+ if let Some(ref name) = col.name {+ if !name.is_empty() && name != "Uncategorized" {+ // Sanitize collection name for filesystem+ let safe_name: String = name.chars()+ .map(|c| match c {+ '/' | '\\' | ':' | '*' | '?' | '"' | '<' | '>' | '|' => '_',+ c if c.is_control() => '_',+ c => c,+ })+ .collect::<String>()+ .trim()+ .to_string();+ path.push(safe_name);+ }+ }+ }++ // Generate filename - just use ID with a generic extension for now+ let filename = format!("file_{}.dat", file.id);+ path.push(filename);++ Ok(path)+}\ No newline at end of filediff --git a/rust/src/commands/mod.rs b/rust/src/commands/mod.rsindex 35f0b12b28..9c034b0875 100644--- a/rust/src/commands/mod.rs+++ b/rust/src/commands/mod.rs@@ -1,3 +1,4 @@pub mod account;+pub mod export;pub use account::handle_account_command;diff --git a/rust/src/main.rs b/rust/src/main.rsindex f888db32f7..e7b87319db 100644--- a/rust/src/main.rs+++ b/rust/src/main.rs@@ -30,9 +30,8 @@ async fn main() -> Result<()> {Commands::Account(account_cmd) => {commands::account::handle_account_command(account_cmd, &storage).await?;}- Commands::Export(_export_cmd) => {- // TODO: Implement export command- println!("Export command not yet implemented");+ Commands::Export(export_cmd) => {+ commands::export::run_export(export_cmd.account).await?;}}diff --git a/rust/src/sync/download.rs b/rust/src/sync/download.rsnew file mode 100644index 0000000000..bf8539f756--- /dev/null+++ b/rust/src/sync/download.rs@@ -0,0 +1,247 @@+use crate::api::client::ApiClient;+use crate::api::methods::ApiMethods;+use crate::crypto::decrypt_chacha;+use crate::models::file::RemoteFile;+use crate::storage::Storage;+use crate::Result;+use base64::{Engine, engine::general_purpose::STANDARD as BASE64};+use std::collections::HashMap;+use std::path::{Path, PathBuf};+use tokio::fs;+use tokio::io::AsyncWriteExt;++/// Manages file downloads with parallel processing and error recovery+pub struct DownloadManager {+ api_client: ApiClient,+ storage: Storage,+ temp_dir: PathBuf,+ collection_keys: HashMap<i64, Vec<u8>>,+ concurrent_downloads: usize,+}++impl DownloadManager {+ /// Create a new download manager+ pub fn new(api_client: ApiClient, storage: Storage) -> Result<Self> {+ let temp_dir = std::env::temp_dir().join("ente-downloads");+ std::fs::create_dir_all(&temp_dir)?;++ Ok(Self {+ api_client,+ storage,+ temp_dir,+ collection_keys: HashMap::new(),+ concurrent_downloads: 4, // Default concurrent downloads+ })+ }++ /// Set collection keys for file decryption+ pub fn set_collection_keys(&mut self, keys: HashMap<i64, Vec<u8>>) {+ self.collection_keys = keys;+ }++ /// Set number of concurrent downloads+ pub fn set_concurrent_downloads(&mut self, count: usize) {+ self.concurrent_downloads = count.max(1).min(10); // Limit between 1-10+ }++ /// Download a single file+ pub async fn download_file(+ &self,+ account_id: &str,+ file: &RemoteFile,+ destination: &Path,+ ) -> Result<()> {+ log::debug!("Downloading file {} to {:?}", file.id, destination);++ // Ensure destination directory exists+ if let Some(parent) = destination.parent() {+ fs::create_dir_all(parent).await?;+ }++ // Check if file already exists+ if destination.exists() {+ log::debug!("File already exists at {:?}, skipping", destination);+ return Ok(());+ }++ // Download to temp file first+ let temp_path = self.temp_dir.join(format!("{}.tmp", file.id));++ // Get file data+ let api = ApiMethods::new(&self.api_client);+ let encrypted_data = api.download_file(account_id, file.id).await?;++ // Decrypt file+ let decrypted_data = self.decrypt_file_data(file, &encrypted_data)?;++ // Write to temp file+ let mut temp_file = fs::File::create(&temp_path).await?;+ temp_file.write_all(&decrypted_data).await?;+ temp_file.sync_all().await?;+ drop(temp_file);++ // Move to final destination+ fs::rename(&temp_path, destination).await?;++ // TODO: Update storage with local path+ // self.storage.sync().update_file_local_path(file.id, destination.to_str().unwrap())?;++ log::info!("Downloaded file {} to {:?}", file.id, destination);+ Ok(())+ }++ /// Download multiple files with concurrency control+ pub async fn download_files(+ &self,+ account_id: &str,+ files: Vec<(RemoteFile, PathBuf)>,+ ) -> Result<DownloadStats> {+ use futures::stream::{self, StreamExt};++ let total = files.len();+ log::info!("Starting download of {} files", total);++ let mut stats = DownloadStats {+ total,+ ..Default::default()+ };++ // Process files in parallel with concurrency limit+ let results: Vec<_> = stream::iter(files)+ .map(|(file, path)| {+ let account_id = account_id.to_string();+ async move {+ let result = self.download_file(&account_id, &file, &path).await;+ (file.id, result)+ }+ })+ .buffer_unordered(self.concurrent_downloads)+ .collect()+ .await;++ // Count results+ for (_file_id, result) in results {+ match result {+ Ok(_) => stats.successful += 1,+ Err(e) => {+ log::error!("Download failed: {}", e);+ stats.failed += 1;+ }+ }+ }++ log::info!("Download completed: {} successful, {} failed",+ stats.successful, stats.failed);+ Ok(stats)+ }++ /// Download thumbnail for a file+ pub async fn download_thumbnail(+ &self,+ account_id: &str,+ file: &RemoteFile,+ destination: &Path,+ ) -> Result<()> {+ log::debug!("Downloading thumbnail for file {} to {:?}", file.id, destination);++ // Ensure destination directory exists+ if let Some(parent) = destination.parent() {+ fs::create_dir_all(parent).await?;+ }++ // Get thumbnail data+ let api = ApiMethods::new(&self.api_client);+ let encrypted_data = api.download_thumbnail(account_id, file.id).await?;++ // Decrypt thumbnail+ let decrypted_data = self.decrypt_file_data(file, &encrypted_data)?;++ // Write to file+ let mut file_handle = fs::File::create(destination).await?;+ file_handle.write_all(&decrypted_data).await?;+ file_handle.sync_all().await?;++ log::debug!("Thumbnail downloaded for file {}", file.id);+ Ok(())+ }++ /// Decrypt file data using file key and collection key+ fn decrypt_file_data(&self, file: &RemoteFile, encrypted_data: &[u8]) -> Result<Vec<u8>> {+ // Get collection key+ let collection_key = self.collection_keys.get(&file.collection_id)+ .ok_or_else(|| crate::Error::Crypto("Missing collection key for file decryption".into()))?;++ // Decrypt file key using collection key+ let file_key = if let Some(ref encrypted_key) = file.encrypted_key {+ let key_bytes = BASE64.decode(encrypted_key)?;+ let nonce = BASE64.decode(file.key_decryption_nonce.as_ref().unwrap_or(&String::new()))?;+ decrypt_chacha(&key_bytes, collection_key, &nonce)?+ } else {+ return Err(crate::Error::Crypto("Missing file encryption key".into()));+ };++ // Decrypt file data using file key+ let file_nonce = BASE64.decode(file.file.file_nonce.as_ref().unwrap_or(&String::new()))?;+ let decrypted = decrypt_chacha(encrypted_data, &file_key, &file_nonce)?;++ Ok(decrypted)+ }++ /// Resume a partial download (for future implementation)+ pub async fn resume_download(+ &self,+ _account_id: &str,+ _file: &FileModel,+ _destination: &Path,+ _offset: u64,+ ) -> Result<()> {+ // TODO: Implement resume functionality using Range headers+ todo!("Resume download not yet implemented")+ }++ /// Clean up temporary files+ pub async fn cleanup(&self) -> Result<()> {+ log::debug!("Cleaning up temporary download files");++ let mut entries = fs::read_dir(&self.temp_dir).await?;+ let mut count = 0;++ while let Some(entry) = entries.next_entry().await? {+ if entry.path().extension().and_then(|s| s.to_str()) == Some("tmp") {+ if let Err(e) = fs::remove_file(entry.path()).await {+ log::warn!("Failed to remove temp file {:?}: {}", entry.path(), e);+ } else {+ count += 1;+ }+ }+ }++ log::debug!("Cleaned up {} temporary files", count);+ Ok(())+ }+}++/// Statistics from download operations+#[derive(Debug, Default)]+pub struct DownloadStats {+ pub total: usize,+ pub successful: usize,+ pub failed: usize,+ pub skipped: usize,+}++impl DownloadStats {+ /// Check if all downloads were successful+ pub fn all_successful(&self) -> bool {+ self.failed == 0 && self.successful == self.total+ }++ /// Get success rate as percentage+ pub fn success_rate(&self) -> f64 {+ if self.total == 0 {+ 100.0+ } else {+ (self.successful as f64 / self.total as f64) * 100.0+ }+ }+}\ No newline at end of filediff --git a/rust/src/sync/engine.rs b/rust/src/sync/engine.rsnew file mode 100644index 0000000000..c1403ba9b1--- /dev/null+++ b/rust/src/sync/engine.rs@@ -0,0 +1,218 @@+use crate::api::client::ApiClient;+use crate::api::methods::ApiMethods;+use crate::models::{account::Account, file::RemoteFile};+use crate::storage::Storage;+use crate::Result;++/// Core sync engine responsible for fetching and tracking remote changes+pub struct SyncEngine {+ api_client: ApiClient,+ 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 {+ Self {+ api_client,+ storage,+ account,+ }+ }++ /// Run a full sync for the account+ pub async fn sync(&mut 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?;++ log::info!("Sync completed: {:?}", stats);+ Ok(stats)+ }++ /// Sync collections (albums)+ async fn sync_collections(&mut self, account_id: &str) -> Result<SyncResult> {+ log::debug!("Syncing collections...");++ let sync_store = self.storage.sync();++ // Get last sync time for collections+ let last_sync = sync_store+ .get_last_sync(self.account.id, "collections")?+ .unwrap_or(0);++ let api = ApiMethods::new(&self.api_client);+ let collections = api.get_collections(account_id, last_sync).await?;++ let mut result = SyncResult {+ total: collections.len(),+ new: 0,+ updated: 0,+ deleted: 0,+ };++ // Process each collection+ for collection in &collections {+ log::debug!("Processing collection: {} ({})", collection.name, collection.id);++ // Upsert collection (insert or update)+ sync_store.upsert_collection(self.account.id, collection)?;++ // Count as new or updated based on updation time+ if collection.updation_time > last_sync {+ if collection.creation_time > last_sync {+ result.new += 1;+ } else {+ result.updated += 1;+ }+ }+ }++ // Update sync timestamp+ let now = chrono::Utc::now().timestamp_micros();+ sync_store.update_sync_state(self.account.id, "collections", now)?;++ log::info!("Collections synced: {} new, {} updated", result.new, result.updated);+ Ok(result)+ }++ /// Sync files incrementally+ async fn sync_files(&mut self, account_id: &str) -> Result<SyncResult> {+ log::debug!("Syncing files...");++ let sync_store = self.storage.sync();++ // Get last sync time for files+ let mut last_sync = sync_store+ .get_last_sync(self.account.id, "files")?+ .unwrap_or(0);++ let api = ApiMethods::new(&self.api_client);+ let mut result = SyncResult::default();+ let mut has_more = true;+ const BATCH_SIZE: i32 = 500;++ // Fetch files in batches+ while has_more {+ log::debug!("Fetching files batch, since_time: {}", last_sync);++ let (files, more) = api.get_diff(account_id, last_sync, BATCH_SIZE).await?;+ has_more = more;++ if files.is_empty() {+ break;+ }++ result.total += files.len();++ // Convert API files to RemoteFile and process+ for file in files {+ log::trace!("Processing file: {}", file.id);++ // Create RemoteFile from API response+ let remote_file = RemoteFile {+ id: file.id,+ collection_id: file.collection_id,+ owner_id: file.owner_id,+ encrypted_key: file.encrypted_key,+ key_decryption_nonce: file.key_decryption_nonce,+ file: crate::models::file::FileInfo {+ file_nonce: file.file_nonce.clone(),+ thumbnail_nonce: file.thumbnail.as_ref().and_then(|t| t.decryption_header.clone()),+ metadata_nonce: file.metadata_decryption_header.clone(),+ },+ thumbnail: file.thumbnail.map(|t| crate::models::file::ThumbnailInfo {+ encrypted_path: t.encrypted_path,+ decryption_header: t.decryption_header,+ size: t.size,+ }).unwrap_or_default(),+ metadata: crate::models::file::EncryptedMetadata {+ encrypted_data: file.metadata.clone(),+ header: file.metadata_decryption_header.clone(),+ },+ is_deleted: file.is_deleted,+ updated_at: file.updation_time,+ };++ // Upsert file (insert or update)+ sync_store.upsert_file(self.account.id, &remote_file)?;++ // Count as new or updated+ if file.updation_time > last_sync {+ if file.creation_time > last_sync {+ result.new += 1;+ } else {+ result.updated += 1;+ }+ }++ // Track the latest updation time for next sync+ if file.updation_time > last_sync {+ last_sync = file.updation_time;+ }+ }++ // Update sync state after each batch+ sync_store.update_sync_state(self.account.id, "files", last_sync)?;+ }++ log::info!("Files synced: {} new, {} updated", result.new, result.updated);+ Ok(result)+ }++ /// Get list of files that need to be downloaded+ pub async fn get_pending_downloads(&self) -> Result<Vec<RemoteFile>> {+ let sync_store = self.storage.sync();++ // Get all non-deleted files for this account+ // Note: We'll need to check all collections for this account+ let collections = sync_store.get_collections(self.account.id)?;++ let mut all_files = Vec::new();+ for collection in collections {+ let files = sync_store.get_files_by_collection(self.account.id, collection.id)?;+ all_files.extend(files);+ }++ // Filter out deleted files+ let pending: Vec<RemoteFile> = all_files+ .into_iter()+ .filter(|f| !f.is_deleted)+ .collect();++ log::info!("Found {} files pending download", pending.len());+ Ok(pending)+ }++ /// Get collections for decryption keys+ pub async fn get_collections(&self) -> Result<Vec<crate::models::collection::Collection>> {+ let sync_store = self.storage.sync();+ sync_store.get_collections(self.account.id)+ }+}++/// Statistics from a sync operation+#[derive(Debug, Default)]+pub struct SyncStats {+ pub collections: SyncResult,+ pub files: SyncResult,+}++/// Result of syncing a specific type of data+#[derive(Debug, Default)]+pub struct SyncResult {+ pub total: usize,+ pub new: usize,+ pub updated: usize,+ pub deleted: usize,+}\ No newline at end of filediff --git a/rust/src/sync/files.rs b/rust/src/sync/files.rsnew file mode 100644index 0000000000..ed746bfb99--- /dev/null+++ b/rust/src/sync/files.rs@@ -0,0 +1,191 @@+use crate::crypto::{decrypt_chacha, secret_box_open};+use crate::models::{file::RemoteFile, collection::Collection};+use crate::Result;+use base64::{Engine, engine::general_purpose::STANDARD as BASE64};+use chrono::{Utc, TimeZone};+use serde::{Deserialize, Serialize};+use std::collections::HashMap;+use std::path::PathBuf;++/// Processes files for export, handling decryption and path generation+pub struct FileProcessor {+ export_dir: PathBuf,+ collection_keys: HashMap<i64, Vec<u8>>,+}++impl FileProcessor {+ /// Create a new file processor+ pub fn new(export_dir: PathBuf) -> Self {+ Self {+ export_dir,+ collection_keys: HashMap::new(),+ }+ }++ /// Set collection keys for decryption+ pub fn set_collection_keys(&mut self, collections: &[Collection], master_key: &[u8]) -> Result<()> {+ for collection in collections {+ if let Some(encrypted_key) = &collection.encrypted_key {+ // Decrypt collection key using master key+ let key_bytes = BASE64.decode(encrypted_key)?;+ let nonce = BASE64.decode(collection.key_decryption_nonce.as_ref().unwrap_or(&String::new()))?;+ let collection_key = decrypt_chacha(&key_bytes, master_key, &nonce)?;+ self.collection_keys.insert(collection.id, collection_key);+ }+ }+ Ok(())+ }++ /// Process a file and determine its export path+ pub fn process_file(&self, file: &RemoteFile, collection: Option<&Collection>) -> Result<ProcessedFile> {+ log::trace!("Processing file {}", file.id);++ // Decrypt file metadata if available+ let metadata = if file.metadata.encrypted_data.is_some() {+ self.decrypt_file_metadata(file)?+ } else {+ FileMetadata::default()+ };++ // Determine file name+ let file_name = self.get_file_name(file, &metadata)?;++ // Build export path based on date and collection+ let export_path = self.build_export_path(file, &metadata, collection, &file_name)?;++ Ok(ProcessedFile {+ file_id: file.id,+ file_name,+ export_path,+ metadata,+ needs_download: !export_path.exists(),+ })+ }++ /// Decrypt file metadata+ fn decrypt_file_metadata(&self, file: &RemoteFile) -> Result<FileMetadata> {+ // Get collection key+ let collection_key = self.collection_keys.get(&file.collection_id)+ .ok_or_else(|| crate::Error::Crypto("Missing collection key".into()))?;++ // Get encrypted metadata+ let encrypted_data = file.metadata.encrypted_data.as_ref()+ .ok_or_else(|| crate::Error::Crypto("Missing encrypted metadata".into()))?;++ // Decode encrypted metadata+ let encrypted_bytes = BASE64.decode(encrypted_data)?;++ // Decrypt using collection key+ let decrypted = if let Some(ref header) = file.metadata.header {+ let nonce_bytes = BASE64.decode(header)?;+ decrypt_chacha(&encrypted_bytes, collection_key, &nonce_bytes)?+ } else if let Some(ref nonce) = file.key_decryption_nonce {+ // Legacy: use secret_box_open for older files+ let nonce_bytes = BASE64.decode(nonce)?;+ secret_box_open(&encrypted_bytes, &nonce_bytes, collection_key)?+ } else {+ return Err(crate::Error::Crypto("Missing decryption header".into()));+ };++ // Parse JSON metadata+ let metadata: FileMetadata = serde_json::from_slice(&decrypted)?;+ Ok(metadata)+ }++ /// Get file name from metadata or generate one+ fn get_file_name(&self, file: &RemoteFile, metadata: &FileMetadata) -> Result<String> {+ if let Some(ref title) = metadata.title {+ return Ok(title.clone());+ }++ // Fallback to ID-based name with extension+ let extension = self.get_extension(metadata.file_type.unwrap_or(0));+ Ok(format!("file_{}.{}", file.id, extension))+ }++ /// Get file extension based on file type+ fn get_extension(&self, file_type: i32) -> &str {+ match file_type {+ 0 => "jpg", // Image+ 1 => "mp4", // Video+ _ => "bin", // Other/unknown+ }+ }++ /// Build the export path for a file+ fn build_export_path(+ &self,+ file: &RemoteFile,+ metadata: &FileMetadata,+ collection: Option<&Collection>,+ file_name: &str,+ ) -> Result<PathBuf> {+ // Start with export directory+ let mut path = self.export_dir.clone();++ // Add date-based directory structure (YYYY/MM-MonthName)+ let creation_time = metadata.creation_time+ .or(metadata.modification_time)+ .unwrap_or(file.updated_at);++ let datetime = Utc.timestamp_micros(creation_time).single()+ .ok_or_else(|| crate::Error::Generic("Invalid timestamp".into()))?;++ let year = datetime.format("%Y").to_string();+ let month = datetime.format("%m-%B").to_string(); // e.g., "01-January"++ path.push(year);+ path.push(month);++ // Add collection name if available and not default+ if let Some(col) = collection {+ if !col.name.is_empty() && col.name != "Uncategorized" {+ // Sanitize collection name for filesystem+ let safe_name = sanitize_filename(&col.name);+ path.push(safe_name);+ }+ }++ // Add file name+ path.push(file_name);++ Ok(path)+ }+}++/// Processed file information+#[derive(Debug)]+pub struct ProcessedFile {+ pub file_id: i64,+ pub file_name: String,+ pub export_path: PathBuf,+ pub metadata: FileMetadata,+ pub needs_download: bool,+}++/// Decrypted file metadata+#[derive(Debug, Default, Deserialize, Serialize)]+#[serde(rename_all = "camelCase")]+pub struct FileMetadata {+ pub title: Option<String>,+ pub description: Option<String>,+ pub creation_time: Option<i64>,+ pub modification_time: Option<i64>,+ pub latitude: Option<f64>,+ pub longitude: Option<f64>,+ pub file_type: Option<i32>,+ pub device_folder: Option<String>,+}++/// Sanitize a filename for safe filesystem usage+fn sanitize_filename(name: &str) -> String {+ name.chars()+ .map(|c| match c {+ '/' | '\\' | ':' | '*' | '?' | '"' | '<' | '>' | '|' => '_',+ c if c.is_control() => '_',+ c => c,+ })+ .collect::<String>()+ .trim()+ .to_string()+}\ No newline at end of filediff --git a/rust/src/sync/mod.rs b/rust/src/sync/mod.rsindex 951a255363..2f6626060f 100644--- a/rust/src/sync/mod.rs+++ b/rust/src/sync/mod.rs@@ -1 +1,8 @@-// TODO: Implement sync functionality+// TODO: Fix sync modules compilation issues+// mod engine;+// mod files;+// mod download;++// pub use engine::SyncEngine;+// pub use files::FileProcessor;+// pub use download::DownloadManager;\ No newline at end of file