π End-to-end encrypted cloud for everything.
Dart 2faandroidauthye2eeencryptionend-to-end-encryptionfluttergolanggoogle-photosgoogle-photos-alternativeiosopensourcephotosprivacyprivacy-toolstypescriptzero-knowledge
Replace the Rust CLI with ente
Manav Rathi3b815740964d
diff --git a/.github/checks/rust-ci-paths/check.mjs b/.github/checks/rust-ci-paths/check.mjsindex 844e3eb54e..ac6681e162 100644--- a/.github/checks/rust-ci-paths/check.mjs+++ b/.github/checks/rust-ci-paths/check.mjs@@ -79,8 +79,7 @@ function wasmRoots() {}function nativeRoots(workflow) {- if (workflow === "rust-cli-test")- return [resolve(root, "rust/apps/cli-next")];+ if (workflow === "rust-cli-test") return [resolve(root, "rust/apps/cli")];return [...globSync(`rust/bindings/${bindings[workflow]}/*/Cargo.toml`, {cwd: root,diff --git a/.github/checks/rust-ci-paths/test.mjs b/.github/checks/rust-ci-paths/test.mjsindex 977ad3245c..73704eca96 100644--- a/.github/checks/rust-ci-paths/test.mjs+++ b/.github/checks/rust-ci-paths/test.mjs@@ -100,7 +100,7 @@ builder = { path = "../../crates/builder" }`,);crate(- "apps/cli-next",+ "apps/cli","cli",`[dev-dependencies]test-only = { path = "../../crates/test-only" }`,@@ -162,14 +162,14 @@ test-only = { path = "../../crates/test-only" }`,);assert.equal(result.status, 0, result.stderr);- result = run(["rust/apps/cli-next/**", ...base], "rust-cli-test");+ result = run(["rust/apps/cli/**", ...base], "rust-cli-test");assert.equal(result.status, 1, result.stderr);assert.equal(result.stderr,`${pathsFile}: rust-cli-test missing Rust dependency path "rust/crates/test-only/**"\n`,);result = run(- ["rust/apps/cli-next/**", "rust/crates/test-only/**", ...base],+ ["rust/apps/cli/**", "rust/crates/test-only/**", ...base],"rust-cli-test",);assert.equal(result.status, 0, result.stderr);diff --git a/.github/scripts/ci/paths.json b/.github/scripts/ci/paths.jsonindex c9d1b7c1e9..626a8ca041 100644--- a/.github/scripts/ci/paths.json+++ b/.github/scripts/ci/paths.json@@ -113,7 +113,7 @@"rust/.cargo/config.toml","rust/Cargo.lock","rust/Cargo.toml",- "rust/apps/cli-next/**",+ "rust/apps/cli/**","rust/crates/accounts/**","rust/crates/assets/**","rust/crates/auth/**",diff --git a/.github/scripts/ci/test.mjs b/.github/scripts/ci/test.mjsindex cfb8bebeac..a765602e07 100644--- a/.github/scripts/ci/test.mjs+++ b/.github/scripts/ci/test.mjs@@ -53,7 +53,7 @@ test("shared build inputs select their consumers", (t) => {"web-lint",]);assert.ok(select(t, ["server/pkg/api.go"]).includes("rust-test"));- assert.deepEqual(select(t, ["rust/apps/cli-next/src/main.rs"]), [+ assert.deepEqual(select(t, ["rust/apps/cli/src/main.rs"]), ["repo-lint","rust-cli-test","rust-lint",diff --git a/.github/workflows/rust-cli-test.yml b/.github/workflows/rust-cli-test.ymlindex 54b1721ae6..3805b2554f 100644--- a/.github/workflows/rust-cli-test.yml+++ b/.github/workflows/rust-cli-test.yml@@ -56,7 +56,7 @@ jobs:security set-key-partition-list -S apple-tool:,apple: -s -k "$password" "$keychain"security list-keychains -d user -s "$keychain"security default-keychain -d user -s "$keychain"- python3 apps/cli-next/scripts/native-keyring.py test --sign 'Ente CLI CI'+ python3 apps/cli/scripts/native-keyring.py test --sign 'Ente CLI CI'- name: Remove the disposable keychainif: always()@@ -91,4 +91,4 @@ jobs:shared-key: rust-cli- name: Run with Windows Credential Manager- run: python apps/cli-next/scripts/native-keyring.py test+ run: python apps/cli/scripts/native-keyring.py testdiff --git a/.github/workflows/rust-test.yml b/.github/workflows/rust-test.ymlindex b302cca76e..e2009d2e0c 100644--- a/.github/workflows/rust-test.yml+++ b/.github/workflows/rust-test.yml@@ -58,7 +58,7 @@ jobs:~/.cache/go-build~/.cache/.theseus/postgresql- - run: cargo test --locked --workspace --exclude ente-cli-next --features museum,ente-ml/ml-assets+ - run: cargo test --locked --workspace --exclude ente-cli --features museum,ente-ml/ml-assetsif: matrix.suite == 'workspace'# postgresql_embedded downloads its binaries from GitHub.# GITHUB_TOKEN raises the API rate limit for those downloads.@@ -66,10 +66,10 @@ jobs:GITHUB_TOKEN: ${{ github.token }}# Avoid unifying SQLCipher into other packages' SQLite tests.- - run: cargo test --locked -p ente-cli-next --features museum+ - run: cargo test --locked -p ente-cli --features museumif: matrix.suite == 'cli'env:GITHUB_TOKEN: ${{ github.token }}- - run: apps/cli-next/scripts/test-with-keyring-linux.sh --features museum+ - run: apps/cli/scripts/test-with-keyring-linux.sh --features museumif: matrix.suite == 'cli'diff --git a/.github/workflows/warm-caches.yml b/.github/workflows/warm-caches.ymlindex 939b490585..7b1105e4c7 100644--- a/.github/workflows/warm-caches.yml+++ b/.github/workflows/warm-caches.yml@@ -66,11 +66,11 @@ jobs:~/.cache/go-build~/.cache/.theseus/postgresql- - run: cargo test --locked --workspace --exclude ente-cli-next --features museum,ente-ml/ml-assets+ - run: cargo test --locked --workspace --exclude ente-cli --features museum,ente-ml/ml-assetsenv:GITHUB_TOKEN: ${{ github.token }}- - run: cargo test --locked -p ente-cli-next --features museum --no-run+ - run: cargo test --locked -p ente-cli --features museum --no-run- run: node .github/actions/restore-rust-target/mtimes.mjs saveworking-directory: ${{ github.workspace }}@@ -111,7 +111,7 @@ jobs:lookup-only: trueshared-key: rust-cli- - run: cargo test --locked -p ente-cli-next --test cli --no-run+ - run: cargo test --locked -p ente-cli --test cli --no-run- run: node .github/actions/restore-rust-target/mtimes.mjs saveworking-directory: ${{ github.workspace }}diff --git a/rust/Cargo.lock b/rust/Cargo.lockindex 3a57916254..2b11348063 100644--- a/rust/Cargo.lock+++ b/rust/Cargo.lock@@ -2125,7 +2125,6 @@ checksum = "25f104b501bf2364e78d0d3974cbc774f738f5865306ed128e1e0d7499c0ad96"dependencies = ["console","shell-words",- "tempfile","zeroize",]@@ -2525,8 +2524,8 @@ dependencies = [][[package]]-name = "ente-cli-next"-version = "0.1.0"+name = "ente-cli"+version = "0.4.0"dependencies = ["anyhow","chrono",@@ -2955,36 +2954,6 @@ dependencies = ["ente-wasm-lib",]-[[package]]-name = "ente-rs"-version = "0.0.1"-dependencies = [- "chrono",- "clap",- "dialoguer",- "dirs",- "ente-accounts",- "ente-core",- "ente-paste",- "ente-test-support",- "env_logger 0.11.11",- "futures",- "indicatif",- "log",- "mockito",- "open",- "rusqlite",- "serde",- "serde_json",- "thiserror 2.0.21",- "tokio",- "url",- "urlencoding",- "uuid",- "zeroize",- "zip",-]-[[package]]name = "ente-space"version = "0.0.1"@@ -3168,10 +3137,7 @@ version = "0.11.11"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "de671bd27a75a797dc9ae289ba1e77276e75e2026408aab65185384e2d5cd3f6"dependencies = [- "anstream",- "anstyle","env_filter 2.0.0",- "jiff","log",]@@ -5354,30 +5320,6 @@ dependencies = ["system-deps",]-[[package]]-name = "jiff"-version = "0.2.24"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "f00b5dbd620d61dfdcb6007c9c1f6054ebd75319f163d886a9055cec1155073d"-dependencies = [- "jiff-static",- "log",- "portable-atomic",- "portable-atomic-util",- "serde_core",-]--[[package]]-name = "jiff-static"-version = "0.2.24"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "e000de030ff8022ea1da3f466fbb0f3a809f5e51ed31f6dd931c35181ad8e6d7"-dependencies = [- "proc-macro2",- "quote",- "syn 2.0.117",-]-[[package]]name = "jni"version = "0.21.1"@@ -8215,7 +8157,6 @@ dependencies = ["fallible-streaming-iterator","hashlink 0.12.2","libsqlite3-sys",- "serde_json","smallvec","sqlite-wasm-rs",]diff --git a/rust/Cargo.toml b/rust/Cargo.tomlindex 620e9f4259..39eb130f0c 100644--- a/rust/Cargo.toml+++ b/rust/Cargo.toml@@ -2,7 +2,6 @@resolver = "2"members = ["apps/cli",- "apps/cli-next","apps/ensu/src-tauri","bindings/frb/lib","bindings/frb/locker",diff --git a/rust/README.md b/rust/README.mdindex fde9c104ae..e000275ce0 100644--- a/rust/README.md+++ b/rust/README.md@@ -8,9 +8,10 @@ Cargo workspace for Ente's Rust code.cargo fmt # Formatcargo clippy # Lintcargo build # Build-cargo test # Test+cargo test --workspace --exclude ente-cli # Test libraries with SQLite+cargo test -p ente-cli # Test CLI with SQLCipher-cargo run --bin ente-rs -- --help # Run the Ente Rust CLI+cargo run -p ente-cli -- --help # Run the Ente Rust CLI```CI runs with `RUSTFLAGS="-D warnings"` so warnings will cause checks to fail.@@ -23,5 +24,6 @@ cargo codegen frb # Regenerate bindings used by Flutter appscargo codegen napi # Regenerate bindings used by Desktop (Electron) apps# Run integration tests against a local Museum-cargo test --features museum,ente-ml/ml-assets+cargo test --workspace --exclude ente-cli --features museum,ente-ml/ml-assets+cargo test -p ente-cli --features museum```diff --git a/rust/apps/cli-next/Cargo.toml b/rust/apps/cli-next/Cargo.tomldeleted file mode 100644index 3e355d6075..0000000000--- a/rust/apps/cli-next/Cargo.toml+++ /dev/null@@ -1,50 +0,0 @@-[package]-name = "ente-cli-next"-version = "0.1.0"-edition.workspace = true-publish = false--[features]-museum = []--[dependencies]-anyhow.workspace = true-chrono = { workspace = true, features = ["std", "clock"] }-clap = { workspace = true, features = ["derive", "string"] }-clap_complete.workspace = true-dialoguer = { workspace = true, features = ["password"] }-dirs.workspace = true-ente-accounts.workspace = true-ente-auth.workspace = true-ente-collections.workspace = true-ente-core.workspace = true-ente-paste.workspace = true-ente-photos.workspace = true-ente-photos-export.workspace = true-env_logger.workspace = true-keyring = { workspace = true, features = ["apple-native", "windows-native", "linux-native-sync-persistent", "crypto-rust"] }-open.workspace = true-reqwest.workspace = true-rusqlite = { workspace = true, features = ["bundled-sqlcipher"] }-serde.workspace = true-serde_json.workspace = true-tempfile.workspace = true-thiserror.workspace = true-tokio = { workspace = true, features = ["macros", "rt-multi-thread", "signal", "sync", "time"] }-url.workspace = true-uuid = { workspace = true, features = ["serde", "v4"] }-zeroize.workspace = true--[target.'cfg(windows)'.dependencies]-rusqlite = { workspace = true, features = ["bundled-sqlcipher-vendored-openssl"] }--[dev-dependencies]-ente-test-support.workspace = true-futures-util.workspace = true-mockito.workspace = true-same-file.workspace = true-sha2.workspace = true-zip.workspace = true--[lints]-workspace = truediff --git a/rust/apps/cli-next/README.md b/rust/apps/cli-next/README.mddeleted file mode 100644index 7b2b39bd43..0000000000--- a/rust/apps/cli-next/README.md+++ /dev/null@@ -1,7 +0,0 @@-WIP replacement Ente Rust CLI.--## Development--```sh-cargo run -p ente-cli-next -- --help-```diff --git a/rust/apps/cli-next/src/main.rs b/rust/apps/cli-next/src/main.rsdeleted file mode 100644index 643a032183..0000000000--- a/rust/apps/cli-next/src/main.rs+++ /dev/null@@ -1,398 +0,0 @@-mod account;-mod admin;-mod api;-mod args;-mod auth;-mod core_db;-mod db;-mod home;-mod login;-mod migration;-mod output;-mod password;-mod paste;-mod photos;-mod vault;--use std::{- io::{Read, Write},- path::Path,-};--use anyhow::{Context, Result, bail, ensure};-use clap::FromArgMatches;-use ente_core::{b64, crypto::Key};-use serde::de::DeserializeOwned;-use serde_json::json;-use zeroize::Zeroizing;--use args::{AccountCommand, App, Cli, Command, KeyCommand, LockerCommand, Options, VaultCommand};-use output::AccountView;-use vault::{Account, State, Vault};--#[tokio::main]-async fn main() {- env_logger::Builder::from_env(env_logger::Env::default().default_filter_or("warn"))- .format(|out, record| writeln!(out, "{}", record.args()))- .init();- let mut command = args::command();- let arguments: Vec<_> = std::env::args_os().collect();- let matches = command- .try_get_matches_from_mut(&arguments)- .unwrap_or_else(|mut error| {- migration::hint(&command, &arguments, &mut error);- error.exit()- });- let result = if let Some(help) = matches.subcommand_matches("help") {- command.build();- print_help(&mut command, help, &mut std::io::stdout().lock())- } else {- let cli = Cli::from_arg_matches(&matches)- .unwrap_or_else(|error| error.format(&mut command).exit());- run(cli).await- };- if let Err(error) = result {- eprintln!("Error: {error:#}");- std::process::exit(1);- }-}--fn print_help(- command: &mut clap::Command,- mut matches: &clap::ArgMatches,- output: &mut impl Write,-) -> Result<()> {- if matches.get_flag("all") {- if matches.subcommand_name().is_some() {- command- .find_subcommand_mut("help")- .context("missing help command")?- .error(- clap::error::ErrorKind::ArgumentConflict,- "help --all cannot be combined with a command or topic",- )- .exit();- }- return print_all_help(command, output);- }- if matches.subcommand_name() == Some("migration") {- return migration::print(- command.get_bin_name().unwrap_or_else(|| command.get_name()),- output,- );- }- let mut target = command;- while let Some((name, child)) = matches.subcommand() {- target = target- .find_subcommand_mut(name)- .context("unknown help command")?;- matches = child;- }- write!(output, "{}", target.render_long_help())?;- Ok(())-}--fn print_all_help(command: &mut clap::Command, output: &mut impl Write) -> Result<()> {- writeln!(- output,- "=== {} ===",- command.get_bin_name().unwrap_or_else(|| command.get_name())- )?;- writeln!(output, "{}", command.render_long_help())?;- let mut children: Vec<_> = command- .get_subcommands_mut()- .filter(|child| !child.is_hide_set() && child.get_name() != "help")- .collect();- children.sort_by(|a, b| {- (a.get_display_order(), a.get_name()).cmp(&(b.get_display_order(), b.get_name()))- });- for child in children {- print_all_help(child, output)?;- }- Ok(())-}--async fn run(cli: Cli) -> Result<()> {- let Cli { options, command } = cli;- match command {- Command::Photos { selector, command } => {- photos::run(command, selector.account.as_deref(), &options).await- }- Command::Locker {- selector,- command: LockerCommand::Api(args),- } => api::run(App::Locker, args, selector.account.as_deref(), &options).await,- Command::Auth { selector, command } => {- auth::run(command, selector.account.as_deref(), &options).await- }- Command::Paste { command } => paste::run(command, &options).await,- Command::Account { command } => account_command(command, &options).await,- Command::Vault {- command:- VaultCommand::Key {- command: KeyCommand::Generate,- },- } => vault_key(options.json),- Command::Completion { shell } => {- let mut command = args::command();- let name = command.get_name().to_owned();- clap_complete::generate(shell, &mut command, name, &mut std::io::stdout().lock());- Ok(())- }- Command::Admin {- selector,- app,- command,- } => admin::run(command, selector.account.as_deref(), app, &options).await,- }-}--fn vault_key(json_output: bool) -> Result<()> {- let key = Zeroizing::new(b64::encode(Key::generate().as_bytes()));- if json_output {- output::json(&json!({ "key": key.as_str() }))- } else {- writeln!(std::io::stdout(), "{}", key.as_str()).map_err(Into::into)- }-}--async fn account_command(command: AccountCommand, options: &Options) -> Result<()> {- match command {- AccountCommand::RequestOtp {- email,- app,- host,- purpose,- } => account::request_otp(email, app, host, purpose, options).await,- AccountCommand::Create(args) => {- let app = args.app;- let (state, index) = account::create(args, options).await?;- let account = AccountView::new(&state.accounts[index], state.selected);- output::action(- options.json,- &json!({"account": account, "app": app}),- &format!(- "Created {} and signed into {}.",- output::escape_controls(&state.accounts[index].name),- app.display_name()- ),- )- }- AccountCommand::Totp {- selector,- app,- command,- } => account::totp(command, selector.account.as_deref(), app, options).await,- AccountCommand::RecoveryKey { name } => {- let state = State::load()?;- let account = &state.accounts[state.resolve(name.as_deref())?];- let key = Zeroizing::new(ente_accounts::auth::recovery_key_to_mnemonic(- &account.identity.recovery_key,- )?);- if options.json {- output::json(&json!({"recoveryKey": key.as_str()}))- } else {- writeln!(std::io::stdout(), "{}", key.as_str()).map_err(Into::into)- }- }- AccountCommand::Login(args) => {- ensure!(!options.offline, "login requires network access");- let app = args.app;- let (state, index) = login::login(args, options).await?;- let account = AccountView::new(&state.accounts[index], state.selected);- if options.json {- output::json(&json!({ "account": account, "app": app }))- } else {- output::account(&account)- }- }- AccountCommand::List => {- let state = State::load()?;- let accounts: Vec<_> = state- .accounts- .iter()- .map(|a| AccountView::new(a, state.selected))- .collect();- if options.json {- output::json(&accounts)- } else {- output::accounts(&accounts)- }- }- AccountCommand::View { name } => {- let state = State::load()?;- let index = state.resolve(name.as_deref())?;- output_account(state, index, options.json)- }- AccountCommand::Token { name, app } => {- let state = State::load()?;- let index = state.resolve(name.as_deref())?;- let token = Zeroizing::new(b64::encode_url_safe(state.accounts[index].token(app)?));- if options.json {- output::json(&json!({ "token": token.as_str() }))- } else {- writeln!(std::io::stdout(), "{}", token.as_str()).map_err(Into::into)- }- }- AccountCommand::Switch { name } => {- let mut vault = Vault::open()?;- let state = &mut vault.state;- let index = state.named(&name)?;- let selected = Some(state.accounts[index].storage_id);- if state.selected != selected {- state.selected = selected;- vault.save()?;- }- output_account(vault.into_state(), index, options.json)- }- AccountCommand::Rename { name, new_name } => {- let mut vault = Vault::open()?;- let state = &mut vault.state;- let (index, new_name) = match new_name {- Some(new_name) => (state.named(&name)?, new_name),- None => (state.resolve(None)?, name),- };- if state.accounts[index].name != new_name {- state.check_name(&new_name)?;- state.accounts[index].name = new_name;- vault.save()?;- }- output_account(vault.into_state(), index, options.json)- }- AccountCommand::Logout { name, app, local } => {- ensure!(- !options.offline || local,- "logging out on the server requires network access; use --local to forget the account on this device"- );- let mut vault = Vault::open()?;- let index = vault.state.resolve(name.as_deref())?;- let account = &vault.state.accounts[index];- let name = account.name.clone();- let apps = match app {- Some(app) => vec![app],- None => account.sessions.keys().copied().collect(),- };- let home = home::try_lock_account(account.storage_id)?;- let removal = if account- .sessions- .keys()- .all(|saved| app.is_none_or(|app| *saved == app))- {- Some(home.for_removal()?)- } else {- None- };- if !local {- for (completed, app) in apps.iter().enumerate() {- if let Err(error) = api::logout(&vault.state.accounts[index], *app).await {- if completed > 0 {- vault.save()?;- }- let remaining = vault.state.accounts[index]- .sessions- .keys()- .copied()- .collect::<Vec<_>>();- bail!(- "cannot log out of {} for {name:?}: {error:#}. Still logged in: {}. Retry when the server is reachable, or use --local to forget the account on this device.",- app.display_name(),- app_names(&remaining),- );- }- vault.state.accounts[index].sessions.remove(app);- }- } else {- vault.state.accounts[index].sessions.clear();- }- let removed = vault.state.accounts[index]- .sessions- .is_empty()- .then(|| remove_account(&mut vault.state, index));- vault.save()?;- if let Some(removal) = removal {- removal.remove()?;- }- let state = vault.into_state();- let account = AccountView::new(- removed.as_ref().unwrap_or_else(|| &state.accounts[index]),- state.selected,- );- let message = if removed.is_none() {- format!("Logged out of {} for {name:?}.", app_names(&apps))- } else if local && !apps.is_empty() {- format!("Removed account {name:?} from this device. Server logout was skipped.")- } else if apps.is_empty() {- format!("Removed account {name:?} from this device.")- } else {- format!(- "Logged out of {}. Removed account {name:?} from this device.",- app_names(&apps)- )- };- let result = match app {- Some(app) => json!({ "account": account, "app": app, "remoteLogout": !local }),- None => json!({ "account": account, "apps": apps, "remoteLogout": !local }),- };- output::action(options.json, &result, &message)- }- }-}--fn remove_account(state: &mut State, index: usize) -> Account {- let account = state.accounts.remove(index);- if state.selected == Some(account.storage_id) {- state.selected = None;- }- account-}--fn app_names(apps: &[App]) -> String {- let names = apps- .iter()- .map(|app| app.display_name())- .collect::<Vec<_>>();- match names.as_slice() {- [] => String::new(),- [name] => (*name).to_owned(),- [first, second] => format!("{first} and {second}"),- [first, middle @ .., last] => {- format!("{first}, {}, and {last}", middle.join(", "))- }- }-}--fn output_account(state: State, index: usize, json_output: bool) -> Result<()> {- let account = AccountView::new(&state.accounts[index], state.selected);- if json_output {- output::json(&account)- } else {- output::account(&account)- }-}--fn read_input(path: &Path, limit: u64) -> Result<Zeroizing<Vec<u8>>> {- let mut bytes = Zeroizing::new(Vec::new());- if path == Path::new("-") {- std::io::stdin()- .take(limit)- .read_to_end(&mut bytes)- .context("cannot read stdin")?;- } else {- std::fs::File::open(path)- .with_context(|| format!("cannot open {}", path.display()))?- .take(limit)- .read_to_end(&mut bytes)- .with_context(|| format!("cannot read {}", path.display()))?;- }- Ok(bytes)-}--fn parse_json<T: DeserializeOwned>(bytes: &[u8]) -> Result<T> {- serde_json::from_slice(bytes).map_err(|error| {- anyhow::anyhow!(- "invalid JSON at line {}, column {}",- error.line(),- error.column()- )- })-}diff --git a/rust/apps/cli/.gitignore b/rust/apps/cli/.gitignoredeleted file mode 100644index 4fba2bae82..0000000000--- a/rust/apps/cli/.gitignore+++ /dev/null@@ -1 +0,0 @@-exports/diff --git a/rust/apps/cli/Cargo.toml b/rust/apps/cli/Cargo.tomlindex b715df0e12..b2cd4fddfb 100644--- a/rust/apps/cli/Cargo.toml+++ b/rust/apps/cli/Cargo.toml@@ -1,42 +1,54 @@[package]-name = "ente-rs"-version = "0.0.1"+name = "ente-cli"+version = "0.4.0"edition.workspace = true-description = "Command-line interface for Ente"-homepage = "https://ente.com"-repository = "https://github.com/ente/ente"-license = "AGPL-3.0-only"+publish = false++[[bin]]+name = "ente"+path = "src/main.rs"[features]museum = [][dependencies]-chrono = { workspace = true, default-features = true }-clap = { workspace = true, features = ["derive", "env"] }-dialoguer = { workspace = true, default-features = true }+anyhow.workspace = true+chrono = { workspace = true, features = ["std", "clock"] }+clap = { workspace = true, features = ["derive", "string"] }+clap_complete.workspace = true+dialoguer = { workspace = true, features = ["password"] }dirs.workspace = trueente-accounts.workspace = true+ente-auth.workspace = true+ente-collections.workspace = trueente-core.workspace = trueente-paste.workspace = true-env_logger = { workspace = true, features = ["auto-color", "humantime", "regex"] }-futures = "0.3.34"-indicatif = "0.18.6"-log.workspace = true+ente-photos.workspace = true+ente-photos-export.workspace = true+env_logger.workspace = true+keyring = { workspace = true, features = ["apple-native", "windows-native", "linux-native-sync-persistent", "crypto-rust"] }open.workspace = true-rusqlite = { workspace = true, default-features = true, features = ["serde_json"] }+reqwest.workspace = true+rusqlite = { workspace = true, features = ["bundled-sqlcipher"] }serde.workspace = trueserde_json.workspace = true+tempfile.workspace = truethiserror.workspace = true-tokio = { workspace = true, features = ["full"] }-urlencoding.workspace = true+tokio = { workspace = true, features = ["macros", "rt-multi-thread", "signal", "sync", "time"] }+url.workspace = trueuuid = { workspace = true, features = ["serde", "v4"] }zeroize.workspace = true-zip.workspace = true++[target.'cfg(windows)'.dependencies]+rusqlite = { workspace = true, features = ["bundled-sqlcipher-vendored-openssl"] }[dev-dependencies]ente-test-support.workspace = true+futures-util.workspace = truemockito.workspace = true-url.workspace = true+same-file.workspace = true+sha2.workspace = true+zip.workspace = true[lints]workspace = truediff --git a/rust/apps/cli/README.md b/rust/apps/cli/README.mdindex 060cc1b0a0..8a7d7bdb8a 100644--- a/rust/apps/cli/README.md+++ b/rust/apps/cli/README.md@@ -1,18 +1,5 @@-WIP Ente Rust CLI.--## Development--```sh-cargo run --bin ente-rs -- --help-```--## Integration tests--The integration tests run against a live Museum spun up by-[ente-test-support](../../crates/test-support) (see its README for setup). They-are gated behind the `museum` Cargo feature, so a plain `cargo test -p ente-rs`-skips them. To run them:+Ente client for terminals and agents.```sh-cargo test -p ente-rs --features museum+cargo run -p ente-cli -- --help```diff --git a/rust/apps/cli-next/scripts/native-keyring.py b/rust/apps/cli/scripts/native-keyring.pysimilarity index 97%rename from rust/apps/cli-next/scripts/native-keyring.pyrename to rust/apps/cli/scripts/native-keyring.pyindex e58c303cc4..ca329a9061 100644--- a/rust/apps/cli-next/scripts/native-keyring.py+++ b/rust/apps/cli/scripts/native-keyring.py@@ -21,7 +21,7 @@ if args.mode == "build" and not args.sign:app = Path(__file__).resolve().parent.parentcargo = {- "build": ["cargo", "build", "--bin", "ente-cli-next"],+ "build": ["cargo", "build", "--bin", "ente"],"test": ["cargo", "test", "--test", "cli", "--no-run"],}[args.mode]cargo += ["--locked", "--message-format=json-render-diagnostics"]diff --git a/rust/apps/cli-next/scripts/test-with-keyring-linux.sh b/rust/apps/cli/scripts/test-with-keyring-linux.shsimilarity index 94%rename from rust/apps/cli-next/scripts/test-with-keyring-linux.shrename to rust/apps/cli/scripts/test-with-keyring-linux.shindex 7e41c46bd7..df0ac10aec 100755--- a/rust/apps/cli-next/scripts/test-with-keyring-linux.sh+++ b/rust/apps/cli/scripts/test-with-keyring-linux.sh@@ -8,7 +8,7 @@ if [[ $(uname -s) != Linux ]]; thenfitest_name=native_keyring_survives_separate_processes-executable=$(cargo test --locked -p ente-cli-next --test cli --no-run \+executable=$(cargo test --locked -p ente-cli --test cli --no-run \--message-format=json-render-diagnostics "$@" | python3 -c 'import json, sysartifacts = [json.loads(line) for line in sys.stdin]diff --git a/rust/apps/cli-next/src/account.rs b/rust/apps/cli/src/account.rssimilarity index 100%rename from rust/apps/cli-next/src/account.rsrename to rust/apps/cli/src/account.rsdiff --git a/rust/apps/cli-next/src/admin.rs b/rust/apps/cli/src/admin.rssimilarity index 100%rename from rust/apps/cli-next/src/admin.rsrename to rust/apps/cli/src/admin.rsdiff --git a/rust/apps/cli-next/src/api.rs b/rust/apps/cli/src/api.rssimilarity index 98%rename from rust/apps/cli-next/src/api.rsrename to rust/apps/cli/src/api.rsindex 78a4fbf18b..4a02c873a7 100644--- a/rust/apps/cli-next/src/api.rs+++ b/rust/apps/cli/src/api.rs@@ -21,7 +21,7 @@ use crate::{vault::{Account, State},};-pub(crate) const USER_AGENT: &str = concat!("ente-cli-next/", env!("CARGO_PKG_VERSION"));+pub(crate) const USER_AGENT: &str = concat!(env!("CARGO_PKG_NAME"), "/", env!("CARGO_PKG_VERSION"));pub fn normalize_host(host: &str) -> Result<String> {let input = if host.contains("://") {diff --git a/rust/apps/cli/src/api/client.rs b/rust/apps/cli/src/api/client.rsdeleted file mode 100644index 3aa47c0aba..0000000000--- a/rust/apps/cli/src/api/client.rs+++ /dev/null@@ -1,168 +0,0 @@-use crate::models::account::App;-use crate::models::error::Result;-use ente_core::http::{self, Api, ApiConfig, Auth, Http, RetryProfile};-use ente_core::urls::PRODUCTION_API_ORIGIN;-use std::sync::{PoisonError, RwLock};--pub(crate) const USER_AGENT: &str = concat!("ente-rs/", env!("CARGO_PKG_VERSION"));-const FILES_ORIGIN: &str = "https://files.ente.com";-const THUMBNAILS_ORIGIN: &str = "https://thumbnails.ente.com";--pub struct AppClient {- origin: String,- app: App,- museum: Api,- proxies: Option<DownloadProxies>,- token: RwLock<Option<String>>,-}--pub(crate) struct DownloadProxies {- pub(crate) files: Api,- pub(crate) thumbnails: Api,-}--impl AppClient {- pub fn new(origin: Option<String>, app: App) -> Result<Self> {- let http = Http::new()?;- let origin = origin.unwrap_or_else(|| PRODUCTION_API_ORIGIN.to_string());- let client_package = app.client_package();- let museum = new_api(&http, &origin, client_package);- let proxies = (origin == PRODUCTION_API_ORIGIN).then(|| DownloadProxies {- files: new_api(&http, FILES_ORIGIN, client_package),- thumbnails: new_api(&http, THUMBNAILS_ORIGIN, client_package),- });- Ok(Self {- origin,- app,- museum,- proxies,- token: RwLock::new(None),- })- }-- pub fn set_token(&self, token: &str) {- self.museum.set_auth(Some(Auth::User(token.to_owned())));- if let Some(proxies) = &self.proxies {- proxies.files.set_auth(Some(Auth::User(token.to_owned())));- proxies- .thumbnails- .set_auth(Some(Auth::User(token.to_owned())));- }- *self.token.write().unwrap_or_else(PoisonError::into_inner) = Some(token.to_owned());- }-- pub fn token(&self) -> Option<String> {- self.token- .read()- .unwrap_or_else(PoisonError::into_inner)- .clone()- }-- pub fn origin(&self) -> &str {- &self.origin- }-- pub fn app(&self) -> App {- self.app- }-- pub(crate) fn api(&self) -> &Api {- &self.museum- }-- pub(crate) fn download_proxies(&self) -> Option<&DownloadProxies> {- self.proxies.as_ref()- }-- pub(crate) async fn download_url(&self, url: &str) -> Result<Vec<u8>> {- Ok(- http::retry_with_profile(RetryProfile::Background, || async {- self.museum- .http()- .get(url)- .send()- .await?- .error_for_status()?- .bytes()- .await- })- .await?,- )- }-}--fn new_api(http: &Http, origin: &str, client_package: &str) -> Api {- Api::new(- http.clone(),- ApiConfig {- origin: origin.to_owned(),- client_package: Some(client_package.to_owned()),- client_version: None,- user_agent: Some(USER_AGENT.to_string()),- auth: None,- },- )-}--pub(crate) async fn download_from_proxy(api: &Api, file_id: i64) -> Result<Vec<u8>> {- Ok(- http::retry_with_profile(RetryProfile::Background, || async {- api.get("/")- .query(&[("fileID", file_id)])- .send()- .await?- .error_for_status()?- .bytes()- .await- })- .await?,- )-}--#[cfg(test)]-mod tests {- use super::*;- use mockito::{Matcher, Server};-- #[test]- fn selects_download_backend_from_origin() {- let production = AppClient::new(None, App::Photos).unwrap();- assert!(production.download_proxies().is_some());-- let self_hosted = AppClient::new(Some("https://example.com".into()), App::Photos).unwrap();- assert!(self_hosted.download_proxies().is_none());- }-- #[tokio::test]- async fn app_clients_keep_museum_auth_scoped_to_app() {- let mut server = Server::new_async().await;- let auth_download = server- .mock("GET", "/")- .match_query(Matcher::UrlEncoded("fileID".into(), "1".into()))- .match_header("x-auth-token", "auth-token")- .match_header("x-client-package", "io.ente.auth")- .with_body("auth")- .create_async()- .await;- let photos_download = server- .mock("GET", "/")- .match_query(Matcher::UrlEncoded("fileID".into(), "2".into()))- .match_header("x-auth-token", "photos-token")- .match_header("x-client-package", "io.ente.photos")- .with_body("photos")- .create_async()- .await;- let auth_client = AppClient::new(Some(server.url()), App::Auth).unwrap();- auth_client.set_token("auth-token");- let photos_client = AppClient::new(Some(server.url()), App::Photos).unwrap();- photos_client.set_token("photos-token");-- let auth_bytes = download_from_proxy(auth_client.api(), 1).await.unwrap();- let photos_bytes = download_from_proxy(photos_client.api(), 2).await.unwrap();-- auth_download.assert_async().await;- photos_download.assert_async().await;- assert_eq!(auth_bytes, b"auth");- assert_eq!(photos_bytes, b"photos");- }-}diff --git a/rust/apps/cli/src/api/methods.rs b/rust/apps/cli/src/api/methods.rsdeleted file mode 100644index 5e79e2e714..0000000000--- a/rust/apps/cli/src/api/methods.rs+++ /dev/null@@ -1,253 +0,0 @@-use crate::api::client::{AppClient, download_from_proxy};-use crate::api::models::{- Collection, File, GetCollectionsResponse, GetDiffResponse, GetFileResponse, GetFileUrlResponse,- GetFilesResponse, GetThumbnailUrlResponse, UserDetails,-};-use crate::models::error::Result;-use ente_core::http;--pub struct ApiMethods<'a> {- client: &'a AppClient,-}--impl<'a> ApiMethods<'a> {- pub fn new(client: &'a AppClient) -> Self {- Self { client }- }-- pub async fn get_user_details(&self) -> Result<UserDetails> {- let api = self.client.api();- Ok(http::retry(|| async {- api.get("/users/details")- .send()- .await?- .error_for_code()- .await?- .json()- .await- })- .await?)- }-- pub async fn get_collections(&self, since_time: i64) -> Result<Vec<Collection>> {- let api = self.client.api();- let response: GetCollectionsResponse = http::retry(|| async {- api.get("/collections/v2")- .query(&[("sinceTime", since_time.to_string())])- .send()- .await?- .error_for_code()- .await?- .json()- .await- })- .await?;- Ok(response.collections)- }-- pub async fn get_collection(&self, collection_id: i64) -> Result<Collection> {- let api = self.client.api();- Ok(http::retry(|| async {- api.get(&format!("/collections/{collection_id}"))- .send()- .await?- .error_for_code()- .await?- .json()- .await- })- .await?)- }-- pub async fn get_collection_files(- &self,- collection_id: i64,- since_time: i64,- ) -> Result<(Vec<File>, bool)> {- let api = self.client.api();- let response: GetFilesResponse = http::retry(|| async {- api.get("/collections/v2/diff")- .query(&[- ("collectionID", collection_id.to_string()),- ("sinceTime", since_time.to_string()),- ])- .send()- .await?- .error_for_code()- .await?- .json()- .await- })- .await?;- Ok((response.diff, response.has_more))- }-- pub async fn get_file(&self, collection_id: i64, file_id: i64) -> Result<File> {- let api = self.client.api();- let response: GetFileResponse = http::retry(|| async {- api.get("/collections/file")- .query(&[- ("collectionID", collection_id.to_string()),- ("fileID", file_id.to_string()),- ])- .send()- .await?- .error_for_code()- .await?- .json()- .await- })- .await?;- Ok(response.file)- }-- pub async fn get_diff(&self, since_time: i64, limit: i32) -> Result<(Vec<File>, bool)> {- let api = self.client.api();- let response: GetDiffResponse = http::retry(|| async {- api.get("/diff")- .query(&[- ("sinceTime", since_time.to_string()),- ("limit", limit.to_string()),- ])- .send()- .await?- .error_for_code()- .await?- .json()- .await- })- .await?;- Ok((response.diff, response.has_more))- }-- async fn get_signed_file_url(&self, file_id: i64) -> Result<String> {- let api = self.client.api();- let response: GetFileUrlResponse = http::retry(|| async {- api.get(&format!("/files/download/v3/{file_id}"))- .send()- .await?- .error_for_code()- .await?- .json()- .await- })- .await?;- Ok(response.url)- }-- async fn get_signed_thumbnail_url(&self, file_id: i64) -> Result<String> {- let api = self.client.api();- let response: GetThumbnailUrlResponse = http::retry(|| async {- api.get(&format!("/files/thumbnail/v3/{file_id}"))- .send()- .await?- .error_for_code()- .await?- .json()- .await- })- .await?;- Ok(response.url)- }-- pub async fn download_file(&self, file_id: i64) -> Result<Vec<u8>> {- match self.client.download_proxies() {- Some(proxies) => download_from_proxy(&proxies.files, file_id).await,- None => {- let url = self.get_signed_file_url(file_id).await?;- self.client.download_url(&url).await- }- }- }-- pub async fn download_thumbnail(&self, file_id: i64) -> Result<Vec<u8>> {- match self.client.download_proxies() {- Some(proxies) => download_from_proxy(&proxies.thumbnails, file_id).await,- None => {- let url = self.get_signed_thumbnail_url(file_id).await?;- self.client.download_url(&url).await- }- }- }-- pub async fn get_trash(&self, since_time: i64) -> Result<(Vec<File>, bool)> {- let api = self.client.api();- let response: GetDiffResponse = http::retry(|| async {- api.get("/trash/v2")- .query(&[("sinceTime", since_time.to_string())])- .send()- .await?- .error_for_code()- .await?- .json()- .await- })- .await?;- Ok((response.diff, response.has_more))- }-- pub async fn delete_from_trash(&self, file_ids: &[i64]) -> Result<()> {- let api = self.client.api();- let body = serde_json::json!({ "fileIDs": file_ids });- http::retry(|| async {- api.post("/trash/delete")- .json(&body)- .send()- .await?- .error_for_code()- .await?;- Ok(())- })- .await?;- Ok(())- }-- pub async fn empty_trash(&self) -> Result<()> {- let api = self.client.api();- http::retry(|| async {- api.delete("/trash/empty")- .send()- .await?- .error_for_code()- .await?;- Ok(())- })- .await?;- Ok(())- }-}--#[cfg(test)]-mod tests {- use super::*;- use mockito::{Matcher, Server};-- #[tokio::test]- async fn test_self_hosted_download_uses_signed_url() {- let mut server = Server::new_async().await;- let signed_url = format!("{}/object", server.url());- let url_mock = server- .mock("GET", "/files/download/v3/12345")- .match_header("x-auth-token", "token")- .match_header("x-client-package", "io.ente.locker")- .with_body(format!(r#"{{"url":"{signed_url}"}}"#))- .create_async()- .await;- let download_mock = server- .mock("GET", "/object")- .match_header("x-auth-token", Matcher::Missing)- .match_header("x-client-package", Matcher::Missing)- .with_body("file")- .create_async()- .await;- let client =- AppClient::new(Some(server.url()), crate::models::account::App::Locker).unwrap();- client.set_token("token");-- let bytes = ApiMethods::new(&client).download_file(12345).await.unwrap();-- url_mock.assert_async().await;- download_mock.assert_async().await;- assert_eq!(bytes, b"file");- }-}diff --git a/rust/apps/cli/src/api/mod.rs b/rust/apps/cli/src/api/mod.rsdeleted file mode 100644index 85806a665b..0000000000--- a/rust/apps/cli/src/api/mod.rs+++ /dev/null@@ -1,7 +0,0 @@-pub mod client;-pub mod methods;-pub mod models;--pub use client::AppClient;-pub use methods::ApiMethods;-pub use models::*;diff --git a/rust/apps/cli/src/api/models.rs b/rust/apps/cli/src/api/models.rsdeleted file mode 100644index 9988f6f48e..0000000000--- a/rust/apps/cli/src/api/models.rs+++ /dev/null@@ -1,463 +0,0 @@-use std::fmt;--use serde::{Deserialize, Serialize};-use uuid::Uuid;--fn default_email_mfa_enabled() -> bool {- true-}--#[derive(Debug, Deserialize, Serialize)]-pub struct SrpAttributes {- #[serde(rename = "srpUserID")]- pub srp_user_id: Uuid,- #[serde(rename = "srpSalt")]- pub srp_salt: String,- #[serde(rename = "memLimit")]- pub mem_limit: u32,- #[serde(rename = "opsLimit")]- pub ops_limit: u32,- #[serde(rename = "kekSalt")]- pub kek_salt: String,- #[serde(rename = "isEmailMFAEnabled", default = "default_email_mfa_enabled")]- pub is_email_mfa_enabled: bool,-}--#[derive(Debug, Deserialize)]-#[serde(rename_all = "camelCase")]-pub struct GetSrpAttributesResponse {- pub attributes: SrpAttributes,-}--#[derive(Debug, Serialize)]-pub struct CreateSrpSessionRequest {- #[serde(rename = "srpUserID")]- pub srp_user_id: String,- #[serde(rename = "srpA")]- pub srp_a: String,-}--#[derive(Debug, Deserialize)]-pub struct CreateSrpSessionResponse {- #[serde(rename = "sessionID")]- pub session_id: Uuid,- #[serde(rename = "srpB")]- pub srp_b: String,-}--#[derive(Debug, Serialize)]-pub struct VerifySrpSessionRequest {- #[serde(rename = "srpUserID")]- pub srp_user_id: String,- #[serde(rename = "sessionID")]- pub session_id: String,- #[serde(rename = "srpM1")]- pub srp_m1: String,-}--#[derive(Debug, Clone, Deserialize, Serialize)]-#[serde(rename_all = "camelCase")]-pub struct KeyAttributes {- pub kek_salt: 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: u32,- pub ops_limit: u32,- pub master_key_encrypted_with_recovery_key: Option<String>,- pub master_key_decryption_nonce: Option<String>,- pub recovery_key_encrypted_with_master_key: Option<String>,- pub recovery_key_decryption_nonce: Option<String>,-}--#[derive(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>,- #[serde(rename = "twoFactorSessionID")]- pub two_factor_session_id: Option<String>,- #[serde(rename = "twoFactorSessionIDV2")]- pub two_factor_session_id_v2: Option<String>,- #[serde(rename = "passkeySessionID")]- pub passkey_session_id: Option<String>,- pub srp_m2: Option<String>,- pub accounts_url: Option<String>,-}--impl fmt::Debug for AuthResponse {- fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {- f.debug_struct("AuthResponse")- .field("id", &self.id)- .field("has_key_attributes", &self.key_attributes.is_some())- .field(- "encrypted_token",- &self.encrypted_token.as_ref().map(|_| "[REDACTED]"),- )- .field("token", &self.token.as_ref().map(|_| "[REDACTED]"))- .field(- "two_factor_session_id",- &self.two_factor_session_id.as_ref().map(|_| "[REDACTED]"),- )- .field(- "two_factor_session_id_v2",- &self.two_factor_session_id_v2.as_ref().map(|_| "[REDACTED]"),- )- .field(- "passkey_session_id",- &self.passkey_session_id.as_ref().map(|_| "[REDACTED]"),- )- .field("srp_m2", &self.srp_m2.as_ref().map(|_| "[REDACTED]"))- .field("accounts_url", &self.accounts_url)- .finish()- }-}--impl AuthResponse {- pub fn get_two_factor_session_id(&self) -> Option<&String> {- self.two_factor_session_id- .as_ref()- .filter(|s| !s.is_empty())- .or_else(|| {- self.two_factor_session_id_v2- .as_ref()- .filter(|s| !s.is_empty())- })- }-- pub fn is_mfa_required(&self) -> bool {- self.get_two_factor_session_id().is_some()- }-- pub fn is_passkey_required(&self) -> bool {- self.passkey_session_id- .as_ref()- .is_some_and(|s| !s.is_empty())- }-}--#[derive(Debug, Serialize)]-pub struct SendOtpRequest {- pub email: String,- pub purpose: String,-}--#[derive(Serialize)]-pub struct VerifyEmailRequest {- pub email: String,- pub ott: String,- #[serde(skip_serializing_if = "Option::is_none")]- pub source: Option<String>,-}--impl fmt::Debug for VerifyEmailRequest {- fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {- f.debug_struct("VerifyEmailRequest")- .field("email", &self.email)- .field("ott", &"[REDACTED]")- .field("source", &self.source)- .finish()- }-}--#[derive(Serialize)]-#[serde(rename_all = "camelCase")]-pub struct VerifyTotpRequest {- pub session_id: String,- pub code: String,-}--impl fmt::Debug for VerifyTotpRequest {- fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {- f.debug_struct("VerifyTotpRequest")- .field("session_id", &"[REDACTED]")- .field("code", &"[REDACTED]")- .finish()- }-}--#[derive(Debug, Serialize)]-#[serde(rename_all = "camelCase")]-pub struct SetUserAttributesRequest {- pub key_attributes: KeyAttributes,-}--#[derive(Debug, Serialize)]-pub struct SetupSrpRequest {- #[serde(rename = "srpUserID")]- pub srp_user_id: String,- #[serde(rename = "srpSalt")]- pub srp_salt: String,- #[serde(rename = "srpVerifier")]- pub srp_verifier: String,- #[serde(rename = "srpA")]- pub srp_a: String,-}--#[derive(Debug, Deserialize)]-pub struct SetupSrpResponse {- #[serde(rename = "setupID")]- pub setup_id: Uuid,- #[serde(rename = "srpB")]- pub srp_b: String,-}--#[derive(Debug, Serialize)]-pub struct CompleteSrpSetupRequest {- #[serde(rename = "setupID")]- pub setup_id: String,- #[serde(rename = "srpM1")]- pub srp_m1: String,-}--#[derive(Debug, Deserialize)]-pub struct CompleteSrpSetupResponse {- #[serde(rename = "setupID")]- pub setup_id: Uuid,- #[serde(rename = "srpM2")]- pub srp_m2: String,-}--#[derive(Debug, Deserialize)]-#[serde(rename_all = "camelCase")]-pub struct SessionValidityResponse {- pub has_set_keys: bool,- pub key_attributes: Option<KeyAttributes>,-}--#[derive(Deserialize)]-#[serde(rename_all = "camelCase")]-pub struct TwoFactorSecret {- pub secret_code: String,- pub qr_code: String,-}--impl fmt::Debug for TwoFactorSecret {- fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {- f.debug_struct("TwoFactorSecret")- .field("secret_code", &"[REDACTED]")- .field("qr_code", &"[REDACTED]")- .finish()- }-}--#[derive(Serialize)]-#[serde(rename_all = "camelCase")]-pub struct EnableTwoFactorRequest {- pub code: String,- pub encrypted_two_factor_secret: String,- pub two_factor_secret_decryption_nonce: String,-}--impl fmt::Debug for EnableTwoFactorRequest {- fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {- f.debug_struct("EnableTwoFactorRequest")- .field("code", &"[REDACTED]")- .field("encrypted_two_factor_secret", &"[REDACTED]")- .field("two_factor_secret_decryption_nonce", &"[REDACTED]")- .finish()- }-}--#[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,-}--#[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: Option<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>>,- #[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)]-#[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>,-}--#[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>,-}--#[derive(Debug, Deserialize, Serialize, Clone)]-#[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,- pub file: FileAttributes,- pub thumbnail: FileAttributes,- pub metadata: FileAttributes,- pub is_deleted: bool,- pub updation_time: i64,- pub magic_metadata: Option<MagicMetadata>,- #[serde(rename = "pubMagicMetadata")]- pub pub_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,- pub size: Option<i64>,-}--#[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,-}--#[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,-}--#[derive(Debug, Deserialize)]-pub struct GetFileUrlResponse {- pub url: String,-}--#[derive(Debug, Deserialize)]-pub struct GetThumbnailUrlResponse {- pub url: String,-}diff --git a/rust/apps/cli-next/src/args.rs b/rust/apps/cli/src/args.rssimilarity index 96%rename from rust/apps/cli-next/src/args.rsrename to rust/apps/cli/src/args.rsindex 847753fde3..cc78169f4b 100644--- a/rust/apps/cli-next/src/args.rs+++ b/rust/apps/cli/src/args.rs@@ -5,7 +5,7 @@ use clap_complete::Shell;use serde::{Deserialize, Serialize};#[derive(Parser)]-#[command(version, about = "Ente client for terminals and agents")]+#[command(name = "ente", version, about = "Ente client for terminals and agents")]pub struct Cli {#[command(flatten, next_help_heading = "Global options")]pub options: Options,@@ -130,9 +130,14 @@ pub enum Command {#[command(about = "Generate a vault key for unattended use",after_help = "Environment:- ENTE_CLI_HOME Directory containing the encrypted vault.+ ENTE_CLI_HOME Directory for saved accounts and encrypted databases.ENTE_CLI_VAULT_KEY Base64 key from `vault key generate`; bypasses the OS keychain.+Default locations:+ macOS: ~/Library/Application Support/ente-cli+ Linux: $XDG_DATA_HOME/ente-cli (defaults to ~/.local/share/ente-cli)+ Windows: %LOCALAPPDATA%\\ente-cli+Keep the same home and key across unattended invocations.")]Vault {@@ -143,18 +148,18 @@ Keep the same home and key across unattended invocations."about = "Print a shell completion script",after_help = "Enable completion in the current shell, or add the commands to its startup file:Bash (~/.bashrc):- eval \"$(ente-cli-next completion bash)\"+ eval \"$(ente completion bash)\"Zsh (~/.zshrc):autoload -Uz compinit; compinit- source <(ente-cli-next completion zsh)+ source <(ente completion zsh)PowerShell ($PROFILE):- ente-cli-next completion powershell | Out-String | Invoke-Expression+ ente completion powershell | Out-String | Invoke-ExpressionElvish (~/.config/elvish/rc.elv):- eval (ente-cli-next completion elvish | slurp)+ eval (ente completion elvish | slurp)Fish loads a saved script on demand. Write it once, and again after upgrading:mkdir -p ~/.config/fish/completions- ente-cli-next completion fish > ~/.config/fish/completions/ente-cli-next.fish+ ente completion fish > ~/.config/fish/completions/ente.fishPrints the script to stdout, including when --json is set.")]@@ -188,7 +193,7 @@ With --password --no-input, ENTE_CLI_PASSWORD is required.Prints the paste URL. With --json: {\"url\": \"...\"}. Requires network access.Example:- ente-cli-next paste create --input notes.txt"+ ente paste create --input notes.txt")]Create {#[arg(@@ -254,8 +259,8 @@ JSON summary fields: output, codes, failures.total. --json does not change backuBackups written to stdout have no summary.Examples:- ente-cli-next auth export ~/Backups/Auth- ente-cli-next auth export --plaintext --output codes.txt"+ ente auth export ~/Backups/Auth+ ente auth export --plaintext --output codes.txt")]Export(AuthExportArgs),#[command(about = "Decrypt an Auth export without an account")]@@ -308,8 +313,8 @@ HOTP values are not supported yet.Codes use your computer's clock. Make sure its date and time are correct.Examples:- ente-cli-next auth code view github- ente-cli-next auth code view \"GitHub ([email protected])\""+ ente auth code view github+ ente auth code view \"GitHub ([email protected])\"")]View {#[arg(@@ -361,8 +366,8 @@ files and copies are null when the full export size could not be determined.changes contains exported, metadataUpdated, renamed and movedToTrash counts; failures contains total and conflicts.Examples:- ente-cli-next photos export ~/Pictures/Ente- ente-cli-next photos export ~/Pictures/Ente --album Holidays --account personal"+ ente photos export ~/Pictures/Ente+ ente photos export ~/Pictures/Ente --album Holidays --account personal")]Export(PhotosExportArgs),#[command(about = "Manage albums")]@@ -591,8 +596,8 @@ With --no-input, supply credentials through --input PATH or --input -.For unattended vault access, set ENTE_CLI_VAULT_KEY (see vault --help).Examples:- ente-cli-next account login --app photos- ente-cli-next account login --app auth --account personal"+ ente account login --app photos+ ente account login --app auth --account personal")]Login(LoginArgs),#[command(@@ -790,7 +795,7 @@ pub enum KeyCommand {const ADMIN_HELP: &str ="Uses the selected account's server and saved login; the server grants administrator access.-Log in with: ente-cli-next account login --account NAME --app photos --host URL+Log in with: ente account login --account NAME --app photos --host URL--account selects a saved account by name; otherwise uses the selected or sole account.--app selects its saved login; otherwise uses the only saved app, then Photos.With multiple apps and no Photos login, supply --app.@@ -821,7 +826,7 @@ Lists users in creation order. Fetches all users matching --since before applyinJSON returns an array: id and email (strings), createdAt (RFC3339).Example:- ente-cli-next admin --account home user list --all --no-input --json"+ ente admin --account home user list --all --no-input --json")]List {#[command(flatten)]@@ -836,7 +841,7 @@ subscription contains productId, storageBytes and expiresAt, or null when unavaiIDs are strings; timestamps are RFC3339; storageBytes is an integer.Example:- ente-cli-next admin --account home user view [email protected]"+ ente admin --account home user view [email protected]")]View {#[arg(value_name = "USER", help = "User email or numeric ID")]@@ -873,7 +878,7 @@ Dates accept YYYY-MM-DD (00:00 UTC at the start of that date) or RFC3339 with aShows old and new limits before confirmation. Paid plans are rejected.Example:- ente-cli-next admin --account home user update-subscription [email protected] --no-limit"+ ente admin --account home user update-subscription [email protected] --no-limit")]UpdateSubscription(SubscriptionArgs),}diff --git a/rust/apps/cli-next/src/auth/code.rs b/rust/apps/cli/src/auth/code.rssimilarity index 100%rename from rust/apps/cli-next/src/auth/code.rsrename to rust/apps/cli/src/auth/code.rsdiff --git a/rust/apps/cli-next/src/auth/mod.rs b/rust/apps/cli/src/auth/mod.rssimilarity index 100%rename from rust/apps/cli-next/src/auth/mod.rsrename to rust/apps/cli/src/auth/mod.rsdiff --git a/rust/apps/cli-next/src/auth/output.rs b/rust/apps/cli/src/auth/output.rssimilarity index 100%rename from rust/apps/cli-next/src/auth/output.rsrename to rust/apps/cli/src/auth/output.rsdiff --git a/rust/apps/cli-next/src/auth/replica.rs b/rust/apps/cli/src/auth/replica.rssimilarity index 100%rename from rust/apps/cli-next/src/auth/replica.rsrename to rust/apps/cli/src/auth/replica.rsdiff --git a/rust/apps/cli/src/cli/account.rs b/rust/apps/cli/src/cli/account.rsdeleted file mode 100644index 52f5c09fd0..0000000000--- a/rust/apps/cli/src/cli/account.rs+++ /dev/null@@ -1,145 +0,0 @@-use clap::{Args, Subcommand};--#[derive(Args)]-pub struct AccountCommand {- #[command(subcommand)]- pub command: AccountSubcommands,-}--#[derive(Subcommand)]-pub enum AccountSubcommands {- /// List configured accounts- List,-- /// Login into existing account- #[command(alias = "login")]- Add(AddArgs),-- /// Create a new account via email verification, key setup, and SRP registration- #[command(alias = "signup")]- Create(CreateArgs),-- /// Update an existing account's export directory- Update {- /// Email address of the account- #[arg(long)]- email: String,-- /// Export directory path- #[arg(long)]- dir: String,-- /// Specify the app (photos, locker, auth)- #[arg(long, default_value = "photos")]- app: String,- },-- /// Get token for an account for a specific app- GetToken {- /// Email address of the account- #[arg(long)]- email: String,-- /// Specify the app (photos, locker, auth)- #[arg(long, default_value = "photos")]- app: String,- },-- /// Enable TOTP two-factor for an existing account- #[command(name = "two-factor", alias = "2fa")]- TwoFactor {- /// Email address of the account- #[arg(long)]- email: String,-- /// Specify the app (photos, locker, auth)- #[arg(long, default_value = "photos")]- app: String,-- /// TOTP code to use for enabling two-factor- #[arg(long)]- totp_code: Option<String>,-- /// Print the recovery key after enabling two-factor- #[arg(long)]- show_recovery_key: bool,- },-}--#[derive(Args)]-pub struct AddArgs {- /// Email address (optional - will prompt if not provided)- #[arg(long)]- pub email: Option<String>,-- /// Password (optional - will prompt if not provided)- #[arg(long)]- pub password: Option<String>,-- /// Specify the app (photos, locker, auth)- #[arg(long, default_value = "photos")]- pub app: String,-- /// API endpoint (defaults to https://api.ente.com)- #[arg(long, default_value = "https://api.ente.com")]- pub endpoint: String,-- /// Export directory path- #[arg(long)]- pub export_dir: Option<String>,-- /// Email verification code for email-MFA accounts- #[arg(long)]- pub otp: Option<String>,-- /// TOTP code to use if login requires two-factor verification- #[arg(long)]- pub totp_code: Option<String>,-- /// Preferred second-factor method when multiple are available (totp or passkey)- #[arg(long)]- pub second_factor: Option<String>,-}--#[derive(Args)]-pub struct CreateArgs {- /// Email address (optional - will prompt if not provided)- #[arg(long)]- pub email: Option<String>,-- /// Password (optional - will prompt if not provided)- #[arg(long)]- pub password: Option<String>,-- /// Specify the app (photos, locker, auth)- #[arg(long, default_value = "photos")]- pub app: String,-- /// API endpoint (defaults to https://api.ente.com)- #[arg(long, default_value = "https://api.ente.com")]- pub endpoint: String,-- /// Export directory path- #[arg(long)]- pub export_dir: Option<String>,-- /// Signup email verification code- #[arg(long)]- pub otp: Option<String>,-- /// Referral/source string to pass during verify-email- #[arg(long)]- pub source: Option<String>,-- /// Enable TOTP two-factor immediately after signup- #[arg(long)]- pub setup_2fa: bool,-- /// TOTP code to use when enabling two-factor- #[arg(long)]- pub totp_code: Option<String>,-- /// Print the recovery key after signup- #[arg(long)]- pub show_recovery_key: bool,-}diff --git a/rust/apps/cli/src/cli/export.rs b/rust/apps/cli/src/cli/export.rsdeleted file mode 100644index 6cea339626..0000000000--- a/rust/apps/cli/src/cli/export.rs+++ /dev/null@@ -1,24 +0,0 @@-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_t = true, action = clap::ArgAction::Set)]- pub shared: bool,-- /// Include hidden albums (pass --hidden=false to exclude)- #[arg(long, default_value_t = true, action = clap::ArgAction::Set)]- pub hidden: bool,-- /// Comma-separated list of album names to export- #[arg(long, value_delimiter = ',')]- pub albums: Option<Vec<String>>,-- /// Comma-separated list of account emails to export from- #[arg(long, value_delimiter = ',')]- pub emails: Option<Vec<String>>,-}diff --git a/rust/apps/cli/src/cli/mod.rs b/rust/apps/cli/src/cli/mod.rsdeleted file mode 100644index 933dde6702..0000000000--- a/rust/apps/cli/src/cli/mod.rs+++ /dev/null@@ -1,29 +0,0 @@-use clap::{Parser, Subcommand};--pub mod account;-pub mod export;-pub mod paste;-pub mod version;--#[derive(Parser)]-#[command(name = "ente")]-#[command(about = "Command-line interface for Ente", long_about = None)]-pub struct Cli {- #[command(subcommand)]- pub command: Commands,-}--#[derive(Subcommand)]-pub enum Commands {- /// Manage account settings- Account(account::AccountCommand),-- /// Export photos and files- Export(export::ExportCommand),-- /// Create and consume encrypted pastes- Paste(paste::PasteCommand),-- /// Print version information- Version,-}diff --git a/rust/apps/cli/src/cli/paste.rs b/rust/apps/cli/src/cli/paste.rsdeleted file mode 100644index d86b6fa340..0000000000--- a/rust/apps/cli/src/cli/paste.rs+++ /dev/null@@ -1,56 +0,0 @@-use clap::{Args, Subcommand};-use std::path::PathBuf;--#[derive(Args)]-pub struct PasteCommand {- #[command(subcommand)]- pub command: PasteSubcommands,-}--#[derive(Subcommand)]-pub enum PasteSubcommands {- /// Create a one-time encrypted paste- Create {- /// Text to paste. If omitted, stdin is used when piped.- #[arg(value_name = "TEXT", conflicts_with = "file")]- text: Option<String>,-- /// Read paste text from a file. Use '-' for stdin.- #[arg(short, long)]- file: Option<PathBuf>,-- /// API endpoint- #[arg(long, default_value = "https://api.ente.com")]- endpoint: String,-- /// Public paste origin used for the generated link- #[arg(long, default_value = "https://paste.ente.com")]- paste_origin: String,-- /// Require a password to consume the paste- #[arg(long)]- password: bool,- },-- /// Consume a one-time encrypted paste.- ///- /// Control characters are escaped when stdout is a terminal. Use --raw to print verbatim.- #[command(alias = "read")]- Consume {- /// Paste URL or access token- link_or_token: String,-- /// Print paste text verbatim even when stdout is a terminal.- #[arg(long)]- raw: bool,-- /// Fragment key when passing only an access token.- /// Password-protected keys include the `p-` prefix.- #[arg(long)]- key: Option<String>,-- /// API endpoint- #[arg(long, default_value = "https://api.ente.com")]- endpoint: String,- },-}diff --git a/rust/apps/cli/src/cli/version.rs b/rust/apps/cli/src/cli/version.rsdeleted file mode 100644index 9d8f5293c1..0000000000--- a/rust/apps/cli/src/cli/version.rs+++ /dev/null@@ -1 +0,0 @@-pub const VERSION: &str = env!("CARGO_PKG_VERSION");diff --git a/rust/apps/cli/src/commands/account.rs b/rust/apps/cli/src/commands/account.rsdeleted file mode 100644index a955457853..0000000000--- a/rust/apps/cli/src/commands/account.rs+++ /dev/null@@ -1,561 +0,0 @@-use crate::{- api::client::USER_AGENT,- cli::account::{AccountCommand, AccountSubcommands, AddArgs, CreateArgs},- models::{- account::{Account, App},- error::{Error, Result},- },- storage::Storage,-};-use dialoguer::{Input, Password, Select};-use ente_accounts::{- AccountsClient, AccountsClientConfig, AuthenticatedAccount, TwoFactorSetup,- login::{LoginFlow, LoginStep},- signup::Signup,-};-use ente_core::b64;-use ente_core::urls::PRODUCTION_API_ORIGIN;-use std::{path::PathBuf, str::FromStr};-use zeroize::Zeroizing;--pub async fn handle_account_command(cmd: AccountCommand, storage: &Storage) -> Result<()> {- match cmd.command {- AccountSubcommands::List => list_accounts(storage),- AccountSubcommands::Add(args) => add_account(storage, args).await,- AccountSubcommands::Create(args) => create_account(storage, args).await,- AccountSubcommands::Update { email, dir, app } => {- update_account(storage, &email, &dir, &app)- }- AccountSubcommands::GetToken { email, app } => get_token(storage, &email, &app),- AccountSubcommands::TwoFactor {- email,- app,- totp_code,- show_recovery_key,- } => enable_two_factor(storage, &email, &app, totp_code, show_recovery_key).await,- }-}--#[derive(Clone, Copy)]-enum SecondFactorMethod {- Totp,- Passkey,-}--async fn login(- client: &AccountsClient,- email: &str,- password: Option<String>,- mut otp: Option<String>,- mut totp_code: Option<String>,- second_factor: Option<SecondFactorMethod>,-) -> Result<AuthenticatedAccount> {- let interactive_password = password.is_none();- let mut password = Zeroizing::new(prompt_password(password, "Enter your password")?);- let (mut flow, mut step) = LoginFlow::start(client, email.into()).await?;- loop {- step = match step {- LoginStep::EmailCode => {- let mut resent = false;- loop {- let prompt = if resent {- format!("Enter the new email-MFA code sent to {email}")- } else {- format!("Enter the email-MFA code sent to {email}")- };- let code = take_code(&mut otp, &prompt)?;- match flow.submit_code(client, &code).await {- Ok(next) => break next,- Err(ente_accounts::Error::IncorrectEmailVerificationCode) => {- println!("\nIncorrect email verification code. Try again.");- resent = false;- }- Err(ente_accounts::Error::EmailVerificationCodeExpired) => {- flow.resend_code(client).await?;- resent = true;- }- Err(error) => return Err(error.into()),- }- }- }- LoginStep::Password => loop {- match flow.submit_password(client, &password).await {- Ok(next) => break next,- Err(ente_accounts::Error::IncorrectPassword) if interactive_password => {- println!("\nIncorrect password. Try again.");- password = Zeroizing::new(prompt_password(None, "Re-enter your password")?);- }- Err(error) => return Err(error.into()),- }- },- LoginStep::SecondFactor { totp, passkey } => {- let method = match (totp, passkey) {- (true, true) => match second_factor {- Some(method) => method,- None => match Select::new()- .with_prompt("Choose verification method")- .items(["TOTP (Authenticator app)", "Passkey"])- .default(0)- .interact()- .map_err(|error| Error::InvalidInput(error.to_string()))?- {- 0 => SecondFactorMethod::Totp,- _ => SecondFactorMethod::Passkey,- },- },- (true, false) => SecondFactorMethod::Totp,- (false, true) => SecondFactorMethod::Passkey,- (false, false) => {- return Err(- ente_accounts::Error::Protocol("Missing second factor".into()).into(),- );- }- };- match method {- SecondFactorMethod::Totp => loop {- let code = take_code(&mut totp_code, "Enter TOTP code")?;- match flow.submit_code(client, &code).await {- Ok(next) => break next,- Err(ente_accounts::Error::IncorrectTotp) => {- println!("\nIncorrect TOTP code. Try again.")- }- Err(error) => return Err(error.into()),- }- },- SecondFactorMethod::Passkey => {- let url = flow.passkey_url(client, "ente-cli://passkey")?;- println!("\nPasskey verification required");- println!("Open this URL in your browser to verify your passkey:\n{url}");- if can_open_automatically(&url) && open::that(&url).is_err() {- log::error!("failed to open browser");- }- loop {- Input::<String>::new()- .with_prompt(- "Press Enter once you have completed passkey verification",- )- .allow_empty(true)- .interact_text()- .map_err(|error| Error::InvalidInput(error.to_string()))?;- if let Some(next) = flow.poll_passkey(client).await? {- break next;- }- }- }- }- }- LoginStep::Complete(account) => return Ok(*account),- };- }-}--async fn signup(- client: &AccountsClient,- email: &str,- password: &str,- mut otp: Option<String>,- source: Option<&str>,-) -> Result<AuthenticatedAccount> {- client.send_otp(email, "signup").await?;- let mut resent = false;- let verification = loop {- let prompt = if resent {- format!("Enter the new signup verification code sent to {email}")- } else {- format!("Enter the signup verification code sent to {email}")- };- let code = take_code(&mut otp, &prompt)?;- match client.verify_email(email, &code, source).await {- Ok(response) => break response,- Err(ente_accounts::Error::IncorrectEmailVerificationCode) => {- println!("\nIncorrect email verification code. Try again.");- resent = false;- }- Err(ente_accounts::Error::EmailVerificationCodeExpired) => {- client.send_otp(email, "signup").await?;- resent = true;- }- Err(error) => return Err(error.into()),- }- };- Ok(Signup::verified(email.into(), verification)?- .prepare(client, password)- .await?- .finish(client)- .await?)-}--async fn setup_two_factor(- client: &AccountsClient,- master_key: &[u8],- key_attributes: &ente_accounts::KeyAttributes,- mut code: Option<String>,-) -> Result<TwoFactorSetup> {- let setup = TwoFactorSetup::start(client, master_key, key_attributes).await?;- println!("\nTOTP setup secret: {}", setup.secret_code);- println!("Add this secret to your authenticator app, then enter the current code.");- loop {- let code = take_code(- &mut code,- "Enter the current TOTP from your authenticator app",- )?;- match setup.enable(client, &code).await {- Ok(()) => return Ok(setup),- Err(ente_accounts::Error::IncorrectTotp) => println!(- "Incorrect TOTP code. Enter the current code from your authenticator app and try again."- ),- Err(error) => return Err(error.into()),- }- }-}--fn take_code(code: &mut Option<String>, prompt: &str) -> Result<String> {- match code.take() {- Some(code) => Ok(code),- None => read_six_digit_code(prompt),- }-}--fn list_accounts(storage: &Storage) -> Result<()> {- let accounts = storage.accounts().list()?;-- if accounts.is_empty() {- println!("No accounts configured. Use 'ente account create' or 'ente account add'.");- return Ok(());- }-- println!("\nConfigured accounts:\n");- println!(- "{:<30} {:<10} {:<30} {:<40}",- "Email", "App", "Endpoint", "Export Directory"- );- println!("{}", "-".repeat(110));-- for account in accounts {- let endpoint_display = if account.endpoint == PRODUCTION_API_ORIGIN {- "api.ente.com (prod)".to_string()- } else if account.endpoint.starts_with("http://localhost") {- format!(- "localhost:{}",- account.endpoint.split(':').next_back().unwrap_or("")- )- } else {- account.endpoint.clone()- };-- println!(- "{:<30} {:<10} {:<30} {:<40}",- account.email,- account.app.to_string(),- endpoint_display,- account.export_dir.as_deref().unwrap_or("Not configured")- );- }-- Ok(())-}--async fn add_account(storage: &Storage, args: AddArgs) -> Result<()> {- println!("\n=== Add Existing Ente Account ===\n");-- let AddArgs {- email,- password,- app,- endpoint,- export_dir,- otp,- totp_code,- second_factor,- } = args;-- let email = prompt_email(email)?;- let app = resolve_app(&app)?;- let second_factor = parse_second_factor(second_factor.as_deref())?;-- if let Ok(Some(_)) = storage.accounts().get(&email, app) {- println!("\nAccount already exists for {email} with app {app}");- return Ok(());- }-- let export_dir = resolve_export_dir(export_dir, &email)?;- ensure_export_dir(&export_dir)?;-- let client = new_accounts_client(&endpoint, app)?;- let authenticated = login(&client, &email, password, otp, totp_code, second_factor).await?;-- persist_account(storage, &email, app, &endpoint, &export_dir, &authenticated)?;-- println!("\nAccount added successfully!");- println!(" Email: {email}");- println!(" App: {app}");- println!(" Endpoint: {endpoint}");- println!(" Export directory: {export_dir}");-- Ok(())-}--async fn create_account(storage: &Storage, args: CreateArgs) -> Result<()> {- println!("\n=== Create Ente Account ===\n");-- let CreateArgs {- email,- password,- app,- endpoint,- export_dir,- otp,- source,- setup_2fa,- totp_code,- show_recovery_key,- } = args;-- let email = prompt_email(email)?;- let password = Zeroizing::new(prompt_password(password, "Choose a password")?);- let app = resolve_app(&app)?;-- if let Ok(Some(_)) = storage.accounts().get(&email, app) {- println!("\nAccount already exists for {email} with app {app}");- return Ok(());- }-- let export_dir = resolve_export_dir(export_dir, &email)?;- ensure_export_dir(&export_dir)?;-- let client = new_accounts_client(&endpoint, app)?;- let created = signup(&client, &email, &password, otp, source.as_deref()).await?;-- persist_account(storage, &email, app, &endpoint, &export_dir, &created)?;-- println!("\nAccount created successfully!");- println!(" Email: {email}");- println!(" App: {app}");- println!(" Endpoint: {endpoint}");- println!(" Export directory: {export_dir}");-- if show_recovery_key {- if let Some(recovery_key) = created.recovery_key.as_deref() {- println!("\nRecovery key: {recovery_key}");- } else {- println!("\nRecovery key is not available for this account.");- }- }-- if setup_2fa {- let result = setup_two_factor(- &client,- &created.secrets.master_key,- &created.key_attributes,- totp_code,- )- .await?;-- println!("\nTwo-factor authentication enabled.");- if show_recovery_key {- println!("Recovery key: {}", result.recovery_key);- }- }-- Ok(())-}--async fn enable_two_factor(- storage: &Storage,- email: &str,- app_arg: &str,- totp_code: Option<String>,- show_recovery_key: bool,-) -> Result<()> {- let app = resolve_app(app_arg)?;- let account = storage- .accounts()- .get(email, app)?- .ok_or_else(|| Error::NotFound(format!("Account not found: {email}")))?;- let secrets = storage- .accounts()- .get_secrets(account.user_id, account.app)?- .ok_or_else(|| Error::NotFound(format!("Secrets not found for account {email}")))?;-- let client = new_accounts_client(&account.endpoint, app)?;- let token = b64::encode_url_safe(&secrets.token);- client.set_auth_token(Some(token));-- let key_attributes = client- .get_session_validity()- .await?- .key_attributes- .ok_or(ente_accounts::Error::MissingKeyAttributes)?;- let result = setup_two_factor(&client, &secrets.master_key, &key_attributes, totp_code).await?;-- println!("\nTwo-factor authentication enabled for {email}.");- if show_recovery_key {- println!("Recovery key: {}", result.recovery_key);- }-- Ok(())-}--fn update_account(storage: &Storage, email: &str, dir: &str, app_str: &str) -> Result<()> {- let app = resolve_app(app_str)?;-- if storage.accounts().get(email, app)?.is_none() {- return Err(Error::NotFound(format!(- "Account not found: {email} (app: {app})"- )));- }-- ensure_export_dir(dir)?;- storage.accounts().update_export_dir(email, app, dir)?;-- println!("\nAccount updated successfully!");- println!(" Email: {email}");- println!(" App: {app}");- println!(" New export directory: {dir}");-- Ok(())-}--fn get_token(storage: &Storage, email: &str, app_str: &str) -> Result<()> {- let app = resolve_app(app_str)?;-- let account = storage- .accounts()- .get(email, app)?- .ok_or_else(|| Error::NotFound(format!("Account not found: {email}")))?;-- let secrets = storage- .accounts()- .get_secrets(account.user_id, account.app)?- .ok_or_else(|| Error::NotFound(format!("Secrets not found for account {email}")))?;-- let token = b64::encode_url_safe(&secrets.token);- println!("{token}");-- Ok(())-}--fn persist_account(- storage: &Storage,- email: &str,- app: App,- endpoint: &str,- export_dir: &str,- authenticated: &AuthenticatedAccount,-) -> Result<()> {- let account = Account {- user_id: authenticated.user_id,- email: email.to_string(),- app,- endpoint: endpoint.to_string(),- export_dir: Some(export_dir.to_string()),- };-- storage.accounts().add(&account)?;- storage- .accounts()- .store_secrets(account.user_id, account.app, &authenticated.secrets)?;-- Ok(())-}--fn prompt_email(email_arg: Option<String>) -> Result<String> {- if let Some(email) = email_arg {- Ok(email)- } else {- Input::new()- .with_prompt("Enter your email address")- .interact_text()- .map_err(|e| Error::InvalidInput(e.to_string()))- }-}--fn prompt_password(password_arg: Option<String>, prompt: &str) -> Result<String> {- if let Some(password) = password_arg {- Ok(password)- } else {- Password::new()- .with_prompt(prompt)- .interact()- .map_err(|e| Error::InvalidInput(e.to_string()))- }-}--fn resolve_export_dir(export_dir_arg: Option<String>, email: &str) -> Result<String> {- if let Some(dir) = export_dir_arg {- Ok(dir)- } else {- Input::new()- .with_prompt("Enter export directory path")- .default(format!("./exports/{email}"))- .interact_text()- .map_err(|e| Error::InvalidInput(e.to_string()))- }-}--fn ensure_export_dir(dir: &str) -> Result<()> {- let export_path = PathBuf::from(dir);- if !export_path.exists() {- println!("Creating export directory: {dir}");- std::fs::create_dir_all(&export_path).map_err(Error::Io)?;- }- Ok(())-}--fn resolve_app(app_arg: &str) -> Result<App> {- App::from_str(app_arg).map_err(Error::InvalidInput)-}--fn parse_second_factor(second_factor: Option<&str>) -> Result<Option<SecondFactorMethod>> {- second_factor- .map(|value| match value.trim().to_ascii_lowercase().as_str() {- "totp" => Ok(SecondFactorMethod::Totp),- "passkey" => Ok(SecondFactorMethod::Passkey),- other => Err(Error::InvalidInput(format!(- "Invalid second-factor method: {other}. Must be one of: totp, passkey"- ))),- })- .transpose()-}--fn new_accounts_client(endpoint: &str, app: App) -> Result<AccountsClient> {- AccountsClient::new(- AccountsClientConfig::new(app.client_package())- .with_origin(endpoint.to_string())- .with_user_agent(USER_AGENT),- )- .map_err(Error::from)-}--fn can_open_automatically(url: &str) -> bool {- url.split_once("://").is_some_and(|(scheme, _)| {- scheme.eq_ignore_ascii_case("https") || scheme.eq_ignore_ascii_case("http")- })-}--fn read_six_digit_code(prompt: &str) -> Result<String> {- Input::new()- .with_prompt(prompt)- .validate_with(|input: &String| {- if input.len() == 6 && input.chars().all(char::is_numeric) {- Ok(())- } else {- Err("Code must be 6 digits")- }- })- .interact_text()- .map_err(|e| Error::InvalidInput(e.to_string()))-}--#[cfg(test)]-mod tests {- use super::can_open_automatically;-- #[test]- fn automatic_opening_is_limited_to_web_urls() {- assert!(can_open_automatically("https://accounts.ente.io"));- assert!(can_open_automatically("HTTP://localhost:3000"));- assert!(!can_open_automatically("ente-cli://passkey"));- assert!(!can_open_automatically("file:///etc/hosts"));- }-}diff --git a/rust/apps/cli/src/commands/export.rs b/rust/apps/cli/src/commands/export.rsdeleted file mode 100644index 2e48282e85..0000000000--- a/rust/apps/cli/src/commands/export.rs+++ /dev/null@@ -1,1076 +0,0 @@-use crate::Result;-use crate::api::AppClient;-use crate::api::methods::ApiMethods;-use crate::live_photo::extract_live_photo;-use crate::models::{- account::Account,- export_metadata::{AlbumMetadata, DiskFileMetadata},- filter::ExportFilter,- metadata::FileMetadata,-};-use crate::storage::Storage;-use crate::sync::SyncEngine;-use ente_core::b64;-use ente_core::crypto;-use std::collections::{HashMap, hash_map::Entry};-use std::path::{Path, PathBuf};-use tokio::fs;-use tokio::io::AsyncWriteExt;--#[derive(Debug, Clone)]-struct ExistingFile {- file_path: PathBuf,- meta_path: PathBuf,-}--async fn load_album_metadata(- export_path: &Path,- album_name: &str,-) -> Result<HashMap<i64, ExistingFile>> {- let mut existing_files = HashMap::new();-- let meta_dir = export_path.join(album_name).join(".meta");- if !meta_dir.exists() {- return Ok(existing_files);- }-- let mut entries = match fs::read_dir(&meta_dir).await {- Ok(entries) => entries,- Err(e) => {- log::warn!("Failed to read metadata directory {meta_dir:?}: {e}");- return Ok(existing_files);- }- };-- while let Some(entry) = entries.next_entry().await? {- let meta_path = entry.path();-- if meta_path.extension().is_none_or(|ext| ext != "json") {- continue;- }-- if meta_path- .file_name()- .is_some_and(|name| name == "album_meta.json")- {- continue;- }-- let json_content = match fs::read_to_string(&meta_path).await {- Ok(content) => content,- Err(e) => {- log::warn!("Failed to read metadata file {meta_path:?}: {e}");- continue;- }- };-- let disk_metadata: DiskFileMetadata = match serde_json::from_str(&json_content) {- Ok(metadata) => metadata,- Err(e) => {- log::warn!("Failed to parse metadata file {meta_path:?}: {e}");- continue;- }- };-- for filename in &disk_metadata.info.file_names {- let filename = validate_stored_file_name(filename)?;- let file_path = export_path.join(album_name).join(filename);- if file_path.try_exists()? {- existing_files.insert(- disk_metadata.info.id,- ExistingFile {- file_path,- meta_path: meta_path.clone(),- },- );- break;- }- }- }-- Ok(existing_files)-}--pub async fn run_export(account_email: Option<String>, filter: ExportFilter) -> Result<()> {- let config_dir = crate::utils::get_cli_config_dir()?;- let db_path = config_dir.join("ente.db");- let storage = Storage::new(&db_path)?;-- let accounts = if let Some(email) = account_email {- let all_accounts = storage.accounts().list()?;- log::debug!("Found {} total accounts", all_accounts.len());- let matching: Vec<Account> = all_accounts- .into_iter()- .filter(|a| a.email == email)- .collect();-- if matching.is_empty() {- return Err(crate::Error::NotFound(format!(- "Account not found: {email}"- )));- }- matching- } else {- storage.accounts().list()?- };-- if accounts.is_empty() {- println!("No accounts configured. Use 'ente-rs account add' first.");- return Ok(());- }-- let accounts_to_export: Vec<Account> = if let Some(ref emails) = filter.emails {- if emails.is_empty() {- accounts- } else {- accounts- .into_iter()- .filter(|a| {- let should_export = emails- .iter()- .any(|e| e.eq_ignore_ascii_case(a.email.trim()));- if !should_export {- log::info!("Skip account {}: account is excluded by filter", a.email);- }- should_export- })- .collect()- }- } else {- accounts- };-- if accounts_to_export.is_empty() {- println!("No accounts match the email filter.");- return Ok(());- }-- let mut failures = 0;- for account in accounts_to_export {- println!("\n=== Exporting account: {} ===", account.email);-- println!("Syncing account data...");- if let Err(e) = sync_account_before_export(&storage, &account).await {- log::error!("Failed to sync account {}: {}", account.email, e);- println!("β Sync failed: {e}");- failures += 1;- continue;- }- println!("β Sync completed!");-- if let Err(e) = export_account(&storage, &account, &filter).await {- log::error!("Failed to export account {}: {}", account.email, e);- println!("β Export failed: {e}");- failures += 1;- } else {- println!("β Export completed successfully!");- }- }-- if failures > 0 {- return Err(crate::Error::Generic(format!(- "export failed for {failures} account(s)"- )));- }- Ok(())-}--async fn sync_account_before_export(storage: &Storage, account: &Account) -> Result<()> {- let secrets = storage- .accounts()- .get_secrets(account.user_id, account.app)?- .ok_or_else(|| crate::Error::NotFound("Account secrets not found".into()))?;-- let api_client = AppClient::new(Some(account.endpoint.clone()), account.app)?;-- let token = b64::encode_url_safe(&secrets.token);- api_client.set_token(&token);-- let db_path = storage- .db_path()- .ok_or_else(|| crate::Error::Generic("Database path not available".into()))?;-- let sync_storage = Storage::new(db_path)?;-- let sync_engine = SyncEngine::new(api_client, sync_storage, account.clone());-- let stats = sync_engine.sync().await?;-- log::info!(- "Sync completed: {} new collections, {} new files",- stats.collections.new,- stats.files.new- );-- Ok(())-}--async fn export_account(storage: &Storage, account: &Account, filter: &ExportFilter) -> Result<()> {- 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}");-- fs::create_dir_all(export_path).await?;-- let mut exported_hashes: HashMap<String, PathBuf> = HashMap::new();-- let mut albums_with_metadata: HashMap<String, bool> = HashMap::new();-- let mut album_file_indices: HashMap<String, usize> = HashMap::new();-- let mut album_existing_files: HashMap<String, HashMap<i64, ExistingFile>> = HashMap::new();-- let secrets = storage- .accounts()- .get_secrets(account.user_id, account.app)?- .ok_or_else(|| crate::Error::NotFound("Account secrets not found".into()))?;-- let api_client = AppClient::new(Some(account.endpoint.clone()), account.app)?;-- let token = b64::encode_url_safe(&secrets.token);- api_client.set_token(&token);-- let api = ApiMethods::new(&api_client);-- let master_key = &secrets.master_key;-- let secret_key = &secrets.secret_key;- let public_key = &secrets.public_key;-- println!("\nFetching collections...");- let collections = api.get_collections(0).await?;- println!("Found {} collections", collections.len());-- let mut collection_map: HashMap<i64, (crate::api::models::Collection, Vec<u8>)> =- HashMap::new();-- for mut collection in collections {- if collection.is_deleted {- continue;- }-- let owner_info = if collection.owner.email.is_empty() {- format!("owner_id={}", collection.owner.id)- } else {- format!("owner={}", collection.owner.email)- };-- log::debug!(- "Processing collection {}: name={:?}, encrypted_name={:?}, {}",- collection.id,- collection.name,- collection.encrypted_name,- owner_info- );-- // Owned collection keys use secretbox with the master key.- // Collections shared with us use sealed box.- let collection_key = if let Some(ref key_nonce) = collection.key_decryption_nonce {- match decrypt_collection_key(- &collection.encrypted_key,- key_nonce,- master_key,- secret_key,- ) {- Ok(key) => key,- Err(e) => {- log::error!(- "Failed to decrypt owned collection key for {}: {e}",- collection.id- );- continue;- }- }- } else {- if collection.owner.id == account.user_id {- log::warn!(- "Collection {} owned by current user but missing key_decryption_nonce, skipping",- collection.id- );- continue;- }-- log::info!(- "Collection {} is shared from user {}, using sealed_box decryption",- collection.id,- collection.owner.id- );-- match decrypt_shared_collection_key(&collection.encrypted_key, public_key, secret_key) {- Ok(key) => key,- Err(e) => {- log::error!(- "Failed to decrypt shared collection key for {}: {e}",- collection.id- );- continue;- }- }- };-- if collection.name.as_ref().is_none_or(String::is_empty)- && let Some(ref encrypted_name) = collection.encrypted_name- && let Some(ref nonce) = collection.name_decryption_nonce- {- match decrypt_collection_name(encrypted_name, nonce, &collection_key) {- Ok(name) => {- log::debug!("Decrypted collection {} name: {}", collection.id, name);- collection.name = Some(name);- }- Err(e) => {- log::warn!("Failed to decrypt collection {} name: {}", collection.id, e);- }- }- }-- collection_map.insert(collection.id, (collection, collection_key));- }-- println!("\nFetching all files...");- let mut all_files = Vec::new();-- for collection_id in collection_map.keys() {- let mut has_more = true;- let mut since_time = 0i64;-- while has_more {- let (files, more) = api.get_collection_files(*collection_id, since_time).await?;- has_more = more;-- if files.is_empty() {- break;- }-- for file in &files {- if file.updation_time > since_time {- since_time = file.updation_time;- }- }-- all_files.extend(files);- }- }-- println!("Found {} total files", all_files.len());-- let mut total_files = 0;- let mut exported_files = 0;- let mut skipped_files = 0;- let mut deleted_files = 0;-- for file in all_files {- if file.is_deleted {- deleted_files += 1;- continue;- }-- total_files += 1;-- let Some(collection_info) = collection_map.get(&file.collection_id) else {- log::debug!(- "File {} belongs to unknown/deleted collection {}",- file.id,- file.collection_id- );- continue;- };-- let (collection, collection_key) = collection_info;-- let collection_name = collection.name.as_deref().unwrap_or("Unnamed");-- let is_shared = collection.sharees.as_ref().is_some_and(|s| !s.is_empty())- || collection.shared_magic_metadata.is_some()- || collection.owner.id != account.user_id;-- let is_hidden = check_collection_visibility(collection, collection_key);-- log::debug!(- "Collection {}: name={:?}, is_hidden={}, is_shared={}",- collection.id,- collection.name,- is_hidden,- is_shared- );-- if !filter.should_include_collection(collection_name, is_shared, is_hidden) {- log::debug!("Skipping file in filtered collection: {collection_name}");- continue;- }-- let file_key = match decrypt_file_key(- &file.encrypted_key,- &file.key_decryption_nonce,- collection_key,- ) {- Ok(key) => key,- Err(e) => {- log::error!("Failed to decrypt key for file {}: {}", file.id, e);- continue;- }- };-- let metadata = match decrypt_file_metadata(&file, &file_key) {- Ok(meta) => meta,- Err(e) => {- log::warn!("Failed to decrypt metadata for file {}: {}", file.id, e);- None- }- };-- let pub_magic_metadata = if let Some(pub_magic_metadata) = file.pub_magic_metadata.as_ref()- {- match decrypt_magic_metadata(pub_magic_metadata, &file_key) {- Ok(meta) => meta,- Err(e) => {- log::debug!(- "Failed to decrypt public magic metadata for file {}: {}",- file.id,- e- );- None- }- }- } else {- None- };-- let content_hash = if let Some(ref meta) = metadata {- let hash = match meta.get_file_type() {- crate::models::metadata::FileType::Image => {- meta.image_hash.as_ref().or(meta.hash.as_ref())- }- crate::models::metadata::FileType::Video => {- meta.video_hash.as_ref().or(meta.hash.as_ref())- }- _ => meta.hash.as_ref(),- };- if let Some(h) = hash {- log::debug!("File {} has hash: {}", file.id, h);- } else {- log::debug!("File {} has no hash in metadata", file.id);- }- hash- } else {- log::debug!("File {} has no metadata", file.id);- None- };-- let file_path = generate_export_path(- export_path,- &file,- Some(collection),- metadata.as_ref(),- pub_magic_metadata.as_ref(),- )?;-- let album_folder = if let Some(ref name) = collection.name- && !name.is_empty()- {- sanitize_album_name(name)- } else {- "Uncategorized".to_string()- };-- let existing_files = match album_existing_files.entry(album_folder.clone()) {- Entry::Occupied(entry) => entry.into_mut(),- Entry::Vacant(entry) => {- let existing = load_album_metadata(export_path, entry.key()).await?;- log::debug!(- "Loaded {} existing files for album {}",- existing.len(),- entry.key()- );- entry.insert(existing)- }- };- // Remove current files so only deleted files remain after the loop.- if let Some(existing) = existing_files.remove(&file.id) {- if existing.file_path == file_path {- log::debug!(- "File {} already exists at correct path: {:?}",- file.id,- file_path- );- skipped_files += 1;-- if let Some(hash) = content_hash {- exported_hashes.insert(hash.clone(), file_path.clone());- }- continue;- } else {- log::info!(- "File {} renamed from {:?} to {:?}",- file.id,- existing.file_path,- file_path- );-- if existing.file_path.exists() {- log::debug!("Removing old file: {:?}", existing.file_path);- fs::remove_file(&existing.file_path).await.ok();- }-- let is_live_photo = metadata- .as_ref()- .map(FileMetadata::is_live_photo)- .unwrap_or(false);-- if is_live_photo {- let old_mov_path = existing.file_path.with_extension("MOV");- if old_mov_path.exists() {- log::debug!("Removing old live photo MOV component: {old_mov_path:?}");- fs::remove_file(&old_mov_path).await.ok();- }-- let old_mov_path_lower = existing.file_path.with_extension("mov");- if old_mov_path_lower.exists() && old_mov_path_lower != old_mov_path {- log::debug!(- "Removing old live photo mov component: {old_mov_path_lower:?}"- );- fs::remove_file(&old_mov_path_lower).await.ok();- }- }-- if existing.meta_path.exists() {- log::debug!("Removing old metadata: {:?}", existing.meta_path);- fs::remove_file(&existing.meta_path).await.ok();- }- }- } else if file_path.exists() {- log::debug!("File already exists (not tracked by ID): {file_path:?}");- skipped_files += 1;-- if let Some(hash) = content_hash {- exported_hashes.insert(hash.clone(), file_path.clone());- }- continue;- }-- let need_download = if let Some(hash) = content_hash- && let Some(existing_path) = exported_hashes.get(hash)- && existing_path != &file_path- {- log::info!(- "File {} has same content as {}, copying instead of downloading",- file.id,- existing_path.display()- );-- if let Some(parent) = file_path.parent() {- fs::create_dir_all(parent).await?;- }- fs::copy(existing_path, &file_path).await?;-- let is_live_photo = metadata- .as_ref()- .map(FileMetadata::is_live_photo)- .unwrap_or(false);-- if is_live_photo {- let existing_mov = existing_path.with_extension("MOV");- let new_mov = file_path.with_extension("MOV");- if existing_mov.exists() {- log::debug!(- "Copying live photo MOV component from {existing_mov:?} to {new_mov:?}"- );- fs::copy(&existing_mov, &new_mov).await.ok();- } else {- let existing_mov_lower = existing_path.with_extension("mov");- let new_mov_lower = file_path.with_extension("mov");- if existing_mov_lower.exists() {- log::debug!(- "Copying live photo mov component from {existing_mov_lower:?} to {new_mov_lower:?}"- );- fs::copy(&existing_mov_lower, &new_mov_lower).await.ok();- }- }- }-- false- } else {- true- };-- if need_download {- log::debug!("Downloading file {} to {:?}", file.id, file_path);-- if let Some(parent) = file_path.parent() {- fs::create_dir_all(parent).await?;- }-- let encrypted_data = api.download_file(file.id).await?;-- // The API stores the file header separately from its ciphertext.- let file_nonce = match b64::decode(&file.file.decryption_header) {- Ok(nonce) => nonce,- Err(e) => {- log::error!("Failed to decode file nonce for file {}: {}", file.id, e);- continue;- }- };-- let decrypt_result = crypto::Header::try_from_slice(&file_nonce).and_then(|header| {- crypto::stream::decrypt_file_data(- &encrypted_data,- &header,- &crypto::Key::try_from_slice(&file_key)?,- )- });- let decrypted = match decrypt_result {- Ok(data) => data,- Err(e) => {- log::error!("Failed to decrypt file {}: {}", file.id, e);- log::debug!(- "File size: {}, header length: {}",- encrypted_data.len(),- file_nonce.len()- );- continue;- }- };-- let is_live_photo = metadata- .as_ref()- .map(FileMetadata::is_live_photo)- .unwrap_or(false);-- if is_live_photo {- if let Err(e) = extract_live_photo(&decrypted, &file_path).await {- log::error!("Failed to extract live photo {}: {}", file.id, e);- let mut file_handle = fs::File::create(&file_path).await?;- file_handle.write_all(&decrypted).await?;- file_handle.sync_all().await?;- }- } else {- let mut file_handle = fs::File::create(&file_path).await?;- file_handle.write_all(&decrypted).await?;- file_handle.sync_all().await?;- }- }-- exported_files += 1;-- if let Some(hash) = content_hash {- exported_hashes.insert(hash.clone(), file_path.clone());- }-- if !albums_with_metadata.contains_key(&album_folder) {- write_album_metadata(export_path, &album_folder, collection, account.user_id).await?;- albums_with_metadata.insert(album_folder.clone(), true);- }-- let file_index = album_file_indices.entry(album_folder.clone()).or_insert(0);-- let filename = file_path- .file_name()- .and_then(|n| n.to_str())- .ok_or_else(|| crate::Error::Generic(format!("Invalid file path: {file_path:?}")))?;- write_file_metadata(- export_path,- &album_folder,- &file,- metadata.as_ref(),- filename,- *file_index,- )- .await?;-- *file_index += 1;-- if exported_files % 10 == 0 || exported_files == 1 {- println!(" [{exported_files}/{total_files}] Exported files...");- }- }-- let mut removed_files = 0;- for (album_name, remaining_files) in album_existing_files {- for (file_id, existing_file) in remaining_files {- log::info!(- "Removing deleted file {} from album {}: {:?}",- file_id,- album_name,- existing_file.file_path- );-- if existing_file.file_path.exists() {- if let Err(e) = fs::remove_file(&existing_file.file_path).await {- log::warn!(- "Failed to remove deleted file {:?}: {}",- existing_file.file_path,- e- );- } else {- removed_files += 1;- }- }-- let mov_path = existing_file.file_path.with_extension("MOV");- if mov_path.exists() {- log::debug!("Removing live photo MOV component: {mov_path:?}");- fs::remove_file(&mov_path).await.ok();- }-- let mov_path_lower = existing_file.file_path.with_extension("mov");- if mov_path_lower.exists() && mov_path_lower != mov_path {- log::debug!("Removing live photo mov component: {mov_path_lower:?}");- fs::remove_file(&mov_path_lower).await.ok();- }-- if existing_file.meta_path.exists() {- log::debug!(- "Removing metadata for deleted file: {:?}",- existing_file.meta_path- );- if let Err(e) = fs::remove_file(&existing_file.meta_path).await {- log::warn!(- "Failed to remove metadata {:?}: {}",- existing_file.meta_path,- e- );- }- }- }- }-- if removed_files > 0 {- log::info!("Removed {removed_files} deleted files from disk");- }-- println!("\n{}", "=".repeat(50));- println!("Export Summary:");- println!("{}", "=".repeat(50));- println!(" π Total files (non-deleted): {total_files}");- println!(" β Successfully exported: {exported_files}");-- if skipped_files > 0 {- println!(" βοΈ Skipped (already exists): {skipped_files}");- }-- if deleted_files > 0 {- println!(" ποΈ Deleted files (skipped): {deleted_files}");- }-- if removed_files > 0 {- println!(" π§Ή Removed from disk: {removed_files}");- }-- let failed = total_files - exported_files - skipped_files;- if failed > 0 {- println!(" β Failed to export: {failed}");- }-- if exported_files == total_files {- println!("\nπ All files exported successfully!");- } else if exported_files > 0 {- println!("\nβ¨ Export completed with {exported_files} new files!");- } else if skipped_files == total_files {- println!("\nβ¨ All files already exported!");- }-- Ok(())-}--fn generate_export_path(- export_dir: &Path,- file: &crate::api::models::File,- collection: Option<&crate::api::models::Collection>,- metadata: Option<&FileMetadata>,- pub_magic_metadata: Option<&serde_json::Value>,-) -> Result<PathBuf> {- let mut path = export_dir.to_path_buf();-- let album_folder = if let Some(col) = collection- && let Some(ref name) = col.name- && !name.is_empty()- {- sanitize_album_name(name)- } else {- "Uncategorized".to_string()- };-- path.push(album_folder);-- let filename = {- if let Some(pub_meta) = pub_magic_metadata- && let Some(edited_name) = pub_meta.get("editedName")- && let Some(name_str) = edited_name.as_str()- && !name_str.is_empty()- {- sanitize_filename(name_str)- } else if let Some(meta) = metadata {- if let Some(title) = meta.get_title() {- sanitize_filename(title)- } else {- return Err(crate::Error::Generic(format!(- "File {} has no title in metadata",- file.id- )));- }- } else {- return Err(crate::Error::Generic(format!(- "File {} has no metadata",- file.id- )));- }- };- path.push(filename);-- Ok(path)-}--fn decrypt_collection_key(- encrypted_key: &str,- nonce: &str,- master_key: &[u8],- _secret_key: &[u8],-) -> Result<Vec<u8>> {- let encrypted_bytes = b64::decode(encrypted_key)?;- let nonce_bytes = b64::decode(nonce)?;-- Ok(crypto::secretbox::decrypt(- &encrypted_bytes,- &crypto::Nonce::try_from_slice(&nonce_bytes)?,- &crypto::Key::try_from_slice(master_key)?,- )?)-}--fn decrypt_shared_collection_key(- encrypted_key: &str,- public_key: &[u8],- secret_key: &[u8],-) -> Result<Vec<u8>> {- let encrypted_bytes = b64::decode(encrypted_key)?;-- Ok(crypto::sealed::open(- &encrypted_bytes,- &crypto::PublicKey::try_from_slice(public_key)?,- &crypto::SecretKey::try_from_slice(secret_key)?,- )?)-}--fn decrypt_collection_name(- encrypted_name: &str,- nonce: &str,- collection_key: &[u8],-) -> Result<String> {- let encrypted_bytes = b64::decode(encrypted_name)?;- let nonce_bytes = b64::decode(nonce)?;-- let decrypted = crypto::secretbox::decrypt(- &encrypted_bytes,- &crypto::Nonce::try_from_slice(&nonce_bytes)?,- &crypto::Key::try_from_slice(collection_key)?,- )?;-- String::from_utf8(decrypted)- .map_err(|e| crate::Error::Generic(format!("Invalid UTF-8 in collection name: {e}")))-}--fn decrypt_file_key(encrypted_key: &str, nonce: &str, collection_key: &[u8]) -> Result<Vec<u8>> {- let encrypted_bytes = b64::decode(encrypted_key)?;- let nonce_bytes = b64::decode(nonce)?;-- Ok(crypto::secretbox::decrypt(- &encrypted_bytes,- &crypto::Nonce::try_from_slice(&nonce_bytes)?,- &crypto::Key::try_from_slice(collection_key)?,- )?)-}--// Reduce a sanitized name to one path component, never `.`, `..`, or empty.-fn safe_path_component(name: String) -> String {- let trimmed = name.trim();- if trimmed.is_empty() || trimmed == "." || trimmed == ".." {- "_".to_string()- } else {- trimmed.to_string()- }-}--fn validate_stored_file_name(name: &str) -> Result<&str> {- let path = Path::new(name);- if path.file_name() == Some(path.as_os_str()) {- Ok(name)- } else {- Err(crate::Error::Generic(format!(- "Unsafe filename in export metadata: {name:?}"- )))- }-}--fn sanitize_filename(name: &str) -> String {- let sanitized = name- .chars()- .map(|c| match c {- '/' | '\\' | ':' | '*' | '?' | '"' | '<' | '>' | '|' => '_',- '\0' => '_',- c if c.is_control() => '_',- c => c,- })- .collect::<String>();- safe_path_component(sanitized)-}--fn sanitize_album_name(name: &str) -> String {- let sanitized = name- .chars()- .map(|c| match c {- '/' | '\\' | ':' => '_',- '\0' => '_',- c if c.is_control() => '_',- c => c,- })- .collect::<String>();- safe_path_component(sanitized)-}--fn decrypt_file_metadata(- file: &crate::api::models::File,- file_key: &[u8],-) -> Result<Option<FileMetadata>> {- let Some(encrypted_data) = &file.metadata.encrypted_data else {- return Ok(None);- };- if file.metadata.decryption_header.is_empty() {- return Ok(None);- }-- let encrypted_bytes = b64::decode(encrypted_data)?;- let header_bytes = b64::decode(&file.metadata.decryption_header)?;-- let decrypted = crypto::blob::decrypt(- &encrypted_bytes,- &crypto::Header::try_from_slice(&header_bytes)?,- &crypto::Key::try_from_slice(file_key)?,- )?;-- let metadata: FileMetadata = serde_json::from_slice(&decrypted)?;- Ok(Some(metadata))-}--fn decrypt_magic_metadata(- magic_metadata: &crate::api::models::MagicMetadata,- file_key: &[u8],-) -> Result<Option<serde_json::Value>> {- if magic_metadata.data.is_empty() || magic_metadata.header.is_empty() {- return Ok(None);- }-- let encrypted_bytes = b64::decode(&magic_metadata.data)?;- let header_bytes = b64::decode(&magic_metadata.header)?;-- let decrypted = crypto::blob::decrypt(- &encrypted_bytes,- &crypto::Header::try_from_slice(&header_bytes)?,- &crypto::Key::try_from_slice(file_key)?,- )?;-- let metadata: serde_json::Value = serde_json::from_slice(&decrypted)?;- Ok(Some(metadata))-}--fn check_collection_visibility(- collection: &crate::api::models::Collection,- collection_key: &[u8],-) -> bool {- if let Some(ref magic_metadata) = collection.magic_metadata- && let Ok(Some(decrypted_json)) = decrypt_magic_metadata(magic_metadata, collection_key)- && let Some(visibility) = decrypted_json- .get("visibility")- .and_then(serde_json::Value::as_i64)- {- log::debug!(- "Collection {} has visibility: {} (hidden={})",- collection.id,- visibility,- visibility == 2- );- return visibility == 2;- }-- false-}--async fn write_album_metadata(- export_path: &Path,- album_folder: &str,- collection: &crate::api::models::Collection,- account_id: i64,-) -> Result<()> {- let meta_dir = export_path.join(album_folder).join(".meta");- fs::create_dir_all(&meta_dir).await?;-- let album_meta = AlbumMetadata::new(- collection.id,- collection.owner.id,- collection- .name- .clone()- .unwrap_or_else(|| "Unnamed".to_string()),- account_id,- );-- let meta_path = meta_dir.join("album_meta.json");- let json = serde_json::to_string_pretty(&album_meta)?;- fs::write(meta_path, json).await?;-- Ok(())-}--async fn write_file_metadata(- export_path: &Path,- album_folder: &str,- file: &crate::api::models::File,- metadata: Option<&FileMetadata>,- filename: &str,- file_index: usize,-) -> Result<PathBuf> {- let meta_dir = export_path.join(album_folder).join(".meta");- fs::create_dir_all(&meta_dir).await?;-- let base_name = Path::new(filename)- .file_stem()- .and_then(|s| s.to_str())- .ok_or_else(|| crate::Error::Generic("Invalid filename for metadata".to_string()))?;- let extension = Path::new(filename)- .extension()- .and_then(|s| s.to_str())- .unwrap_or("");-- let meta_filename = format!("{base_name}_{file_index}.{extension}.json");-- let mut disk_metadata = DiskFileMetadata::from_file(file, metadata, filename.to_string());- disk_metadata.meta_file_name = meta_filename.clone();-- let meta_path = meta_dir.join(meta_filename);- let json = serde_json::to_string_pretty(&disk_metadata)?;- fs::write(&meta_path, json).await?;-- Ok(meta_path)-}--#[cfg(test)]-mod tests {- use super::validate_stored_file_name;-- #[test]- fn validates_stored_file_names_without_rewriting() {- assert_eq!(validate_stored_file_name("a*b.jpg").unwrap(), "a*b.jpg");-- for name in [- "",- ".",- "..",- "../photo.jpg",- "album/photo.jpg",- "/photo.jpg",- ] {- assert!(validate_stored_file_name(name).is_err());- }- }-}diff --git a/rust/apps/cli/src/commands/mod.rs b/rust/apps/cli/src/commands/mod.rsdeleted file mode 100644index 4d84f6b5f7..0000000000--- a/rust/apps/cli/src/commands/mod.rs+++ /dev/null@@ -1,6 +0,0 @@-pub mod account;-pub mod export;-pub mod paste;--pub use account::handle_account_command;-pub use paste::handle_paste_command;diff --git a/rust/apps/cli/src/commands/paste.rs b/rust/apps/cli/src/commands/paste.rsdeleted file mode 100644index b20fab76d3..0000000000--- a/rust/apps/cli/src/commands/paste.rs+++ /dev/null@@ -1,358 +0,0 @@-use crate::{- api::client::USER_AGENT,- cli::paste::{PasteCommand, PasteSubcommands},- models::error::{Error, Result},-};-use dialoguer::Password;-use ente_paste::{PasteKey, PasteLink, PastePayload};-use std::ffi::OsStr;-use std::io::{self, IsTerminal, Read};-use std::path::PathBuf;--const PASTE_PASSWORD_ENV: &str = "ENTE_PASTE_PASSWORD";--pub async fn handle_paste_command(cmd: PasteCommand) -> Result<()> {- match cmd.command {- PasteSubcommands::Create {- text,- file,- endpoint,- paste_origin,- password,- } => {- let text = read_paste_text(text, file)?;- let password = if password {- Some(resolve_new_paste_password()?)- } else {- None- };- let client = paste_client(endpoint)?;- let link = client.create(&text, password.as_deref()).await?;- println!("{}", link.url(&paste_origin));- Ok(())- }- PasteSubcommands::Consume {- link_or_token,- raw,- key,- endpoint,- } => {- let link = PasteLink::parse(&link_or_token, key.as_deref())?;- let text = consume_paste(endpoint, &link.access_token, &link.key).await?;- print_consumed_paste(&text, raw);- Ok(())- }- }-}--fn paste_client(endpoint: String) -> Result<ente_paste::Client> {- Ok(ente_paste::Client::new(- endpoint,- Some(USER_AGENT.to_string()),- )?)-}--async fn consume_paste(- endpoint: String,- access_token: &str,- paste_key: &PasteKey,-) -> Result<String> {- consume_paste_with_password_resolver(- endpoint,- access_token,- paste_key,- resolve_paste_password_attempt,- )- .await-}--async fn consume_paste_with_password_resolver<F>(- endpoint: String,- access_token: &str,- paste_key: &PasteKey,- resolve_password: F,-) -> Result<String>-where- F: FnOnce() -> Result<PastePasswordAttempt>,-{- let client = paste_client(endpoint)?;- let password = if paste_key.password_required {- client.check(access_token).await?;- Some(resolve_password()?)- } else {- None- };- let payload = client.consume(access_token).await?;-- match password {- Some(password) => decrypt_password_protected_paste_with_prompt(- paste_key,- &payload,- password,- prompt_raw_paste_password,- ),- None => Ok(ente_paste::decrypt(&payload, paste_key, None)?),- }-}--fn decrypt_password_protected_paste_with_prompt<F>(- paste_key: &PasteKey,- payload: &PastePayload,- password: PastePasswordAttempt,- prompt_password: F,-) -> Result<String>-where- F: FnMut() -> Result<String>,-{- decrypt_password_protected_paste_with(password, prompt_password, |password| {- ente_paste::decrypt(payload, paste_key, Some(password))- })-}--fn decrypt_password_protected_paste_with<F, D>(- mut password: PastePasswordAttempt,- mut prompt_password: F,- mut decrypt: D,-) -> Result<String>-where- F: FnMut() -> Result<String>,- D: FnMut(&str) -> ente_paste::Result<String>,-{- loop {- match decrypt(password.value()) {- Err(ente_paste::Error::IncorrectPassword) if password.can_retry() => {- eprintln!("Incorrect paste password. Try again.");- password = PastePasswordAttempt::Prompted(prompt_valid_paste_password(- &mut prompt_password,- )?);- }- Err(ente_paste::Error::IncorrectPassword) => {- return Err(Error::AuthenticationFailed(- "Incorrect paste password".to_string(),- ));- }- result => return Ok(result?),- }- }-}--fn print_consumed_paste(text: &str, raw: bool) {- if !raw && io::stdout().is_terminal() {- print!("{}", terminal_safe_paste_text(text));- } else {- print!("{text}");- }-}--fn terminal_safe_paste_text(text: &str) -> String {- let mut output = String::with_capacity(text.len());- let mut chars = text.chars().peekable();- while let Some(ch) = chars.next() {- match ch {- '\n' | '\t' => output.push(ch),- '\r' if chars.peek() == Some(&'\n') => {- chars.next();- output.push('\r');- output.push('\n');- }- _ if ch.is_control() => output.extend(ch.escape_default()),- _ => output.push(ch),- }- }- output-}--fn read_paste_text(text: Option<String>, file: Option<PathBuf>) -> Result<String> {- let text = match (text, file) {- (Some(text), None) => text,- (None, Some(path)) if path.as_os_str() == OsStr::new("-") => read_stdin()?,- (None, Some(path)) => std::fs::read_to_string(path)?,- (None, None) if !io::stdin().is_terminal() => read_stdin()?,- (None, None) => {- return Err(Error::InvalidInput(- "Provide text, --file, or pipe text on stdin".to_string(),- ));- }- (Some(_), Some(_)) => unreachable!("clap prevents text and --file together"),- };-- ente_paste::validate_text(&text)?;- Ok(text)-}--fn read_stdin() -> Result<String> {- let mut input = String::new();- io::stdin().read_to_string(&mut input)?;- Ok(input)-}--fn resolve_new_paste_password() -> Result<String> {- match paste_password_from_env()? {- Some(password) => Ok(password),- None => prompt_new_paste_password(),- }-}--fn resolve_paste_password_attempt() -> Result<PastePasswordAttempt> {- match paste_password_from_env()? {- Some(password) => Ok(PastePasswordAttempt::Env(password)),- None => Ok(PastePasswordAttempt::Prompted(prompt_paste_password()?)),- }-}--fn paste_password_from_env() -> Result<Option<String>> {- match std::env::var(PASTE_PASSWORD_ENV) {- Ok(password) => {- validate_password(&password)?;- Ok(Some(password))- }- Err(std::env::VarError::NotPresent) => Ok(None),- Err(error) => Err(Error::InvalidInput(format!(- "{PASTE_PASSWORD_ENV} is not valid Unicode: {error}"- ))),- }-}--fn prompt_new_paste_password() -> Result<String> {- let password = Password::new()- .with_prompt("Paste password")- .with_confirmation("Confirm paste password", "Passwords do not match")- .interact()- .map_err(dialoguer_error)?;- validate_password(&password)?;- Ok(password)-}--fn prompt_paste_password() -> Result<String> {- prompt_valid_paste_password(prompt_raw_paste_password)-}--fn prompt_raw_paste_password() -> Result<String> {- Password::new()- .with_prompt("Paste password")- .interact()- .map_err(dialoguer_error)-}--fn prompt_valid_paste_password<F>(mut prompt_password: F) -> Result<String>-where- F: FnMut() -> Result<String>,-{- loop {- let password = prompt_password()?;- match validate_password(&password) {- Ok(()) => return Ok(password),- Err(error) => eprintln!("{error}"),- }- }-}--fn dialoguer_error(error: dialoguer::Error) -> Error {- match error {- dialoguer::Error::IO(source) => Error::Io(source),- }-}--fn validate_password(password: &str) -> Result<()> {- if password.is_empty() {- Err(Error::InvalidInput(- "Paste password cannot be empty".to_string(),- ))- } else {- Ok(())- }-}--enum PastePasswordAttempt {- Env(String),- Prompted(String),-}--impl PastePasswordAttempt {- fn value(&self) -> &str {- match self {- Self::Env(password) | Self::Prompted(password) => password,- }- }-- fn can_retry(&self) -> bool {- matches!(self, Self::Prompted(_))- }-}--#[cfg(test)]-mod tests {- use super::*;-- fn test_decrypt_password_protected_paste(password: &str) -> ente_paste::Result<String> {- match password {- "correct horse" => Ok("protected paste".to_string()),- _ => Err(ente_paste::Error::IncorrectPassword),- }- }-- #[test]- fn default_tty_output_escapes_controls() {- let text = "ok\n\x1b]52;c;AAAA\x07\rhidden\tend\u{85}";-- assert_eq!(- terminal_safe_paste_text(text),- "ok\n\\u{1b}]52;c;AAAA\\u{7}\\rhidden\tend\\u{85}",- );- }-- #[test]- fn terminal_safe_paste_text_preserves_crlf() {- assert_eq!(terminal_safe_paste_text("one\r\ntwo\r\n"), "one\r\ntwo\r\n");- }-- #[test]- fn terminal_safe_paste_text_preserves_printable_unicode() {- let text = "api key: fran\u{e7}ais \u{1f510}";-- assert_eq!(terminal_safe_paste_text(text), text);- }-- #[test]- fn prompted_password_retry_can_recover() {- let (paste_key, payload) =- ente_paste::encrypt("protected paste", Some("correct horse")).unwrap();- let mut retry_passwords = ["correct horse"].into_iter();- let text = decrypt_password_protected_paste_with_prompt(- &paste_key,- &payload,- PastePasswordAttempt::Prompted("wrong horse".to_string()),- || Ok::<_, Error>(retry_passwords.next().expect("retry password").to_string()),- )- .unwrap();-- assert_eq!(text, "protected paste");- assert_eq!(retry_passwords.next(), None);- }-- #[test]- fn prompted_password_retry_ignores_empty_password() {- let mut retry_passwords = ["", "correct horse"].into_iter();- let text = decrypt_password_protected_paste_with(- PastePasswordAttempt::Prompted("wrong horse".to_string()),- || Ok::<_, Error>(retry_passwords.next().expect("retry password").to_string()),- test_decrypt_password_protected_paste,- )- .unwrap();-- assert_eq!(text, "protected paste");- assert_eq!(retry_passwords.next(), None);- }-- #[test]- fn wrong_env_password_fails_without_retry() {- let error = decrypt_password_protected_paste_with(- PastePasswordAttempt::Env("wrong horse".to_string()),- || panic!("environment passwords must not be retried"),- test_decrypt_password_protected_paste,- )- .unwrap_err();-- assert!(matches!(error, Error::AuthenticationFailed(_)));- }-}diff --git a/rust/apps/cli/src/commands/sync.rs b/rust/apps/cli/src/commands/sync.rsdeleted file mode 100644index affd72bd9f..0000000000--- a/rust/apps/cli/src/commands/sync.rs+++ /dev/null@@ -1,448 +0,0 @@-use crate::Result;-use crate::api::AppClient;-use crate::api::methods::ApiMethods;-use crate::models::{account::Account, metadata::FileMetadata};-use crate::storage::Storage;-use crate::sync::{SyncEngine, SyncStats, download::DownloadManager};-use ente_core::b64;-use ente_core::crypto;-use std::collections::HashMap;-use std::path::{Path, PathBuf};--pub async fn run_sync(- account_email: Option<String>,- metadata_only: bool,- full_sync: bool,-) -> Result<()> {- let config_dir = crate::utils::get_cli_config_dir()?;- let db_path = config_dir.join("ente.db");- let storage = Storage::new(&db_path)?;-- let accounts = if let Some(email) = account_email {- let all_accounts = storage.accounts().list()?;- let matching: Vec<Account> = all_accounts- .into_iter()- .filter(|a| a.email == email)- .collect();-- if matching.is_empty() {- return Err(crate::Error::NotFound(format!(- "Account not found: {email}"- )));- }- matching- } else {- storage.accounts().list()?- };-- if accounts.is_empty() {- println!("No accounts configured. Use 'ente-rs account add' first.");- return Ok(());- }-- for account in accounts {- println!("\n=== Syncing account: {} ===", account.email);-- if let Err(e) = sync_account(&storage, &account, metadata_only, full_sync).await {- log::error!("Failed to sync account {}: {}", account.email, e);- println!("β Sync failed: {e}");- } else {- println!("β Sync completed successfully!");- }- }-- Ok(())-}--async fn sync_account(- storage: &Storage,- account: &Account,- metadata_only: bool,- full_sync: bool,-) -> Result<()> {- let secrets = storage- .accounts()- .get_secrets(account.user_id, account.app)?- .ok_or_else(|| crate::Error::NotFound("Account secrets not found".into()))?;-- let api_client = AppClient::new(Some(account.endpoint.clone()), account.app)?;-- let token = b64::encode_url_safe(&secrets.token);- api_client.set_token(&token);-- if full_sync {- println!("Performing full sync (clearing existing sync state)...");- storage.sync().clear_sync_state(account.user_id)?;- }-- let db_path = storage- .db_path()- .ok_or_else(|| crate::Error::Generic("Database path not available".into()))?;-- let sync_api_client = AppClient::new(Some(account.endpoint.clone()), account.app)?;- sync_api_client.set_token(&token);-- let sync_storage = Storage::new(db_path)?;- let sync_engine = SyncEngine::new(sync_api_client, sync_storage, account.clone());-- println!("Fetching collections and files...");- let stats = sync_engine.sync().await?;-- display_sync_stats(&stats);-- if !metadata_only {- let pending_files = storage.sync().get_pending_downloads(account.user_id)?;-- if !pending_files.is_empty() {- println!("\nπ₯ Found {} files to download", pending_files.len());-- let api = ApiMethods::new(&api_client);- let api_collections = api.get_collections(0).await?;-- let collection_keys = decrypt_collection_keys(- &api_collections,- &secrets.master_key,- &secrets.secret_key,- )?;-- let download_api_client =- AppClient::new(Some(account.endpoint.clone()), account.app)?;- download_api_client.set_token(&token);-- let mut download_manager = DownloadManager::new(download_api_client)?;- download_manager.set_collection_keys(collection_keys);-- let export_dir = if let Some(ref dir) = account.export_dir {- PathBuf::from(dir)- } else {- std::env::current_dir()?.join("ente-export")- };-- let download_tasks = prepare_download_tasks(- &pending_files,- &export_dir,- &api_collections,- &download_manager,- )- .await?;-- let mut already_synced = 0;- let mut to_download = Vec::new();-- for (file, path) in download_tasks {- if path.exists() {- storage- .sync()- .mark_file_synced(file.id, Some(path.to_str().unwrap_or("")))?;- already_synced += 1;- } else {- to_download.push((file, path));- }- }-- 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());-- let download_stats = download_manager.download_files(to_download).await?;-- for (file, path) in &download_stats.successful_downloads {- storage- .sync()- .mark_file_synced(file.id, Some(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");- }- } else {- println!("\nπ Metadata-only sync completed (skipping file downloads)");- }-- Ok(())-}--fn display_sync_stats(stats: &SyncStats) {- println!("\nπ Sync Statistics:");- println!("βββββββββββββββββββββββββββββββββββββββ");- println!("β Collections: β");- println!(- "β Total: {:5} β",- stats.collections.total- );- println!(- "β New: {:5} β",- stats.collections.new- );- println!(- "β Updated: {:5} β",- stats.collections.updated- );- println!("βββββββββββββββββββββββββββββββββββββββ€");- println!("β Files: β");- println!("β Total: {:5} β", stats.files.total);- println!("β New: {:5} β", stats.files.new);- println!(- "β Updated: {:5} β",- stats.files.updated- );- println!("βββββββββββββββββββββββββββββββββββββββ");-}--fn decrypt_collection_keys(- collections: &[crate::api::models::Collection],- master_key: &[u8],- _secret_key: &[u8],-) -> Result<HashMap<i64, Vec<u8>>> {-- let mut keys = HashMap::new();-- for collection in collections {- if collection.is_deleted {- continue;- }-- let encrypted_bytes = b64::decode(&collection.encrypted_key)?;- let nonce_bytes = b64::decode(&collection.key_decryption_nonce)?;-- let decrypted = crypto::Nonce::try_from_slice(&nonce_bytes).and_then(|nonce| {- crypto::secretbox::decrypt(- &encrypted_bytes,- &nonce,- &crypto::Key::try_from_slice(master_key)?,- )- });- match decrypted {- Ok(key) => {- keys.insert(collection.id, key);- }- Err(e) => {- log::warn!(- "Failed to decrypt key for collection {}: {}",- collection.id,- e- );- }- }- }-- Ok(keys)-}--fn sanitize_filename(name: &str) -> String {- name.chars()- .map(|c| match c {- '/' | '\\' | ':' | '*' | '?' | '"' | '<' | '>' | '|' => '_',- '\0' => '_',- c if c.is_control() => '_',- c => c,- })- .collect::<String>()- .trim()- .to_string()-}--async fn prepare_download_tasks(- files: &[crate::models::file::RemoteFile],- export_dir: &Path,- collections: &[crate::api::models::Collection],- download_manager: &DownloadManager,-) -> Result<Vec<(crate::models::file::RemoteFile, PathBuf)>> {- use chrono::{TimeZone, Utc};-- let mut tasks = Vec::new();- let mut seen_hashes: HashMap<String, PathBuf> = HashMap::new();-- let collection_map: HashMap<i64, &crate::api::models::Collection> =- collections.iter().map(|c| (c.id, c)).collect();-- for file in files {- let collection = collection_map.get(&file.collection_id);-- let (metadata, pub_magic_metadata) = if let Some(col_key) =- download_manager.collection_keys.get(&file.collection_id)- {- let file_key = {- let key_bytes = b64::decode(&file.encrypted_key)?;- let nonce = b64::decode(&file.key_decryption_nonce)?;- crypto::secretbox::decrypt(- &key_bytes,- &crypto::Nonce::try_from_slice(&nonce)?,- &crypto::Key::try_from_slice(col_key)?,- )?- };-- let regular_meta = if !file.metadata.encrypted_data.is_empty() {- if !file.metadata.decryption_header.is_empty() {- let encrypted_bytes = b64::decode(&file.metadata.encrypted_data)?;- let header_bytes = b64::decode(&file.metadata.decryption_header)?;-- let decrypted =- crypto::Header::try_from_slice(&header_bytes).and_then(|header| {- crypto::blob::decrypt(- &encrypted_bytes,- &header,- &crypto::Key::try_from_slice(&file_key)?,- )- });- match decrypted {- Ok(decrypted) => serde_json::from_slice::<FileMetadata>(&decrypted).ok(),- Err(e) => {- log::warn!("Failed to decrypt metadata for file {}: {}", file.id, e);- None- }- }- } else {- None- }- } else {- None- };-- let pub_meta = if let Some(ref magic) = file.pub_magic_metadata {- if !magic.data.is_empty() && !magic.header.is_empty() {- let encrypted_bytes = b64::decode(&magic.data)?;- let header_bytes = b64::decode(&magic.header)?;-- let decrypted =- crypto::Header::try_from_slice(&header_bytes).and_then(|header| {- crypto::blob::decrypt(- &encrypted_bytes,- &header,- &crypto::Key::try_from_slice(&file_key)?,- )- });- match decrypted {- Ok(decrypted) => {- serde_json::from_slice::<serde_json::Value>(&decrypted).ok()- }- Err(e) => {- log::debug!(- "Failed to decrypt public magic metadata for file {}: {}",- file.id,- e- );- None- }- }- } else {- None- }- } else {- None- };-- (regular_meta, pub_meta)- } else {- (None, None)- };-- let mut path = export_dir.to_path_buf();-- let datetime = Utc- .timestamp_micros(file.updated_at)- .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();-- path.push(year);- path.push(month);-- if let Some(col) = collection- && let Some(ref name) = col.name- && !name.is_empty()- && name != "Uncategorized"- {- let safe_name: String = name- .chars()- .map(|c| match c {- '/' | '\\' | ':' | '*' | '?' | '"' | '<' | '>' | '|' => '_',- c if c.is_control() => '_',- c => c,- })- .collect();- path.push(safe_name.trim());- }-- let filename = {- let base_name = if let Some(ref pub_meta) = pub_magic_metadata- && let Some(edited_name) = pub_meta.get("editedName")- && let Some(name_str) = edited_name.as_str()- && !name_str.is_empty()- {- sanitize_filename(name_str)- } else if let Some(ref meta) = metadata {- if let Some(title) = meta.get_title() {- sanitize_filename(title)- } else {- log::error!("File {} has no title in metadata", file.id);- continue;- }- } else {- log::error!("File {} has no metadata", file.id);- continue;- };-- if let Some(ref meta) = metadata {- if meta.is_live_photo() && !base_name.to_lowercase().ends_with(".zip") {- if let Some(pos) = base_name.rfind('.') {- format!("{}.zip", &base_name[..pos])- } else {- format!("{}.zip", base_name)- }- } else {- base_name- }- } else {- base_name- }- };-- path.push(filename);-- let content_hash = if let Some(ref meta) = metadata {- match meta.get_file_type() {- crate::models::metadata::FileType::Image => {- meta.image_hash.as_ref().or(meta.hash.as_ref())- }- crate::models::metadata::FileType::Video => {- meta.video_hash.as_ref().or(meta.hash.as_ref())- }- _ => meta.hash.as_ref(),- }- } else {- None- };-- if let Some(hash) = content_hash {- if let Some(existing_path) = seen_hashes.get(hash) {- log::info!(- "Skipping duplicate file {} (same hash as {})",- file.id,- existing_path.display()- );- continue;- }- seen_hashes.insert(hash.clone(), path.clone());- }-- tasks.push((file.clone(), path));- }-- Ok(tasks)-}diff --git a/rust/apps/cli-next/src/core_db.rs b/rust/apps/cli/src/core_db.rssimilarity index 100%rename from rust/apps/cli-next/src/core_db.rsrename to rust/apps/cli/src/core_db.rsdiff --git a/rust/apps/cli-next/src/db.rs b/rust/apps/cli/src/db.rssimilarity index 100%rename from rust/apps/cli-next/src/db.rsrename to rust/apps/cli/src/db.rsdiff --git a/rust/apps/cli-next/src/home.rs b/rust/apps/cli/src/home.rssimilarity index 100%rename from rust/apps/cli-next/src/home.rsrename to rust/apps/cli/src/home.rsdiff --git a/rust/apps/cli/src/lib.rs b/rust/apps/cli/src/lib.rsdeleted file mode 100644index 5688297689..0000000000--- a/rust/apps/cli/src/lib.rs+++ /dev/null@@ -1,10 +0,0 @@-pub mod api;-pub mod cli;-pub mod commands;-mod live_photo;-pub mod models;-pub mod storage;-pub mod sync;-pub mod utils;--pub use models::error::{Error, Result};diff --git a/rust/apps/cli/src/live_photo.rs b/rust/apps/cli/src/live_photo.rsdeleted file mode 100644index 147df7a6a8..0000000000--- a/rust/apps/cli/src/live_photo.rs+++ /dev/null@@ -1,228 +0,0 @@-use std::io::{Cursor, Read};-use std::path::Path;--use tokio::fs;-use tokio::io::AsyncWriteExt;-use zip::ZipArchive;--use crate::{Error, Result};--const MAX_EXPANDED_RATIO: u64 = 20;-const MAX_EXPANDED_OVERHEAD: u64 = 16 * 1024 * 1024;--struct Entry {- index: usize,- extension: String,- size: u64,-}--pub(crate) async fn extract_live_photo(zip_data: &[u8], output_path: &Path) -> Result<()> {- let mut archive = ZipArchive::new(Cursor::new(zip_data))?;- if archive.len() != 2 {- return Err(Error::Generic(- "Live photo ZIP must contain one image and one video".into(),- ));- }-- let mut image = None;- let mut video = None;- for index in 0..archive.len() {- let file = archive.by_index(index)?;- let name = file.name()?;- let (kind, extension) = parse_entry_name(&name)?;- let entry = Entry {- index,- extension: extension.to_string(),- size: file.size(),- };- let slot = if kind == "image" {- &mut image- } else {- &mut video- };- if slot.replace(entry).is_some() {- return Err(Error::Generic(format!(- "Live photo ZIP contains multiple {kind} entries"- )));- }- }-- let image = image.ok_or_else(|| Error::Generic("Live photo ZIP has no image".into()))?;- let video = video.ok_or_else(|| Error::Generic("Live photo ZIP has no video".into()))?;- let max_expanded = zip_data.len() as u64 * MAX_EXPANDED_RATIO + MAX_EXPANDED_OVERHEAD;- if image.size + video.size > max_expanded {- return Err(Error::Generic("Live photo ZIP expands beyond limit".into()));- }-- let parent = output_path- .parent()- .ok_or_else(|| Error::Generic("Invalid output path".into()))?;- let base = output_path- .file_stem()- .and_then(|name| name.to_str())- .ok_or_else(|| Error::Generic("Invalid filename".into()))?;- let mut expanded = 0;- let mut buffer = vec![0; 64 * 1024];- for entry in [image, video] {- let mut input = archive.by_index(entry.index)?;- let path = parent.join(format!("{base}.{}", entry.extension));- let mut output = fs::File::create(&path).await?;- loop {- let count = input.read(&mut buffer)?;- if count == 0 {- break;- }- expanded += count as u64;- if expanded > max_expanded {- return Err(Error::Generic("Live photo ZIP expands beyond limit".into()));- }- output.write_all(&buffer[..count]).await?;- }- output.sync_all().await?;- log::debug!("Extracted live photo component: {path:?}");- }- Ok(())-}--fn parse_entry_name(name: &str) -> Result<(&str, &str)> {- let (kind, extension) = name- .split_once('.')- .ok_or_else(|| Error::Generic(format!("Invalid live photo entry: {name}")))?;- if !matches!(kind, "image" | "video")- || extension.is_empty()- || extension.len() > 16- || !extension.bytes().all(|byte| byte.is_ascii_alphanumeric())- {- return Err(Error::Generic(format!("Invalid live photo entry: {name}")));- }- Ok((kind, extension))-}--#[cfg(test)]-mod tests {- use std::io::{Cursor, Write};- use std::path::Path;-- use ente_core::{b64, crypto};- use mockito::Server;- use zip::{CompressionMethod, ZipWriter, write::SimpleFileOptions};-- use super::{extract_live_photo, parse_entry_name};- use crate::api::client::AppClient;- use crate::models::{account::App, file::RemoteFile};- use crate::sync::DownloadManager;-- fn archive(entries: &[(&str, &[u8])], compression: CompressionMethod) -> Vec<u8> {- let mut writer = ZipWriter::new(Cursor::new(Vec::new()));- for (name, data) in entries {- writer- .start_file(- *name,- SimpleFileOptions::default().compression_method(compression),- )- .unwrap();- writer.write_all(data).unwrap();- }- writer.finish().unwrap().into_inner()- }-- #[test]- fn validates_entry_names() {- assert_eq!(parse_entry_name("image.heic").unwrap(), ("image", "heic"));- assert_eq!(parse_entry_name("video.mov").unwrap(), ("video", "mov"));- assert!(parse_entry_name("thumbnail.jpg").is_err());- assert!(parse_entry_name("image.jpg.exe").is_err());- assert!(parse_entry_name("video../clip").is_err());- }-- #[tokio::test]- async fn extracts_stored_and_deflated_components() {- for compression in [CompressionMethod::Stored, CompressionMethod::Deflated] {- let data = archive(- &[("image.jpg", b"image"), ("video.mov", b"video")],- compression,- );- let directory =- std::env::temp_dir().join(format!("ente-live-photo-test-{}", uuid::Uuid::new_v4()));- std::fs::create_dir(&directory).unwrap();-- extract_live_photo(&data, &directory.join("photo.zip"))- .await- .unwrap();- assert_eq!(- std::fs::read(directory.join("photo.jpg")).unwrap(),- b"image"- );- assert_eq!(- std::fs::read(directory.join("photo.mov")).unwrap(),- b"video"- );-- std::fs::remove_dir_all(directory).unwrap();- }- }-- #[tokio::test]- async fn download_preserves_invalid_live_photo_archive() {- let data = archive(&[("image.jpg", b"image")], CompressionMethod::Deflated);- let collection_key = crypto::Key::generate();- let file_key = crypto::Key::generate();- let encrypted_key = crypto::secretbox::encrypt(file_key.as_bytes(), &collection_key);- let mut encrypted_data = Vec::new();- let header =- crypto::stream::encrypt_file(&mut data.as_slice(), &mut encrypted_data, &file_key)- .unwrap();- let file_id = uuid::Uuid::new_v4().as_u64_pair().0 as i64;- let file: RemoteFile = serde_json::from_value(serde_json::json!({- "id": file_id,- "collectionID": 1,- "ownerID": 1,- "encryptedKey": b64::encode(&encrypted_key.encrypted_data),- "keyDecryptionNonce": b64::encode(encrypted_key.nonce.as_bytes()),- "file": { "decryptionHeader": b64::encode(header.as_bytes()) },- "thumbnail": { "decryptionHeader": "" },- "metadata": { "encryptedData": "", "decryptionHeader": "" },- "isDeleted": false,- "updatedAt": 0- }))- .unwrap();- let mut server = Server::new_async().await;- let url_mock = server- .mock("GET", format!("/files/download/v3/{file_id}").as_str())- .with_body(serde_json::json!({ "url": format!("{}/object", server.url()) }).to_string())- .create_async()- .await;- let download_mock = server- .mock("GET", "/object")- .with_body(encrypted_data)- .create_async()- .await;- let client = AppClient::new(Some(server.url()), App::Photos).unwrap();- let mut manager = DownloadManager::new(client).unwrap();- manager.set_collection_keys([(1, collection_key.as_bytes().to_vec())].into());- let directory =- std::env::temp_dir().join(format!("ente-live-photo-test-{}", uuid::Uuid::new_v4()));- let destination = directory.join("photo.zip");-- manager.download_file(&file, &destination).await.unwrap();-- url_mock.assert_async().await;- download_mock.assert_async().await;- assert_eq!(std::fs::read(destination).unwrap(), data);- std::fs::remove_dir_all(directory).unwrap();- }-- #[tokio::test]- async fn rejects_excessive_expansion() {- let oversized = vec![0; super::MAX_EXPANDED_OVERHEAD as usize + 1024 * 1024];- let data = archive(- &[("image.jpg", &oversized), ("video.mov", b"video")],- CompressionMethod::Deflated,- );- assert!(- extract_live_photo(&data, Path::new("photo.zip"))- .await- .is_err()- );- }-}diff --git a/rust/apps/cli-next/src/login.rs b/rust/apps/cli/src/login.rssimilarity index 100%rename from rust/apps/cli-next/src/login.rsrename to rust/apps/cli/src/login.rsdiff --git a/rust/apps/cli/src/main.rs b/rust/apps/cli/src/main.rsindex 70198a484c..643a032183 100644--- a/rust/apps/cli/src/main.rs+++ b/rust/apps/cli/src/main.rs@@ -1,51 +1,398 @@-use clap::Parser;-use ente_rs::{- Result,- cli::{Cli, Commands},- commands,- storage::Storage,+mod account;+mod admin;+mod api;+mod args;+mod auth;+mod core_db;+mod db;+mod home;+mod login;+mod migration;+mod output;+mod password;+mod paste;+mod photos;+mod vault;++use std::{+ io::{Read, Write},+ path::Path,};+use anyhow::{Context, Result, bail, ensure};+use clap::FromArgMatches;+use ente_core::{b64, crypto::Key};+use serde::de::DeserializeOwned;+use serde_json::json;+use zeroize::Zeroizing;++use args::{AccountCommand, App, Cli, Command, KeyCommand, LockerCommand, Options, VaultCommand};+use output::AccountView;+use vault::{Account, State, Vault};+#[tokio::main]async fn main() {- if let Err(e) = run().await {- eprintln!("{}", ente_core::error::chain(&e));+ env_logger::Builder::from_env(env_logger::Env::default().default_filter_or("warn"))+ .format(|out, record| writeln!(out, "{}", record.args()))+ .init();+ let mut command = args::command();+ let arguments: Vec<_> = std::env::args_os().collect();+ let matches = command+ .try_get_matches_from_mut(&arguments)+ .unwrap_or_else(|mut error| {+ migration::hint(&command, &arguments, &mut error);+ error.exit()+ });+ let result = if let Some(help) = matches.subcommand_matches("help") {+ command.build();+ print_help(&mut command, help, &mut std::io::stdout().lock())+ } else {+ let cli = Cli::from_arg_matches(&matches)+ .unwrap_or_else(|error| error.format(&mut command).exit());+ run(cli).await+ };+ if let Err(error) = result {+ eprintln!("Error: {error:#}");std::process::exit(1);}}-async fn run() -> Result<()> {- env_logger::init();-- let config_dir = ente_rs::utils::get_cli_config_dir()?;- let db_path = config_dir.join("ente.db");- let storage = Storage::new(&db_path)?;+fn print_help(+ command: &mut clap::Command,+ mut matches: &clap::ArgMatches,+ output: &mut impl Write,+) -> Result<()> {+ if matches.get_flag("all") {+ if matches.subcommand_name().is_some() {+ command+ .find_subcommand_mut("help")+ .context("missing help command")?+ .error(+ clap::error::ErrorKind::ArgumentConflict,+ "help --all cannot be combined with a command or topic",+ )+ .exit();+ }+ return print_all_help(command, output);+ }+ if matches.subcommand_name() == Some("migration") {+ return migration::print(+ command.get_bin_name().unwrap_or_else(|| command.get_name()),+ output,+ );+ }+ let mut target = command;+ while let Some((name, child)) = matches.subcommand() {+ target = target+ .find_subcommand_mut(name)+ .context("unknown help command")?;+ matches = child;+ }+ write!(output, "{}", target.render_long_help())?;+ Ok(())+}- let cli = Cli::parse();+fn print_all_help(command: &mut clap::Command, output: &mut impl Write) -> Result<()> {+ writeln!(+ output,+ "=== {} ===",+ command.get_bin_name().unwrap_or_else(|| command.get_name())+ )?;+ writeln!(output, "{}", command.render_long_help())?;+ let mut children: Vec<_> = command+ .get_subcommands_mut()+ .filter(|child| !child.is_hide_set() && child.get_name() != "help")+ .collect();+ children.sort_by(|a, b| {+ (a.get_display_order(), a.get_name()).cmp(&(b.get_display_order(), b.get_name()))+ });+ for child in children {+ print_all_help(child, output)?;+ }+ Ok(())+}- match cli.command {- Commands::Version => {- println!("ente-rs version {}", ente_rs::cli::version::VERSION);+async fn run(cli: Cli) -> Result<()> {+ let Cli { options, command } = cli;+ match command {+ Command::Photos { selector, command } => {+ photos::run(command, selector.account.as_deref(), &options).await+ }+ Command::Locker {+ selector,+ command: LockerCommand::Api(args),+ } => api::run(App::Locker, args, selector.account.as_deref(), &options).await,+ Command::Auth { selector, command } => {+ auth::run(command, selector.account.as_deref(), &options).await}- Commands::Account(account_cmd) => {- commands::account::handle_account_command(account_cmd, &storage).await?;+ Command::Paste { command } => paste::run(command, &options).await,+ Command::Account { command } => account_command(command, &options).await,+ Command::Vault {+ command:+ VaultCommand::Key {+ command: KeyCommand::Generate,+ },+ } => vault_key(options.json),+ Command::Completion { shell } => {+ let mut command = args::command();+ let name = command.get_name().to_owned();+ clap_complete::generate(shell, &mut command, name, &mut std::io::stdout().lock());+ Ok(())}- Commands::Export(export_cmd) => {- use ente_rs::models::filter::ExportFilter;+ Command::Admin {+ selector,+ app,+ command,+ } => admin::run(command, selector.account.as_deref(), app, &options).await,+ }+}- let filter = ExportFilter {- include_shared: export_cmd.shared,- include_hidden: export_cmd.hidden,- albums: export_cmd.albums,- emails: export_cmd.emails,- };+fn vault_key(json_output: bool) -> Result<()> {+ let key = Zeroizing::new(b64::encode(Key::generate().as_bytes()));+ if json_output {+ output::json(&json!({ "key": key.as_str() }))+ } else {+ writeln!(std::io::stdout(), "{}", key.as_str()).map_err(Into::into)+ }+}- commands::export::run_export(export_cmd.account, filter).await?;+async fn account_command(command: AccountCommand, options: &Options) -> Result<()> {+ match command {+ AccountCommand::RequestOtp {+ email,+ app,+ host,+ purpose,+ } => account::request_otp(email, app, host, purpose, options).await,+ AccountCommand::Create(args) => {+ let app = args.app;+ let (state, index) = account::create(args, options).await?;+ let account = AccountView::new(&state.accounts[index], state.selected);+ output::action(+ options.json,+ &json!({"account": account, "app": app}),+ &format!(+ "Created {} and signed into {}.",+ output::escape_controls(&state.accounts[index].name),+ app.display_name()+ ),+ )+ }+ AccountCommand::Totp {+ selector,+ app,+ command,+ } => account::totp(command, selector.account.as_deref(), app, options).await,+ AccountCommand::RecoveryKey { name } => {+ let state = State::load()?;+ let account = &state.accounts[state.resolve(name.as_deref())?];+ let key = Zeroizing::new(ente_accounts::auth::recovery_key_to_mnemonic(+ &account.identity.recovery_key,+ )?);+ if options.json {+ output::json(&json!({"recoveryKey": key.as_str()}))+ } else {+ writeln!(std::io::stdout(), "{}", key.as_str()).map_err(Into::into)+ }+ }+ AccountCommand::Login(args) => {+ ensure!(!options.offline, "login requires network access");+ let app = args.app;+ let (state, index) = login::login(args, options).await?;+ let account = AccountView::new(&state.accounts[index], state.selected);+ if options.json {+ output::json(&json!({ "account": account, "app": app }))+ } else {+ output::account(&account)+ }+ }+ AccountCommand::List => {+ let state = State::load()?;+ let accounts: Vec<_> = state+ .accounts+ .iter()+ .map(|a| AccountView::new(a, state.selected))+ .collect();+ if options.json {+ output::json(&accounts)+ } else {+ output::accounts(&accounts)+ }+ }+ AccountCommand::View { name } => {+ let state = State::load()?;+ let index = state.resolve(name.as_deref())?;+ output_account(state, index, options.json)}- Commands::Paste(paste_cmd) => {- commands::paste::handle_paste_command(paste_cmd).await?;+ AccountCommand::Token { name, app } => {+ let state = State::load()?;+ let index = state.resolve(name.as_deref())?;+ let token = Zeroizing::new(b64::encode_url_safe(state.accounts[index].token(app)?));+ if options.json {+ output::json(&json!({ "token": token.as_str() }))+ } else {+ writeln!(std::io::stdout(), "{}", token.as_str()).map_err(Into::into)+ }+ }+ AccountCommand::Switch { name } => {+ let mut vault = Vault::open()?;+ let state = &mut vault.state;+ let index = state.named(&name)?;+ let selected = Some(state.accounts[index].storage_id);+ if state.selected != selected {+ state.selected = selected;+ vault.save()?;+ }+ output_account(vault.into_state(), index, options.json)+ }+ AccountCommand::Rename { name, new_name } => {+ let mut vault = Vault::open()?;+ let state = &mut vault.state;+ let (index, new_name) = match new_name {+ Some(new_name) => (state.named(&name)?, new_name),+ None => (state.resolve(None)?, name),+ };+ if state.accounts[index].name != new_name {+ state.check_name(&new_name)?;+ state.accounts[index].name = new_name;+ vault.save()?;+ }+ output_account(vault.into_state(), index, options.json)+ }+ AccountCommand::Logout { name, app, local } => {+ ensure!(+ !options.offline || local,+ "logging out on the server requires network access; use --local to forget the account on this device"+ );+ let mut vault = Vault::open()?;+ let index = vault.state.resolve(name.as_deref())?;+ let account = &vault.state.accounts[index];+ let name = account.name.clone();+ let apps = match app {+ Some(app) => vec![app],+ None => account.sessions.keys().copied().collect(),+ };+ let home = home::try_lock_account(account.storage_id)?;+ let removal = if account+ .sessions+ .keys()+ .all(|saved| app.is_none_or(|app| *saved == app))+ {+ Some(home.for_removal()?)+ } else {+ None+ };+ if !local {+ for (completed, app) in apps.iter().enumerate() {+ if let Err(error) = api::logout(&vault.state.accounts[index], *app).await {+ if completed > 0 {+ vault.save()?;+ }+ let remaining = vault.state.accounts[index]+ .sessions+ .keys()+ .copied()+ .collect::<Vec<_>>();+ bail!(+ "cannot log out of {} for {name:?}: {error:#}. Still logged in: {}. Retry when the server is reachable, or use --local to forget the account on this device.",+ app.display_name(),+ app_names(&remaining),+ );+ }+ vault.state.accounts[index].sessions.remove(app);+ }+ } else {+ vault.state.accounts[index].sessions.clear();+ }+ let removed = vault.state.accounts[index]+ .sessions+ .is_empty()+ .then(|| remove_account(&mut vault.state, index));+ vault.save()?;+ if let Some(removal) = removal {+ removal.remove()?;+ }+ let state = vault.into_state();+ let account = AccountView::new(+ removed.as_ref().unwrap_or_else(|| &state.accounts[index]),+ state.selected,+ );+ let message = if removed.is_none() {+ format!("Logged out of {} for {name:?}.", app_names(&apps))+ } else if local && !apps.is_empty() {+ format!("Removed account {name:?} from this device. Server logout was skipped.")+ } else if apps.is_empty() {+ format!("Removed account {name:?} from this device.")+ } else {+ format!(+ "Logged out of {}. Removed account {name:?} from this device.",+ app_names(&apps)+ )+ };+ let result = match app {+ Some(app) => json!({ "account": account, "app": app, "remoteLogout": !local }),+ None => json!({ "account": account, "apps": apps, "remoteLogout": !local }),+ };+ output::action(options.json, &result, &message)}}+}- Ok(())+fn remove_account(state: &mut State, index: usize) -> Account {+ let account = state.accounts.remove(index);+ if state.selected == Some(account.storage_id) {+ state.selected = None;+ }+ account+}++fn app_names(apps: &[App]) -> String {+ let names = apps+ .iter()+ .map(|app| app.display_name())+ .collect::<Vec<_>>();+ match names.as_slice() {+ [] => String::new(),+ [name] => (*name).to_owned(),+ [first, second] => format!("{first} and {second}"),+ [first, middle @ .., last] => {+ format!("{first}, {}, and {last}", middle.join(", "))+ }+ }+}++fn output_account(state: State, index: usize, json_output: bool) -> Result<()> {+ let account = AccountView::new(&state.accounts[index], state.selected);+ if json_output {+ output::json(&account)+ } else {+ output::account(&account)+ }+}++fn read_input(path: &Path, limit: u64) -> Result<Zeroizing<Vec<u8>>> {+ let mut bytes = Zeroizing::new(Vec::new());+ if path == Path::new("-") {+ std::io::stdin()+ .take(limit)+ .read_to_end(&mut bytes)+ .context("cannot read stdin")?;+ } else {+ std::fs::File::open(path)+ .with_context(|| format!("cannot open {}", path.display()))?+ .take(limit)+ .read_to_end(&mut bytes)+ .with_context(|| format!("cannot read {}", path.display()))?;+ }+ Ok(bytes)+}++fn parse_json<T: DeserializeOwned>(bytes: &[u8]) -> Result<T> {+ serde_json::from_slice(bytes).map_err(|error| {+ anyhow::anyhow!(+ "invalid JSON at line {}, column {}",+ error.line(),+ error.column()+ )+ })}diff --git a/rust/apps/cli-next/src/migration.rs b/rust/apps/cli/src/migration.rssimilarity index 99%rename from rust/apps/cli-next/src/migration.rsrename to rust/apps/cli/src/migration.rsindex 434ccc9153..24f106c5bc 100644--- a/rust/apps/cli-next/src/migration.rs+++ b/rust/apps/cli/src/migration.rs@@ -234,8 +234,8 @@ Log in again with {binary} account login; old saved logins and config.yaml are nAPP is photos, auth or locker. NAME is a local account name.Choose the server with --host on login or creation; later commands use the saved server.Use the same app and server when requesting an email code and completing login or creation.-ENTE_CLI_HOME replaces ENTE_CLI_CONFIG_DIR for choosing this CLI's local storage.-For unattended access, see {binary} vault --help for ENTE_CLI_VAULT_KEY.+ENTE_CLI_HOME replaces ENTE_CLI_CONFIG_DIR for choosing this CLI's storage folder.+See {binary} vault --help for default locations and unattended access with ENTE_CLI_VAULT_KEY.Admin commands use --account NAME instead of --admin-user/-a; USER is positional.Use --json for structured results. Old output formats are not preserved.")?;diff --git a/rust/apps/cli/src/models/account.rs b/rust/apps/cli/src/models/account.rsdeleted file mode 100644index e16d8cf0bc..0000000000--- a/rust/apps/cli/src/models/account.rs+++ /dev/null@@ -1,62 +0,0 @@-pub use ente_accounts::AccountSecrets;-use serde::{Deserialize, Serialize};-use std::{fmt, str::FromStr};--#[derive(Debug, Clone, Serialize, Deserialize)]-pub struct Account {- pub user_id: i64,- pub email: String,- pub app: App,- pub endpoint: String,- pub export_dir: Option<String>,-}--#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]-#[serde(rename_all = "lowercase")]-pub enum App {- Photos,- Locker,- Auth,-}--impl App {- pub fn client_package(&self) -> &'static str {- match self {- App::Photos => "io.ente.photos",- App::Locker => "io.ente.locker",- App::Auth => "io.ente.auth",- }- }-}--impl fmt::Display for App {- fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {- let value = match self {- App::Photos => "photos",- App::Locker => "locker",- App::Auth => "auth",- };- write!(f, "{value}")- }-}--impl FromStr for App {- type Err = String;-- fn from_str(value: &str) -> std::result::Result<Self, Self::Err> {- match value.trim().to_ascii_lowercase().as_str() {- "photos" => Ok(App::Photos),- "locker" => Ok(App::Locker),- "auth" => Ok(App::Auth),- other => Err(format!(- "Invalid app: {other}. Must be one of: photos, locker, auth"- )),- }- }-}--impl Account {- pub fn account_key(&self) -> String {- format!("{}:{}", self.email, self.app.client_package())- }-}diff --git a/rust/apps/cli/src/models/collection.rs b/rust/apps/cli/src/models/collection.rsdeleted file mode 100644index f152f18488..0000000000--- a/rust/apps/cli/src/models/collection.rs+++ /dev/null@@ -1,54 +0,0 @@-use serde::{Deserialize, Serialize};--#[derive(Debug, Clone, Serialize, Deserialize)]-pub struct Collection {- pub id: i64,- pub owner: i64,- pub key: String,- pub name: String,- #[serde(rename = "type")]- pub collection_type: CollectionType,- pub attributes: Option<CollectionAttributes>,- #[serde(rename = "sharees")]- pub sharees: Option<Vec<Sharee>>,- #[serde(rename = "publicURLs")]- pub public_urls: Option<Vec<PublicURL>>,- #[serde(rename = "updatedAt")]- pub updated_at: i64,- #[serde(rename = "isDeleted")]- pub is_deleted: bool,-}--#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]-pub enum CollectionType {- #[serde(rename = "folder")]- Folder,- #[serde(rename = "favorites")]- Favorites,- #[serde(rename = "album")]- Album,-}--#[derive(Debug, Clone, Serialize, Deserialize)]-pub struct CollectionAttributes {- #[serde(rename = "encryptedPath")]- pub encrypted_path: Option<String>,- #[serde(rename = "pathDecryptionNonce")]- pub path_decryption_nonce: Option<String>,-}--#[derive(Debug, Clone, Serialize, Deserialize)]-pub struct Sharee {- pub id: i64,- pub email: String,- pub role: String,-}--#[derive(Debug, Clone, Serialize, Deserialize)]-pub struct PublicURL {- pub url: String,- #[serde(rename = "deviceLimit")]- pub device_limit: i32,- #[serde(rename = "validTill")]- pub valid_till: i64,-}diff --git a/rust/apps/cli/src/models/error.rs b/rust/apps/cli/src/models/error.rsdeleted file mode 100644index 4117cc8bef..0000000000--- a/rust/apps/cli/src/models/error.rs+++ /dev/null@@ -1,96 +0,0 @@-use ente_core::{b64, crypto};-use thiserror::Error;--#[derive(Error, Debug)]-pub enum Error {- #[error("IO error: {0}")]- Io(#[from] std::io::Error),-- #[error("System clock error: {0}")]- SystemTime(#[from] std::time::SystemTimeError),-- #[error("Serialization error: {0}")]- Serialization(#[from] serde_json::Error),-- #[error("Database error: {0}")]- Database(#[from] rusqlite::Error),-- #[error("Crypto error: {0}")]- Crypto(String),-- #[error("Authentication failed: {0}")]- AuthenticationFailed(String),-- #[error("Invalid configuration: {0}")]- InvalidConfig(String),-- #[error("Not found: {0}")]- NotFound(String),-- #[error("Invalid input: {0}")]- InvalidInput(String),-- #[error("SRP error: {0}")]- Srp(String),-- #[error("Base64 decode error: {0}")]- Base64Decode(#[from] b64::DecodeError),-- #[error("ZIP error: {0}")]- Zip(#[from] zip::result::ZipError),-- #[error(transparent)]- Http(#[from] ente_core::http::Error),-- #[error(transparent)]- Accounts(#[from] ente_accounts::Error),-- #[error("{0}")]- Generic(String),-}--impl From<ente_paste::Error> for Error {- fn from(err: ente_paste::Error) -> Self {- use ente_paste::Error as E;- match err {- E::Http(source) => Error::Http(source),- E::Crypto(source) => Error::from(source),- E::IncorrectPassword => {- Error::AuthenticationFailed("Incorrect paste password".to_string())- }- E::Unavailable => {- Error::Generic("This paste has expired or was already opened.".to_string())- }- E::EmptyText => Error::InvalidInput("Paste text cannot be empty".to_string()),- E::TextTooLong => Error::InvalidInput(format!(- "Paste is limited to {} characters",- ente_paste::MAX_PASTE_CHARS- )),- E::InvalidLink => {- Error::InvalidInput("Paste URL or access token is invalid".to_string())- }- E::InvalidAccessToken => Error::InvalidInput("Invalid paste access token".to_string()),- E::InvalidKey => Error::InvalidInput("Invalid paste key".to_string()),- E::MissingKey => {- Error::InvalidInput("Paste key missing. Pass a full paste URL or --key".to_string())- }- E::KeyMismatch => {- Error::InvalidInput("Paste URL fragment and --key do not match".to_string())- }- E::PasswordRequired => Error::InvalidInput("Paste password is required".to_string()),- E::SessionNotOpen => Error::Generic("Paste is not open".to_string()),- other => Error::Generic(other.to_string()),- }- }-}--impl From<crypto::Error> for Error {- fn from(err: crypto::Error) -> Self {- match err {- crypto::Error::Io(source) => Error::Io(source),- other => Error::Crypto(other.to_string()),- }- }-}--pub type Result<T> = std::result::Result<T, Error>;diff --git a/rust/apps/cli/src/models/export_metadata.rs b/rust/apps/cli/src/models/export_metadata.rsdeleted file mode 100644index 10069862cd..0000000000--- a/rust/apps/cli/src/models/export_metadata.rs+++ /dev/null@@ -1,174 +0,0 @@-use chrono::{DateTime, Local, TimeZone};-use serde::{Deserialize, Deserializer, Serialize, Serializer};--#[expect(- clippy::trivially_copy_pass_by_ref,- reason = "Serde serialize_with functions receive references"-)]-fn serialize_timestamp_as_iso8601<S>(- timestamp_micros: &i64,- serializer: S,-) -> Result<S::Ok, S::Error>-where- S: Serializer,-{- let timestamp_secs = timestamp_micros / 1_000_000;- let timestamp_nanos = ((timestamp_micros % 1_000_000) * 1000) as u32;-- let datetime = Local- .timestamp_opt(timestamp_secs, timestamp_nanos)- .single()- .ok_or_else(|| serde::ser::Error::custom("Invalid timestamp"))?;-- let iso_string = datetime.to_rfc3339_opts(chrono::SecondsFormat::Millis, true);-- serializer.serialize_str(&iso_string)-}--fn deserialize_timestamp_from_iso_or_i64<'de, D>(deserializer: D) -> Result<i64, D::Error>-where- D: Deserializer<'de>,-{- use serde::de::Error;-- #[derive(Deserialize)]- #[serde(untagged)]- enum TimestampFormat {- Microseconds(i64),- IsoString(String),- }-- match TimestampFormat::deserialize(deserializer)? {- TimestampFormat::Microseconds(micros) => Ok(micros),- TimestampFormat::IsoString(s) => DateTime::parse_from_rfc3339(&s)- .map(|dt| dt.timestamp_micros())- .map_err(|e| Error::custom(format!("Invalid ISO timestamp: {e}"))),- }-}--#[derive(Debug, Clone, Serialize, Deserialize)]-#[serde(rename_all = "camelCase")]-pub struct AlbumMetadata {- pub id: i64,- #[serde(rename = "ownerID")]- pub owner_id: i64,- pub album_name: String,- pub is_deleted: bool,- #[serde(rename = "accountOwnerIDs")]- pub account_owner_ids: Vec<i64>,- #[serde(skip)]- pub folder_name: String,-}--impl AlbumMetadata {- pub fn new(id: i64, owner_id: i64, album_name: String, account_id: i64) -> Self {- Self {- id,- owner_id,- album_name,- is_deleted: false,- account_owner_ids: vec![account_id],- folder_name: String::new(),- }- }-}--#[derive(Debug, Clone, Serialize, Deserialize)]-#[serde(rename_all = "camelCase")]-pub struct DiskFileMetadata {- pub title: String,- #[serde(skip_serializing_if = "Option::is_none")]- pub description: Option<String>,- #[serde(skip_serializing_if = "Option::is_none")]- pub location: Option<Location>,- #[serde(- serialize_with = "serialize_timestamp_as_iso8601",- deserialize_with = "deserialize_timestamp_from_iso_or_i64"- )]- pub creation_time: i64,- #[serde(- serialize_with = "serialize_timestamp_as_iso8601",- deserialize_with = "deserialize_timestamp_from_iso_or_i64"- )]- pub modification_time: i64,- pub info: FileInfo,- #[serde(skip)]- pub meta_file_name: String,-}--#[derive(Debug, Clone, Serialize, Deserialize)]-#[serde(rename_all = "camelCase")]-pub struct FileInfo {- pub id: i64,- #[serde(skip_serializing_if = "Option::is_none")]- pub hash: Option<String>,- #[serde(rename = "ownerID")]- pub owner_id: i64,- pub file_names: Vec<String>,-}--#[derive(Debug, Clone, Serialize, Deserialize)]-#[serde(rename_all = "camelCase")]-pub struct Location {- pub latitude: f64,- pub longitude: f64,-}--impl DiskFileMetadata {- pub fn from_file(- file: &crate::api::models::File,- metadata: Option<&crate::models::metadata::FileMetadata>,- filename: String,- ) -> Self {- let (title, location, creation_time) = if let Some(meta) = metadata {- let title = meta.get_title().unwrap_or(&filename).to_string();- let location = meta.latitude.and_then(|lat| {- meta.longitude.map(|lon| Location {- latitude: lat,- longitude: lon,- })- });-- let creation_time = meta.creation_time.unwrap_or(file.updation_time);-- (title, location, creation_time)- } else {- let title = filename.clone();- let creation_time = file.updation_time;- (title, None, creation_time)- };-- let modification_time = metadata- .and_then(|m| m.modification_time)- .unwrap_or(file.updation_time);-- let hash = metadata.and_then(|m| {- m.hash- .as_ref()- .or(m.image_hash.as_ref())- .or(m.video_hash.as_ref())- .cloned()- });-- Self {- title,- description: None,- location,- creation_time,- modification_time,- info: FileInfo {- id: file.id,- hash,- owner_id: file.owner_id,- file_names: vec![filename],- },- meta_file_name: String::new(),- }- }-- pub fn add_file_name(&mut self, filename: String) {- if !self.info.file_names.contains(&filename) {- self.info.file_names.push(filename);- }- }-}diff --git a/rust/apps/cli/src/models/file.rs b/rust/apps/cli/src/models/file.rsdeleted file mode 100644index 72eb6adc93..0000000000--- a/rust/apps/cli/src/models/file.rs+++ /dev/null@@ -1,58 +0,0 @@-use serde::{Deserialize, Serialize};--#[derive(Debug, Clone, Serialize, Deserialize)]-pub struct RemoteFile {- pub id: i64,- #[serde(rename = "collectionID")]- pub collection_id: i64,- #[serde(rename = "ownerID")]- pub owner_id: i64,- #[serde(rename = "encryptedKey")]- pub encrypted_key: String,- #[serde(rename = "keyDecryptionNonce")]- pub key_decryption_nonce: String,- pub file: FileInfo,- pub thumbnail: FileInfo,- pub metadata: MetadataInfo,- #[serde(rename = "isDeleted")]- pub is_deleted: bool,- #[serde(rename = "updatedAt")]- pub updated_at: i64,- #[serde(rename = "pubMagicMetadata")]- pub pub_magic_metadata: Option<MagicMetadata>,-}--#[derive(Debug, Clone, Serialize, Deserialize)]-pub struct MagicMetadata {- pub version: i32,- pub count: i32,- pub data: String,- pub header: String,-}--#[derive(Debug, Clone, Serialize, Deserialize)]-pub struct FileInfo {- #[serde(rename = "encryptedData")]- pub encrypted_data: Option<String>,- #[serde(rename = "decryptionHeader")]- pub decryption_header: String,- #[serde(rename = "objectKey")]- pub object_key: Option<String>,- pub size: Option<i64>,-}--#[derive(Debug, Clone, Serialize, Deserialize)]-pub struct MetadataInfo {- #[serde(rename = "encryptedData")]- pub encrypted_data: String,- #[serde(rename = "decryptionHeader")]- pub decryption_header: String,-}--#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]-pub enum FileType {- Image,- Video,- LivePhoto,- Other,-}diff --git a/rust/apps/cli/src/models/filter.rs b/rust/apps/cli/src/models/filter.rsdeleted file mode 100644index 91b00d3e7d..0000000000--- a/rust/apps/cli/src/models/filter.rs+++ /dev/null@@ -1,48 +0,0 @@-#[derive(Debug, Clone, Default)]-pub struct ExportFilter {- pub include_shared: bool,-- pub include_hidden: bool,-- pub albums: Option<Vec<String>>,-- pub emails: Option<Vec<String>>,-}--impl ExportFilter {- pub fn should_include_collection(- &self,- collection_name: &str,- is_shared: bool,- is_hidden: bool,- ) -> bool {- if is_shared && !self.include_shared {- return false;- }-- if is_hidden && !self.include_hidden {- return false;- }-- if let Some(ref albums) = self.albums- && !albums.is_empty()- && !albums.iter().any(|a| a == collection_name)- {- return false;- }-- true- }-- pub fn should_include_file_by_owner(&self, owner_email: Option<&str>) -> bool {- if let Some(ref emails) = self.emails- && !emails.is_empty()- {- if let Some(email) = owner_email {- return emails.iter().any(|e| e == email);- }- return false;- }- true- }-}diff --git a/rust/apps/cli/src/models/metadata.rs b/rust/apps/cli/src/models/metadata.rsdeleted file mode 100644index 95a5b99ac1..0000000000--- a/rust/apps/cli/src/models/metadata.rs+++ /dev/null@@ -1,65 +0,0 @@-use serde::{Deserialize, Serialize};-use serde_json::Value;-use std::collections::HashMap;--#[derive(Debug, Clone, Serialize, Deserialize)]-#[serde(rename_all = "camelCase")]-pub struct FileMetadata {- #[serde(rename = "fileType")]- pub file_type: Option<i32>,- pub title: Option<String>,- pub creation_time: Option<i64>,- pub modification_time: Option<i64>,- pub latitude: Option<f64>,- pub longitude: Option<f64>,- pub hash: Option<String>,- #[serde(rename = "imageHash")]- pub image_hash: Option<String>,- #[serde(rename = "videoHash")]- pub video_hash: Option<String>,- #[serde(flatten)]- pub other: HashMap<String, Value>,-}--impl FileMetadata {- pub fn get_title(&self) -> Option<&str> {- self.title.as_deref()- }-- pub fn get_file_type(&self) -> FileType {- match self.file_type {- Some(0) => FileType::Image,- Some(1) => FileType::Video,- Some(2) => FileType::LivePhoto,- _ => FileType::Unknown,- }- }-- pub fn is_live_photo(&self) -> bool {- matches!(self.get_file_type(), FileType::LivePhoto)- }-}--#[derive(Debug, Clone, Copy, PartialEq, Eq)]-pub enum FileType {- Image = 0,- Video = 1,- LivePhoto = 2,- Unknown = 127,-}--#[derive(Debug, Clone, Serialize, Deserialize)]-#[serde(rename_all = "camelCase")]-pub struct PublicMetadata {- pub edited_name: Option<String>,- pub edited_time: Option<i64>,- pub caption: Option<String>,- #[serde(flatten)]- pub other: HashMap<String, Value>,-}--#[derive(Debug, Clone, Serialize, Deserialize)]-pub struct PrivateMetadata {- #[serde(flatten)]- pub data: HashMap<String, Value>,-}diff --git a/rust/apps/cli/src/models/mod.rs b/rust/apps/cli/src/models/mod.rsdeleted file mode 100644index ff504429f1..0000000000--- a/rust/apps/cli/src/models/mod.rs+++ /dev/null@@ -1,9 +0,0 @@-pub mod account;-pub mod collection;-pub mod error;-pub mod export_metadata;-pub mod file;-pub mod filter;-pub mod metadata;--pub use error::{Error, Result};diff --git a/rust/apps/cli-next/src/output.rs b/rust/apps/cli/src/output.rssimilarity index 100%rename from rust/apps/cli-next/src/output.rsrename to rust/apps/cli/src/output.rsdiff --git a/rust/apps/cli-next/src/password.rs b/rust/apps/cli/src/password.rssimilarity index 100%rename from rust/apps/cli-next/src/password.rsrename to rust/apps/cli/src/password.rsdiff --git a/rust/apps/cli-next/src/paste.rs b/rust/apps/cli/src/paste.rssimilarity index 100%rename from rust/apps/cli-next/src/paste.rsrename to rust/apps/cli/src/paste.rsdiff --git a/rust/apps/cli-next/src/photos/export/mod.rs b/rust/apps/cli/src/photos/export/mod.rssimilarity index 100%rename from rust/apps/cli-next/src/photos/export/mod.rsrename to rust/apps/cli/src/photos/export/mod.rsdiff --git a/rust/apps/cli-next/src/photos/export/source.rs b/rust/apps/cli/src/photos/export/source.rssimilarity index 100%rename from rust/apps/cli-next/src/photos/export/source.rsrename to rust/apps/cli/src/photos/export/source.rsdiff --git a/rust/apps/cli-next/src/photos/mod.rs b/rust/apps/cli/src/photos/mod.rssimilarity index 100%rename from rust/apps/cli-next/src/photos/mod.rsrename to rust/apps/cli/src/photos/mod.rsdiff --git a/rust/apps/cli-next/src/photos/replica.rs b/rust/apps/cli/src/photos/replica.rssimilarity index 100%rename from rust/apps/cli-next/src/photos/replica.rsrename to rust/apps/cli/src/photos/replica.rsdiff --git a/rust/apps/cli/src/storage/account.rs b/rust/apps/cli/src/storage/account.rsdeleted file mode 100644index ec559bfdf2..0000000000--- a/rust/apps/cli/src/storage/account.rs+++ /dev/null@@ -1,160 +0,0 @@-use crate::{- Result,- models::account::{Account, AccountSecrets, App},-};-use rusqlite::{Connection, OptionalExtension, Row, params};-use std::time::{SystemTime, UNIX_EPOCH};--pub struct AccountStore<'a> {- conn: &'a Connection,-}--impl<'a> AccountStore<'a> {- pub fn new(conn: &'a Connection) -> Self {- Self { conn }- }-- pub fn add(&self, account: &Account) -> Result<()> {- let now = current_timestamp()?;-- self.conn.execute(- "INSERT INTO accounts (user_id, app, email, endpoint, export_dir, created_at, updated_at)- VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)",- params![- account.user_id,- format!("{:?}", account.app).to_lowercase(),- account.email,- account.endpoint,- account.export_dir,- now,- now- ],- )?;-- Ok(())- }-- pub fn get(&self, email: &str, app: App) -> Result<Option<Account>> {- let mut stmt = self.conn.prepare(- "SELECT user_id, app, email, endpoint, export_dir FROM accounts- WHERE email = ?1 AND app = ?2",- )?;-- let account = stmt- .query_row(params![email, format!("{app:?}").to_lowercase()], |row| {- row_to_account(row)- })- .optional()?;-- Ok(account)- }-- pub fn list(&self) -> Result<Vec<Account>> {- let mut stmt = self.conn.prepare(- "SELECT user_id, app, email, endpoint, export_dir FROM accounts- ORDER BY email, app",- )?;-- let accounts = stmt- .query_map([], row_to_account)?- .collect::<std::result::Result<Vec<_>, _>>()?;-- Ok(accounts)- }-- pub fn update_export_dir(&self, email: &str, app: App, export_dir: &str) -> Result<()> {- let now = current_timestamp()?;-- let rows_affected = self.conn.execute(- "UPDATE accounts SET export_dir = ?1, updated_at = ?2- WHERE email = ?3 AND app = ?4",- params![export_dir, now, email, format!("{app:?}").to_lowercase()],- )?;-- if rows_affected == 0 {- return Err(crate::Error::NotFound(format!(- "Account not found: {email} (app: {app:?})"- )));- }-- Ok(())- }-- pub fn delete(&self, user_id: i64, app: App) -> Result<()> {- let rows_affected = self.conn.execute(- "DELETE FROM accounts WHERE user_id = ?1 AND app = ?2",- params![user_id, format!("{app:?}").to_lowercase()],- )?;-- if rows_affected == 0 {- return Err(crate::Error::NotFound(format!(- "Account not found: user_id={user_id} (app: {app:?})"- )));- }-- Ok(())- }-- pub fn store_secrets(&self, user_id: i64, app: App, secrets: &AccountSecrets) -> Result<()> {- let now = current_timestamp()?;-- self.conn.execute(- "INSERT OR REPLACE INTO secrets- (user_id, app, token, master_key, secret_key, public_key, updated_at)- VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)",- params![- user_id,- format!("{app:?}").to_lowercase(),- &secrets.token,- &secrets.master_key,- &secrets.secret_key,- &secrets.public_key,- now- ],- )?;-- Ok(())- }-- pub fn get_secrets(&self, user_id: i64, app: App) -> Result<Option<AccountSecrets>> {- let mut stmt = self.conn.prepare(- "SELECT token, master_key, secret_key, public_key FROM secrets- WHERE user_id = ?1 AND app = ?2",- )?;-- let secrets = stmt- .query_row(params![user_id, format!("{app:?}").to_lowercase()], |row| {- Ok(AccountSecrets {- token: row.get(0)?,- master_key: row.get(1)?,- secret_key: row.get(2)?,- public_key: row.get(3)?,- })- })- .optional()?;-- Ok(secrets)- }-}--fn row_to_account(row: &Row) -> rusqlite::Result<Account> {- let app_str: String = row.get(1)?;- let app = match app_str.as_str() {- "photos" => App::Photos,- "locker" => App::Locker,- "auth" => App::Auth,- _ => App::Photos,- };-- Ok(Account {- user_id: row.get(0)?,- app,- email: row.get(2)?,- endpoint: row.get(3)?,- export_dir: row.get(4)?,- })-}--fn current_timestamp() -> Result<i64> {- Ok(SystemTime::now().duration_since(UNIX_EPOCH)?.as_secs() as i64)-}diff --git a/rust/apps/cli/src/storage/config.rs b/rust/apps/cli/src/storage/config.rsdeleted file mode 100644index a4e8eb202b..0000000000--- a/rust/apps/cli/src/storage/config.rs+++ /dev/null@@ -1,58 +0,0 @@-use crate::Result;-use rusqlite::{Connection, OptionalExtension, params};-use std::time::{SystemTime, UNIX_EPOCH};--pub struct ConfigStore<'a> {- conn: &'a Connection,-}--impl<'a> ConfigStore<'a> {- pub fn new(conn: &'a Connection) -> Self {- Self { conn }- }-- pub fn set(&self, key: &str, value: &str) -> Result<()> {- let now = SystemTime::now().duration_since(UNIX_EPOCH)?.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(())- }-- pub 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()?;-- Ok(value)- }-- pub fn delete(&self, key: &str) -> Result<()> {- self.conn- .execute("DELETE FROM config WHERE key = ?1", params![key])?;-- Ok(())- }-- pub 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<_>, _>>()?;-- Ok(configs)- }-}diff --git a/rust/apps/cli/src/storage/mod.rs b/rust/apps/cli/src/storage/mod.rsdeleted file mode 100644index 01e0307d71..0000000000--- a/rust/apps/cli/src/storage/mod.rs+++ /dev/null@@ -1,83 +0,0 @@-use crate::Result;-use rusqlite::Connection;-use serde::{Deserialize, Serialize};-use std::path::{Path, PathBuf};--pub mod account;-pub mod config;-pub mod schema;-pub mod sync;--pub use account::AccountStore;-pub use config::ConfigStore;-pub use sync::SyncStore;--pub struct Storage {- conn: Connection,- path: Option<PathBuf>,-}--impl Storage {- pub fn new<P: AsRef<Path>>(path: P) -> Result<Self> {- let path_buf = path.as_ref().to_path_buf();- let conn = Connection::open(&path_buf)?;-- conn.execute("PRAGMA foreign_keys = ON", [])?;-- schema::create_tables(&conn)?;-- Ok(Self {- conn,- path: Some(path_buf),- })- }-- pub fn new_in_memory() -> Result<Self> {- let conn = Connection::open_in_memory()?;- conn.execute("PRAGMA foreign_keys = ON", [])?;- schema::create_tables(&conn)?;- Ok(Self { conn, path: None })- }-- pub fn conn(&self) -> &Connection {- &self.conn- }-- pub fn transaction<F, R>(&mut self, f: F) -> Result<R>- where- F: FnOnce(&rusqlite::Transaction) -> Result<R>,- {- let tx = self.conn.transaction()?;- let result = f(&tx)?;- tx.commit()?;- Ok(result)- }-- pub fn accounts(&self) -> AccountStore<'_> {- AccountStore::new(&self.conn)- }-- pub fn config(&self) -> ConfigStore<'_> {- ConfigStore::new(&self.conn)- }-- pub fn sync(&self) -> SyncStore<'_> {- SyncStore::new(&self.conn)- }-- pub fn db_path(&self) -> Option<&Path> {- self.path.as_deref()- }-}--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)?)- }-}--impl<T> JsonValue for T where T: Serialize + for<'de> Deserialize<'de> {}diff --git a/rust/apps/cli/src/storage/schema.rs b/rust/apps/cli/src/storage/schema.rsdeleted file mode 100644index 022c920f5b..0000000000--- a/rust/apps/cli/src/storage/schema.rs+++ /dev/null@@ -1,163 +0,0 @@-use crate::Result;-use rusqlite::Connection;--pub fn create_tables(conn: &Connection) -> Result<()> {- // A user can have accounts for multiple apps, so the key includes the app.- conn.execute(- "CREATE TABLE IF NOT EXISTS accounts (- user_id INTEGER NOT NULL,- app TEXT NOT NULL,- email TEXT NOT NULL,- endpoint TEXT NOT NULL DEFAULT 'https://api.ente.com',- export_dir TEXT,- created_at INTEGER NOT NULL,- updated_at INTEGER NOT NULL,- PRIMARY KEY (user_id, app),- UNIQUE(email, app, endpoint)- )",- [],- )?;-- conn.execute(- "CREATE TABLE IF NOT EXISTS secrets (- user_id INTEGER NOT NULL,- app TEXT NOT NULL,- token BLOB NOT NULL,- master_key BLOB NOT NULL,- secret_key BLOB NOT NULL,- public_key BLOB NOT NULL,- updated_at INTEGER NOT NULL,- PRIMARY KEY (user_id, app),- FOREIGN KEY (user_id, app) REFERENCES accounts(user_id, app) ON DELETE CASCADE- )",- [],- )?;-- conn.execute(- "CREATE TABLE IF NOT EXISTS config (- key TEXT PRIMARY KEY,- value TEXT NOT NULL,- updated_at INTEGER NOT NULL- )",- [],- )?;-- // Collection IDs are global; owner records the owning user.- conn.execute(- "CREATE TABLE IF NOT EXISTS collections (- collection_id INTEGER PRIMARY KEY,- owner INTEGER NOT NULL,- name TEXT NOT NULL,- type TEXT NOT NULL,- is_deleted INTEGER NOT NULL DEFAULT 0,- metadata TEXT,- updated_at INTEGER NOT NULL- )",- [],- )?;-- // File IDs are global; owner_id records the owning user.- conn.execute(- "CREATE TABLE IF NOT EXISTS files (- file_id INTEGER PRIMARY KEY,- owner_id INTEGER NOT NULL,- collection_id INTEGER NOT NULL,- encrypted_key TEXT NOT NULL,- key_decryption_nonce TEXT NOT NULL,- file_info TEXT NOT NULL,- metadata TEXT NOT NULL,- pub_magic_metadata TEXT,- content_hash TEXT,- 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 (collection_id) REFERENCES collections(collection_id)- )",- [],- )?;-- conn.execute(- "CREATE TABLE IF NOT EXISTS album_files (- album_id INTEGER NOT NULL,- file_id INTEGER NOT NULL,- synced_locally INTEGER NOT NULL DEFAULT 0,- created_at INTEGER NOT NULL,- PRIMARY KEY (album_id, file_id),- FOREIGN KEY (album_id) REFERENCES collections(collection_id),- FOREIGN KEY (file_id) REFERENCES files(file_id)- )",- [],- )?;-- conn.execute(- "CREATE TABLE IF NOT EXISTS sync_state (- user_id INTEGER NOT NULL,- app TEXT NOT NULL,- last_file_sync INTEGER,- last_collection_sync INTEGER,- last_album_sync INTEGER,- sync_status TEXT,- PRIMARY KEY (user_id, app),- FOREIGN KEY (user_id, app) REFERENCES accounts(user_id, app) ON DELETE CASCADE- )",- [],- )?;-- conn.execute(- "CREATE TABLE IF NOT EXISTS collection_sync_state (- user_id INTEGER NOT NULL,- collection_id INTEGER NOT NULL,- last_sync_time INTEGER NOT NULL,- updated_at INTEGER NOT NULL,- PRIMARY KEY (user_id, collection_id),- FOREIGN KEY (collection_id) REFERENCES collections(collection_id) ON DELETE CASCADE- )",- [],- )?;-- conn.execute(- "CREATE INDEX IF NOT EXISTS idx_files_collection- ON files(collection_id)",- [],- )?;-- conn.execute(- "CREATE INDEX IF NOT EXISTS idx_files_owner- ON files(owner_id)",- [],- )?;-- conn.execute(- "CREATE INDEX IF NOT EXISTS idx_album_files_album- ON album_files(album_id)",- [],- )?;-- conn.execute(- "CREATE INDEX IF NOT EXISTS idx_collections_owner- ON collections(owner)",- [],- )?;-- conn.execute(- "CREATE INDEX IF NOT EXISTS idx_accounts_email- ON accounts(email)",- [],- )?;-- conn.execute(- "CREATE INDEX IF NOT EXISTS idx_collection_sync_state- ON collection_sync_state(user_id, collection_id)",- [],- )?;-- conn.execute(- "CREATE INDEX IF NOT EXISTS idx_files_hash- ON files(owner_id, content_hash)- WHERE content_hash IS NOT NULL AND is_deleted = 0",- [],- )?;-- Ok(())-}diff --git a/rust/apps/cli/src/storage/sync.rs b/rust/apps/cli/src/storage/sync.rsdeleted file mode 100644index bf570a9949..0000000000--- a/rust/apps/cli/src/storage/sync.rs+++ /dev/null@@ -1,398 +0,0 @@-use crate::{- Result,- models::{collection::Collection, file::RemoteFile},-};-use rusqlite::{Connection, OptionalExtension, params};-use serde_json;--pub struct SyncStore<'a> {- conn: &'a Connection,-}--impl<'a> SyncStore<'a> {- pub fn new(conn: &'a Connection) -> Self {- Self { conn }- }-- pub fn upsert_collection(&self, collection: &Collection) -> Result<()> {- let metadata = serde_json::to_string(&collection)?;-- self.conn.execute(- "INSERT OR REPLACE INTO collections- (collection_id, owner, name, type, is_deleted, metadata, updated_at)- VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)",- params![- collection.id,- collection.owner,- collection.name,- format!("{:?}", collection.collection_type).to_lowercase(),- collection.is_deleted as i32,- metadata,- collection.updated_at- ],- )?;-- Ok(())- }-- pub fn get_collections(&self, user_id: i64) -> Result<Vec<Collection>> {- let mut stmt = self.conn.prepare(- "SELECT metadata FROM collections- WHERE owner = ?1 AND is_deleted = 0- ORDER BY collection_id",- )?;-- stmt.query_map(params![user_id], |row| row.get::<_, String>(0))?- .map(|metadata| Ok(serde_json::from_str(&metadata?)?))- .collect()- }-- pub fn upsert_file(&self, file: &RemoteFile) -> Result<()> {- self.upsert_file_with_hash(file, None)- }-- pub fn upsert_file_with_hash(- &self,- file: &RemoteFile,- content_hash: Option<&str>,- ) -> Result<()> {- let file_info = serde_json::to_string(&file.file)?;- let metadata = serde_json::to_string(&file.metadata)?;- let pub_magic_metadata = match &file.pub_magic_metadata {- Some(meta) => Some(serde_json::to_string(meta)?),- None => None,- };-- // Refreshing remote metadata must preserve the local-sync flag.- let existing_sync_status: Option<i32> = self- .conn- .query_row(- "SELECT is_synced_locally FROM files WHERE file_id = ?1",- params![file.id],- |row| row.get(0),- )- .optional()?;-- let is_synced = existing_sync_status.unwrap_or(0);-- self.conn.execute(- "INSERT OR REPLACE INTO files- (file_id, owner_id, collection_id, encrypted_key, key_decryption_nonce,- file_info, metadata, pub_magic_metadata, content_hash, is_deleted, is_synced_locally, updated_at)- VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12)",- params![- file.id,- file.owner_id,- file.collection_id,- file.encrypted_key,- file.key_decryption_nonce,- file_info,- metadata,- pub_magic_metadata,- content_hash,- file.is_deleted as i32,- is_synced,- file.updated_at- ],- )?;-- Ok(())- }-- pub fn get_files_by_collection(- &self,- user_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_at, owner_id, pub_magic_metadata- FROM files- WHERE owner_id = ?1 AND collection_id = ?2 AND is_deleted = 0- ORDER BY file_id",- )?;-- let files = stmt- .query_map(params![user_id, collection_id], |row| {- let file_info: String = row.get(4)?;- let metadata: String = row.get(5)?;- let pub_magic_metadata_json: Option<String> = row.get(9)?;-- 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)))?;-- let pub_magic_metadata = match pub_magic_metadata_json {- Some(json) => Some(- serde_json::from_str(&json)- .map_err(|e| rusqlite::Error::ToSqlConversionFailure(Box::new(e)))?,- ),- None => None,- };-- 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: row.get(8)?,- encrypted_key: row.get(2)?,- key_decryption_nonce: row.get(3)?,- file: file_obj,- thumbnail,- metadata: metadata_obj,- is_deleted: row.get::<_, i32>(6)? != 0,- updated_at: row.get(7)?,- pub_magic_metadata,- })- })?- .collect::<std::result::Result<Vec<_>, _>>()?;-- Ok(files)- }-- pub fn update_sync_state(&self, user_id: i64, sync_type: &str, timestamp: i64) -> Result<()> {- if sync_type.starts_with("collection_") {- let collection_id = sync_type- .strip_prefix("collection_")- .and_then(|s| s.strip_suffix("_files"))- .and_then(|s| s.parse::<i64>().ok())- .ok_or_else(|| {- crate::Error::InvalidInput(format!("Invalid sync type: {sync_type}"))- })?;-- let now = chrono::Utc::now().timestamp_micros();- self.conn.execute(- "INSERT OR REPLACE INTO collection_sync_state- (user_id, collection_id, last_sync_time, updated_at)- VALUES (?1, ?2, ?3, ?4)",- params![user_id, collection_id, timestamp, now],- )?;- return Ok(());- }-- 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 (user_id, app, {column}) VALUES (?1, 'photos', ?2)- ON CONFLICT(user_id, app) DO UPDATE SET {column} = ?2"- );-- self.conn.execute(&query, params![user_id, timestamp])?;-- Ok(())- }-- pub fn get_last_sync(&self, user_id: i64, sync_type: &str) -> Result<Option<i64>> {- if sync_type.starts_with("collection_") {- let collection_id = sync_type- .strip_prefix("collection_")- .and_then(|s| s.strip_suffix("_files"))- .and_then(|s| s.parse::<i64>().ok())- .ok_or_else(|| {- crate::Error::InvalidInput(format!("Invalid sync type: {sync_type}"))- })?;-- let timestamp = self- .conn- .query_row(- "SELECT last_sync_time FROM collection_sync_state- WHERE user_id = ?1 AND collection_id = ?2",- params![user_id, collection_id],- |row| row.get::<_, i64>(0),- )- .optional()?;-- return Ok(timestamp);- }-- 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!("SELECT {column} FROM sync_state WHERE user_id = ?1 AND app = 'photos'");- let mut stmt = self.conn.prepare(&query)?;-- let timestamp = stmt- .query_row(params![user_id], |row| row.get::<_, Option<i64>>(0))- .optional()?- .flatten();-- Ok(timestamp)- }-- pub fn mark_album_file_synced(&self, album_id: i64, file_id: i64) -> Result<()> {- self.conn.execute(- "UPDATE album_files SET synced_locally = 1- WHERE album_id = ?1 AND file_id = ?2",- params![album_id, file_id],- )?;-- Ok(())- }-- pub fn clear_sync_state(&self, user_id: i64) -> Result<()> {- self.conn.execute(- "DELETE FROM sync_state WHERE user_id = ?1 AND app = 'photos'",- params![user_id],- )?;-- self.conn.execute(- "DELETE FROM collection_sync_state WHERE user_id = ?1",- params![user_id],- )?;-- Ok(())- }-- pub fn get_pending_downloads(&self, user_id: i64) -> Result<Vec<RemoteFile>> {- let synced_count: i64 = self.conn.query_row(- "SELECT COUNT(*) FROM files WHERE owner_id = ?1 AND is_synced_locally = 1",- params![user_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_at, owner_id, pub_magic_metadata- FROM files- WHERE owner_id = ?1 AND is_deleted = 0 AND is_synced_locally = 0- ORDER BY file_id",- )?;-- let files = stmt- .query_map(params![user_id], |row| {- let file_info: String = row.get(4)?;- let metadata: String = row.get(5)?;- let pub_magic_metadata_json: Option<String> = row.get(9)?;-- 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)))?;-- let pub_magic_metadata = match pub_magic_metadata_json {- Some(json) => Some(- serde_json::from_str(&json)- .map_err(|e| rusqlite::Error::ToSqlConversionFailure(Box::new(e)))?,- ),- None => None,- };-- 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: row.get(8)?,- encrypted_key: row.get(2)?,- key_decryption_nonce: row.get(3)?,- file: file_obj,- thumbnail,- metadata: metadata_obj,- is_deleted: row.get::<_, i32>(6)? != 0,- updated_at: row.get(7)?,- pub_magic_metadata,- })- })?- .collect::<std::result::Result<Vec<_>, _>>()?;-- Ok(files)- }-- pub fn mark_file_synced(&self, file_id: i64, local_path: Option<&str>) -> Result<()> {- let rows_updated = if let Some(path) = local_path {- self.conn.execute(- "UPDATE files SET is_synced_locally = 1, local_path = ?2- WHERE file_id = ?1",- params![file_id, path],- )?- } else {- self.conn.execute(- "UPDATE files SET is_synced_locally = 1- WHERE file_id = ?1",- params![file_id],- )?- };-- log::debug!("Marked file {file_id} as synced locally, rows affected: {rows_updated}");-- Ok(())- }-- pub fn find_duplicate_by_hash(&self, owner_id: i64, content_hash: &str) -> Result<Option<i64>> {- let file_id: Option<i64> = self- .conn- .query_row(- "SELECT file_id FROM files- WHERE owner_id = ?1 AND content_hash = ?2 AND is_deleted = 0- AND is_synced_locally = 1- LIMIT 1",- params![owner_id, content_hash],- |row| row.get(0),- )- .optional()?;-- Ok(file_id)- }-- pub fn get_file_local_path(&self, file_id: i64) -> Result<Option<String>> {- let path: Option<String> = self- .conn- .query_row(- "SELECT local_path FROM files WHERE file_id = ?1",- params![file_id],- |row| row.get(0),- )- .optional()?;-- Ok(path)- }-}--#[cfg(test)]-mod tests {- use crate::{Error, Result, storage::Storage};-- #[test]- fn malformed_collection_metadata_returns_error() -> Result<()> {- let storage = Storage::new_in_memory()?;- storage.conn().execute(- "INSERT INTO collections- (collection_id, owner, name, type, metadata, updated_at)- VALUES (1, 1, 'album', 'album', '{', 0)",- [],- )?;-- assert!(matches!(- storage.sync().get_collections(1),- Err(Error::Serialization(_))- ));- Ok(())- }-}diff --git a/rust/apps/cli/src/sync/download.rs b/rust/apps/cli/src/sync/download.rsdeleted file mode 100644index 6c440c44d8..0000000000--- a/rust/apps/cli/src/sync/download.rs+++ /dev/null@@ -1,295 +0,0 @@-use crate::Result;-use crate::api::client::AppClient;-use crate::api::methods::ApiMethods;-use crate::live_photo::extract_live_photo;-use crate::models::file::RemoteFile;-use ente_core::b64;-use ente_core::crypto;-use indicatif::{MultiProgress, ProgressBar, ProgressStyle};-use std::collections::HashMap;-use std::path::{Path, PathBuf};-use std::sync::Arc;-use tokio::fs;-use tokio::io::AsyncWriteExt;--pub struct DownloadManager {- api_client: AppClient,- temp_dir: PathBuf,- pub collection_keys: HashMap<i64, Vec<u8>>,- concurrent_downloads: usize,- show_progress: bool,-}--impl DownloadManager {- pub fn new(api_client: AppClient) -> Result<Self> {- let temp_dir = std::env::temp_dir().join("ente-downloads");- std::fs::create_dir_all(&temp_dir)?;-- Ok(Self {- api_client,- temp_dir,- collection_keys: HashMap::new(),- concurrent_downloads: 4,- show_progress: true,- })- }-- pub fn set_collection_keys(&mut self, keys: HashMap<i64, Vec<u8>>) {- self.collection_keys = keys;- }-- pub fn set_concurrent_downloads(&mut self, count: usize) {- self.concurrent_downloads = count.clamp(1, 10);- }-- pub fn set_show_progress(&mut self, show: bool) {- self.show_progress = show;- }-- pub async fn download_file(&self, file: &RemoteFile, destination: &Path) -> Result<()> {- self.download_file_with_progress(file, destination, None)- .await- }-- async fn download_file_with_progress(- &self,- file: &RemoteFile,- destination: &Path,- progress: Option<Arc<ProgressBar>>,- ) -> Result<()> {- log::debug!("Downloading file {} to {:?}", file.id, destination);-- if let Some(parent) = destination.parent() {- fs::create_dir_all(parent).await?;- }-- if destination.exists() {- log::debug!(- "File already exists at {destination:?}, skipping download but marking as successful"- );- return Ok(());- }-- let temp_path = self.temp_dir.join(format!("{}.tmp", file.id));-- let api = ApiMethods::new(&self.api_client);- let encrypted_data = api.download_file(file.id).await?;-- let decrypted_data = self.decrypt_file_data(file, &encrypted_data)?;-- let is_live_photo = destination- .extension()- .and_then(|ext| ext.to_str())- .map(|ext| ext.to_lowercase() == "zip")- .unwrap_or(false);-- if is_live_photo {- if let Err(e) = extract_live_photo(&decrypted_data, destination).await {- log::warn!(- "Failed to extract live photo components for file {}, saving as ZIP: {}",- file.id,- e- );- 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);- fs::copy(&temp_path, destination).await?;- fs::remove_file(&temp_path).await?;- }- } else {- 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);-- // Temp and destination may be on different filesystems.- fs::copy(&temp_path, destination).await?;- fs::remove_file(&temp_path).await?;- }-- // TODO: Update storage with the local path.-- if let Some(pb) = progress {- pb.inc(1);- }-- log::info!("Downloaded file {} to {:?}", file.id, destination);- Ok(())- }-- pub async fn download_files(&self, files: Vec<(RemoteFile, PathBuf)>) -> Result<DownloadStats> {- use futures::stream::{self, StreamExt};-- let total = files.len();- log::info!("Starting download of {total} files");-- let mut stats = DownloadStats {- total,- ..Default::default()- };-- let (_multi_progress, progress_bar) = if self.show_progress && total > 0 {- let mp = MultiProgress::new();- let pb = mp.add(ProgressBar::new(total as u64));- #[expect(- clippy::expect_used,- reason = "The progress template is a fixed literal"- )]- pb.set_style(- ProgressStyle::default_bar()- .template("{spinner:.green} [{elapsed_precise}] [{bar:40.cyan/blue}] {pos}/{len} ({percent}%) {msg}")- .expect("valid download progress template")- .progress_chars("#>-"),- );- pb.set_message("Downloading files...");- (Some(Arc::new(mp)), Some(Arc::new(pb)))- } else {- (None, None)- };-- let pb_clone = progress_bar.clone();- let results: Vec<_> = stream::iter(files)- .map(|(file, path)| {- let file_clone = file.clone();- let path_clone = path.clone();- let pb = pb_clone.clone();- async move {- let result = self.download_file_with_progress(&file, &path, pb).await;- (file_clone, path_clone, result)- }- })- .buffer_unordered(self.concurrent_downloads)- .collect()- .await;-- for (file, path, result) in results {- match result {- Ok(_) => {- stats.successful += 1;- stats.successful_downloads.push((file, path));- }- Err(e) => {- log::error!("Download failed for file {}: {}", file.id, e);- stats.failed += 1;- }- }- }-- if let Some(pb) = progress_bar {- pb.finish_with_message(format!("Downloaded {} files", stats.successful));- }-- log::info!(- "Download completed: {} successful, {} failed",- stats.successful,- stats.failed- );- Ok(stats)- }-- pub async fn download_thumbnail(&self, file: &RemoteFile, destination: &Path) -> Result<()> {- log::debug!(- "Downloading thumbnail for file {} to {:?}",- file.id,- destination- );-- if let Some(parent) = destination.parent() {- fs::create_dir_all(parent).await?;- }-- let api = ApiMethods::new(&self.api_client);- let encrypted_data = api.download_thumbnail(file.id).await?;-- let decrypted_data = self.decrypt_file_data(file, &encrypted_data)?;-- 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(())- }-- fn decrypt_file_data(&self, file: &RemoteFile, encrypted_data: &[u8]) -> Result<Vec<u8>> {- let collection_key = self- .collection_keys- .get(&file.collection_id)- .ok_or_else(|| {- crate::Error::Crypto("Missing collection key for file decryption".into())- })?;-- let file_key = {- let key_bytes = b64::decode(&file.encrypted_key)?;- let nonce = b64::decode(&file.key_decryption_nonce)?;- crypto::secretbox::decrypt(- &key_bytes,- &crypto::Nonce::try_from_slice(&nonce)?,- &crypto::Key::try_from_slice(collection_key)?,- )?- };-- let file_nonce = b64::decode(&file.file.decryption_header)?;- let decrypted = crypto::stream::decrypt_file_data(- encrypted_data,- &crypto::Header::try_from_slice(&file_nonce)?,- &crypto::Key::try_from_slice(&file_key)?,- )?;-- Ok(decrypted)- }-- pub async fn resume_download(- &self,- _file: &RemoteFile,- _destination: &Path,- _offset: u64,- ) -> Result<()> {- // TODO: Implement resume functionality using Range headers- todo!("Resume download not yet implemented")- }-- 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 {count} temporary files");- Ok(())- }-}--#[derive(Debug, Default)]-pub struct DownloadStats {- pub total: usize,- pub successful: usize,- pub failed: usize,- pub skipped: usize,- pub successful_downloads: Vec<(RemoteFile, PathBuf)>,-}--impl DownloadStats {- pub fn all_successful(&self) -> bool {- self.failed == 0 && self.successful == self.total- }-- pub fn success_rate(&self) -> f64 {- if self.total == 0 {- 100.0- } else {- (self.successful as f64 / self.total as f64) * 100.0- }- }-}diff --git a/rust/apps/cli/src/sync/engine.rs b/rust/apps/cli/src/sync/engine.rsdeleted file mode 100644index 2ff6cf6a18..0000000000--- a/rust/apps/cli/src/sync/engine.rs+++ /dev/null@@ -1,287 +0,0 @@-use crate::Result;-use crate::api::client::AppClient;-use crate::api::methods::ApiMethods;-use crate::models::{account::Account, file::RemoteFile};-use crate::storage::Storage;--pub struct SyncEngine {- api_client: AppClient,- storage: Storage,- account: Account,-}--impl SyncEngine {- pub fn new(api_client: AppClient, storage: Storage, account: Account) -> Self {- Self {- api_client,- storage,- account,- }- }-- pub async fn sync(&self) -> Result<SyncStats> {- log::info!("Starting sync for account: {}", self.account.email);-- let stats = SyncStats {- collections: self.sync_collections().await?,- files: self.sync_files().await?,- };-- log::info!("Sync completed: {stats:?}");- Ok(stats)- }-- async fn sync_collections(&self) -> Result<SyncResult> {- log::debug!("Syncing collections...");-- let sync_store = self.storage.sync();-- let last_sync = sync_store- .get_last_sync(self.account.user_id, "collections")?- .unwrap_or(0);-- let api = ApiMethods::new(&self.api_client);- let collections = api.get_collections(last_sync).await?;-- let mut result = SyncResult {- total: collections.len(),- new: 0,- updated: 0,- deleted: 0,- };-- for collection in &collections {- log::debug!(- "Processing collection: {:?} ({})",- collection.name,- collection.id- );-- let storage_collection = crate::models::collection::Collection {- id: collection.id,- owner: collection.owner.id,- key: collection.encrypted_key.clone(),- name: collection.name.clone().unwrap_or_default(),- collection_type: match collection.collection_type.as_str() {- "folder" => crate::models::collection::CollectionType::Folder,- "favorites" => crate::models::collection::CollectionType::Favorites,- _ => crate::models::collection::CollectionType::Album,- },- attributes: None,- sharees: None,- public_urls: None,- updated_at: collection.updation_time,- is_deleted: collection.is_deleted,- };-- sync_store.upsert_collection(&storage_collection)?;-- if collection.updation_time > last_sync {- if last_sync == 0 {- result.new += 1;- } else {- result.updated += 1;- }- }-- if collection.is_deleted {- result.deleted += 1;- }- }-- let now = chrono::Utc::now().timestamp_micros();- sync_store.update_sync_state(self.account.user_id, "collections", now)?;-- log::info!(- "Collections synced: {} new, {} updated",- result.new,- result.updated- );- Ok(result)- }-- async fn sync_files(&self) -> Result<SyncResult> {- log::debug!("Syncing files...");-- let sync_store = self.storage.sync();- let api = ApiMethods::new(&self.api_client);- let mut result = SyncResult::default();-- let collections = sync_store.get_collections(self.account.user_id)?;-- for collection in collections {- if collection.is_deleted {- continue;- }-- log::debug!(- "Syncing files for collection: {} ({})",- collection.name,- collection.id- );-- let initial_sync = sync_store- .get_last_sync(- self.account.user_id,- &format!("collection_{}_files", collection.id),- )?- .unwrap_or(0);-- let mut last_sync = initial_sync;- let is_first_sync = initial_sync == 0;-- if is_first_sync {- log::info!(- "Initial sync for collection: {} ({})",- collection.name,- collection.id- );- } else {- let last_sync_time = chrono::DateTime::from_timestamp_micros(initial_sync)- .map(|dt| dt.format("%Y-%m-%d %H:%M:%S").to_string())- .unwrap_or_else(|| "unknown".to_string());- log::info!(- "Incremental sync for collection: {} ({}) since {}",- collection.name,- collection.id,- last_sync_time- );- }-- let mut has_more = true;- let mut batch_count = 0;- while has_more {- log::debug!(- "Fetching batch {} for collection {}, since_time: {}",- batch_count + 1,- collection.id,- last_sync- );-- let (files, more) = api.get_collection_files(collection.id, last_sync).await?;- has_more = more;- batch_count += 1;-- if files.is_empty() {- log::debug!("No more files to sync for collection {}", collection.id);- break;- }-- result.total += files.len();-- for file in files {- log::trace!("Processing file: {}", file.id);-- let remote_file = RemoteFile {- id: file.id,- collection_id: file.collection_id,- owner_id: file.owner_id,- encrypted_key: file.encrypted_key.clone(),- key_decryption_nonce: file.key_decryption_nonce.clone(),- file: crate::models::file::FileInfo {- encrypted_data: file.file.encrypted_data.clone(),- decryption_header: file.file.decryption_header.clone(),- object_key: None,- size: file.file.size,- },- thumbnail: crate::models::file::FileInfo {- encrypted_data: file.thumbnail.encrypted_data.clone(),- decryption_header: file.thumbnail.decryption_header.clone(),- object_key: None,- size: file.thumbnail.size,- },- metadata: crate::models::file::MetadataInfo {- encrypted_data: file- .metadata- .encrypted_data- .clone()- .unwrap_or_default(),- decryption_header: file.metadata.decryption_header.clone(),- },- is_deleted: file.is_deleted,- updated_at: file.updation_time,- pub_magic_metadata: file.pub_magic_metadata.as_ref().map(|m| {- crate::models::file::MagicMetadata {- version: m.version,- count: m.count,- data: m.data.clone(),- header: m.header.clone(),- }- }),- };-- if is_first_sync && file.is_deleted {- log::trace!("Skipping deleted file {} on initial sync", file.id);- continue;- }-- sync_store.upsert_file(&remote_file)?;-- if file.is_deleted {- result.deleted += 1;- } else if file.updation_time > initial_sync {- if initial_sync == 0 {- result.new += 1;- } else {- result.updated += 1;- }- }-- if file.updation_time > last_sync {- last_sync = file.updation_time;- }- }-- sync_store.update_sync_state(- self.account.user_id,- &format!("collection_{}_files", collection.id),- last_sync,- )?;- }- }-- log::info!(- "Files synced: {} new, {} updated, {} deleted",- result.new,- result.updated,- result.deleted- );- Ok(result)- }-- pub fn get_pending_downloads(&self) -> Result<Vec<RemoteFile>> {- let sync_store = self.storage.sync();-- let collections = sync_store.get_collections(self.account.user_id)?;-- let mut all_files = Vec::new();- for collection in collections {- let files = sync_store.get_files_by_collection(self.account.user_id, collection.id)?;- all_files.extend(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)- }-- pub fn get_collections(&self) -> Result<Vec<crate::models::collection::Collection>> {- let sync_store = self.storage.sync();- sync_store.get_collections(self.account.user_id)- }-}--#[derive(Debug, Default)]-pub struct SyncStats {- pub collections: SyncResult,- pub files: SyncResult,-}--#[derive(Debug, Default)]-pub struct SyncResult {- pub total: usize,- pub new: usize,- pub updated: usize,- pub deleted: usize,-}diff --git a/rust/apps/cli/src/sync/mod.rs b/rust/apps/cli/src/sync/mod.rsdeleted file mode 100644index ec4b370727..0000000000--- a/rust/apps/cli/src/sync/mod.rs+++ /dev/null@@ -1,5 +0,0 @@-pub mod download;-mod engine;--pub use download::DownloadManager;-pub use engine::{SyncEngine, SyncStats};diff --git a/rust/apps/cli/src/utils/mod.rs b/rust/apps/cli/src/utils/mod.rsdeleted file mode 100644index 67b39d5632..0000000000--- a/rust/apps/cli/src/utils/mod.rs+++ /dev/null@@ -1,23 +0,0 @@-use dirs;-use std::path::PathBuf;--pub fn get_cli_config_dir() -> crate::Result<PathBuf> {- if let Ok(config_dir) = std::env::var("ENTE_CLI_CONFIG_DIR") {- return Ok(PathBuf::from(config_dir));- }-- // Use platform-specific config directory- // On Linux: ~/.config/ente-cli- // On macOS: ~/Library/Application Support/ente-cli- // On Windows: %APPDATA%/ente-cli- let config_dir = dirs::config_dir()- .ok_or_else(|| crate::Error::Generic("Could not determine config directory".into()))?;-- let cli_path = config_dir.join("ente-cli");-- if !cli_path.exists() {- std::fs::create_dir_all(&cli_path)?;- }-- Ok(cli_path)-}diff --git a/rust/apps/cli-next/src/vault.rs b/rust/apps/cli/src/vault.rssimilarity index 100%rename from rust/apps/cli-next/src/vault.rsrename to rust/apps/cli/src/vault.rsdiff --git a/rust/apps/cli-next/tests/cli/account.rs b/rust/apps/cli/tests/cli/account.rssimilarity index 99%rename from rust/apps/cli-next/tests/cli/account.rsrename to rust/apps/cli/tests/cli/account.rsindex 49135b57fa..e48d7a4f5e 100644--- a/rust/apps/cli-next/tests/cli/account.rs+++ b/rust/apps/cli/tests/cli/account.rs@@ -398,7 +398,7 @@ fn interactive_creation_password_retry_and_enrollment() -> ente_test_support::TeCommand::new("python3").args([concat!(env!("CARGO_MANIFEST_DIR"), "/tests/cli/account_prompt.py"),- env!("CARGO_BIN_EXE_ente-cli-next"),+ env!("CARGO_BIN_EXE_ente"),&origin,&email,])diff --git a/rust/apps/cli-next/tests/cli/account_prompt.py b/rust/apps/cli/tests/cli/account_prompt.pysimilarity index 100%rename from rust/apps/cli-next/tests/cli/account_prompt.pyrename to rust/apps/cli/tests/cli/account_prompt.pydiff --git a/rust/apps/cli-next/tests/cli/admin.rs b/rust/apps/cli/tests/cli/admin.rssimilarity index 100%rename from rust/apps/cli-next/tests/cli/admin.rsrename to rust/apps/cli/tests/cli/admin.rsdiff --git a/rust/apps/cli-next/tests/cli/admin_museum.rs b/rust/apps/cli/tests/cli/admin_museum.rssimilarity index 99%rename from rust/apps/cli-next/tests/cli/admin_museum.rsrename to rust/apps/cli/tests/cli/admin_museum.rsindex 8b749aa9ed..e3fe3bf8c0 100644--- a/rust/apps/cli-next/tests/cli/admin_museum.rs+++ b/rust/apps/cli/tests/cli/admin_museum.rs@@ -280,7 +280,7 @@ fn admin_interactive_subscription() -> TestResult {.env_clear().args([concat!(env!("CARGO_MANIFEST_DIR"), "/tests/cli/admin_prompt.py"),- env!("CARGO_BIN_EXE_ente-cli-next"),+ env!("CARGO_BIN_EXE_ente"),&email,mode,])diff --git a/rust/apps/cli-next/tests/cli/admin_prompt.py b/rust/apps/cli/tests/cli/admin_prompt.pysimilarity index 100%rename from rust/apps/cli-next/tests/cli/admin_prompt.pyrename to rust/apps/cli/tests/cli/admin_prompt.pydiff --git a/rust/apps/cli-next/tests/cli/auth.rs b/rust/apps/cli/tests/cli/auth.rssimilarity index 100%rename from rust/apps/cli-next/tests/cli/auth.rsrename to rust/apps/cli/tests/cli/auth.rsdiff --git a/rust/apps/cli-next/tests/cli/export.rs b/rust/apps/cli/tests/cli/export.rssimilarity index 100%rename from rust/apps/cli-next/tests/cli/export.rsrename to rust/apps/cli/tests/cli/export.rsdiff --git a/rust/apps/cli-next/tests/cli/export_adoption.rs b/rust/apps/cli/tests/cli/export_adoption.rssimilarity index 100%rename from rust/apps/cli-next/tests/cli/export_adoption.rsrename to rust/apps/cli/tests/cli/export_adoption.rsdiff --git a/rust/apps/cli-next/tests/cli/export_engine.rs b/rust/apps/cli/tests/cli/export_engine.rssimilarity index 100%rename from rust/apps/cli-next/tests/cli/export_engine.rsrename to rust/apps/cli/tests/cli/export_engine.rsdiff --git a/rust/apps/cli-next/tests/cli/export_maintenance.rs b/rust/apps/cli/tests/cli/export_maintenance.rssimilarity index 100%rename from rust/apps/cli-next/tests/cli/export_maintenance.rsrename to rust/apps/cli/tests/cli/export_maintenance.rsdiff --git a/rust/apps/cli-next/tests/cli/export_media.rs b/rust/apps/cli/tests/cli/export_media.rssimilarity index 100%rename from rust/apps/cli-next/tests/cli/export_media.rsrename to rust/apps/cli/tests/cli/export_media.rsdiff --git a/rust/apps/cli-next/tests/cli/export_process.rs b/rust/apps/cli/tests/cli/export_process.rssimilarity index 100%rename from rust/apps/cli-next/tests/cli/export_process.rsrename to rust/apps/cli/tests/cli/export_process.rsdiff --git a/rust/apps/cli-next/tests/cli/export_resources.rs b/rust/apps/cli/tests/cli/export_resources.rssimilarity index 100%rename from rust/apps/cli-next/tests/cli/export_resources.rsrename to rust/apps/cli/tests/cli/export_resources.rsdiff --git a/rust/apps/cli-next/tests/cli/export_sources.rs b/rust/apps/cli/tests/cli/export_sources.rssimilarity index 100%rename from rust/apps/cli-next/tests/cli/export_sources.rsrename to rust/apps/cli/tests/cli/export_sources.rsdiff --git a/rust/apps/cli-next/tests/cli/files.rs b/rust/apps/cli/tests/cli/files.rssimilarity index 96%rename from rust/apps/cli-next/tests/cli/files.rsrename to rust/apps/cli/tests/cli/files.rsindex 62f0c655cb..4f3a0d8ef0 100644--- a/rust/apps/cli-next/tests/cli/files.rs+++ b/rust/apps/cli/tests/cli/files.rs@@ -88,12 +88,6 @@ fn downloads_publish_only_complete_authenticated_originals() {let original = vec![37u8; stream::ENCRYPTION_CHUNK_SIZE + 321];let (file, encrypted) = remote_file(10, &collection_key, &original);page(&mut server, 1, 0, json!([file]), false).create();- let signed = server- .mock("GET", "/files/download/v3/10")- .match_header("x-auth-token", "--8=")- .with_body(json!({"url": format!("{}/original", server.url())}).to_string())- .expect_at_least(1)- .create();let args = ["photos","file",@@ -103,6 +97,31 @@ fn downloads_publish_only_complete_authenticated_originals() {path.to_str().unwrap(),"--json",];+ let unavailable = server+ .mock("GET", "/files/download/v3/10")+ .with_status(404)+ .create();+ assert_eq!(+ failure(&home.run(&args)),+ "Error: cannot download file 10: HTTP 404 at /files/download/v3/10\nFile downloads require the v3 API. Update your Ente server or check its proxy configuration.\n"+ );+ assert!(!path.exists());+ unavailable.assert();+ unavailable.remove();+ let signed = server+ .mock("GET", "/files/download/v3/10")+ .match_header("x-auth-token", "--8=")+ .with_body(json!({"url": format!("{}/original", server.url())}).to_string())+ .expect_at_least(1)+ .create();+ let missing = server.mock("GET", "/original").with_status(404).create();+ assert_eq!(+ failure(&home.run(&args)),+ "Error: cannot download file 10: HTTP 404 at /original\n"+ );+ assert!(!path.exists());+ missing.assert();+ missing.remove();let mut damaged = encrypted.clone();*damaged.last_mut().unwrap() ^= 1;let mut trailing = encrypted.clone();diff --git a/rust/apps/cli-next/tests/cli/main.rs b/rust/apps/cli/tests/cli/main.rssimilarity index 99%rename from rust/apps/cli-next/tests/cli/main.rsrename to rust/apps/cli/tests/cli/main.rsindex 53a2bdeb58..a947875504 100644--- a/rust/apps/cli-next/tests/cli/main.rs+++ b/rust/apps/cli/tests/cli/main.rs@@ -47,7 +47,7 @@ fn completion_prints_scripts_without_storage() {#[test]fn migration_hints_respect_command_and_argument_boundaries() {- let binary = format!("ente-cli-next{}", std::env::consts::EXE_SUFFIX);+ let binary = format!("ente{}", std::env::consts::EXE_SUFFIX);let home = TestHome::new();let path = home.dir.path().join("unused");for (args, suggestion) in [@@ -101,7 +101,7 @@ fn migration_hints_respect_command_and_argument_boundaries() {#[test]fn reads_do_not_initialize_storage() {- let binary = format!("ente-cli-next{}", std::env::consts::EXE_SUFFIX);+ let binary = format!("ente{}", std::env::consts::EXE_SUFFIX);for existing_home in [false, true] {let home = TestHome::new();let path = home.dir.path().join("unused");@@ -1042,7 +1042,7 @@ impl TestHome {}fn command(&self, args: &[&str]) -> Command {- let mut command = Command::new(env!("CARGO_BIN_EXE_ente-cli-next"));+ let mut command = Command::new(env!("CARGO_BIN_EXE_ente"));command.env_clear().env("ENTE_CLI_HOME", self.dir.path())diff --git a/rust/apps/cli-next/tests/cli/museum.rs b/rust/apps/cli/tests/cli/museum.rssimilarity index 100%rename from rust/apps/cli-next/tests/cli/museum.rsrename to rust/apps/cli/tests/cli/museum.rsdiff --git a/rust/apps/cli-next/tests/cli/paste.rs b/rust/apps/cli/tests/cli/paste.rssimilarity index 99%rename from rust/apps/cli-next/tests/cli/paste.rsrename to rust/apps/cli/tests/cli/paste.rsindex 9c13839302..55d3a5f99d 100644--- a/rust/apps/cli-next/tests/cli/paste.rs+++ b/rust/apps/cli/tests/cli/paste.rs@@ -56,7 +56,7 @@ fn create_and_consume_preserve_each_input_without_account_storage() {.mock("POST", "/paste/create").match_header("user-agent",- concat!("ente-cli-next/", env!("CARGO_PKG_VERSION")),+ concat!(env!("CARGO_PKG_NAME"), "/", env!("CARGO_PKG_VERSION")),).with_body_from_request(move |request| {*body.lock().unwrap() =diff --git a/rust/apps/cli-next/tests/fixtures/export-adoption/desktop-file.json b/rust/apps/cli/tests/fixtures/export-adoption/desktop-file.jsonsimilarity index 100%rename from rust/apps/cli-next/tests/fixtures/export-adoption/desktop-file.jsonrename to rust/apps/cli/tests/fixtures/export-adoption/desktop-file.jsondiff --git a/rust/apps/cli-next/tests/fixtures/export-adoption/desktop-manifest.json b/rust/apps/cli/tests/fixtures/export-adoption/desktop-manifest.jsonsimilarity index 100%rename from rust/apps/cli-next/tests/fixtures/export-adoption/desktop-manifest.jsonrename to rust/apps/cli/tests/fixtures/export-adoption/desktop-manifest.jsondiff --git a/rust/apps/cli-next/tests/fixtures/export-adoption/go-album.json b/rust/apps/cli/tests/fixtures/export-adoption/go-album.jsonsimilarity index 100%rename from rust/apps/cli-next/tests/fixtures/export-adoption/go-album.jsonrename to rust/apps/cli/tests/fixtures/export-adoption/go-album.jsondiff --git a/rust/apps/cli-next/tests/fixtures/export-adoption/go-file.json b/rust/apps/cli/tests/fixtures/export-adoption/go-file.jsonsimilarity index 100%rename from rust/apps/cli-next/tests/fixtures/export-adoption/go-file.jsonrename to rust/apps/cli/tests/fixtures/export-adoption/go-file.jsondiff --git a/rust/apps/cli/tests/paste.rs b/rust/apps/cli/tests/paste.rsdeleted file mode 100644index 1594e25c9e..0000000000--- a/rust/apps/cli/tests/paste.rs+++ /dev/null@@ -1,327 +0,0 @@-#![cfg(test)]-#![cfg(feature = "museum")]--mod support;--use support::{Cli, Museum, TestResult};-use url::Url;-use uuid::Uuid;--const PASTE_PASSWORD_ENV: &str = "ENTE_PASTE_PASSWORD";-const PASTE_ORIGIN: &str = "http://127.0.0.1";--#[test]-fn paste() -> TestResult {- Museum::run(|museum| {- full_link_roundtrip(museum)?;- token_and_key_roundtrip(museum)?;- stdin_roundtrip(museum)?;- password_protected_roundtrip(museum)?;- wrong_password_consumes_password_protected_paste(museum)?;- consumed_password_paste_checks_availability_before_password(museum)- })-}--fn full_link_roundtrip(museum: &Museum) -> TestResult {- let cli = support::cli_session(museum, "full-link")?;- let text = unique_text("full-link");- let link = create_paste(&cli, museum, &text)?;-- let consumed = cli.run_ok(&[- "paste",- "consume",- "--endpoint",- museum.endpoint(),- &link.raw,- ])?;- assert_eq!(consumed, text);-- let second_consume = cli.run(&[- "paste",- "consume",- "--endpoint",- museum.endpoint(),- &link.raw,- ])?;- assert!(- !second_consume.status.success(),- "second consume unexpectedly succeeded with stdout: {}",- String::from_utf8_lossy(&second_consume.stdout),- );- assert!(- String::from_utf8_lossy(&second_consume.stderr)- .contains("This paste has expired or was already opened."),- "second consume should report the paste as unavailable, got stderr: {}",- String::from_utf8_lossy(&second_consume.stderr),- );-- Ok(())-}--fn token_and_key_roundtrip(museum: &Museum) -> TestResult {- let cli = support::cli_session(museum, "token-key")?;- let text = unique_text("token-key");- let link = create_paste(&cli, museum, &text)?;-- let consumed = cli.run_ok(&[- "paste",- "consume",- "--endpoint",- museum.endpoint(),- "--key",- &link.key,- &link.token,- ])?;- assert_eq!(consumed, text);-- Ok(())-}--fn stdin_roundtrip(museum: &Museum) -> TestResult {- let cli = support::cli_session(museum, "stdin")?;- let text = format!(- "paste stdin scenario {}\n\nsecond line stays intact\n",- Uuid::new_v4()- );- let link = cli.run_ok_with_stdin(- &[- "paste",- "create",- "--endpoint",- museum.endpoint(),- "--paste-origin",- PASTE_ORIGIN,- ],- &text,- )?;- let link = PasteLink::parse(link.trim(), PASTE_ORIGIN);-- let consumed = cli.run_ok(&[- "paste",- "consume",- "--endpoint",- museum.endpoint(),- &link.raw,- ])?;- assert_eq!(consumed, text);-- Ok(())-}--fn password_protected_roundtrip(museum: &Museum) -> TestResult {- let cli = support::cli_session(museum, "password-protected")?;- let text = unique_text("password-protected");- let password = format!("password {}", Uuid::new_v4());- let link = create_password_paste(&cli, museum, &text, &password)?;- let env = [(PASTE_PASSWORD_ENV, password.as_str())];- assert!(link.password_required);-- let consumed = cli.run_ok_with_env(- &[- "paste",- "consume",- "--endpoint",- museum.endpoint(),- &link.raw,- ],- &env,- )?;- assert_eq!(consumed, text);-- Ok(())-}--fn wrong_password_consumes_password_protected_paste(museum: &Museum) -> TestResult {- let cli = support::cli_session(museum, "wrong-password")?;- let text = unique_text("wrong-password");- let password = format!("password {}", Uuid::new_v4());- let link = create_password_paste(&cli, museum, &text, &password)?;-- let wrong_env = [(PASTE_PASSWORD_ENV, "wrong password")];- let wrong = cli.run_with_env(- &[- "paste",- "consume",- "--endpoint",- museum.endpoint(),- &link.raw,- ],- &wrong_env,- )?;- assert!(- !wrong.status.success(),- "wrong password unexpectedly succeeded"- );- assert!(- String::from_utf8_lossy(&wrong.stderr).contains("Incorrect paste password"),- "wrong password should fail locally, got stderr: {}",- String::from_utf8_lossy(&wrong.stderr),- );-- let correct_env = [(PASTE_PASSWORD_ENV, password.as_str())];- let second = cli.run_with_env(- &[- "paste",- "consume",- "--endpoint",- museum.endpoint(),- &link.raw,- ],- &correct_env,- )?;- assert!(- !second.status.success(),- "second consume unexpectedly succeeded with stdout: {}",- String::from_utf8_lossy(&second.stdout),- );- assert!(- String::from_utf8_lossy(&second.stderr)- .contains("This paste has expired or was already opened."),- "second consume should report the paste as unavailable, got stderr: {}",- String::from_utf8_lossy(&second.stderr),- );-- Ok(())-}--fn consumed_password_paste_checks_availability_before_password(museum: &Museum) -> TestResult {- let cli = support::cli_session(museum, "consumed-password")?;- let text = unique_text("consumed-password");- let password = format!("password {}", Uuid::new_v4());- let link = create_password_paste(&cli, museum, &text, &password)?;- let env = [(PASTE_PASSWORD_ENV, password.as_str())];-- let consumed = cli.run_ok_with_env(- &[- "paste",- "consume",- "--endpoint",- museum.endpoint(),- &link.raw,- ],- &env,- )?;- assert_eq!(consumed, text);-- let invalid_env = [(PASTE_PASSWORD_ENV, "")];- let second = cli.run_with_env(- &[- "paste",- "consume",- "--endpoint",- museum.endpoint(),- &link.raw,- ],- &invalid_env,- )?;- assert!(- !second.status.success(),- "second consume unexpectedly succeeded"- );- assert!(- String::from_utf8_lossy(&second.stderr)- .contains("This paste has expired or was already opened."),- "consumed paste should fail before password validation, got stderr: {}",- String::from_utf8_lossy(&second.stderr),- );- assert!(- !String::from_utf8_lossy(&second.stderr).contains("Paste password cannot be empty"),- "consumed paste validated password before guard: {}",- String::from_utf8_lossy(&second.stderr),- );-- Ok(())-}--fn create_paste(cli: &Cli, museum: &Museum, text: &str) -> TestResult<PasteLink> {- let link = cli.run_ok(&[- "paste",- "create",- "--endpoint",- museum.endpoint(),- "--paste-origin",- PASTE_ORIGIN,- text,- ])?;- Ok(PasteLink::parse(link.trim(), PASTE_ORIGIN))-}--fn create_password_paste(- cli: &Cli,- museum: &Museum,- text: &str,- password: &str,-) -> TestResult<PasteLink> {- let env = [(PASTE_PASSWORD_ENV, password)];- let link = cli.run_ok_with_env(- &[- "paste",- "create",- "--endpoint",- museum.endpoint(),- "--paste-origin",- PASTE_ORIGIN,- "--password",- text,- ],- &env,- )?;- Ok(PasteLink::parse(link.trim(), PASTE_ORIGIN))-}--fn unique_text(scope: &str) -> String {- format!("paste cli {scope} scenario {}", Uuid::new_v4())-}--struct PasteLink {- raw: String,- token: String,- key: String,- password_required: bool,-}--impl PasteLink {- fn parse(raw: &str, expected_origin: &str) -> Self {- let url = Url::parse(raw).unwrap_or_else(|error| {- panic!("invalid paste link {raw}: {error}");- });- let actual_origin = url.origin().ascii_serialization();- let expected_origin = Url::parse(expected_origin)- .expect("expected paste origin should be a URL")- .origin()- .ascii_serialization();- let token = url- .path_segments()- .and_then(|mut segments| segments.rfind(|segment| !segment.is_empty()))- .expect("paste link should include an access token")- .to_string();- let key = url- .fragment()- .expect("paste link should include a decryption key fragment")- .to_string();- let (password_required, fragment_secret) = match key.strip_prefix("p-") {- Some(fragment_secret) => (true, fragment_secret),- None => (false, key.as_str()),- };-- assert_eq!(- actual_origin, expected_origin,- "paste link used unexpected origin: {raw}",- );- assert!(- fragment_secret.len() == 12- && fragment_secret- .bytes()- .all(|byte| byte.is_ascii_alphanumeric()),- "paste link key has unexpected format: {key}",- );- assert!(!token.is_empty(), "paste link token is empty: {raw}");-- Self {- raw: raw.to_string(),- token,- key,- password_required,- }- }-}diff --git a/rust/apps/cli/tests/support/cli.rs b/rust/apps/cli/tests/support/cli.rsdeleted file mode 100644index 4955d08339..0000000000--- a/rust/apps/cli/tests/support/cli.rs+++ /dev/null@@ -1,80 +0,0 @@-use std::{- io::Write,- path::{Path, PathBuf},- process::{Command, Output, Stdio},-};--use super::TestResult;--pub struct Cli {- bin: PathBuf,- config_dir: PathBuf,-}--impl Cli {- pub fn new(config_dir: PathBuf) -> Self {- Self {- bin: PathBuf::from(env!("CARGO_BIN_EXE_ente-rs")),- config_dir,- }- }-- pub fn run(&self, args: &[&str]) -> TestResult<Output> {- Ok(command(&self.bin, &self.config_dir, args).output()?)- }-- pub fn run_with_env(&self, args: &[&str], env: &[(&str, &str)]) -> TestResult<Output> {- let mut command = command(&self.bin, &self.config_dir, args);- command.envs(env.iter().copied());- Ok(command.output()?)- }-- pub fn run_ok(&self, args: &[&str]) -> TestResult<String> {- output_stdout(args, self.run(args)?)- }-- pub fn run_ok_with_env(&self, args: &[&str], env: &[(&str, &str)]) -> TestResult<String> {- output_stdout(args, self.run_with_env(args, env)?)- }-- pub fn run_with_stdin(&self, args: &[&str], stdin: &str) -> TestResult<Output> {- let mut child = command(&self.bin, &self.config_dir, args)- .stdin(Stdio::piped())- .stdout(Stdio::piped())- .stderr(Stdio::piped())- .spawn()?;-- child- .stdin- .take()- .expect("ente-rs stdin should be piped")- .write_all(stdin.as_bytes())?;-- Ok(child.wait_with_output()?)- }-- pub fn run_ok_with_stdin(&self, args: &[&str], stdin: &str) -> TestResult<String> {- output_stdout(args, self.run_with_stdin(args, stdin)?)- }-}--fn command(bin: &Path, config_dir: &Path, args: &[&str]) -> Command {- let mut command = Command::new(bin);- command.args(args).env("ENTE_CLI_CONFIG_DIR", config_dir);- command-}--fn output_stdout(args: &[&str], output: Output) -> TestResult<String> {- if output.status.success() {- Ok(String::from_utf8(output.stdout)?)- } else {- Err(format!(- "ente-rs {} failed\nstatus: {}\nstdout:\n{}\nstderr:\n{}",- args.join(" "),- output.status,- String::from_utf8_lossy(&output.stdout),- String::from_utf8_lossy(&output.stderr),- )- .into())- }-}diff --git a/rust/apps/cli/tests/support/mod.rs b/rust/apps/cli/tests/support/mod.rsdeleted file mode 100644index f7aa2b7998..0000000000--- a/rust/apps/cli/tests/support/mod.rs+++ /dev/null@@ -1,12 +0,0 @@-#![cfg(test)]--mod cli;--pub use cli::Cli;-pub use ente_test_support::{Museum, TestResult};--pub fn cli_session(museum: &Museum, scenario: &str) -> TestResult<Cli> {- let config_dir = museum.temp_dir().join("cli").join(scenario);- std::fs::create_dir_all(&config_dir)?;- Ok(Cli::new(config_dir))-}diff --git a/rust/apps/cli/tests/sync.rs b/rust/apps/cli/tests/sync.rsdeleted file mode 100644index ee643dd515..0000000000--- a/rust/apps/cli/tests/sync.rs+++ /dev/null@@ -1,44 +0,0 @@-#![cfg(feature = "museum")]--#[expect(- dead_code,- reason = "Sync tests use only part of the shared CLI helpers"-)]-mod support;--use ente_test_support::HARDCODED_OTT;-use support::{Museum, TestResult};--#[test]-fn sync() -> TestResult {- Museum::run(|museum| {- let export_dir = museum.temp_dir().join("export");- std::fs::create_dir_all(&export_dir)?;-- for command in ["create", "add"] {- let cli = support::cli_session(museum, command)?;- cli.run_ok(&[- "account",- command,- "--email",- "[email protected]",- "--password",- "sync-test-password",- "--endpoint",- museum.endpoint(),- "--export-dir",- export_dir.to_str().unwrap(),- "--otp",- HARDCODED_OTT,- ])?;-- let output = cli.run_ok(&["export"])?;- assert!(- output.contains("Sync completed"),- "export did not sync: {output}"- );- }-- Ok(())- })-}diff --git a/rust/checks/dependency-boundaries/check.mjs b/rust/checks/dependency-boundaries/check.mjsindex 31d3faeb93..93d019edfe 100644--- a/rust/checks/dependency-boundaries/check.mjs+++ b/rust/checks/dependency-boundaries/check.mjs@@ -27,7 +27,7 @@ const domain = metadata.packages.filter((pkg) =>);const httpOwners = new Set([- "rust/apps/cli-next/Cargo.toml",+ "rust/apps/cli/Cargo.toml","rust/crates/assets/Cargo.toml","rust/crates/core/Cargo.toml","rust/tools/location-dataset/Cargo.toml",diff --git a/rust/checks/lint-exceptions/suppressions.json b/rust/checks/lint-exceptions/suppressions.jsonindex 38938d1d01..c9add6495a 100644--- a/rust/checks/lint-exceptions/suppressions.json+++ b/rust/checks/lint-exceptions/suppressions.json@@ -1,9 +1,4 @@{- "rust/apps/cli/src/models/export_metadata.rs": [- "clippy::trivially_copy_pass_by_ref"- ],- "rust/apps/cli/src/sync/download.rs": ["clippy::expect_used"],- "rust/apps/cli/tests/sync.rs": ["dead_code"],"rust/apps/ensu/src-tauri/src/logging.rs": ["clippy::expect_used"],"rust/bindings/frb/locker/src/lib.rs": ["clippy::allow_attributes",diff --git a/rust/crates/photos/src/files.rs b/rust/crates/photos/src/files.rsindex 637a99af6d..6e9f68d559 100644--- a/rust/crates/photos/src/files.rs+++ b/rust/crates/photos/src/files.rs@@ -63,6 +63,10 @@ pub struct Location {pub enum Error {#[error(transparent)]Http(#[from] http::Error),+ #[error(+ "HTTP 404 at /files/download/v3/{0}\nFile downloads require the v3 API. Update your Ente server or check its proxy configuration."+ )]+ DownloadApiUnavailable(i64),#[error(transparent)]Crypto(#[from] crypto::Error),#[error(transparent)]@@ -92,15 +96,15 @@ pub async fn download<W: std::io::Write>(let output = output();async move {let output = output?;- let signed: DownloadUrl = session+ let response = session.api.get(&format!("/files/download/v3/{id}")).send()- .await?- .error_for_code()- .await?- .json().await?;+ if response.status() == 404 {+ return Err(Error::DownloadApiUnavailable(id));+ }+ let signed: DownloadUrl = response.error_for_code().await?.json().await?;let response = session.api.http()diff --git a/rust/crates/test-support/README.md b/rust/crates/test-support/README.mdindex 4864e0d89d..4e7983fa1e 100644--- a/rust/crates/test-support/README.md+++ b/rust/crates/test-support/README.md@@ -11,5 +11,5 @@ Requires `go` on PATH to build and run Museum. The Postgres binary ([postgresql_Tests that use it are gated behind a Cargo feature so that a plain `cargo test` skips them. They can be run by enabling the `museum` feature, e.g.:```sh-cargo test -p ente-rs --features museum+cargo test -p ente-cli --features museum```