π End-to-end encrypted cloud for everything.
Dart 2faandroidauthye2eeencryptionend-to-end-encryptionfluttergolanggoogle-photosgoogle-photos-alternativeiosopensourcephotosprivacyprivacy-toolstypescriptzero-knowledge
Add Photos file listing and downloads to the replacement CLI
Manav Rathib221f72a6401
diff --git a/rust/Cargo.lock b/rust/Cargo.lockindex 000ecfa2e1..dca96818ef 100644--- a/rust/Cargo.lock+++ b/rust/Cargo.lock@@ -2771,9 +2771,11 @@ dependencies = ["ente-core","ente-exif","ente-location",+ "futures-util","quick-xml","rusqlite","serde",+ "serde_json","tempfile","thiserror 2.0.18",]diff --git a/rust/apps/cli-next/src/args.rs b/rust/apps/cli-next/src/args.rsindex 2b7c1a382a..18a72ad333 100644--- a/rust/apps/cli-next/src/args.rs+++ b/rust/apps/cli-next/src/args.rs@@ -78,6 +78,18 @@ pub enum PhotosCommand {#[command(subcommand)]command: AlbumCommand,},+ #[command(about = "Manage files")]+ File {+ #[arg(+ long,+ global = true,+ value_name = "ALBUM",+ help = "Limit to an album ID or exact name"+ )]+ album: Option<String>,+ #[command(subcommand)]+ command: FileCommand,+ },}#[derive(Subcommand)]@@ -148,6 +160,29 @@ pub struct ApiArgs {pub enum AlbumCommand {#[command(about = "List your albums, including shared and hidden ones")]List,+ #[command(about = "Show an album")]+ View {+ #[arg(help = "Album ID or exact name")]+ album: String,+ },+}++#[derive(Subcommand)]+pub enum FileCommand {+ #[command(about = "List files, including shared and hidden ones")]+ List,+ #[command(about = "Show a file's metadata")]+ View {+ #[arg(help = "File ID or exact name")]+ file: String,+ },+ #[command(about = "Download an original; Live Photos are saved as ZIP archives")]+ Download {+ #[arg(help = "File ID or exact name")]+ file: String,+ #[arg(long, value_name = "PATH", help = "Write to this new file")]+ output: PathBuf,+ },}#[derive(Subcommand)]diff --git a/rust/apps/cli-next/src/main.rs b/rust/apps/cli-next/src/main.rsindex 4a7096879b..cd24731607 100644--- a/rust/apps/cli-next/src/main.rs+++ b/rust/apps/cli-next/src/main.rs@@ -2,6 +2,7 @@ mod api;mod args;mod login;mod output;+mod photos;mod vault;use std::{@@ -12,16 +13,14 @@ use std::{use anyhow::{Context, Result, bail};use clap::Parser;use ente_core::{b64, crypto::Key};-use ente_photos::collections;use serde::de::DeserializeOwned;use serde_json::json;use zeroize::Zeroizing;use args::{- AccountCommand, AlbumCommand, Cli, Command, KeyCommand, PhotosCommand, Product, SessionCommand,- VaultCommand,+ AccountCommand, Cli, Command, KeyCommand, PhotosCommand, Product, SessionCommand, VaultCommand,};-use output::{AccountView, AlbumView};+use output::AccountView;use vault::{State, Vault};#[tokio::main(flavor = "current_thread")]@@ -47,11 +46,12 @@ async fn run(cli: Cli) -> Result<()> {}Command::Photos {selector,- command:- PhotosCommand::Album {- command: AlbumCommand::List,- },- } => album_list(selector.account.as_deref(), json).await,+ command: PhotosCommand::Album { command },+ } => photos::album(command, selector.account.as_deref(), json).await,+ Command::Photos {+ selector,+ command: PhotosCommand::File { album, command },+ } => photos::file(command, album.as_deref(), selector.account.as_deref(), json).await,Command::Accounts { command } => account_command(command, json).await,Command::Vault {command:@@ -71,22 +71,6 @@ fn vault_key(json_output: bool) -> Result<()> {}}-async fn album_list(selected: Option<&str>, json_output: bool) -> Result<()> {- let state = State::load()?;- let account = &state.accounts[state.resolve(selected)?];- let session = api::session(account, Product::Photos)?;- let albums = collections::list(&session)- .await?- .into_iter()- .map(AlbumView::try_from)- .collect::<Result<Vec<_>>>()?;- if json_output {- output::json(&albums)- } else {- output::albums(&albums)- }-}-async fn session(product: Product,command: SessionCommand,diff --git a/rust/apps/cli-next/src/output.rs b/rust/apps/cli-next/src/output.rsindex 3d55deec5e..db4168a686 100644--- a/rust/apps/cli-next/src/output.rs+++ b/rust/apps/cli-next/src/output.rs@@ -3,7 +3,7 @@ use std::io::Write;use anyhow::{Context, Result};use chrono::{DateTime, SecondsFormat};use dialoguer::console::{Alignment, measure_text_width, pad_str};-use ente_photos::collections::{Collection, Visibility};+use ente_photos::{collections::Collection, files::File};use serde::Serialize;use uuid::Uuid;@@ -48,24 +48,74 @@ impl TryFrom<Collection> for AlbumView {type Error = anyhow::Error;fn try_from(album: Collection) -> Result<Self> {- let updated_at = DateTime::from_timestamp_micros(album.updated_at_micros)- .context("album timestamp is outside the supported range")?- .to_rfc3339_opts(SecondsFormat::Micros, true);+ let updated_at = timestamp(album.updated_at_micros)?;Ok(Self {id: album.id.to_string(),name: album.name,kind: album.kind.name(),- visibility: match album.visibility {- Visibility::Visible => "visible",- Visibility::Archived => "archived",- Visibility::Hidden => "hidden",- },+ visibility: album.visibility.name(),owner_id: album.owner_id.to_string(),updated_at,})}}+#[derive(Serialize)]+#[serde(rename_all = "camelCase")]+pub struct FileView<'a> {+ id: String,+ name: &'a str,+ #[serde(rename = "type")]+ kind: &'static str,+ owner_id: String,+ album_ids: Vec<String>,+ created_at: String,+ modified_at: String,+ updated_at: String,+ location: Option<LocationView>,+ caption: Option<&'a str>,+ hash: Option<&'a str>,+ date_time: Option<&'a str>,+ offset_time: Option<&'a str>,+ duration_seconds: Option<u64>,+ width: Option<u32>,+ height: Option<u32>,+ visibility: &'static str,+}++#[derive(Serialize)]+struct LocationView {+ latitude: f64,+ longitude: f64,+}++impl<'a> FileView<'a> {+ pub fn new(file: &'a File, album_ids: &[i64]) -> Result<Self> {+ Ok(Self {+ id: file.id.to_string(),+ name: &file.name,+ kind: file.kind.name(),+ owner_id: file.owner_id.to_string(),+ album_ids: album_ids.iter().map(i64::to_string).collect(),+ created_at: timestamp(file.created_at_micros)?,+ modified_at: timestamp(file.modified_at_micros)?,+ updated_at: timestamp(file.updated_at_micros)?,+ location: file.location.as_ref().map(|location| LocationView {+ latitude: location.latitude,+ longitude: location.longitude,+ }),+ caption: file.caption.as_deref(),+ hash: file.hash.as_deref(),+ date_time: file.date_time.as_deref(),+ offset_time: file.offset_time.as_deref(),+ duration_seconds: file.duration_seconds,+ width: file.width,+ height: file.height,+ visibility: file.visibility.name(),+ })+ }+}+pub fn json(value: &impl Serialize) -> Result<()> {let mut stdout = std::io::stdout().lock();serde_json::to_writer(&mut stdout, value)?;@@ -107,7 +157,7 @@ pub fn accounts(accounts: &[AccountView<'_>]) -> Result<()> {}pub fn account(account: &AccountView<'_>) -> Result<()> {- let fields = [+ write_fields(&[("Name", escape_controls(account.name)),("Email", escape_controls(account.email)),("Host", escape_controls(account.host)),@@ -117,21 +167,7 @@ pub fn account(account: &AccountView<'_>) -> Result<()> {if account.selected { "yes" } else { "no" }.to_owned(),),("ID", account.id.clone()),- ];- let width = fields- .iter()- .map(|(name, _)| measure_text_width(name))- .max()- .unwrap_or(0);- let mut stdout = std::io::stdout().lock();- for (name, value) in fields {- writeln!(- stdout,- "{} {value}",- pad_str(name, width, Alignment::Left, None)- )?;- }- Ok(())+ ])}pub fn albums(albums: &[AlbumView]) -> Result<()> {@@ -159,6 +195,81 @@ pub fn albums(albums: &[AlbumView]) -> Result<()> {)}+pub fn album(album: &AlbumView) -> Result<()> {+ write_fields(&[+ ("Name", escape_controls(&album.name)),+ ("Type", album.kind.to_owned()),+ ("Visibility", album.visibility.to_owned()),+ ("Owner", album.owner_id.clone()),+ ("Updated", album.updated_at.clone()),+ ("ID", album.id.clone()),+ ])+}++pub fn files(files: &[FileView<'_>]) -> Result<()> {+ let mut stdout = std::io::stdout().lock();+ if files.is_empty() {+ return writeln!(stdout, "No files.").map_err(Into::into);+ }+ let rows = files+ .iter()+ .map(|file| {+ [+ file.id.clone(),+ escape_controls(file.name),+ file.kind.to_owned(),+ file.created_at.clone(),+ file.album_ids.join(","),+ ]+ })+ .collect::<Vec<_>>();+ write_table(+ &mut stdout,+ ["ID", "NAME", "TYPE", "CREATED", "ALBUMS"],+ &rows,+ )+}++pub fn file(file: &FileView<'_>) -> Result<()> {+ let mut fields = vec![+ ("Name", escape_controls(file.name)),+ ("Type", file.kind.to_owned()),+ ("Visibility", file.visibility.to_owned()),+ ("Created", file.created_at.clone()),+ ("Modified", file.modified_at.clone()),+ ("Updated", file.updated_at.clone()),+ ("Owner", file.owner_id.clone()),+ ("Albums", file.album_ids.join(", ")),+ ("ID", file.id.clone()),+ ];+ for (label, value) in [+ ("Caption", file.caption.map(escape_controls)),+ (+ "Location",+ file.location+ .as_ref()+ .map(|l| format!("{}, {}", l.latitude, l.longitude)),+ ),+ ("Date/time", file.date_time.map(escape_controls)),+ ("UTC offset", file.offset_time.map(escape_controls)),+ ("Duration", file.duration_seconds.map(|s| format!("{s} s"))),+ ("Width", file.width.map(|w| w.to_string())),+ ("Height", file.height.map(|h| h.to_string())),+ ("Hash", file.hash.map(escape_controls)),+ ] {+ if let Some(value) = value {+ fields.push((label, value));+ }+ }+ write_fields(&fields)+}++fn timestamp(micros: i64) -> Result<String> {+ Ok(DateTime::from_timestamp_micros(micros)+ .context("timestamp is outside the supported range")?+ .to_rfc3339_opts(SecondsFormat::Micros, true))+}+fn products(account: &AccountView<'_>) -> String {let products = account.products@@ -173,6 +284,23 @@ fn products(account: &AccountView<'_>) -> String {}}+fn write_fields(fields: &[(&str, String)]) -> Result<()> {+ let width = fields+ .iter()+ .map(|(name, _)| measure_text_width(name))+ .max()+ .unwrap_or(0);+ let mut stdout = std::io::stdout().lock();+ for (name, value) in fields {+ writeln!(+ stdout,+ "{} {value}",+ pad_str(name, width, Alignment::Left, None)+ )?;+ }+ Ok(())+}+fn write_table<const N: usize>(out: &mut impl Write,header: [&str; N],diff --git a/rust/apps/cli-next/src/photos.rs b/rust/apps/cli-next/src/photos.rsnew file mode 100644index 0000000000..4d181459f6--- /dev/null+++ b/rust/apps/cli-next/src/photos.rs@@ -0,0 +1,156 @@+use std::{collections::BTreeMap, path::Path};++use anyhow::{Context, Result, bail};+use ente_photos::{collections, files};+use serde_json::json;++use crate::{+ api,+ args::{AlbumCommand, FileCommand, Product},+ output::{self, AlbumView, FileView},+ vault::State,+};++pub async fn album(command: AlbumCommand, selected: Option<&str>, json_output: bool) -> Result<()> {+ let state = State::load()?;+ let account = &state.accounts[state.resolve(selected)?];+ let session = api::session(account, Product::Photos)?;+ let albums = collections::list(&session).await?;+ match command {+ AlbumCommand::List => {+ let albums = albums+ .into_iter()+ .map(AlbumView::try_from)+ .collect::<Result<Vec<_>>>()?;+ if json_output {+ output::json(&albums)+ } else {+ output::albums(&albums)+ }+ }+ AlbumCommand::View { album } => {+ let album = select(albums, &album, "album", |a| (a.id, &a.name))?;+ let album = AlbumView::try_from(album)?;+ if json_output {+ output::json(&album)+ } else {+ output::album(&album)+ }+ }+ }+}++pub async fn file(+ command: FileCommand,+ album: Option<&str>,+ selected: Option<&str>,+ json_output: bool,+) -> Result<()> {+ let state = State::load()?;+ let account = &state.accounts[state.resolve(selected)?];+ let session = api::session(account, Product::Photos)?;+ let mut albums = collections::list(&session).await?;+ if let Some(selector) = album {+ albums = vec![select(albums, selector, "album", |a| (a.id, &a.name))?];+ }+ let mut entries: BTreeMap<i64, Entry> = BTreeMap::new();+ for album in albums {+ for file in files::list(&session, &album).await? {+ match entries.entry(file.id) {+ std::collections::btree_map::Entry::Vacant(entry) => {+ entry.insert(Entry {+ file,+ album_ids: vec![album.id],+ });+ }+ std::collections::btree_map::Entry::Occupied(mut entry) => {+ let entry = entry.get_mut();+ entry.album_ids.push(album.id);+ if file.updated_at_micros > entry.file.updated_at_micros {+ entry.file = file;+ }+ }+ }+ }+ }+ let mut entries = entries.into_values().collect::<Vec<_>>();+ for entry in &mut entries {+ entry.album_ids.sort_unstable();+ }+ match command {+ FileCommand::List => {+ let views = entries+ .iter()+ .map(|entry| FileView::new(&entry.file, &entry.album_ids))+ .collect::<Result<Vec<_>>>()?;+ if json_output {+ output::json(&views)+ } else {+ output::files(&views)+ }+ }+ FileCommand::View { file } => {+ let entry = select(entries, &file, "file", |e| (e.file.id, &e.file.name))?;+ let view = FileView::new(&entry.file, &entry.album_ids)?;+ if json_output {+ output::json(&view)+ } else {+ output::file(&view)+ }+ }+ FileCommand::Download { file, output } => {+ let entry = select(entries, &file, "file", |e| (e.file.id, &e.file.name))?;+ let parent = output+ .parent()+ .filter(|p| !p.as_os_str().is_empty())+ .unwrap_or(Path::new("."));+ let mut temporary = tempfile::NamedTempFile::new_in(parent)?;+ files::download(&session, &entry.file, temporary.as_file_mut()).await?;+ temporary.as_file().sync_all()?;+ let bytes = temporary.as_file().metadata()?.len();+ temporary+ .persist_noclobber(&output)+ .map_err(|error| error.error)+ .with_context(|| format!("cannot save download to {}", output.display()))?;+ output::action(+ json_output,+ &json!({ "id": entry.file.id.to_string(), "output": output, "bytes": bytes }),+ &format!("Downloaded {:?} to {}.", entry.file.name, output.display()),+ )+ }+ }+}++struct Entry {+ file: files::File,+ album_ids: Vec<i64>,+}++fn select<T>(+ items: Vec<T>,+ selector: &str,+ kind: &str,+ identity: impl Fn(&T) -> (i64, &str),+) -> Result<T> {+ let mut matches = items+ .into_iter()+ .filter(|item| {+ let (id, name) = identity(item);+ id.to_string() == selector || name == selector+ })+ .collect::<Vec<_>>();+ if matches.len() > 1 {+ let candidates = matches+ .iter()+ .map(|item| {+ let (id, name) = identity(item);+ format!(" {id} {name:?}")+ })+ .collect::<Vec<_>>()+ .join("\n");+ bail!("{kind} {selector:?} is ambiguous:\n{candidates}");+ }+ matches+ .pop()+ .with_context(|| format!("no {kind} matches {selector:?}"))+}diff --git a/rust/apps/cli-next/tests/cli.rs b/rust/apps/cli-next/tests/cli.rsindex 437a40228a..4e008bc530 100644--- a/rust/apps/cli-next/tests/cli.rs+++ b/rust/apps/cli-next/tests/cli.rs@@ -31,6 +31,9 @@ fn reads_do_not_initialize_storage() {vec!["accounts", "list", "--json"],vec!["accounts", "view", "missing"],vec!["photos", "album", "list"],+ vec!["photos", "album", "view", "missing"],+ vec!["photos", "file", "list"],+ vec!["photos", "file", "view", "missing"],vec!["photos", "api", "/users/details/v2"],] {let output = home@@ -102,7 +105,7 @@ fn deleted_collections_are_filtered_before_decryption() {}]}).to_string(),)- .expect(2)+ .expect(3).create();let home = TestHome::new();home.seed(&server.url());@@ -111,6 +114,7 @@ fn deleted_collections_are_filtered_before_decryption() {success(home.run(&["photos", "album", "list"])).stdout,b"No albums.\n");+ assert!(failure(&home.run(&["photos", "album", "view", "12"])).contains("no album matches"));request.assert();}@@ -719,6 +723,9 @@ fn failure(output: &Output) -> String {String::from_utf8_lossy(&output.stderr).into_owned()}+#[path = "support/files.rs"]+mod files;+#[cfg(feature = "museum")]#[path = "support/museum.rs"]mod museum;diff --git a/rust/apps/cli-next/tests/support/files.rs b/rust/apps/cli-next/tests/support/files.rsnew file mode 100644index 0000000000..a23a30b5b4--- /dev/null+++ b/rust/apps/cli-next/tests/support/files.rs@@ -0,0 +1,210 @@+use ente_core::crypto::{secretbox, stream};++use super::*;++#[test]+fn file_pages_preserve_membership_changes_and_metadata() {+ let mut server = mockito::Server::new();+ let home = TestHome::new();+ home.seed(&server.url());+ let collection_key = Key::generate();+ let albums = server+ .mock("GET", "/collections/v2")+ .match_query(mockito::Matcher::Any)+ .with_body(+ json!({"collections": [+ collection(1, "First", &collection_key),+ collection(2, "Second", &collection_key)+ ]})+ .to_string(),+ )+ .expect_at_least(1)+ .create();+ let (first, _) = remote_file(10, &collection_key, b"original");+ let mut second = first.clone();+ second["id"] = json!(11);+ let mut removed = second.clone();+ removed["updationTime"] = json!(20);+ removed["file"]["encryptedData"] = json!("-");+ removed["metadata"]["encryptedData"] = json!("-");+ let page_one = page(&mut server, 1, 0, json!([first, second]), true);+ let page_two = page(&mut server, 1, 10, json!([removed]), false);+ let duplicate = page(&mut server, 2, 0, json!([first]), false);+ let listed = home.json(&["photos", "file", "list"]);+ assert_eq!(listed.as_array().unwrap().len(), 1);+ let file = &listed[0];+ assert_eq!(file["id"], "10");+ assert_eq!(file["albumIds"], json!(["1", "2"]));+ assert_eq!(file["name"], "Edited π§.jpg");+ assert_eq!(file["createdAt"], "2026-09-01T00:00:00.000000Z");+ assert_eq!(file["caption"], "42");+ assert_eq!(+ file["location"],+ json!({"latitude": 12.5, "longitude": 0.0})+ );+ assert_eq!(file["visibility"], "archived");+ assert_eq!(file["dateTime"], "2026-09-01T05:30:00");+ assert_eq!(file["offsetTime"], "+05:30");+ assert_eq!(file["hash"], "original-hash");+ assert!(file.get("key").is_none());+ assert_eq!(+ home.json(&["photos", "file", "view", "Edited π§.jpg"]),+ *file+ );+ assert_eq!(home.json(&["photos", "file", "view", "10"]), *file);+ let scoped = home.json(&["photos", "file", "list", "--album", "First"]);+ assert_eq!(scoped[0]["albumIds"], json!(["1"]));+ assert!(failure(&home.run(&["photos", "file", "view", "11"])).contains("no file matches"));+ assert!(failure(&home.run(&["photos", "file", "view", "Edited"])).contains("no file matches"));+ let human = success(home.run(&["photos", "file", "view", "10"]));+ assert!(+ String::from_utf8(human.stdout)+ .unwrap()+ .contains("Edited π§.jpg")+ );+ albums.assert();+ page_one.assert();+ page_two.assert();+ duplicate.assert();+}++#[test]+fn downloads_publish_only_complete_authenticated_originals() {+ let mut server = mockito::Server::new();+ let home = TestHome::new();+ home.seed(&server.url());+ let output_dir = tempfile::tempdir().unwrap();+ let path = output_dir.path().join("original.jpg");+ let collection_key = Key::generate();+ server+ .mock("GET", "/collections/v2")+ .match_query(mockito::Matcher::Any)+ .with_body(json!({"collections": [collection(1, "First", &collection_key)]}).to_string())+ .create();+ 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);+ 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",+ "download",+ "10",+ "--output",+ path.to_str().unwrap(),+ "--json",+ ];+ let mut damaged = encrypted.clone();+ *damaged.last_mut().unwrap() ^= 1;+ let mut trailing = encrypted.clone();+ trailing.push(0);+ for bytes in [+ damaged,+ encrypted[..stream::DECRYPTION_CHUNK_SIZE].to_vec(),+ trailing,+ ] {+ let object = server.mock("GET", "/original").with_body(bytes).create();+ let output = home.run(&args);+ failure(&output);+ assert!(output.stdout.is_empty());+ assert!(!path.exists());+ assert_eq!(fs::read_dir(output_dir.path()).unwrap().count(), 0);+ object.assert();+ object.remove();+ }+ let object = server+ .mock("GET", "/original")+ .match_header("x-auth-token", mockito::Matcher::Missing)+ .match_header("x-client-package", mockito::Matcher::Missing)+ .with_body(encrypted)+ .expect_at_least(1)+ .create();+ let result: Value = serde_json::from_slice(&success(home.run(&args)).stdout).unwrap();+ assert_eq!(+ result,+ json!({"id": "10", "output": path, "bytes": original.len()})+ );+ assert_eq!(fs::read(&path).unwrap(), original);+ fs::write(&path, b"existing user file").unwrap();+ failure(&home.run(&args));+ assert_eq!(fs::read(&path).unwrap(), b"existing user file");+ assert_eq!(fs::read_dir(output_dir.path()).unwrap().count(), 1);+ signed.assert();+ object.assert();+}++fn collection(id: i64, name: &str, key: &Key) -> Value {+ let wrapped = secretbox::encrypt(key.as_bytes(), &Key::from_bytes([0; 32]));+ json!({+ "id": id, "owner": {"id": 9007199254740993i64}, "name": name, "type": "album",+ "updationTime": 20, "encryptedKey": b64::encode(&wrapped.encrypted_data),+ "keyDecryptionNonce": b64::encode(wrapped.nonce.as_bytes()),+ })+}++fn remote_file(id: i64, collection_key: &Key, original: &[u8]) -> (Value, Vec<u8>) {+ let key = Key::generate();+ let wrapped = secretbox::encrypt(key.as_bytes(), collection_key);+ let metadata = blob::encrypt_json(+ &json!({+ "title": "Original.jpg", "fileType": 0,+ "creationTime": 1_700_000_000_000_000i64,+ "modificationTime": 1_700_000_001_000_000i64,+ "latitude": 1.0, "longitude": 2.0, "hash": "original-hash"+ }),+ &key,+ )+ .unwrap();+ let public = blob::encrypt_json(+ &json!({+ "editedName": "Edited π§.jpg", "editedTime": 1_788_220_800_000_000i64,+ "caption": 42, "lat": 12.5, "long": 0.0,+ "dateTime": "2026-09-01T05:30:00", "offsetTime": "+05:30",+ }),+ &key,+ )+ .unwrap();+ let private = blob::encrypt_json(&json!({"visibility": 1}), &key).unwrap();+ let mut encrypted = Vec::new();+ let header =+ stream::encrypt_file(&mut std::io::Cursor::new(original), &mut encrypted, &key).unwrap();+ (+ json!({+ "id": id, "ownerID": 9007199254740993i64, "collectionID": 1, "updationTime": 10,+ "encryptedKey": b64::encode(&wrapped.encrypted_data),+ "keyDecryptionNonce": b64::encode(wrapped.nonce.as_bytes()),+ "file": {"decryptionHeader": b64::encode(header.as_bytes())},+ "metadata": {"encryptedData": b64::encode(&metadata.encrypted_data),+ "decryptionHeader": b64::encode(metadata.decryption_header.as_bytes())},+ "pubMagicMetadata": {"data": b64::encode(&public.encrypted_data),+ "header": b64::encode(public.decryption_header.as_bytes())},+ "magicMetadata": {"data": b64::encode(&private.encrypted_data),+ "header": b64::encode(private.decryption_header.as_bytes())},+ "isDeleted": false+ }),+ encrypted,+ )+}++fn page(+ server: &mut mockito::ServerGuard,+ collection: i64,+ since: i64,+ diff: Value,+ more: bool,+) -> mockito::Mock {+ server+ .mock("GET", "/collections/v2/diff")+ .match_query(mockito::Matcher::AllOf(vec![+ mockito::Matcher::UrlEncoded("collectionID".into(), collection.to_string()),+ mockito::Matcher::UrlEncoded("sinceTime".into(), since.to_string()),+ ]))+ .with_body(json!({"diff": diff, "hasMore": more}).to_string())+ .expect_at_least(1)+ .create()+}diff --git a/rust/apps/cli-next/tests/support/museum.rs b/rust/apps/cli-next/tests/support/museum.rsindex 15b478ab3b..04ff51b1f7 100644--- a/rust/apps/cli-next/tests/support/museum.rs+++ b/rust/apps/cli-next/tests/support/museum.rs@@ -2,7 +2,7 @@ use ente_accounts::{AccountsClient, AccountsClientConfig, AuthFlow, AuthFlowUi, AuthenticatedAccount,CreateAccountParams, OtpPurpose, SecondFactorMethod, TotpPurpose,};-use ente_core::crypto::{PublicKey, blob, sealed, secretbox};+use ente_core::crypto::{PublicKey, blob, sealed, secretbox, stream};use ente_test_support::{HARDCODED_OTT, Museum, TestResult};use uuid::Uuid;use zeroize::Zeroizing;@@ -190,6 +190,10 @@ async fn exercise(origin: String) -> TestResult {json!({"visibility": 2}),).await;+ let original = b"original photo bytes from Museum";+ let file_id = upload_file(&origin, &alice, album, &key, original)+ .await+ .to_string();let home = TestHome::new();login(&home, "photos", &alice_email, &["--host", &origin]);@@ -232,12 +236,49 @@ async fn exercise(origin: String) -> TestResult {.local_minus_utc(),0);+ for album in albums.as_array().unwrap() {+ for selector in [+ album["id"].as_str().unwrap(),+ album["name"].as_str().unwrap(),+ ] {+ assert_eq!(home.json(&["photos", "album", "view", selector]), *album);+ }+ }+ assert_eq!(+ String::from_utf8(success(home.run(&["photos", "album", "view", "Monsoon π§"])).stdout)+ .unwrap(),+ format!(+ "Name Monsoon π§\nType album\nVisibility visible\nOwner {alice_id}\nUpdated {}\nID {album}\n",+ monsoon["updatedAt"].as_str().unwrap(),+ ),+ );+ for selector in ["missing", "Monsoon", "monsoon π§"] {+ let output = home.run(&["photos", "album", "view", selector, "--json"]);+ assert!(failure(&output).contains("no album matches"));+ assert!(output.stdout.is_empty());+ }let human = String::from_utf8(success(home.run(&["photos", "album", "list"])).stdout).unwrap();assert!(human.starts_with("ID "));let raw: Value =serde_json::from_slice(&success(home.run(&["photos", "api", "/collections/v2"])).stdout).unwrap();assert!(raw["collections"].as_array().unwrap().iter().any(|a| a["id"] == album && a["encryptedName"].as_str().is_some_and(|s| !s.is_empty())));+ let files = home.json(&["photos", "file", "list"]);+ assert_eq!(files.as_array().unwrap().len(), 1);+ assert_eq!(files[0]["id"], file_id);+ assert_eq!(files[0]["name"], "original.jpg");+ assert_eq!(files[0]["albumIds"], json!([album.to_string()]));+ let output_dir = tempfile::tempdir().unwrap();+ let output_path = output_dir.path().join("owned.jpg");+ success(home.run(&[+ "photos",+ "file",+ "download",+ &file_id,+ "--output",+ output_path.to_str().unwrap(),+ ]));+ assert_eq!(fs::read(output_path).unwrap(), original);// Two origins with the same server user ID are still different accounts.let alias_origin = origin.replace("127.0.0.1", "localhost");@@ -303,8 +344,41 @@ async fn exercise(origin: String) -> TestResult {assert_eq!(shared["name"], "Monsoon π§");assert_eq!(shared["ownerId"], alice_id);assert_eq!(shared["visibility"], "hidden");+ assert_eq!(+ home.json(&["photos", "album", "view", "Monsoon π§"]),+ *shared+ );+ assert_eq!(+ home.json(&["photos", "album", "view", "Monsoon π§", "--account", "work"]),+ *monsoon,+ );+ let shared_file = home.json(&["photos", "file", "view", &file_id]);+ assert_eq!(shared_file["ownerId"], alice_id);+ let output_path = output_dir.path().join("shared.jpg");+ success(home.run(&[+ "photos",+ "file",+ "download",+ &file_id,+ "--output",+ output_path.to_str().unwrap(),+ ]));+ assert_eq!(fs::read(output_path).unwrap(), original);login(&home, "photos", &alice_email, &["--host", &origin]);+ for selector in ["Monsoon π§", &album.to_string()] {+ let (conflict, _) = create_album(&origin, &alice, selector, "album").await;+ let output = home.run(&["photos", "album", "view", selector, "--json"]);+ let error = failure(&output);+ assert!(error.contains("is ambiguous"));+ assert!(error.contains(&format!("{album} \"Monsoon π§\"")));+ assert!(error.contains(&format!("{conflict} {selector:?}")));+ assert!(output.stdout.is_empty());+ assert_eq!(+ home.json(&["photos", "album", "view", &conflict.to_string()])["id"],+ conflict.to_string(),+ );+ }let state = home.read_vault();assert_eq!(state["accounts"].as_array().unwrap().len(), 3);assert_eq!(state["selected"], first_id);@@ -433,6 +507,68 @@ async fn create_album((response["collection"]["id"].as_i64().unwrap(), key)}+async fn upload_file(+ origin: &str,+ owner: &AuthenticatedAccount,+ album: i64,+ collection_key: &Key,+ original: &[u8],+) -> i64 {+ let client = reqwest::Client::new();+ let token = b64::encode_url_safe(&owner.secrets.token);+ let urls: Value = client+ .get(format!("{origin}/files/upload-urls"))+ .header("x-auth-token", &token)+ .header("x-client-package", "io.ente.photos")+ .query(&[("count", 2)])+ .send()+ .await+ .unwrap()+ .error_for_status()+ .unwrap()+ .json()+ .await+ .unwrap();+ let key = Key::generate();+ let wrapped = secretbox::encrypt(key.as_bytes(), collection_key);+ let mut encrypted = Vec::new();+ let header =+ stream::encrypt_file(&mut std::io::Cursor::new(original), &mut encrypted, &key).unwrap();+ let thumbnail = blob::encrypt(b"thumbnail", &key).unwrap();+ for (index, bytes) in [&encrypted, &thumbnail.encrypted_data]+ .into_iter()+ .enumerate()+ {+ client+ .put(urls["urls"][index]["url"].as_str().unwrap())+ .body(bytes.clone())+ .send()+ .await+ .unwrap()+ .error_for_status()+ .unwrap();+ }+ let metadata = blob::encrypt_json(+ &json!({+ "title": "original.jpg", "fileType": 0, "creationTime": 1_700_000_000_000_000i64,+ "modificationTime": 1_700_000_000_000_000i64+ }),+ &key,+ )+ .unwrap();+ let result: Value = client.post(format!("{origin}/files"))+ .header("x-auth-token", &token).header("x-client-package", "io.ente.photos")+ .json(&json!({+ "collectionID": album, "encryptedKey": b64::encode(&wrapped.encrypted_data),+ "keyDecryptionNonce": b64::encode(wrapped.nonce.as_bytes()),+ "file": {"objectKey": urls["urls"][0]["objectKey"], "decryptionHeader": b64::encode(header.as_bytes())},+ "thumbnail": {"objectKey": urls["urls"][1]["objectKey"], "decryptionHeader": b64::encode(thumbnail.decryption_header.as_bytes())},+ "metadata": {"encryptedData": b64::encode(&metadata.encrypted_data),+ "decryptionHeader": b64::encode(metadata.decryption_header.as_bytes())}+ })).send().await.unwrap().error_for_status().unwrap().json().await.unwrap();+ result["id"].as_i64().unwrap()+}+async fn set_album_metadata(origin: &str,user: &AuthenticatedAccount,diff --git a/rust/crates/photos/Cargo.toml b/rust/crates/photos/Cargo.tomlindex cf2a52c846..2b9f13c6f5 100644--- a/rust/crates/photos/Cargo.toml+++ b/rust/crates/photos/Cargo.toml@@ -11,8 +11,12 @@ ente-location.workspace = truequick-xml.workspace = truerusqlite = { workspace = true, default-features = true }serde.workspace = true+serde_json.workspace = truethiserror.workspace = true+[target.'cfg(not(target_arch = "wasm32"))'.dependencies]+futures-util.workspace = true+[dev-dependencies]tempfile.workspace = truediff --git a/rust/crates/photos/src/collections.rs b/rust/crates/photos/src/collections.rsindex e44b709495..7623721ff5 100644--- a/rust/crates/photos/src/collections.rs+++ b/rust/crates/photos/src/collections.rs@@ -1,7 +1,7 @@use ente_collections::open_collection_key;use ente_core::{Session, b64,- crypto::{self, Header, Nonce, blob, secretbox},+ crypto::{self, Header, Key, Nonce, blob, secretbox},http,};use serde::Deserialize;@@ -13,6 +13,7 @@ const HIDDEN_VISIBILITY: u8 = 2;#[derive(Debug)]pub struct Collection {pub id: i64,+ pub key: Key,pub name: String,pub kind: Kind,pub visibility: Visibility,@@ -44,6 +45,16 @@ pub enum Visibility {Hidden,}+impl Visibility {+ pub fn name(&self) -> &'static str {+ match self {+ Self::Visible => "visible",+ Self::Archived => "archived",+ Self::Hidden => "hidden",+ }+ }+}+#[derive(Debug, thiserror::Error)]pub enum Error {#[error(transparent)]@@ -123,6 +134,7 @@ pub async fn list(session: &Session) -> Result<Vec<Collection>, Error> {};Ok(Collection {id: c.id,+ key,name,kind: match c.kind.as_str() {"favorites" => Kind::Favorites,diff --git a/rust/crates/photos/src/files.rs b/rust/crates/photos/src/files.rsnew file mode 100644index 0000000000..1b73c05b0e--- /dev/null+++ b/rust/crates/photos/src/files.rs@@ -0,0 +1,371 @@+use std::collections::BTreeMap;++use ente_core::{+ Session, b64,+ crypto::{self, Header, Key, Nonce, blob, secretbox},+ http,+};+use serde::Deserialize;++use crate::collections::{Collection, Visibility};++#[derive(Debug)]+pub struct File {+ pub id: i64,+ pub owner_id: i64,+ pub updated_at_micros: i64,+ pub name: String,+ pub kind: Kind,+ pub created_at_micros: i64,+ pub modified_at_micros: i64,+ pub location: Option<Location>,+ pub caption: Option<String>,+ pub hash: Option<String>,+ pub date_time: Option<String>,+ pub offset_time: Option<String>,+ pub duration_seconds: Option<u64>,+ pub width: Option<u32>,+ pub height: Option<u32>,+ pub visibility: Visibility,+ pub key: Key,+ pub header: Header,+}++#[derive(Debug, Clone, Copy)]+pub enum Kind {+ Image,+ Video,+ LivePhoto,+ Unknown,+}++impl Kind {+ pub fn name(self) -> &'static str {+ match self {+ Self::Image => "image",+ Self::Video => "video",+ Self::LivePhoto => "livephoto",+ Self::Unknown => "unknown",+ }+ }+}++#[derive(Debug)]+pub struct Location {+ pub latitude: f64,+ pub longitude: f64,+}++pub struct Change {+ pub id: i64,+ pub file: Option<File>,+}++pub struct Page {+ pub changes: Vec<Change>,+ pub cursor: i64,+ pub has_more: bool,+}++#[derive(Debug, thiserror::Error)]+pub enum Error {+ #[error(transparent)]+ Http(#[from] http::Error),+ #[error(transparent)]+ Crypto(#[from] crypto::Error),+ #[error(transparent)]+ Base64(#[from] b64::DecodeError),+ #[error(transparent)]+ Io(#[from] std::io::Error),+ #[error("file changes did not advance the cursor for collection {0}")]+ CursorDidNotAdvance(i64),+}++pub async fn diff(session: &Session, collection: &Collection, since: i64) -> Result<Page, Error> {+ let response: DiffResponse = http::retry(|| async {+ session+ .api+ .get("/collections/v2/diff")+ .query(&[("collectionID", collection.id), ("sinceTime", since)])+ .send()+ .await?+ .error_for_code()+ .await?+ .json()+ .await+ })+ .await?;+ let mut cursor = since;+ let mut changes = Vec::with_capacity(response.diff.len());+ for remote in response.diff {+ cursor = cursor.max(remote.updation_time);+ changes.push(Change {+ id: remote.id,+ file: if remote.is_deleted || remote.file.encrypted_data.as_deref() == Some("-") {+ None+ } else {+ Some(remote.open(&collection.key)?)+ },+ });+ }+ if response.has_more && cursor <= since {+ return Err(Error::CursorDidNotAdvance(collection.id));+ }+ Ok(Page {+ changes,+ cursor,+ has_more: response.has_more,+ })+}++pub async fn list(session: &Session, collection: &Collection) -> Result<Vec<File>, Error> {+ let mut files = BTreeMap::new();+ let mut cursor = 0;+ loop {+ let page = diff(session, collection, cursor).await?;+ for change in page.changes {+ if let Some(file) = change.file {+ files.insert(change.id, file);+ } else {+ files.remove(&change.id);+ }+ }+ cursor = page.cursor;+ if !page.has_more {+ return Ok(files.into_values().collect());+ }+ }+}++#[cfg(not(target_arch = "wasm32"))]+pub async fn download(+ session: &Session,+ file: &File,+ output: &mut impl std::io::Write,+) -> Result<(), Error> {+ use ente_core::crypto::stream::{DECRYPTION_CHUNK_SIZE, Decryptor};+ use futures_util::StreamExt;++ let response = http::retry(|| async {+ let signed: DownloadUrl = session+ .api+ .get(&format!("/files/download/v3/{}", file.id))+ .send()+ .await?+ .error_for_code()+ .await?+ .json()+ .await?;+ session+ .api+ .http()+ .get(&signed.url)+ .send()+ .await?+ .error_for_status()+ })+ .await?;+ let body = response.bytes_stream();+ let mut body = std::pin::pin!(body);+ let mut decryptor = Decryptor::new(&file.header, &file.key);+ let mut buffer = Vec::with_capacity(DECRYPTION_CHUNK_SIZE);+ let mut seen_final = false;+ while let Some(chunk) = body.next().await {+ let chunk = chunk?;+ let mut remaining = chunk.as_ref();+ while !remaining.is_empty() {+ if seen_final {+ return Err(crypto::Error::StreamTrailingData.into());+ }+ let count = remaining.len().min(DECRYPTION_CHUNK_SIZE - buffer.len());+ buffer.extend_from_slice(&remaining[..count]);+ remaining = &remaining[count..];+ if buffer.len() == DECRYPTION_CHUNK_SIZE {+ let (plaintext, is_final) = decryptor.pull(&buffer)?;+ output.write_all(&plaintext)?;+ seen_final = is_final;+ buffer.clear();+ }+ }+ }+ if !buffer.is_empty() {+ let (plaintext, _) = decryptor.pull(&buffer)?;+ output.write_all(&plaintext)?;+ }+ decryptor.finish()?;+ Ok(())+}++#[derive(Deserialize)]+#[serde(rename_all = "camelCase")]+struct DiffResponse {+ diff: Vec<RemoteFile>,+ has_more: bool,+}++#[cfg(not(target_arch = "wasm32"))]+#[derive(Deserialize)]+struct DownloadUrl {+ url: String,+}++#[derive(Deserialize)]+#[serde(rename_all = "camelCase")]+struct RemoteFile {+ id: i64,+ #[serde(rename = "ownerID")]+ owner_id: i64,+ encrypted_key: String,+ key_decryption_nonce: String,+ file: FileAttributes,+ metadata: FileAttributes,+ is_deleted: bool,+ updation_time: i64,+ magic_metadata: Option<EncryptedMetadata>,+ pub_magic_metadata: Option<EncryptedMetadata>,+}++impl RemoteFile {+ fn open(self, collection_key: &Key) -> Result<File, Error> {+ let key = Key::try_from_slice(&secretbox::decrypt(+ &b64::decode(&self.encrypted_key)?,+ &Nonce::try_from_slice(&b64::decode(&self.key_decryption_nonce)?)?,+ collection_key,+ )?)?;+ let metadata: Metadata = blob::decrypt_json(+ &blob::EncryptedBlob {+ encrypted_data: b64::decode(self.metadata.encrypted_data.as_deref().unwrap_or(""))?,+ decryption_header: Header::try_from_slice(&b64::decode(+ &self.metadata.decryption_header,+ )?)?,+ },+ &key,+ )?;+ let public: PublicMetadata = match self.pub_magic_metadata {+ Some(encrypted) => encrypted.open(&key)?,+ None => PublicMetadata::default(),+ };+ let private: PrivateMetadata = match self.magic_metadata {+ Some(encrypted) => encrypted.open(&key)?,+ None => PrivateMetadata::default(),+ };+ let kind = match metadata.file_type {+ 0 => Kind::Image,+ 1 => Kind::Video,+ 2 => Kind::LivePhoto,+ _ => Kind::Unknown,+ };+ let hash = metadata.hash.filter(|hash| !hash.is_empty()).or_else(|| {+ if matches!(kind, Kind::LivePhoto) {+ metadata+ .image_hash+ .zip(metadata.video_hash)+ .map(|(image, video)| format!("{image}:{video}"))+ } else {+ None+ }+ });+ let location = public+ .lat+ .zip(public.long)+ .or(metadata.latitude.zip(metadata.longitude))+ .filter(|&(lat, long)| lat != 0.0 || long != 0.0)+ .map(|(latitude, longitude)| Location {+ latitude,+ longitude,+ });+ Ok(File {+ id: self.id,+ owner_id: self.owner_id,+ updated_at_micros: self.updation_time,+ name: public.edited_name.unwrap_or(metadata.title),+ kind,+ created_at_micros: public.edited_time.unwrap_or(metadata.creation_time),+ modified_at_micros: metadata.modification_time.unwrap_or(metadata.creation_time),+ location,+ caption: public.caption.map(|caption| match caption {+ Caption::Text(text) => text,+ Caption::Number(number) => number.to_string(),+ }),+ hash,+ date_time: public.date_time,+ offset_time: public.offset_time,+ duration_seconds: metadata.duration,+ width: public.w,+ height: public.h,+ visibility: match private.visibility {+ Some(1) => Visibility::Archived,+ Some(2) => Visibility::Hidden,+ _ => Visibility::Visible,+ },+ key,+ header: Header::try_from_slice(&b64::decode(&self.file.decryption_header)?)?,+ })+ }+}++#[derive(Deserialize)]+#[serde(rename_all = "camelCase")]+struct FileAttributes {+ encrypted_data: Option<String>,+ decryption_header: String,+}++#[derive(Deserialize)]+struct EncryptedMetadata {+ data: String,+ header: String,+}++impl EncryptedMetadata {+ fn open<T: serde::de::DeserializeOwned>(&self, key: &Key) -> Result<T, Error> {+ Ok(blob::decrypt_json(+ &blob::EncryptedBlob {+ encrypted_data: b64::decode(&self.data)?,+ decryption_header: Header::try_from_slice(&b64::decode(&self.header)?)?,+ },+ key,+ )?)+ }+}++#[derive(Deserialize)]+#[serde(rename_all = "camelCase")]+struct Metadata {+ title: String,+ file_type: i32,+ creation_time: i64,+ modification_time: Option<i64>,+ latitude: Option<f64>,+ longitude: Option<f64>,+ hash: Option<String>,+ image_hash: Option<String>,+ video_hash: Option<String>,+ duration: Option<u64>,+}++#[derive(Default, Deserialize)]+#[serde(rename_all = "camelCase")]+struct PublicMetadata {+ edited_name: Option<String>,+ edited_time: Option<i64>,+ date_time: Option<String>,+ offset_time: Option<String>,+ caption: Option<Caption>,+ lat: Option<f64>,+ long: Option<f64>,+ w: Option<u32>,+ h: Option<u32>,+}++#[derive(Deserialize)]+#[serde(untagged)]+enum Caption {+ Text(String),+ Number(serde_json::Number),+}++#[derive(Default, Deserialize)]+struct PrivateMetadata {+ visibility: Option<u8>,+}diff --git a/rust/crates/photos/src/lib.rs b/rust/crates/photos/src/lib.rsindex d093dcfe12..279f5b6fcc 100644--- a/rust/crates/photos/src/lib.rs+++ b/rust/crates/photos/src/lib.rs@@ -1,5 +1,6 @@pub mod collections;pub mod db;+pub mod files;pub mod location;pub mod metadata;pub mod ml_db;diff --git a/rust/crates/test-support/src/object_store.rs b/rust/crates/test-support/src/object_store.rsindex e25ed3f593..2abb23e7c3 100644--- a/rust/crates/test-support/src/object_store.rs+++ b/rust/crates/test-support/src/object_store.rs@@ -54,7 +54,7 @@ impl Drop for ObjectStore {}}-fn handle(mut stream: TcpStream, objects: &mut HashMap<String, usize>) {+fn handle(mut stream: TcpStream, objects: &mut HashMap<String, Vec<u8>>) {let mut request = Vec::new();let mut buffer = [0; 4096];let header_end = loop {@@ -101,11 +101,18 @@ fn handle(mut stream: TcpStream, objects: &mut HashMap<String, usize>) {let path = target.split('?').next().unwrap_or(&target).to_owned();match method.as_str() {"PUT" => {- objects.insert(path, content_length);+ objects.insert(path, request[header_end..].to_vec());respond(&mut stream, "200 OK", 0);}"HEAD" => match objects.get(&path) {- Some(content_length) => respond(&mut stream, "200 OK", *content_length),+ Some(body) => respond(&mut stream, "200 OK", body.len()),+ None => respond(&mut stream, "404 Not Found", 0),+ },+ "GET" => match objects.get(&path) {+ Some(body) => {+ respond(&mut stream, "200 OK", body.len());+ let _ = stream.write_all(body);+ }None => respond(&mut stream, "404 Not Found", 0),},_ => respond(&mut stream, "405 Method Not Allowed", 0),