💚 End-to-end encrypted cloud for everything.
Dart 2faandroidauthye2eeencryptionend-to-end-encryptionfluttergolanggoogle-photosgoogle-photos-alternativeiosopensourcephotosprivacyprivacy-toolstypescriptzero-knowledge
List places and filter Photos files by place in the CLI
laurenspriem4be718026575
diff --git a/docs/docs/cli/accounts.md b/docs/docs/cli/accounts.mdindex a1f4694ef8..29782d23eb 100644--- a/docs/docs/cli/accounts.md+++ b/docs/docs/cli/accounts.md@@ -114,7 +114,7 @@ Prints `Logged out of Ente Auth for "[email protected]".` Without `--app`, the C## CLI home-The CLI home is the directory where the CLI keeps its data: an encrypted vault with your accounts and keys, and a database per account with synced metadata.+The CLI home is the directory where the CLI keeps its data: an encrypted vault with your accounts and keys, a database per account with synced metadata and, once you use places, the location data they need. Learn more in [Photos](./photos.md#find-files-by-place).| System | CLI home || ------- | ---------------------------------------------------------------------- |diff --git a/docs/docs/cli/photos.md b/docs/docs/cli/photos.mdindex aa775a3733..4932687fd7 100644--- a/docs/docs/cli/photos.md+++ b/docs/docs/cli/photos.md@@ -107,6 +107,21 @@ ente photos file list --type video --min-size 500MBA 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.+## Find files by place++```sh+ente photos place list+ente photos place list --countries --album Holidays+ente photos file list --place lisbon+ente photos file list --country JP --type video+```++`place list` shows the cities where your files were taken, with the number of files in each, most first. `--countries` lists countries instead. Places come from each file's location; files without one are not counted. Locations that match no city or country in the dataset are omitted from that list, so city and country totals can differ. Country filters use the groups shown by `place list --countries`, which can differ from a city's country. For example, photos in French Guiana count under France.++`--place` keeps files taken in a city whose name contains the given text. When one of the cities `place list` shows for the same `--album` has exactly that name, only cities with that name match, so `--place nice` leaves out Venice. `--country` takes a two-letter code such as `PT`, or a full English country name, which matches only that country, so `--country niger` leaves out Nigeria; other text matches every country whose name contains it. `UK` also works for the United Kingdom, whose code is `GB`, and an unknown two-letter code is an error. Both ignore case and accent marks, and combine with the other filters. Type letters such as Å‚ or ø as `place list` shows them: `--place wrocÅ‚aw` finds WrocÅ‚aw, but `--place wroclaw` does not.++The first time you use places, the CLI downloads about 7 MB of location data from Ente (`assets.ente.com`) and keeps it with the account's local data. After that, places work with `--offline`. The location data is adapted from [GeoNames](https://www.geonames.org/) and the European Commission Joint Research Centre's [GHS-UCDB R2024A](https://doi.org/10.2905/1a338be6-7eaf-480c-9664-3a8ade88cbcd), both under [CC BY 4.0](https://creativecommons.org/licenses/by/4.0/), and from [Natural Earth](https://www.naturalearthdata.com/), which is in the public domain.+## Read as JSONLists return arrays and `view` returns one object. IDs are strings; timestamps are RFC 3339 strings in UTC.@@ -116,11 +131,13 @@ Lists return arrays and `view` returns one object. IDs are strings; timestamps a| `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` |+| `place list` | `name`, `country`, `countryCode`, `latitude` and `longitude` (the city's position), `fileCount` |+| `place list --countries` | `name`, `code`, `fileCount` || `export` | See [Automation](./automation.md#export-summary) |## Read offline-`album list`, `album view`, `file list` and `file view` work with `--offline` using the metadata an earlier online run synced. An online `album list` syncs albums only; run `file list` online for each album whose files you want to read offline. Export and download need the network.+`album list`, `album view`, `file list`, `file view` and `place list` work with `--offline` using the metadata an earlier online run synced. An online `album list` syncs albums only; run `file list` online for each album whose files you want to read offline. Places also need the location data that an earlier online `place list`, `--place` or `--country` downloaded. Export and download need the network.## Limitsdiff --git a/docs/docs/cli/troubleshooting.md b/docs/docs/cli/troubleshooting.mdindex 49acf172bc..061b37a360 100644--- a/docs/docs/cli/troubleshooting.md+++ b/docs/docs/cli/troubleshooting.md@@ -58,6 +58,7 @@ Your data in Ente and exported files are untouched. If you have an existing Phot- `no local data; run the command online first` (also `no local Photos data` and `no local Auth data`): `--offline` only reads what an earlier online run synced. Run the command once without `--offline`.- `files for album "Holidays" have not finished syncing; run the command online first`: the last online run did not finish that album.+- `location data has not been downloaded; run the command online first`: places need location data that the CLI downloads the first time you run `place list`, `--place` or `--country` online.- `download requires network access` and `export requires network access; remove --offline`: these commands always need the network.## Export problemsdiff --git a/rust/Cargo.lock b/rust/Cargo.lockindex a10103296f..9545996db2 100644--- a/rust/Cargo.lock+++ b/rust/Cargo.lock@@ -2545,6 +2545,7 @@ dependencies = ["ente-auth","ente-collections","ente-core",+ "ente-location","ente-paste","ente-photos","ente-photos-export",diff --git a/rust/apps/cli/Cargo.toml b/rust/apps/cli/Cargo.tomlindex f4da0d77ba..5bae4c9974 100644--- a/rust/apps/cli/Cargo.toml+++ b/rust/apps/cli/Cargo.toml@@ -22,6 +22,7 @@ ente-accounts.workspace = trueente-auth.workspace = trueente-collections.workspace = trueente-core.workspace = true+ente-location.workspace = trueente-paste.workspace = trueente-photos.workspace = trueente-photos-export.workspace = truediff --git a/rust/apps/cli/changes/places.md b/rust/apps/cli/changes/places.mdnew file mode 100644index 0000000000..fea7203b5e--- /dev/null+++ b/rust/apps/cli/changes/places.md@@ -0,0 +1 @@+- List the cities and countries where your photos were taken with `photos place list`, and filter `photos file list` by `--place` and `--country`.diff --git a/rust/apps/cli/src/args.rs b/rust/apps/cli/src/args.rsindex 7f0b28608e..300c61205d 100644--- a/rust/apps/cli/src/args.rs+++ b/rust/apps/cli/src/args.rs@@ -392,6 +392,18 @@ Examples:#[command(subcommand)]command: FileCommand,},+ #[command(about = "See where your files were taken")]+ Place {+ #[arg(+ long,+ global = true,+ value_name = "ALBUM",+ help = "Limit to an album ID or exact name"+ )]+ album: Option<String>,+ #[command(subcommand)]+ command: PlaceCommand,+ },}#[derive(Args)]@@ -616,6 +628,22 @@ pub struct FileQuery {pub search: Option<String>,#[arg(long, help = "Include only files without a location")]pub no_location: bool,+ #[arg(+ long,+ value_name = "TEXT",+ value_parser = nonempty_search,+ help = "Include files taken in a city whose name contains TEXT",+ long_help = "Include files taken in a city whose name contains TEXT, ignoring case and accent marks. If one of the cities `place list` shows for the same --album is named exactly TEXT, only cities with that name match. Type letters such as Å‚ or ø as `place list` shows them. Downloads location data on first use; see `place list --help`."+ )]+ pub place: Option<String>,+ #[arg(+ long,+ value_name = "COUNTRY",+ value_parser = nonempty_search,+ help = "Include files taken in a country, given by code or name",+ long_help = "Include files taken in the country with this two-letter code, such as PT, or this full English name. UK also selects the United Kingdom (GB); an unknown two-letter code is an error. Other text includes every country whose English name contains it. Names ignore case and accent marks, and are the ones `place list --countries` shows. Downloads location data on first use; see `place list --help`."+ )]+ pub country: Option<String>,#[arg(long,value_name = "SIZE",@@ -644,6 +672,27 @@ pub struct FileQuery {pub reverse: bool,}+const PLACE_HELP: &str = "Refreshes file metadata first; --offline reads previously synced data.+Groups files by their location and lists the most files first. Files without a location,+or whose location matches no city (or with --countries, no country), are not counted.+--country uses the groups --countries shows, which can differ from a city's country:+photos in French Guiana count under France.+On first use, downloads about 7 MB of location data and keeps it with the account's local data.+With --json, returns an array. City fields: name, country, countryCode (strings);+latitude, longitude of the city (numbers); fileCount (integer). With --countries: name, code (strings); fileCount (integer).";++#[derive(Subcommand)]+pub enum PlaceCommand {+ #[command(about = "List the cities or countries where your files were taken")]+ #[command(after_long_help = PLACE_HELP)]+ List {+ #[arg(long, help = "List countries instead of cities")]+ countries: bool,+ #[command(flatten)]+ list: ListArgs,+ },+}+#[derive(Clone, Copy, ValueEnum)]pub enum FileType {Image,diff --git a/rust/apps/cli/src/output.rs b/rust/apps/cli/src/output.rsindex 65ebaafd3f..30bef2d946 100644--- a/rust/apps/cli/src/output.rs+++ b/rust/apps/cli/src/output.rs@@ -4,6 +4,7 @@ use anyhow::{Context, Result, bail};use chrono::{DateTime, SecondsFormat};use dialoguer::console::{Alignment, measure_text_width, pad_str};use ente_accounts::admin::{Subscription, User, UserDetails};+use ente_location::{CityMatch, CountryGroup};use ente_photos::{collections::{Collection, Visibility},files::File,@@ -128,6 +129,48 @@ impl FileView {}}+#[derive(Serialize)]+#[serde(rename_all = "camelCase")]+pub struct CityView {+ name: String,+ country: String,+ country_code: String,+ latitude: f32,+ longitude: f32,+ file_count: usize,+}++impl From<CityMatch> for CityView {+ fn from(group: CityMatch) -> Self {+ Self {+ name: group.city.name,+ country: group.city.country_name,+ country_code: group.city.country_code.to_string(),+ latitude: group.city.latitude as f32,+ longitude: group.city.longitude as f32,+ file_count: group.coordinate_indices.len(),+ }+ }+}++#[derive(Serialize)]+#[serde(rename_all = "camelCase")]+pub struct CountryView {+ name: String,+ code: String,+ file_count: usize,+}++impl CountryView {+ pub fn new(name: &str, group: &CountryGroup) -> Self {+ Self {+ name: name.to_owned(),+ code: group.country.to_string(),+ file_count: group.coordinate_indices.len(),+ }+ }+}+#[derive(Serialize)]#[serde(rename_all = "camelCase")]pub struct AdminUserView {@@ -280,6 +323,48 @@ pub fn files()}+pub fn cities(+ cities: impl Iterator<Item = CityView>,+ args: &ListArgs,+ as_json: bool,+) -> Result<()> {+ list(+ cities.map(Ok),+ args,+ as_json,+ ["CITY", "COUNTRY", "FILES"],+ "No places.",+ |city| {+ [+ escape_controls(&city.name),+ escape_controls(&city.country),+ city.file_count.to_string(),+ ]+ },+ )+}++pub fn countries(+ countries: impl Iterator<Item = CountryView>,+ args: &ListArgs,+ as_json: bool,+) -> Result<()> {+ list(+ countries.map(Ok),+ args,+ as_json,+ ["COUNTRY", "CODE", "FILES"],+ "No places.",+ |country| {+ [+ escape_controls(&country.name),+ country.code,+ country.file_count.to_string(),+ ]+ },+ )+}+pub fn file(file: &FileView) -> Result<()> {let mut fields = vec![("Name", escape_controls(&file.name)),diff --git a/rust/apps/cli/src/photos/mod.rs b/rust/apps/cli/src/photos/mod.rsindex 9903d42b19..ffb4801bf9 100644--- a/rust/apps/cli/src/photos/mod.rs+++ b/rust/apps/cli/src/photos/mod.rs@@ -1,16 +1,21 @@mod export;+mod places;pub mod replica;use std::{cmp::Ordering, io::Seek, path::Path};use anyhow::{Context, Result, ensure};use ente_core::Session;+use ente_location::Coordinate;use ente_photos::files::{self, File, Kind};use serde_json::json;use crate::{api,- args::{AlbumCommand, App, FileCommand, FileQuery, FileSort, FileType, Options, PhotosCommand},+ args::{+ AlbumCommand, App, FileCommand, FileQuery, FileSort, FileType, Options, PhotosCommand,+ PlaceCommand,+ },core_db::SqliteResult,db, home,output::{self, AlbumView, FileView, MAX_CANDIDATES, select},@@ -51,7 +56,26 @@ pub async fn run(command: PhotosCommand, selected: Option<&str>, options: &OptioPhotosCommand::Api(_) | PhotosCommand::Export(_) => unreachable!(),PhotosCommand::Album { command } => album(command, &replica, options),PhotosCommand::File { album, command } => {- file(command, album.as_deref(), &session, &mut replica, options).await+ file(+ command,+ album.as_deref(),+ &session,+ &mut replica,+ &home.path,+ options,+ )+ .await+ }+ PhotosCommand::Place { album, command } => {+ place(+ command,+ album.as_deref(),+ &session,+ &mut replica,+ &home.path,+ options,+ )+ .await}}}@@ -102,13 +126,12 @@ fn album(command: AlbumCommand, replica: &Replica<'_>, options: &Options) -> Res}}-async fn file(- command: FileCommand,+async fn sync_files(album: Option<&str>,session: &Session,replica: &mut Replica<'_>,options: &Options,-) -> Result<()> {+) -> Result<(Option<i64>, bool)> {let mut incomplete = false;let albums =replica.collections(album, album.map(|_| (MAX_CANDIDATES + 1) as i64), |rows| {@@ -149,7 +172,26 @@ async fn file(} else {replica.sync_files(session, &albums).await?;}- let album_id = album.map(|_| albums[0].id);+ Ok((album.map(|_| albums[0].id), incomplete))+}++async fn file(+ command: FileCommand,+ album: Option<&str>,+ session: &Session,+ replica: &mut Replica<'_>,+ home: &Path,+ options: &Options,+) -> Result<()> {+ let (album_id, mut incomplete) = sync_files(album, session, replica, options).await?;+ let placed = match &command {+ FileCommand::List { query, .. } if query.place.is_some() || query.country.is_some() => {+ let index = places::open(home, options.offline).await?;+ let located = located(replica, album_id, |_, _| {})?;+ Some(places::matching(&index, query, &located)?)+ }+ _ => None,+ };let find = |selector: &str| {let entry = replica.files(album_id,@@ -176,7 +218,9 @@ async fn file(Err(error) => return Some(Err(error.into())),};let listed = entry.file.and_then(|file| {- if !matches(&query, &file) {+ if !matches(&query, &file)+ || placed.as_ref().is_some_and(|ids| !ids.contains(&file.id))+ {return Ok(None);}let key = SortKey {@@ -255,6 +299,49 @@ async fn file(Ok(())}+async fn place(+ command: PlaceCommand,+ album: Option<&str>,+ session: &Session,+ replica: &mut Replica<'_>,+ home: &Path,+ options: &Options,+) -> Result<()> {+ let (album_id, mut incomplete) = sync_files(album, session, replica, options).await?;+ let PlaceCommand::List { countries, list } = command;+ let index = places::open(home, options.offline).await?;+ let located = located(replica, album_id, |id, error| {+ eprintln!("file {id}: {error:#}");+ incomplete = true;+ })?;+ let coordinates = located+ .into_iter()+ .map(|(_, coordinate)| coordinate)+ .collect::<Vec<_>>();+ places::list(&index, &coordinates, countries, &list, options.json)?;+ ensure!(!incomplete, "place results are incomplete");+ Ok(())+}++fn located(+ replica: &Replica<'_>,+ album_id: Option<i64>,+ mut failed: impl FnMut(i64, anyhow::Error),+) -> Result<Vec<(i64, Coordinate)>> {+ replica.files(album_id, None, None, |rows| {+ let mut located = Vec::new();+ for row in rows {+ let entry = row?;+ match entry.file {+ Ok(file) => located+ .extend(places::coordinate(&file).map(|coordinate| (file.id, coordinate))),+ Err(error) => failed(entry.id, error),+ }+ }+ Ok(located)+ })+}+struct SortKey {created_at_micros: i64,size: Option<u64>,diff --git a/rust/apps/cli/src/photos/places.rs b/rust/apps/cli/src/photos/places.rsnew file mode 100644index 0000000000..6b2e0f95fe--- /dev/null+++ b/rust/apps/cli/src/photos/places.rs@@ -0,0 +1,171 @@+use std::{collections::HashSet, path::Path};++use anyhow::{Context, Result, ensure};+use ente_location::{Coordinate, CountryCode, normalize_search_text};+use ente_photos::{files::File, location::LocationIndex};++use crate::{+ args::{FileQuery, ListArgs},+ output::{self, CityView, CountryView},+};++pub async fn open(home: &Path, offline: bool) -> Result<LocationIndex> {+ let root = home.join("assets");+ if !LocationIndex::is_downloaded(&root) {+ ensure!(+ !offline,+ "location data has not been downloaded; run the command online first"+ );+ eprintln!("Downloading location data.");+ }+ LocationIndex::open(&root)+ .await+ .context("cannot load location data")+}++pub fn coordinate(file: &File) -> Option<Coordinate> {+ file.location+ .as_ref()+ .map(|location| Coordinate::new(location.latitude, location.longitude))+}++pub fn list(+ index: &LocationIndex,+ coordinates: &[Coordinate],+ countries: bool,+ args: &ListArgs,+ as_json: bool,+) -> Result<()> {+ if countries {+ let mut groups = index.group_countries(coordinates, None)?;+ groups.sort_by(|a, b| {+ b.coordinate_indices+ .len()+ .cmp(&a.coordinate_indices.len())+ .then_with(|| country_name(index, &a.country).cmp(country_name(index, &b.country)))+ });+ output::countries(+ groups+ .iter()+ .map(|group| CountryView::new(country_name(index, &group.country), group)),+ args,+ as_json,+ )+ } else {+ let mut groups = index.group_cities(coordinates, "");+ groups.sort_by(|a, b| {+ b.coordinate_indices+ .len()+ .cmp(&a.coordinate_indices.len())+ .then_with(|| a.city.name.cmp(&b.city.name))+ .then_with(|| a.city.country_name.cmp(&b.city.country_name))+ });+ output::cities(groups.into_iter().map(CityView::from), args, as_json)+ }+}++pub fn matching(+ index: &LocationIndex,+ query: &FileQuery,+ located: &[(i64, Coordinate)],+) -> Result<HashSet<i64>> {+ let coordinates = located+ .iter()+ .map(|&(_, coordinate)| coordinate)+ .collect::<Vec<_>>();+ let mut matched = vec![true; located.len()];+ if let Some(place) = &query.place {+ let groups = index.group_cities(&coordinates, "");+ let place = NameMatch::new(place, groups.iter().map(|group| group.city.name.as_str()));+ keep_members(+ &mut matched,+ groups+ .iter()+ .filter(|group| place.matches(&group.city.name))+ .map(|group| &group.coordinate_indices),+ );+ }+ if let Some(country) = &query.country {+ let country = CountryMatch::new(index, country)?;+ let groups = index.group_countries(&coordinates, None)?;+ keep_members(+ &mut matched,+ groups+ .iter()+ .filter(|group| country.matches(index, group.country))+ .map(|group| &group.coordinate_indices),+ );+ }+ Ok(located+ .iter()+ .zip(matched)+ .filter_map(|(&(id, _), matched)| matched.then_some(id))+ .collect())+}++fn keep_members<'a>(matched: &mut [bool], groups: impl Iterator<Item = &'a Vec<u32>>) {+ let mut members = vec![false; matched.len()];+ for &index in groups.flatten() {+ members[index as usize] = true;+ }+ for (matched, member) in matched.iter_mut().zip(members) {+ *matched &= member;+ }+}++struct NameMatch {+ text: String,+ exact: bool,+}++impl NameMatch {+ fn new<'a>(text: &str, names: impl IntoIterator<Item = &'a str>) -> Self {+ let text = normalize_search_text(text.trim());+ let exact = names+ .into_iter()+ .any(|name| normalize_search_text(name) == text);+ Self { text, exact }+ }++ fn matches(&self, name: &str) -> bool {+ let name = normalize_search_text(name);+ if self.exact {+ name == self.text+ } else {+ name.contains(&self.text)+ }+ }+}++enum CountryMatch {+ Code(CountryCode),+ Name(NameMatch),+}++impl CountryMatch {+ fn new(index: &LocationIndex, text: &str) -> Result<Self> {+ let text = text.trim();+ if text.len() != 2 || !text.bytes().all(|byte| byte.is_ascii_alphabetic()) {+ let names = index.country_names().map(|(_, name)| name);+ return Ok(Self::Name(NameMatch::new(text, names)));+ }+ let upper = text.to_ascii_uppercase();+ let code: CountryCode = if upper == "UK" { "GB" } else { &upper }.parse()?;+ ensure!(+ index.country_name(code).is_some(),+ "no country has the code {text:?}; see place list --countries"+ );+ Ok(Self::Code(code))+ }++ fn matches(&self, index: &LocationIndex, code: CountryCode) -> bool {+ match self {+ Self::Code(selected) => code == *selected,+ Self::Name(name) => name.matches(country_name(index, &code)),+ }+ }+}++fn country_name<'a>(index: &'a LocationIndex, code: &'a CountryCode) -> &'a str {+ index.country_name(*code).unwrap_or(code.as_str())+}diff --git a/rust/apps/cli/tests/cli/museum.rs b/rust/apps/cli/tests/cli/museum.rsindex 5e2d20c33a..c515dd1b4b 100644--- a/rust/apps/cli/tests/cli/museum.rs+++ b/rust/apps/cli/tests/cli/museum.rs@@ -394,6 +394,250 @@ fn file_lists_filter_and_sort_server_metadata() -> TestResult {})}+#[test]+fn places_group_files_by_city_and_country() -> TestResult {+ Museum::run_async(|origin| async move {+ let email = format!("places-{}@example.org", Uuid::new_v4());+ let account = create_account(&origin, &email).await;+ let home = TestHome::new();+ login(&home, "photos", &email, &["--host", &origin]);+ let (trips, trips_key) = create_album(&origin, &account, "Trips", "album").await;+ let (family, family_key) = create_album(&origin, &account, "Family", "album").await;+ let mut uploaded = Vec::new();+ for (album, key, title, location) in [+ (trips, &trips_key, "Tram.jpg", Some((38.7223, -9.1393))),+ (trips, &trips_key, "Square.jpg", Some((38.7253, -9.1500))),+ (trips, &trips_key, "Bridge.jpg", Some((41.1496, -8.6110))),+ (family, &family_key, "Canal.jpg", Some((52.3731, 4.8922))),+ (family, &family_key, "Ocean.jpg", Some((30.0, -40.0))),+ (family, &family_key, "Home.jpg", None),+ (+ family,+ &family_key,+ "Promenade.jpg",+ Some((43.7102, 7.2620)),+ ),+ (trips, &trips_key, "Gondola.jpg", Some((45.4408, 12.3155))),+ (family, &family_key, "Market.jpg", Some((6.6018, 3.3515))),+ (trips, &trips_key, "Bus.jpg", Some((51.5074, -0.1278))),+ ] {+ let created = 1_700_000_000_000_000i64 + uploaded.len() as i64 * 10_000_000_000_000;+ let mut metadata = json!({"title": title, "fileType": 0, "creationTime": created});+ if let Some((latitude, longitude)) = location {+ metadata["latitude"] = json!(latitude);+ metadata["longitude"] = json!(longitude);+ }+ uploaded.push(upload_fixture(&origin, &account, album, key, &[1; 100], metadata).await);+ }+ let Ok(+ [+ (tram, _),+ (square, _),+ (bridge, _),+ (canal, canal_key),+ _,+ (unplaced, unplaced_key),+ (promenade, _),+ (gondola, _),+ (market, _),+ (bus, _),+ ],+ ) = <[(i64, Key); 10]>::try_from(uploaded)+ else {+ unreachable!()+ };++ home.json(&["photos", "file", "list"]);+ assert!(+ failure(&home.run(&["--offline", "photos", "place", "list"]))+ .contains("location data has not been downloaded; run the command online first")+ );++ let output = success(home.run(&["photos", "place", "list"]));+ assert!(String::from_utf8_lossy(&output.stderr).contains("Downloading location data."));+ let table = String::from_utf8(output.stdout).unwrap();+ let rows = table+ .lines()+ .map(|line| line.split_whitespace().collect::<Vec<_>>())+ .collect::<Vec<_>>();+ assert_eq!(rows[0], ["CITY", "COUNTRY", "FILES"]);+ assert_eq!(rows[1], ["Lisbon", "Portugal", "2"]);+ assert_eq!(rows.len(), 8, "{table}");++ let amsterdam = json!({"name": "Amsterdam", "country": "The Netherlands", "countryCode": "NL",+ "latitude": 52.37403, "longitude": 4.88969, "fileCount": 1});+ let lagos = json!({"name": "Lagos", "country": "Nigeria", "countryCode": "NG",+ "latitude": 6.45407, "longitude": 3.39467, "fileCount": 1});+ let nice = json!({"name": "Nice", "country": "France", "countryCode": "FR",+ "latitude": 43.70313, "longitude": 7.26608, "fileCount": 1});+ assert_eq!(+ home.json(&["photos", "place", "list"]),+ json!([+ {"name": "Lisbon", "country": "Portugal", "countryCode": "PT",+ "latitude": 38.72509, "longitude": -9.1498, "fileCount": 2},+ amsterdam,+ lagos,+ {"name": "London", "country": "United Kingdom", "countryCode": "GB",+ "latitude": 51.50853, "longitude": -0.12574, "fileCount": 1},+ nice,+ {"name": "Porto", "country": "Portugal", "countryCode": "PT",+ "latitude": 41.1485, "longitude": -8.61097, "fileCount": 1},+ {"name": "Venice", "country": "Italy", "countryCode": "IT",+ "latitude": 45.43713, "longitude": 12.33265, "fileCount": 1},+ ])+ );+ assert_eq!(+ home.json(&["photos", "place", "list", "--album", "Family"]),+ json!([amsterdam, lagos, nice])+ );+ let countries = home.json(&["photos", "place", "list", "--countries"]);+ assert_eq!(+ countries,+ json!([+ {"name": "Portugal", "code": "PT", "fileCount": 3},+ {"name": "France", "code": "FR", "fileCount": 1},+ {"name": "Nigeria", "code": "NG", "fileCount": 1},+ {"name": "The Netherlands", "code": "NL", "fileCount": 1},+ {"name": "United Kingdom", "code": "GB", "fileCount": 1},+ ])+ );+ assert_eq!(+ home.json(&["--offline", "photos", "place", "list", "--countries"]),+ countries+ );+ for (args, first) in [(vec![], "Lisbon"), (vec!["--countries"], "Portugal")] {+ let mut command = vec!["photos", "place", "list", "--limit", "1", "--json"];+ command.extend(args);+ let output = success(home.run(&command));+ let listed: Value = serde_json::from_slice(&output.stdout).unwrap();+ assert_eq!(listed.as_array().unwrap().len(), 1);+ assert_eq!(listed[0]["name"], first);+ assert!(String::from_utf8_lossy(&output.stderr).contains("Showing first 1 results"));+ }+ assert_eq!(+ home.json(&["photos", "place", "list", "--all"])+ .as_array()+ .unwrap()+ .len(),+ 7+ );++ let ids = |args: &[&str]| {+ let mut command = vec!["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<_>>()+ };+ for (args, expected) in [+ (+ vec!["--place", "LISB", "--sort", "created"],+ vec![square, tram],+ ),+ (+ vec!["--place", "lÃsbon", "--sort", "created"],+ vec![square, tram],+ ),+ (vec!["--place", "porto"], vec![bridge]),+ (vec!["--place", "nice"], vec![promenade]),+ (+ vec!["--place", "ice", "--sort", "created"],+ vec![gondola, promenade],+ ),+ (vec!["--album", "Trips", "--place", "nice"], vec![gondola]),+ (+ vec!["--country", "portugal", "--sort", "created"],+ vec![bridge, square, tram],+ ),+ (vec!["--country", "nether"], vec![canal]),+ (+ vec!["--country", "pt", "--sort", "created"],+ vec![bridge, square, tram],+ ),+ (vec!["--country", "NL"], vec![canal]),+ (vec!["--country", "uk"], vec![bus]),+ (vec!["--country", "GB"], vec![bus]),+ (vec!["--country", "niger"], vec![]),+ (vec!["--country", "nige"], vec![market]),+ (+ vec!["--place", "lisbon", "--country", "netherlands"],+ vec![],+ ),+ (vec!["--album", "Family", "--place", "lisbon"], vec![]),+ (vec!["--place", "lisbon", "--no-location"], vec![]),+ ] {+ assert_eq!(ids(&args), expected, "{args:?}");+ }+ let output = success(home.run(&[+ "--offline",+ "photos",+ "file",+ "list",+ "--place",+ "amsterdam",+ "--json",+ ]));+ assert!(output.stderr.is_empty());+ let offline: Value = serde_json::from_slice(&output.stdout).unwrap();+ assert_eq!(offline.as_array().unwrap().len(), 1);+ assert_eq!(offline[0]["id"], json!(canal.to_string()));+ assert!(+ failure(&home.run(&["photos", "file", "list", "--country", "xx"]))+ .contains("no country has the code \"xx\"")+ );++ export::edit_file(+ &origin,+ &account,+ unplaced,+ &unplaced_key,+ 1,+ json!({"editedTime": i64::MAX}),+ )+ .await;+ assert!(+ failure(&home.run(&["photos", "file", "list"])).contains("file results are incomplete")+ );+ assert_eq!(ids(&["--search", "Tram"]), [tram]);+ assert_eq!(+ ids(&["--place", "lisbon", "--sort", "created"]),+ [square, tram]+ );+ assert_eq!(+ ids(&["--country", "pt", "--sort", "created"]),+ [bridge, square, tram]+ );++ export::edit_file(+ &origin,+ &account,+ canal,+ &canal_key,+ 1,+ json!({"editedName": 42}),+ )+ .await;+ let output = home.run(&["photos", "place", "list", "--json"]);+ let error = failure(&output);+ assert!(error.contains(&format!("file {canal}:")), "{error}");+ assert!(error.contains("place results are incomplete"), "{error}");+ let partial: Value = serde_json::from_slice(&output.stdout).unwrap();+ assert_eq!(+ partial+ .as_array()+ .unwrap()+ .iter()+ .map(|city| city["name"].as_str().unwrap())+ .collect::<Vec<_>>(),+ ["Lisbon", "Lagos", "London", "Nice", "Porto", "Venice"]+ );+ Ok(())+ })+}+async fn exercise(origin: String) -> TestResult {let alice_email = format!("alice-{}@example.org", Uuid::new_v4());let bob_email = format!("bob-{}@example.org", Uuid::new_v4());diff --git a/rust/crates/location/src/city.rs b/rust/crates/location/src/city.rsindex a1310793be..860ff034e7 100644--- a/rust/crates/location/src/city.rs+++ b/rust/crates/location/src/city.rs@@ -197,6 +197,16 @@ impl CityIndex {cities}+ pub fn country_names(&self) -> impl Iterator<Item = (CountryCode, &str)> {+ (0..self.layout.country_count).map(|index| (self.country_code(index), self.country(index)))+ }++ pub fn country_name(&self, code: CountryCode) -> Option<&str> {+ self.country_names()+ .find(|&(candidate, _)| candidate == code)+ .map(|(_, name)| name)+ }+pub fn match_coordinates(&self, coordinates: &[Coordinate], query: &str) -> Vec<CityMatch> {self.match_coordinates_in(coordinates, query, self.tree(), MAX_CATCHMENT_KM)}diff --git a/rust/crates/photos/src/location.rs b/rust/crates/photos/src/location.rsindex b44bc3dc33..697b1f69e2 100644--- a/rust/crates/photos/src/location.rs+++ b/rust/crates/photos/src/location.rs@@ -3,7 +3,7 @@ use std::path::Path;use ente_assets::download::CancellationToken;use ente_assets::{Asset, AssetFile, AssetStore};use ente_location::{- CityIndex, CityMatch, Coordinate, CountryIndex, CountryView, UrbanCenterIndex,+ CityIndex, CityMatch, Coordinate, CountryCode, CountryIndex, CountryView, UrbanCenterIndex,};const ASSET_URL: &str = "https://assets.ente.com/location/v2";@@ -46,6 +46,10 @@ impl LocationIndex {})}+ pub fn is_downloaded(asset_root: impl AsRef<Path>) -> bool {+ asset().is_ok_and(|asset| AssetStore::new(asset_root.as_ref()).is_downloaded(&asset))+ }+pub fn cities(&self) -> Vec<ente_location::City> {self.cities.search("", usize::MAX)}@@ -66,6 +70,14 @@ impl LocationIndex {};Ok(self.countries.group(coordinates, view)?.countries)}++ pub fn country_names(&self) -> impl Iterator<Item = (CountryCode, &str)> {+ self.cities.country_names()+ }++ pub fn country_name(&self, code: CountryCode) -> Option<&str> {+ self.cities.country_name(code)+ }}fn asset() -> Result<Asset, ente_assets::download::Error> {