π End-to-end encrypted cloud for everything.
Dart 2faandroidauthye2eeencryptionend-to-end-encryptionfluttergolanggoogle-photosgoogle-photos-alternativeiosopensourcephotosprivacyprivacy-toolstypescriptzero-knowledge
feat(rust): Complete sync command with file downloads
Manav Rathi80c07d36a9ac
diff --git a/rust/src/commands/sync.rs b/rust/src/commands/sync.rsindex a68a99e92f..8fae922e90 100644--- a/rust/src/commands/sync.rs+++ b/rust/src/commands/sync.rs@@ -131,9 +131,7 @@ async fn sync_account(let download_api_client = ApiClient::new(Some(account.endpoint.clone()))?;download_api_client.add_token(&account.email, &token);- // Create another storage instance for download manager- let download_storage = Storage::new(db_path)?;- let mut download_manager = DownloadManager::new(download_api_client, download_storage)?;+ let mut download_manager = DownloadManager::new(download_api_client)?;download_manager.set_collection_keys(collection_keys);// Determine export directory@@ -152,26 +150,54 @@ async fn sync_account().await?;- // Download files- let download_stats = download_manager- .download_files(&account.email, download_tasks)- .await?;-- // Update local paths in database- for (file, path) in &download_stats.successful_downloads {- storage.sync().update_file_local_path(- account.id,- file.id,- path.to_str().unwrap_or(""),- )?;+ // First, mark files that already exist as synced+ let mut already_synced = 0;+ let mut to_download = Vec::new();++ for (file, path) in download_tasks {+ if path.exists() {+ // File already exists, mark it as synced in database+ storage.sync().update_file_local_path(+ account.id,+ file.id,+ path.to_str().unwrap_or(""),+ )?;+ already_synced += 1;+ } else {+ to_download.push((file, path));+ }}- println!(- "\nβ Downloaded {} files successfully",- download_stats.successful- );- if download_stats.failed > 0 {- println!("β Failed to download {} files", download_stats.failed);+ if already_synced > 0 {+ log::info!("Marked {already_synced} already existing files as synced");+ }++ if !to_download.is_empty() {+ println!("π₯ Downloading {} new files", to_download.len());++ // Download files+ let download_stats = download_manager+ .download_files(&account.email, to_download)+ .await?;++ // Update local paths in database for newly downloaded files+ for (file, path) in &download_stats.successful_downloads {+ storage.sync().update_file_local_path(+ account.id,+ file.id,+ path.to_str().unwrap_or(""),+ )?;+ }++ println!(+ "\nβ Downloaded {} files successfully",+ download_stats.successful+ );+ if download_stats.failed > 0 {+ println!("β Failed to download {} files", download_stats.failed);+ }+ } else {+ println!("\nβ¨ All files are already downloaded");}} else {println!("\nβ¨ All files are already downloaded");diff --git a/rust/src/storage/schema.rs b/rust/src/storage/schema.rsindex 0668bba592..f9a6353292 100644--- a/rust/src/storage/schema.rs+++ b/rust/src/storage/schema.rs@@ -74,6 +74,7 @@ pub fn create_tables(conn: &Connection) -> Result<()> {file_info TEXT NOT NULL,metadata TEXT NOT NULL,is_deleted INTEGER NOT NULL DEFAULT 0,+ is_synced_locally INTEGER NOT NULL DEFAULT 0,local_path TEXT,updated_at INTEGER NOT NULL,FOREIGN KEY (account_id) REFERENCES accounts(id) ON DELETE CASCADE,@@ -130,18 +131,5 @@ pub fn create_tables(conn: &Connection) -> Result<()> {[],)?;- // Add migration for local_path column if it doesn't exist- let has_column = conn- .query_row(- "SELECT COUNT(*) FROM pragma_table_info('files') WHERE name='local_path'",- [],- |row| row.get::<_, i32>(0),- )- .unwrap_or(0);-- if has_column == 0 {- conn.execute("ALTER TABLE files ADD COLUMN local_path TEXT", [])?;- }-Ok(())}diff --git a/rust/src/storage/sync.rs b/rust/src/storage/sync.rsindex 3db312566c..7b8063c6ad 100644--- a/rust/src/storage/sync.rs+++ b/rust/src/storage/sync.rs@@ -62,11 +62,23 @@ impl<'a> SyncStore<'a> {let file_info = serde_json::to_string(&file.file)?;let metadata = serde_json::to_string(&file.metadata)?;+ // First check if file exists and preserve is_synced_locally flag+ let existing_sync_status: Option<i32> = self+ .conn+ .query_row(+ "SELECT is_synced_locally FROM files WHERE account_id = ?1 AND file_id = ?2",+ params![account_id, file.id],+ |row| row.get(0),+ )+ .optional()?;++ let is_synced = existing_sync_status.unwrap_or(0);+self.conn.execute("INSERT OR REPLACE INTO files(account_id, file_id, collection_id, encrypted_key, key_decryption_nonce,- file_info, metadata, is_deleted, updated_at)- VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9)",+ file_info, metadata, is_deleted, is_synced_locally, updated_at)+ VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10)",params![account_id,file.id,@@ -76,6 +88,7 @@ impl<'a> SyncStore<'a> {file_info,metadata,file.is_deleted as i32,+ is_synced,file.updated_at],)?;@@ -102,15 +115,31 @@ impl<'a> SyncStore<'a> {let file_info: String = row.get(4)?;let metadata: String = row.get(5)?;+ // Deserialize stored data - thumbnail might not be stored properly+ let file_obj: crate::models::file::FileInfo = serde_json::from_str(&file_info)+ .map_err(|e| rusqlite::Error::ToSqlConversionFailure(Box::new(e)))?;++ let metadata_obj: crate::models::file::MetadataInfo =+ serde_json::from_str(&metadata)+ .map_err(|e| rusqlite::Error::ToSqlConversionFailure(Box::new(e)))?;++ // Create a default thumbnail info if not available+ let thumbnail = crate::models::file::FileInfo {+ encrypted_data: None,+ decryption_header: String::new(),+ object_key: None,+ size: None,+ };+Ok(RemoteFile {id: row.get(0)?,collection_id: row.get(1)?,owner_id: 0, // Will need to fetch from accountencrypted_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(),+ file: file_obj,+ thumbnail,+ metadata: metadata_obj,is_deleted: row.get::<_, i32>(6)? != 0,updated_at: row.get(7)?,})@@ -205,13 +234,21 @@ impl<'a> SyncStore<'a> {Ok(())}- /// Get files that need downloading (no local_path)+ /// Get files that need downloading (not synced locally)pub fn get_pending_downloads(&self, account_id: i64) -> Result<Vec<RemoteFile>> {+ // First check how many files are already synced+ let synced_count: i64 = self.conn.query_row(+ "SELECT COUNT(*) FROM files WHERE account_id = ?1 AND is_synced_locally = 1",+ params![account_id],+ |row| row.get(0),+ )?;+ log::debug!("Files already synced locally: {synced_count}");+let mut stmt = self.conn.prepare("SELECT file_id, collection_id, encrypted_key, key_decryption_nonce,file_info, metadata, is_deleted, updated_atFROM files- WHERE account_id = ?1 AND is_deleted = 0 AND local_path IS NULL+ WHERE account_id = ?1 AND is_deleted = 0 AND is_synced_locally = 0ORDER BY file_id",)?;@@ -220,15 +257,31 @@ impl<'a> SyncStore<'a> {let file_info: String = row.get(4)?;let metadata: String = row.get(5)?;+ // Deserialize stored data - thumbnail might not be stored properly+ let file_obj: crate::models::file::FileInfo = serde_json::from_str(&file_info)+ .map_err(|e| rusqlite::Error::ToSqlConversionFailure(Box::new(e)))?;++ let metadata_obj: crate::models::file::MetadataInfo =+ serde_json::from_str(&metadata)+ .map_err(|e| rusqlite::Error::ToSqlConversionFailure(Box::new(e)))?;++ // Create a default thumbnail info if not available+ let thumbnail = crate::models::file::FileInfo {+ encrypted_data: None,+ decryption_header: String::new(),+ object_key: None,+ size: None,+ };+Ok(RemoteFile {id: row.get(0)?,collection_id: row.get(1)?,owner_id: 0, // Will need to fetch from accountencrypted_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(),+ file: file_obj,+ thumbnail,+ metadata: metadata_obj,is_deleted: row.get::<_, i32>(6)? != 0,updated_at: row.get(7)?,})@@ -238,19 +291,41 @@ impl<'a> SyncStore<'a> {Ok(files)}- /// Update file local path after successful download- pub fn update_file_local_path(+ /// Mark file as synced locally after successful download+ pub fn mark_file_synced(&self,account_id: i64,file_id: i64,- local_path: &str,+ local_path: Option<&str>,) -> Result<()> {- self.conn.execute(- "UPDATE files SET local_path = ?3- WHERE account_id = ?1 AND file_id = ?2",- params![account_id, file_id, local_path],- )?;+ let rows_updated = if let Some(path) = local_path {+ self.conn.execute(+ "UPDATE files SET is_synced_locally = 1, local_path = ?3+ WHERE account_id = ?1 AND file_id = ?2",+ params![account_id, file_id, path],+ )?+ } else {+ self.conn.execute(+ "UPDATE files SET is_synced_locally = 1+ WHERE account_id = ?1 AND file_id = ?2",+ params![account_id, file_id],+ )?+ };++ log::debug!(+ "Marked file {file_id} (account {account_id}) as synced locally, rows affected: {rows_updated}"+ );Ok(())}++ /// Update file local path (legacy method - consider using mark_file_synced instead)+ pub fn update_file_local_path(+ &self,+ account_id: i64,+ file_id: i64,+ local_path: &str,+ ) -> Result<()> {+ self.mark_file_synced(account_id, file_id, Some(local_path))+ }}diff --git a/rust/src/sync/download.rs b/rust/src/sync/download.rsindex 96a8201040..abd7a5eb96 100644--- a/rust/src/sync/download.rs+++ b/rust/src/sync/download.rs@@ -1,9 +1,8 @@use crate::Result;use crate::api::client::ApiClient;use crate::api::methods::ApiMethods;-use crate::crypto::decrypt_chacha;+use crate::crypto::{decrypt_file_data, secret_box_open};use crate::models::file::RemoteFile;-use crate::storage::Storage;use base64::{Engine, engine::general_purpose::STANDARD as BASE64};use std::collections::HashMap;use std::path::{Path, PathBuf};@@ -13,8 +12,6 @@ use tokio::io::AsyncWriteExt;/// Manages file downloads with parallel processing and error recoverypub struct DownloadManager {api_client: ApiClient,- #[allow(dead_code)]- storage: Storage,temp_dir: PathBuf,pub collection_keys: HashMap<i64, Vec<u8>>,concurrent_downloads: usize,@@ -22,13 +19,12 @@ pub struct DownloadManager {impl DownloadManager {/// Create a new download manager- pub fn new(api_client: ApiClient, storage: Storage) -> Result<Self> {+ pub fn new(api_client: ApiClient) -> 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@@ -61,7 +57,11 @@ impl DownloadManager {// Check if file already existsif destination.exists() {- log::debug!("File already exists at {destination:?}, skipping");+ log::debug!(+ "File already exists at {destination:?}, skipping download but marking as successful"+ );+ // Even though we skip downloading, we should still update the database+ // This is handled by returning Ok(()) which will mark it as successfulreturn Ok(());}@@ -188,16 +188,16 @@ impl DownloadManager {crate::Error::Crypto("Missing collection key for file decryption".into())})?;- // Decrypt file key using collection key+ // Decrypt file key using collection key (XSalsa20-Poly1305)let file_key = {let key_bytes = BASE64.decode(&file.encrypted_key)?;let nonce = BASE64.decode(&file.key_decryption_nonce)?;- decrypt_chacha(&key_bytes, collection_key, &nonce)?+ secret_box_open(&key_bytes, &nonce, collection_key)?};- // Decrypt file data using file key+ // Decrypt file data using file key (Streaming XChaCha20-Poly1305)let file_nonce = BASE64.decode(&file.file.decryption_header)?;- let decrypted = decrypt_chacha(encrypted_data, &file_key, &file_nonce)?;+ let decrypted = decrypt_file_data(encrypted_data, &file_nonce, &file_key)?;Ok(decrypted)}