Skip to content

armgit / ente

Public Imported from GitHub
0

πŸ’š End-to-end encrypted cloud for everything.

Filter and sort Photos file lists in the CLI

laurenspriem41b7d741a057
diff --git a/docs/docs/cli/photos.md b/docs/docs/cli/photos.md
index bb34be2c66..e87364ac42 100644
--- a/docs/docs/cli/photos.md
+++ b/docs/docs/cli/photos.md
@@ -90,16 +90,31 @@ ente photos file download 1580559962386999 --output ./IMG_0001.jpg
A file selector is a file ID or an exact name; when several files share a name, the CLI lists the candidates and you pick an ID. Download prints `Downloaded "IMG_0001.jpg" to ./IMG_0001.jpg.` and refuses to overwrite an existing file. A Live Photo downloads as a ZIP archive. Lists show 100 results and then print `Showing first 100 results; use --limit N or --all to see more.` on the terminal.
+## Filter and sort files
+
+```sh
+ente photos file list --type video --since 2024-01-01 --before 2025-01-01
+ente photos file list --search "beach sunset" --no-location
+ente photos file list --sort size --limit 20
+```
+
+- `--type` takes `image`, `video` or `livephoto`; repeat it to include several types.
+- `--since` and `--before` compare `createdAt`, which includes dates edited in Ente. `--since` includes the given instant and `--before` excludes it. Both accept `YYYY-MM-DD` (midnight UTC) or RFC 3339 with a timezone, such as `2024-06-01T00:00:00+02:00`.
+- `--search` finds files whose name or caption contains every word, ignoring case.
+- `--no-location` keeps files without a location.
+
+A file must match every filter you pass. `--sort created` lists the newest files first and `--sort size` the largest first; add `--reverse` for the opposite order. Files with an unknown size sort as the smallest, and ties keep ID order. Without `--sort`, files are listed by ID.
+
## Read as JSON
Lists return arrays and `view` returns one object. IDs are strings; timestamps are RFC 3339 strings in UTC.
-| Command | Fields |
-| -------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
-| `album list`, `album view` | `id`, `name`, `type` (`album`, `folder`, `favorites`, `uncategorized`, `defaultHidden`, `quicklink`), `visibility` (`visible`, `archived`, `hidden`), `ownerId`, `updatedAt` |
-| `file list`, `file view` | `id`, `name`, `type` (`image`, `video`, `livephoto`), `ownerId`, `albumIds`, `createdAt`, `updatedAt`; nullable `modifiedAt`, `location` (`latitude`, `longitude`), `caption`, `hash`, `dateTime`, `offsetTime`, `visibility`, `durationSeconds`, `width`, `height` |
-| `file download` | `id`, `output`, `bytes` |
-| `export` | See [Automation](./automation.md#export-summary) |
+| Command | Fields |
+| -------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| `album list`, `album view` | `id`, `name`, `type` (`album`, `folder`, `favorites`, `uncategorized`, `defaultHidden`, `quicklink`), `visibility` (`visible`, `archived`, `hidden`), `ownerId`, `updatedAt` |
+| `file list`, `file view` | `id`, `name`, `type` (`image`, `video`, `livephoto`), `ownerId`, `albumIds`, `createdAt`, `updatedAt`; nullable `modifiedAt`, `location` (`latitude`, `longitude`), `caption`, `hash`, `dateTime`, `offsetTime`, `visibility`, `durationSeconds`, `width`, `height`, `sizeBytes` |
+| `file download` | `id`, `output`, `bytes` |
+| `export` | See [Automation](./automation.md#export-summary) |
## Read offline
diff --git a/rust/apps/cli/changes/file-list-filters.md b/rust/apps/cli/changes/file-list-filters.md
new file mode 100644
index 0000000000..7ca970586f
--- /dev/null
+++ b/rust/apps/cli/changes/file-list-filters.md
@@ -0,0 +1 @@
+- Filter `photos file list` by type, creation date, name or caption words, and missing location, and sort it by creation time or size. Files now show their size.
diff --git a/rust/apps/cli/src/args.rs b/rust/apps/cli/src/args.rs
index b7bf32c94e..1e849edb06 100644
--- a/rust/apps/cli/src/args.rs
+++ b/rust/apps/cli/src/args.rs
@@ -549,15 +549,20 @@ Use --album to limit the albums read. With --json, list returns an array and vie
Fields: id, name, type, ownerId (strings); albumIds (string array);
createdAt, updatedAt (RFC3339 timestamp strings).
Nullable fields: modifiedAt (RFC3339 string); location ({latitude, longitude}, numbers);
-caption, hash, dateTime, offsetTime, visibility (strings); durationSeconds, width, height (integers).
-dateTime and offsetTime retain the stored metadata strings.
+caption, hash, dateTime, offsetTime, visibility (strings); durationSeconds, width, height, sizeBytes (integers).
+dateTime and offsetTime retain the stored metadata strings. sizeBytes is the stored size reported by the server.
hash comes from Ente's stored metadata. For Live Photos, it can contain the image and video hashes separated by a colon.";
#[derive(Subcommand)]
pub enum FileCommand {
#[command(about = "List files, including shared and hidden ones")]
#[command(after_long_help = FILE_HELP)]
- List(ListArgs),
+ List {
+ #[command(flatten)]
+ query: FileQuery,
+ #[command(flatten)]
+ list: ListArgs,
+ },
#[command(about = "Show a file's metadata")]
#[command(after_long_help = FILE_HELP)]
View {
@@ -576,6 +581,75 @@ pub enum FileCommand {
},
}
+#[derive(Args)]
+pub struct FileQuery {
+ #[arg(
+ long = "type",
+ value_enum,
+ value_name = "TYPE",
+ help = "Include files of this type; repeat for multiple types"
+ )]
+ pub types: Vec<FileType>,
+ #[arg(
+ long,
+ value_name = "WHEN",
+ value_parser = crate::admin::parse_date,
+ help = "Include files created at or after this instant",
+ long_help = "Include files created at or after this instant. Accepts YYYY-MM-DD (00:00 UTC at the start of that date) or RFC3339 with a timezone. Compares createdAt, which includes edits to a file's date."
+ )]
+ pub since: Option<i64>,
+ #[arg(
+ long,
+ value_name = "WHEN",
+ value_parser = crate::admin::parse_date,
+ help = "Include files created before this instant",
+ long_help = "Include files created before this instant. Accepts YYYY-MM-DD (00:00 UTC at the start of that date) or RFC3339 with a timezone. Compares createdAt, which includes edits to a file's date."
+ )]
+ pub before: Option<i64>,
+ #[arg(
+ long,
+ value_name = "TEXT",
+ value_parser = nonempty_search,
+ help = "Find files by words in their name or caption",
+ long_help = "Find files whose name or caption contains every word of TEXT, ignoring case. Quote text containing spaces."
+ )]
+ pub search: Option<String>,
+ #[arg(long, help = "Include only files without a location")]
+ pub no_location: bool,
+ #[arg(
+ long,
+ value_enum,
+ value_name = "ORDER",
+ help = "Sort by creation time or size instead of ID",
+ long_help = "Sort by createdAt, newest first, or by sizeBytes, largest first. Files with an unknown size sort as the smallest. Ties keep ID order."
+ )]
+ pub sort: Option<FileSort>,
+ #[arg(long, requires = "sort", help = "Reverse the --sort order")]
+ pub reverse: bool,
+}
+
+#[derive(Clone, Copy, ValueEnum)]
+pub enum FileType {
+ Image,
+ Video,
+ #[value(name = "livephoto")]
+ LivePhoto,
+}
+
+#[derive(Clone, Copy, ValueEnum)]
+pub enum FileSort {
+ Created,
+ Size,
+}
+
+fn nonempty_search(text: &str) -> Result<String, String> {
+ if text.trim().is_empty() {
+ Err("supply search text".into())
+ } else {
+ Ok(text.to_owned())
+ }
+}
+
const ACCOUNT_HELP: &str = "Reads accounts stored on this device without network access.
With --json, list returns an array and view returns one object.
Fields: id, name, email, host (strings); apps (string array); selected (boolean).";
diff --git a/rust/apps/cli/src/output.rs b/rust/apps/cli/src/output.rs
index fd5021f164..8c44b0b674 100644
--- a/rust/apps/cli/src/output.rs
+++ b/rust/apps/cli/src/output.rs
@@ -90,6 +90,7 @@ pub struct FileView {
duration_seconds: Option<u64>,
width: Option<u32>,
height: Option<u32>,
+ size_bytes: Option<u64>,
visibility: Option<&'static str>,
}
@@ -121,6 +122,7 @@ impl FileView {
duration_seconds: file.duration_seconds,
width: file.width,
height: file.height,
+ size_bytes: file.size,
visibility: file.visibility.map(Visibility::name),
})
}
@@ -261,7 +263,7 @@ pub fn files(
files,
args,
as_json,
- ["ID", "NAME", "TYPE", "CREATED", "ALBUMS"],
+ ["ID", "NAME", "TYPE", "CREATED", "SIZE", "ALBUMS"],
"No files.",
|file| {
[
@@ -269,6 +271,9 @@ pub fn files(
escape_controls(&file.name),
type_label(file.kind).to_owned(),
file.created_at,
+ file.size_bytes
+ .map(|bytes| bytes.to_string())
+ .unwrap_or_default(),
file.album_ids.join(","),
]
},
@@ -306,6 +311,12 @@ pub fn file(file: &FileView) -> Result<()> {
("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())),
+ (
+ "Size",
+ file.size_bytes
+ .and_then(|bytes| i64::try_from(bytes).ok())
+ .map(storage_size),
+ ),
("Hash", file.hash.as_deref().map(escape_controls)),
] {
if let Some(value) = value {
diff --git a/rust/apps/cli/src/photos/mod.rs b/rust/apps/cli/src/photos/mod.rs
index fe09d4f5bf..733487a49d 100644
--- a/rust/apps/cli/src/photos/mod.rs
+++ b/rust/apps/cli/src/photos/mod.rs
@@ -1,16 +1,16 @@
mod export;
pub mod replica;
-use std::{io::Seek, path::Path};
+use std::{cmp::Ordering, io::Seek, path::Path};
use anyhow::{Context, Result, ensure};
use ente_core::Session;
-use ente_photos::files;
+use ente_photos::files::{self, File, Kind};
use serde_json::json;
use crate::{
api,
- args::{AlbumCommand, App, FileCommand, Options, PhotosCommand},
+ args::{AlbumCommand, App, FileCommand, FileQuery, FileSort, FileType, Options, PhotosCommand},
core_db::SqliteResult,
db, home,
output::{self, AlbumView, FileView, MAX_CANDIDATES, select},
@@ -169,17 +169,24 @@ async fn file(
Ok::<_, anyhow::Error>((file, entry.album_ids))
};
match command {
- FileCommand::List(args) => replica.files(album_id, None, None, |rows| {
+ FileCommand::List { query, list } => replica.files(album_id, None, None, |rows| {
let files = rows.filter_map(|row| {
let entry = match row {
Ok(entry) => entry,
Err(error) => return Some(Err(error.into())),
};
- match entry
- .file
- .and_then(|file| FileView::new(file, &entry.album_ids))
- {
- Ok(file) => Some(Ok(file)),
+ let listed = entry.file.and_then(|file| {
+ if !matches(&query, &file) {
+ return Ok(None);
+ }
+ let key = SortKey {
+ created_at_micros: file.created_at_micros,
+ size: file.size,
+ };
+ FileView::new(file, &entry.album_ids).map(|view| Some((key, view)))
+ });
+ match listed {
+ Ok(listed) => listed.map(Ok),
Err(error) => {
eprintln!("file {}: {error:#}", entry.id);
incomplete = true;
@@ -187,7 +194,20 @@ async fn file(
}
}
});
- output::files(files, &args, options.json)
+ let Some(sort) = query.sort else {
+ return output::files(
+ files.map(|row| row.map(|(_, view)| view)),
+ &list,
+ options.json,
+ );
+ };
+ let mut files = files.collect::<Result<Vec<_>>>()?;
+ files.sort_by(|(a, _), (b, _)| compare(sort, query.reverse, a, b));
+ output::files(
+ files.into_iter().map(|(_, view)| Ok(view)),
+ &list,
+ options.json,
+ )
}),
FileCommand::View { file } => {
let (file, album_ids) = find(&file)?;
@@ -234,3 +254,51 @@ async fn file(
ensure!(!incomplete, "file results are incomplete");
Ok(())
}
+
+struct SortKey {
+ created_at_micros: i64,
+ size: Option<u64>,
+}
+
+fn matches(query: &FileQuery, file: &File) -> bool {
+ (query.types.is_empty() || query.types.iter().any(|&kind| file_kind(kind) == file.kind))
+ && query
+ .since
+ .is_none_or(|since| file.created_at_micros >= since)
+ && query
+ .before
+ .is_none_or(|before| file.created_at_micros < before)
+ && (!query.no_location || file.location.is_none())
+ && query
+ .search
+ .as_deref()
+ .is_none_or(|text| contains_words(file, text))
+}
+
+fn file_kind(kind: FileType) -> Kind {
+ match kind {
+ FileType::Image => Kind::Image,
+ FileType::Video => Kind::Video,
+ FileType::LivePhoto => Kind::LivePhoto,
+ }
+}
+
+fn contains_words(file: &File, text: &str) -> bool {
+ let name = file.name.to_lowercase();
+ let caption = file.caption.as_deref().unwrap_or_default().to_lowercase();
+ text.to_lowercase()
+ .split_whitespace()
+ .all(|word| name.contains(word) || caption.contains(word))
+}
+
+fn compare(sort: FileSort, reverse: bool, a: &SortKey, b: &SortKey) -> Ordering {
+ let newest_or_largest_first = match sort {
+ FileSort::Created => b.created_at_micros.cmp(&a.created_at_micros),
+ FileSort::Size => b.size.cmp(&a.size),
+ };
+ if reverse {
+ newest_or_largest_first.reverse()
+ } else {
+ newest_or_largest_first
+ }
+}
diff --git a/rust/apps/cli/tests/cli/files.rs b/rust/apps/cli/tests/cli/files.rs
index ce296c41e5..ccfe64b9ee 100644
--- a/rust/apps/cli/tests/cli/files.rs
+++ b/rust/apps/cli/tests/cli/files.rs
@@ -596,6 +596,143 @@ fn photos_lists_limit_output_and_stream_complete_results() {
}
}
+#[test]
+fn file_lists_filter_and_sort_synced_metadata() {
+ let mut server = mockito::Server::new();
+ let home = TestHome::new();
+ home.seed(&server.url());
+ let key = Key::generate();
+ let albums = server
+ .mock("GET", "/collections/v2")
+ .match_query(mockito::Matcher::Any)
+ .with_body(json!({"collections": [collection(1, "Album", &key)]}).to_string())
+ .create();
+ let file = |id: i64, metadata: Value, public: Value, size: Option<u64>| {
+ let (mut file, _) = remote_file_with(id, &key, b"original", &metadata, &public);
+ if let Some(size) = size {
+ file["info"] = json!({"fileSize": size});
+ }
+ file
+ };
+ let files = page(
+ &mut server,
+ 1,
+ 0,
+ json!([
+ file(
+ 1,
+ json!({"title": "Beach.jpg", "fileType": 0, "creationTime": 1_700_000_000_000_000i64,
+ "latitude": 1.0, "longitude": 2.0}),
+ json!({"caption": "Sunset at the beach"}),
+ Some(1200),
+ ),
+ file(
+ 2,
+ json!({"title": "Clip.mp4", "fileType": 1, "creationTime": 1_717_200_000_000_000i64}),
+ json!({}),
+ Some(5000),
+ ),
+ file(
+ 3,
+ json!({"title": "Live.heic", "fileType": 2, "creationTime": 1_735_689_600_000_000i64}),
+ json!({"caption": "Family dinner", "lat": 3.0, "long": 4.0}),
+ None,
+ ),
+ file(
+ 4,
+ json!({"title": "Holiday.JPG", "fileType": 0, "creationTime": 1_262_304_000_000_000i64,
+ "latitude": 0.0, "longitude": 0.0}),
+ json!({"editedTime": 1_710_028_800_000_000i64}),
+ Some(1200),
+ ),
+ ]),
+ false,
+ )
+ .expect(1)
+ .create();
+ let ids = |args: &[&str]| {
+ let mut command = vec!["--offline", "photos", "file", "list"];
+ command.extend(args);
+ home.json(&command)
+ .as_array()
+ .unwrap()
+ .iter()
+ .map(|file| file["id"].as_str().unwrap().parse::<i64>().unwrap())
+ .collect::<Vec<_>>()
+ };
+
+ let listed = home.json(&["photos", "file", "list"]);
+ assert_eq!(listed[0]["sizeBytes"], 1200);
+ assert_eq!(listed[2]["sizeBytes"], Value::Null);
+ albums.assert();
+ files.assert();
+ drop(server);
+
+ for (args, expected) in [
+ (vec![], vec![1, 2, 3, 4]),
+ (vec!["--type", "image"], vec![1, 4]),
+ (vec!["--type", "video", "--type", "livephoto"], vec![2, 3]),
+ (vec!["--since", "2024-06-01"], vec![2, 3]),
+ (vec!["--before", "2024-06-01"], vec![1, 4]),
+ (
+ vec!["--since", "2024-01-01", "--before", "2025-01-01"],
+ vec![2, 4],
+ ),
+ (vec!["--since", "2024-03-10T01:00:00+01:00"], vec![2, 3, 4]),
+ (vec!["--search", "BEACH sunset"], vec![1]),
+ (vec!["--search", "family dinner"], vec![3]),
+ (vec!["--search", "holiday jpg"], vec![4]),
+ (vec!["--search", "beach dinner"], vec![]),
+ (vec!["--no-location"], vec![2, 4]),
+ (vec!["--type", "image", "--no-location"], vec![4]),
+ (vec!["--sort", "created"], vec![3, 2, 4, 1]),
+ (vec!["--sort", "created", "--reverse"], vec![1, 4, 2, 3]),
+ (vec!["--sort", "size"], vec![2, 1, 4, 3]),
+ (vec!["--sort", "size", "--reverse"], vec![3, 1, 4, 2]),
+ (
+ vec!["--type", "image", "--sort", "size", "--all"],
+ vec![1, 4],
+ ),
+ (
+ vec!["--sort", "size", "--album", "1", "--limit", "2"],
+ vec![2, 1],
+ ),
+ ] {
+ assert_eq!(ids(&args), expected, "{args:?}");
+ }
+
+ let output = success(home.run(&[
+ "--offline",
+ "photos",
+ "file",
+ "list",
+ "--sort",
+ "size",
+ "--limit",
+ "1",
+ ]));
+ let stdout = String::from_utf8_lossy(&output.stdout);
+ let mut lines = stdout.lines();
+ assert!(lines.next().unwrap().contains("SIZE"));
+ assert!(lines.next().unwrap().starts_with("2 "));
+ assert!(String::from_utf8_lossy(&output.stderr).contains("Showing first 1"));
+ let output = success(home.run(&["--offline", "photos", "file", "view", "1"]));
+ assert!(String::from_utf8_lossy(&output.stdout).contains("1200 bytes"));
+
+ for args in [
+ vec!["--since", "yesterday"],
+ vec!["--before", "2024-06-01T00:00:00"],
+ vec!["--search", " "],
+ vec!["--type", "gif"],
+ vec!["--sort", "name"],
+ vec!["--reverse"],
+ ] {
+ let mut command = vec!["--offline", "photos", "file", "list"];
+ command.extend(&args);
+ failure(&home.run(&command));
+ }
+}
+
pub(super) fn collection(id: i64, name: &str, key: &Key) -> Value {
let wrapped = secretbox::encrypt(key.as_bytes(), &Key::from_bytes([0; 32]));
json!({
@@ -606,27 +743,35 @@ pub(super) fn collection(id: i64, name: &str, key: &Key) -> Value {
}
pub(super) 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(
+ remote_file_with(
+ id,
+ collection_key,
+ original,
&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();
+}
+
+fn remote_file_with(
+ id: i64,
+ collection_key: &Key,
+ original: &[u8],
+ metadata: &Value,
+ public: &Value,
+) -> (Value, Vec<u8>) {
+ let key = Key::generate();
+ let wrapped = secretbox::encrypt(key.as_bytes(), collection_key);
+ let metadata = blob::encrypt_json(metadata, &key).unwrap();
+ let public = blob::encrypt_json(public, &key).unwrap();
let private = blob::encrypt_json(&json!({"visibility": 1}), &key).unwrap();
let mut encrypted = Vec::new();
let header =
diff --git a/rust/apps/cli/tests/cli/museum.rs b/rust/apps/cli/tests/cli/museum.rs
index 56a2b2f03e..55e97db5de 100644
--- a/rust/apps/cli/tests/cli/museum.rs
+++ b/rust/apps/cli/tests/cli/museum.rs
@@ -395,6 +395,7 @@ async fn exercise(origin: String) -> TestResult {
assert_eq!(files[0]["id"], file_id);
assert_eq!(files[0]["name"], "original.jpg");
assert_eq!(files[0]["type"], "image");
+ assert!(files[0]["sizeBytes"].as_u64().is_some_and(|size| size > 0));
assert_eq!(files[0]["albumIds"], json!([album.to_string()]));
let output_dir = tempfile::tempdir().unwrap();
let output_path = output_dir.path().join("owned.jpg");
diff --git a/rust/crates/photos/src/files.rs b/rust/crates/photos/src/files.rs
index 6e9f68d559..163b17d32e 100644
--- a/rust/crates/photos/src/files.rs
+++ b/rust/crates/photos/src/files.rs
@@ -29,6 +29,7 @@ pub struct File {
pub duration_seconds: Option<u64>,
pub width: Option<u32>,
pub height: Option<u32>,
+ pub size: Option<u64>,
pub visibility: Option<Visibility>,
pub key: Key,
pub header: Header,
@@ -211,6 +212,11 @@ pub fn interpret(
duration_seconds: metadata.duration,
width: public.w,
height: public.h,
+ size: remote
+ .extra
+ .get("info")
+ .and_then(|info| info.get("fileSize"))
+ .and_then(serde_json::Value::as_u64),
visibility: if remote.owner_id == user_id {
Some(Visibility::from_value(private.visibility)?)
} else {