From cb5ff8b8da122736e7f2af1ab965556eb179f349 Mon Sep 17 00:00:00 2001 From: Nils Pukropp Date: Thu, 19 Nov 2026 11:42:47 +0100 Subject: [PATCH] feat(photos): integrate the shared Gallery engine Share gallery settings and layout with Proton Gallery. Preserve Git source mappings so COPR can resolve the dependency offline. --- .github/workflows/release.yml | 8 +- Cargo.lock | 81 ++ Cargo.toml | 2 + crates/pdfs-cli/src/main.rs | 1 + crates/pdfs-core/Cargo.toml | 1 + crates/pdfs-core/src/auth.rs | 42 + crates/pdfs-core/src/control.rs | 490 +++++++++-- crates/pdfs-core/src/db/albums.rs | 56 +- crates/pdfs-core/src/db/photos.rs | 121 ++- crates/pdfs-core/src/db/tests.rs | 27 + crates/pdfs-fuse/Cargo.toml | 7 + crates/pdfs-fuse/src/albums.rs | 3 +- crates/pdfs-fuse/src/control.rs | 132 ++- crates/pdfs-fuse/src/gallery.rs | 431 +++++++++ crates/pdfs-fuse/src/gallery/video.rs | 205 +++++ crates/pdfs-fuse/src/lib.rs | 2 + crates/pdfs-fuse/src/link.rs | 3 + crates/pdfs-fuse/src/mount.rs | 12 + crates/pdfs-fuse/src/photos.rs | 30 +- crates/pdfs-fuse/src/sim/daemon.rs | 1 + crates/pdfs-gui/Cargo.toml | 2 + crates/pdfs-gui/resources/style.css | 1 + crates/pdfs-gui/src/app/events.rs | 26 + crates/pdfs-gui/src/app/main.rs | 6 + .../pdfs-gui/src/app/pages/drive_galleries.rs | 822 ++++++++++++++++++ crates/pdfs-gui/src/app/pages/login.rs | 4 + crates/pdfs-gui/src/app/pages/mod.rs | 1 + crates/pdfs-gui/src/app/pages/photo_viewer.rs | 92 +- crates/pdfs-gui/src/app/pages/photos.rs | 98 +-- docs/CHANGELOG.md | 13 + packaging/copr/README.md | 2 +- packaging/nix/package.nix | 5 +- packaging/proton-drive-linux.spec | 11 +- po/POTFILES.in | 1 + 34 files changed, 2492 insertions(+), 247 deletions(-) create mode 100644 crates/pdfs-fuse/src/gallery.rs create mode 100644 crates/pdfs-fuse/src/gallery/video.rs create mode 100644 crates/pdfs-gui/src/app/pages/drive_galleries.rs diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index d96d82a..b314769 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -129,8 +129,12 @@ jobs: # Every crate the build needs, so COPR can build the spec without network. - name: Package vendored crates (.tar.xz) run: | - cargo vendor --locked dist/vendor > /dev/null - tar -cJf proton-drive-linux-vendor-${{ env.VERSION }}.tar.xz -C dist vendor + mkdir -p dist/.cargo + ( + cd dist + cargo vendor --locked --manifest-path ../Cargo.toml vendor > .cargo/config.toml + ) + tar -cJf proton-drive-linux-vendor-${{ env.VERSION }}.tar.xz -C dist vendor .cargo/config.toml - name: Package Debian package (.deb) run: | diff --git a/Cargo.lock b/Cargo.lock index cdb2d44..16a9237 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -49,6 +49,7 @@ dependencies = [ "cipher 0.5.2", "cpubits", "cpufeatures 0.3.1", + "zeroize", ] [[package]] @@ -77,6 +78,7 @@ dependencies = [ "ctr 0.10.1", "ctutils", "ghash 0.6.0", + "zeroize", ] [[package]] @@ -1878,6 +1880,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2eecf2d5dc9b66b732b97707a0210906b1d30523eb773193ab777c0c84b3e8d5" dependencies = [ "polyval 0.7.3", + "zeroize", ] [[package]] @@ -2237,6 +2240,12 @@ version = "1.10.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87" +[[package]] +name = "httpdate" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df3b46402a9d5adb4c86a0cf463f42e19994e3ee891101b1841f30a545cb49a9" + [[package]] name = "hybrid-array" version = "0.4.15" @@ -2260,6 +2269,7 @@ dependencies = [ "http", "http-body", "httparse", + "httpdate", "itoa", "pin-project-lite", "smallvec", @@ -3601,6 +3611,7 @@ dependencies = [ name = "pdfs-core" version = "3.8.1" dependencies = [ + "argon2", "async-trait", "base64 0.23.1", "chrono", @@ -3635,12 +3646,18 @@ dependencies = [ "base64 0.23.1", "fuser", "futures", + "getrandom 0.4.3", + "http-body-util", + "hyper", + "hyper-util", "image", "libc", "lofty", "notify", "parking_lot 0.13.0", "pdfs-core", + "pg-app", + "pg-core", "proton-drive-rs", "serde", "serde_json", @@ -3648,6 +3665,7 @@ dependencies = [ "tokio", "tracing", "tracing-subscriber", + "zeroize", "zip", ] @@ -3657,6 +3675,7 @@ version = "3.8.1" dependencies = [ "anyhow", "async-channel", + "base64 0.23.1", "gettext-rs", "gtk4", "kamadak-exif", @@ -3664,6 +3683,7 @@ dependencies = [ "libadwaita", "pangocairo", "pdfs-core", + "pg-core", "reqwest", "serde", "serde_json", @@ -3688,6 +3708,65 @@ version = "2.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220" +[[package]] +name = "pg-app" +version = "0.2.0" +source = "git+https://github.com/narrrl/proton-gallery.git?rev=72d83a29ad2836c698b18e2f5189a423c60c2399#72d83a29ad2836c698b18e2f5189a423c60c2399" +dependencies = [ + "async-trait", + "hex", + "pg-core", + "pg-drive", + "proton-drive-rs", + "proton-sdk", + "serde_json", + "sha2 0.11.1", + "tempfile", + "thiserror 2.0.21", + "tokio", + "tracing", + "zeroize", +] + +[[package]] +name = "pg-core" +version = "0.2.0" +source = "git+https://github.com/narrrl/proton-gallery.git?rev=72d83a29ad2836c698b18e2f5189a423c60c2399#72d83a29ad2836c698b18e2f5189a423c60c2399" +dependencies = [ + "aes-gcm 0.11.1", + "async-trait", + "getrandom 0.4.3", + "hex", + "rusqlite", + "serde", + "serde_json", + "sha2 0.11.1", + "tempfile", + "thiserror 2.0.21", + "tokio", + "tokio-util", + "zeroize", +] + +[[package]] +name = "pg-drive" +version = "0.2.0" +source = "git+https://github.com/narrrl/proton-gallery.git?rev=72d83a29ad2836c698b18e2f5189a423c60c2399#72d83a29ad2836c698b18e2f5189a423c60c2399" +dependencies = [ + "async-trait", + "hex", + "pg-core", + "proton-drive-rs", + "proton-sdk", + "serde", + "serde_json", + "sha2 0.11.1", + "thiserror 2.0.21", + "tokio", + "tracing", + "zeroize", +] + [[package]] name = "pgp" version = "0.21.0" @@ -3825,6 +3904,7 @@ dependencies = [ "cpubits", "cpufeatures 0.3.1", "universal-hash 0.6.1", + "zeroize", ] [[package]] @@ -5191,6 +5271,7 @@ dependencies = [ "bytes", "futures-core", "futures-sink", + "futures-util", "libc", "pin-project-lite", "tokio", diff --git a/Cargo.toml b/Cargo.toml index bcd827d..1795e75 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -17,6 +17,8 @@ categories = ["filesystem", "command-line-utilities"] [workspace.dependencies] proton-sdk = { version = "0.12.1" } proton-drive-rs = { version = "0.12.1" } +pg-app = { git = "https://github.com/narrrl/proton-gallery.git", rev = "72d83a29ad2836c698b18e2f5189a423c60c2399" } +pg-core = { git = "https://github.com/narrrl/proton-gallery.git", rev = "72d83a29ad2836c698b18e2f5189a423c60c2399" } chrono = { version = "0.4", default-features = false, features = ["std"] } # Internal crates. diff --git a/crates/pdfs-cli/src/main.rs b/crates/pdfs-cli/src/main.rs index f6692ed..52fb31b 100644 --- a/crates/pdfs-cli/src/main.rs +++ b/crates/pdfs-cli/src/main.rs @@ -2696,6 +2696,7 @@ fn mount_once(mountpoint: Option) -> Result { db, pdfs_fuse::MountOptions { username, + gallery_session: Some(session.clone()), sweep_mode: config.resolved_conflict_sweep(), upload_limit: config.upload_limit.unwrap_or(0), download_limit: config.download_limit.unwrap_or(0), diff --git a/crates/pdfs-core/Cargo.toml b/crates/pdfs-core/Cargo.toml index 9deceea..46a80a3 100644 --- a/crates/pdfs-core/Cargo.toml +++ b/crates/pdfs-core/Cargo.toml @@ -10,6 +10,7 @@ homepage.workspace = true description = "Core auth/session/config for the Proton Drive Linux client" [dependencies] +argon2 = "0.5" proton-sdk.workspace = true proton-drive-rs.workspace = true chrono.workspace = true diff --git a/crates/pdfs-core/src/auth.rs b/crates/pdfs-core/src/auth.rs index fe57852..b22dd6d 100644 --- a/crates/pdfs-core/src/auth.rs +++ b/crates/pdfs-core/src/auth.rs @@ -128,6 +128,48 @@ fn with_keyring(op: impl Fn(&Entry) -> keyring_core::Result) -> Result with_keyring_entry(KEYRING_SERVICE, KEYRING_USER, op) } +/// Verify the machine-local Gallery passphrase, setting it on first use. +pub fn unlock_gallery(username: &str, passphrase: &str) -> std::result::Result<(), String> { + use argon2::password_hash::{PasswordHash, PasswordHasher, PasswordVerifier, SaltString}; + use std::io::Read; + + if passphrase.is_empty() || passphrase.len() > 1024 { + return Err("Enter your Gallery passphrase.".into()); + } + static VERIFY: parking_lot::Mutex<()> = parking_lot::Mutex::new(()); + let _verify = VERIFY.lock(); + let service = "io.narl.protongallery"; + let user = format!("hidden-albums:{username}"); + let argon = argon2::Argon2::default(); + match with_keyring_entry(service, &user, Entry::get_password) { + Ok(stored) => { + let hash = PasswordHash::new(&stored) + .map_err(|_| "The saved Gallery passphrase is unreadable.")?; + argon + .verify_password(passphrase.as_bytes(), &hash) + .map_err(|_| "The Gallery passphrase is incorrect.".into()) + } + Err(Error::Keyring(keyring_core::Error::NoEntry)) => { + if passphrase.chars().count() < 12 { + return Err("Choose a Gallery passphrase with at least 12 characters.".into()); + } + let mut bytes = [0; 16]; + std::fs::File::open("/dev/urandom") + .and_then(|mut file| file.read_exact(&mut bytes)) + .map_err(|_| "Couldn’t generate the passphrase salt.")?; + let salt = SaltString::encode_b64(&bytes) + .map_err(|_| "Couldn’t generate the passphrase salt.")?; + let hash = argon + .hash_password(passphrase.as_bytes(), &salt) + .map_err(|_| "Couldn’t protect the Gallery passphrase.")? + .to_string(); + with_keyring_entry(service, &user, |entry| entry.set_password(&hash)) + .map_err(|_| "Couldn’t save the Gallery passphrase in the system keyring.".into()) + } + Err(_) => Err("The system keyring is locked or unavailable.".into()), + } +} + /// Run `op` on the entry `service`/`user`, reconnecting once if the Secret /// Service fails the call. /// diff --git a/crates/pdfs-core/src/control.rs b/crates/pdfs-core/src/control.rs index e82fd9e..d9df2aa 100644 --- a/crates/pdfs-core/src/control.rs +++ b/crates/pdfs-core/src/control.rs @@ -44,14 +44,20 @@ pub enum Request { /// Report mount status (account, mountpoint, pin count). Status, /// Pin a file (path relative to the mountpoint, or absolute under it). - Pin { path: String }, + Pin { + path: String, + }, /// Unpin a file, evicting its cached content. - Unpin { path: String }, + Unpin { + path: String, + }, /// List pinned files. ListPins, /// List a directory for the in-app file browser. `path` is /// mountpoint-relative (empty or "." = the mount root). - ListDir { path: String }, + ListDir { + path: String, + }, /// Fetch a page of the photos timeline, newest first. Returns metadata only: /// a thumbnail path comes back only for photos already in the cache, so the /// reply never waits on the network. Front-ends ask for the thumbnails they @@ -83,7 +89,9 @@ pub enum Request { /// live photo and its clip. Replies with [`Response::Photos`], holding one /// item per file in server order; a photo that stands alone comes back as a /// single item. The lightbox uses it to switch between a shot's files. - PhotoGroup { uid: String }, + PhotoGroup { + uid: String, + }, /// The months the timeline spans (newest first, with per-month counts) so a /// front-end can build a date scrubber without paging the whole library. /// `kind` scopes the counts to one tab when set. @@ -94,7 +102,9 @@ pub enum Request { /// Photos taken on today's date in earlier years, newest first, at most /// `limit` of them — the "On this day" strip above the timeline. Replies /// with [`Response::Photos`]; a front-end groups them by year itself. - PhotosOnThisDay { limit: usize }, + PhotosOnThisDay { + limit: usize, + }, /// Sets of photos that are byte-identical copies of each other, going by /// the server's content hash. Replies with [`Response::PhotoDuplicates`]. PhotoDuplicates, @@ -118,7 +128,9 @@ pub enum Request { }, /// Every photo taken in one town with where exactly it was taken, for the /// map's close-up. Replies with [`Response::PhotoLocations`]. - PlaceLocations { id: u32 }, + PlaceLocations { + id: u32, + }, /// List the account's photo albums, newest activity first, including the /// albums other people share with us. Metadata only — an album's cover /// thumbnail is fetched with [`Request::PhotoThumbs`] like any other photo. @@ -134,9 +146,14 @@ pub enum Request { limit: usize, }, /// Create an album named `name`. Replies with [`Response::AlbumCreated`]. - CreateAlbum { name: String }, + CreateAlbum { + name: String, + }, /// Rename the album `uid`. Replies with [`Response::Ok`]. - RenameAlbum { uid: String, name: String }, + RenameAlbum { + uid: String, + name: String, + }, /// Delete the album `uid`. Its photos stay in the timeline; with /// `delete_photos` set, photos that exist only in the album (saved from a /// shared album) are deleted with it, which the server otherwise refuses. @@ -148,14 +165,22 @@ pub enum Request { }, /// Add timeline photos to the album `uid`. Replies with /// [`Response::AlbumChanged`]. - AddToAlbum { uid: String, photos: Vec }, + AddToAlbum { + uid: String, + photos: Vec, + }, /// Take photos out of the album `uid`. They stay in the timeline: this is /// not a trash. Replies with [`Response::AlbumChanged`]. - RemoveFromAlbum { uid: String, photos: Vec }, + RemoveFromAlbum { + uid: String, + photos: Vec, + }, /// Fetch thumbnails for the given photo uids, downloading the ones not /// already cached (one batched round-trip) and replying with their on-disk /// paths. Keep the batch small — it is served on demand, as tiles scroll in. - PhotoThumbs { uids: Vec }, + PhotoThumbs { + uids: Vec, + }, /// Trash photos by node uid, answered with [`Response::Trashed`]. /// /// Uid-addressed rather than path-addressed because the photos volume is not @@ -190,11 +215,15 @@ pub enum Request { ReserveFileThumbGeneration, /// Stop ordinary-file thumbnail work belonging to older listings. Photos /// timeline work and an explicit recursive build are deliberately separate. - CancelFileThumbs { generation: u64 }, + CancelFileThumbs { + generation: u64, + }, /// Start building local thumbnails for every supported image below `path`. /// The request returns immediately; progress is read with /// [`Request::ThumbnailBuildStatus`]. - StartThumbnailBuild { path: String }, + StartThumbnailBuild { + path: String, + }, /// Stop the current recursive ordinary-file thumbnail build, if any. CancelThumbnailBuild, /// Read progress for the recursive ordinary-file thumbnail build. @@ -206,7 +235,25 @@ pub enum Request { /// is how a front-end knows when the refreshed timeline is worth re-reading. PhotosRefreshStatus, /// Download a photo's full content into the cache; replies with its path. - OpenPhoto { uid: String }, + OpenPhoto { + uid: String, + }, + /// Open a revision for playback in the local viewer. + OpenGalleryVideo { + uid: String, + }, + OpenGalleryImage { + uid: String, + }, + CloseGalleryVideo { + token: String, + }, + GalleryThumbnail { + uid: String, + }, + DriveGallery { + action: GalleryAction, + }, /// Add or remove Proton's `Favorite` tag on a photo. Replies with /// [`Response::Ok`]. /// @@ -214,7 +261,10 @@ pub enum Request { /// one shared with us, or one that lives only in an album — needs it /// re-encrypted for our timeline, which the SDK does not implement yet; the /// daemon reports that as an error rather than silently doing nothing. - SetPhotoFavorite { uid: String, favorite: bool }, + SetPhotoFavorite { + uid: String, + favorite: bool, + }, /// Import Google Photos **Takeout** archives into Proton Photos. /// /// `archives` are absolute paths to the export's `.zip` parts on the @@ -326,7 +376,10 @@ pub enum Request { /// Search the daemon's index of *local* (non-Drive) files on this machine. /// Independent of [`Request::Search`] so a front-end can fire both at once and /// render whichever lands first. Replies with [`Response::LocalResults`]. - SearchLocal { query: String, limit: usize }, + SearchLocal { + query: String, + limit: usize, + }, /// Search both the Drive metadata index and the local-file index in one /// round-trip. This is the preferred prompt API; the two legacy search /// requests remain available for older clients. `limit` applies to each @@ -342,30 +395,48 @@ pub enum Request { }, /// Rename a file or folder. `path` is mountpoint-relative; `new_name` is a /// single path component (no separators). Replies with [`Response::Ok`]. - Rename { path: String, new_name: String }, + Rename { + path: String, + new_name: String, + }, /// Move a file or folder into a new parent folder. Both `path` and /// `new_parent` are mountpoint-relative, or both absolute local paths; two /// absolute paths may lie in different locations (My files, an on-demand /// or a mirror synced folder), and the move is still made on Proton Drive /// without transferring content. Replies with [`Response::Ok`]. - Move { path: String, new_parent: String }, + Move { + path: String, + new_parent: String, + }, /// Copy a file or folder into a folder on Proton Drive, without /// downloading or uploading it. Both `path` and `new_parent` are /// mountpoint-relative, or absolute paths inside My files. A name already /// taken in `new_parent` gets the next free ` (n)` suffix. Replies with /// [`Response::Ok`]. - Copy { path: String, new_parent: String }, + Copy { + path: String, + new_parent: String, + }, /// Ask Proton Drive how much the folder at mountpoint-relative `path` /// holds. Replies with [`Response::FolderSize`]. - FolderSize { path: String }, + FolderSize { + path: String, + }, /// The by-uid twin of [`Request::FolderSize`]. - FolderSizeByUid { uid: String }, + FolderSizeByUid { + uid: String, + }, /// Trash a file or folder. `path` is mountpoint-relative. Replies with /// [`Response::Ok`]. - Delete { path: String }, + Delete { + path: String, + }, /// Create a new folder named `name` under the mountpoint-relative `parent`. /// Replies with [`Response::Ok`]. - CreateFolder { parent: String, name: String }, + CreateFolder { + parent: String, + name: String, + }, // There is deliberately no bytes-carrying single-file upload: it was // `UploadFile { parent, name, bytes }`, and it OOMed on anything large for // the reason described on `UploadPhoto`. `UploadPaths` covers the same case @@ -388,11 +459,16 @@ pub enum Request { /// Retune the on-disk cache's soft byte cap at runtime (`0` = unlimited) and /// persist it to config so the next mount keeps it. Replies with /// [`Response::Ok`]. - SetCacheBudget { bytes: u64 }, + SetCacheBudget { + bytes: u64, + }, /// Cap uploads and downloads at these bytes per second (`0` = no cap), /// live for running transfers, and persist both to config so the next /// mount keeps them. Replies with [`Response::Ok`]. - SetBandwidthLimits { upload: u64, download: u64 }, + SetBandwidthLimits { + upload: u64, + download: u64, + }, /// Report on the health of the metadata database and content cache: sizes, /// row counts, and — when `deep` — SQLite's own integrity check. Replies /// with [`Response::CacheReport`]. @@ -429,10 +505,14 @@ pub enum Request { ListTrash, /// Restore trashed nodes, by uid, to the folders they were trashed from. /// Replies with [`Response::Ok`]. - Restore { uids: Vec }, + Restore { + uids: Vec, + }, /// Permanently delete trashed nodes by uid. Irreversible: the content is /// gone from Proton Drive, not moved. Replies with [`Response::Ok`]. - DeleteForever { uids: Vec }, + DeleteForever { + uids: Vec, + }, /// Permanently delete everything in the trash. Irreversible. /// Replies with [`Response::Ok`]. EmptyTrash, @@ -443,7 +523,9 @@ pub enum Request { /// only notices another client's changes when its TTL lapses, so a user who /// knows the cache is stale needs a way to say so. Cheap and idempotent — /// it invalidates, it does not fetch. - Refresh { scope: RefreshScope }, + Refresh { + scope: RefreshScope, + }, // ---- locations -------------------------------------------------------- /// List every local Proton Drive location. Replies with @@ -454,26 +536,37 @@ pub enum Request { /// List the account's registered devices. Replies with [`Response::Devices`]. ListDevices, /// Rename a device by its uid. Replies with [`Response::Ok`]. - RenameDevice { uid: String, name: String }, + RenameDevice { + uid: String, + name: String, + }, /// Delete (deregister) a device by its uid. Replies with [`Response::Ok`]. - DeleteDevice { uid: String }, + DeleteDevice { + uid: String, + }, /// Adopt an existing device as this machine's, pinning its uid in /// `config.json` so a hostname change or reinstall re-attaches to it instead /// of registering a duplicate. `uid: None` clears the pin. /// Replies with [`Response::Ok`]. - AdoptDevice { uid: Option }, + AdoptDevice { + uid: Option, + }, /// Move every folder another device backs up into this machine's own /// device, as server-side moves on the main volume. The other device stays /// registered, without those folders. Sync folders here that already track /// one of them follow it to its new share. Nothing is downloaded: the moved /// folders are then offered by [`Request::ListRestorableFolders`]. /// Replies with [`Response::Ok`]. - MigrateDevice { uid: String }, + MigrateDevice { + uid: String, + }, // ---- device folder sync ---------------------------------- /// Add a local folder to this machine's device, uploading its tree and /// registering the device on first use. Replies with [`Response::Ok`]. - AddSyncFolder { local_path: String }, + AddSyncFolder { + local_path: String, + }, /// Keep a real local directory in step with an existing folder in My files. /// First sync unions one-sided files and preserves differing versions. /// Replies with [`Response::Ok`]; no device backup is created. @@ -485,42 +578,65 @@ pub enum Request { ListSyncFolders, /// Remove a synced folder by id; `delete_remote` also trashes its cloud copy. /// Replies with [`Response::Ok`]. - RemoveSyncFolder { id: i64, delete_remote: bool }, + RemoveSyncFolder { + id: i64, + delete_remote: bool, + }, /// Switch a synced folder between `mirror` and `ondemand` (Phase 3). Replies /// with [`Response::Ok`]. - SetSyncFolderMode { id: i64, mode: String }, + SetSyncFolderMode { + id: i64, + mode: String, + }, /// Pause or resume one mirror folder's reconcile, independent of the /// global pause. Persisted until resumed. Replies with [`Response::Ok`]. - SetSyncFolderPaused { id: i64, paused: bool }, + SetSyncFolderPaused { + id: i64, + paused: bool, + }, /// Forget what a mirror folder synced before, so its next pass compares /// both sides afresh: what is on one side only is copied to the other, and /// a file that differs keeps both versions. Nothing is deleted. Replies /// with [`Response::Ok`]. - ResetSyncFolder { id: i64 }, + ResetSyncFolder { + id: i64, + }, /// Force a reconcile pass: one folder by id, or all when `id` is `None`. /// Replies with [`Response::Ok`]. - SyncNow { id: Option }, + SyncNow { + id: Option, + }, /// Pause or resume syncing: queued uploads and changes stop draining and /// mirror folders stop reconciling, while reads through the mount keep /// working. `until` is the Unix second a pause ends by itself; `None` /// pauses until resumed. Ignored when resuming. Replies with /// [`Response::Ok`]. - SetSyncPaused { paused: bool, until: Option }, + SetSyncPaused { + paused: bool, + until: Option, + }, /// List the queue of uploads and changes not yet on the remote. Replies /// with [`Response::PendingOps`]. ListPendingOps, /// Retry a backed-off queued op now instead of waiting out its backoff; /// every failed op when `id` is `None`. Replies with [`Response::Ok`]. - RetryPendingOp { id: Option }, + RetryPendingOp { + id: Option, + }, /// Copy the content of a queued upload (`id` from /// [`Request::ListPendingOps`]) to `dest`, an absolute path that must not /// exist yet. The op stays queued. Replies with [`Response::Ok`]. - ExportPendingOp { id: i64, dest: String }, + ExportPendingOp { + id: i64, + dest: String, + }, /// Drop a queued change (`id` from [`Request::ListPendingOps`]) and undo /// it locally: a node made here goes, a node Drive has goes back to what /// Drive has, along with every other change queued on it. Its content is /// lost unless it was exported first. Replies with [`Response::Ok`]. - DiscardPendingOp { id: i64 }, + DiscardPendingOp { + id: i64, + }, /// List the `(sync-conflict …)` copies under My Files and in synced /// folders. Replies with /// [`Response::Conflicts`]. @@ -529,18 +645,25 @@ pub enum Request { /// copy in a synced folder). /// Everything removed goes to the Proton trash. Replies with /// [`Response::Ok`]. - ResolveConflict { path: String, keep: ConflictKeep }, + ResolveConflict { + path: String, + keep: ConflictKeep, + }, /// List the folders under this machine's device that can be synced here, /// each with a proposed local path. Replies with /// [`Response::RestorableFolders`]. ListRestorableFolders, /// Attach the given remote device folders to local paths and sync them down. /// Replies with [`Response::Ok`]. - RestoreSyncFolders { items: Vec }, + RestoreSyncFolders { + items: Vec, + }, /// [`Request::ListRestorableFolders`] for another registered device, by /// uid, so its folders can be synced down to this machine. Replies with /// [`Response::RestorableFolders`]. - ListDeviceRestorableFolders { device: String }, + ListDeviceRestorableFolders { + device: String, + }, /// [`Request::RestoreSyncFolders`] for folders under another device. A /// separate variant rather than an optional field: an older daemon that /// ignored the field would attach the folders under this machine's device @@ -571,9 +694,13 @@ pub enum Request { }, /// List the members, pending invitations and public link of the node at /// mountpoint-relative `path`. Replies with [`Response::Share`]. - ListShare { path: String }, + ListShare { + path: String, + }, /// The by-uid twin of [`Request::ListShare`]. - ListShareByUid { uid: String }, + ListShareByUid { + uid: String, + }, /// Change the role of a share entry (member or pending invitation) on the node /// at `path`. `id` and `kind` identify the entry (from [`Response::Share`]). /// Replies with [`Response::Ok`]. @@ -621,9 +748,15 @@ pub enum Request { }, /// Remove the public link `id` from the node at `path`. Replies with /// [`Response::Ok`]. - RemovePublicLink { path: String, id: String }, + RemovePublicLink { + path: String, + id: String, + }, /// The by-uid twin of [`Request::RemovePublicLink`]. - RemovePublicLinkByUid { uid: String, id: String }, + RemovePublicLinkByUid { + uid: String, + id: String, + }, /// Change the public link `id` on the node at `path`, keeping its URL. /// `role` is "viewer" or "editor", or `None` to keep the current one. /// Replies with [`Response::PublicLink`]. @@ -646,28 +779,48 @@ pub enum Request { /// invitation and every member. Each removal is attempted even if an /// earlier one fails. Replies with [`Response::Ok`], or an error naming /// what is still shared. - StopSharing { path: String }, + StopSharing { + path: String, + }, /// The by-uid twin of [`Request::StopSharing`]. - StopSharingByUid { uid: String }, + StopSharingByUid { + uid: String, + }, // ---- revisions -------------------------------------------------------- /// List the version history of the file at mountpoint-relative `path`, /// newest first. Replies with [`Response::Revisions`]. - ListRevisions { path: String }, + ListRevisions { + path: String, + }, /// The by-uid twin of [`Request::ListRevisions`]. - ListRevisionsByUid { uid: String }, + ListRevisionsByUid { + uid: String, + }, /// Make revision `revision_id` of the file at `path` current again. The /// server applies this asynchronously, so the restored content may take a /// moment to appear. Replies with [`Response::Ok`]. - RestoreRevision { path: String, revision_id: String }, + RestoreRevision { + path: String, + revision_id: String, + }, /// The by-uid twin of [`Request::RestoreRevision`]. - RestoreRevisionByUid { uid: String, revision_id: String }, + RestoreRevisionByUid { + uid: String, + revision_id: String, + }, /// Permanently delete revision `revision_id` of the file at `path`. The /// content is unrecoverable, and the server refuses to delete the revision /// that is currently active. Replies with [`Response::Ok`]. - DeleteRevision { path: String, revision_id: String }, + DeleteRevision { + path: String, + revision_id: String, + }, /// The by-uid twin of [`Request::DeleteRevision`]. - DeleteRevisionByUid { uid: String, revision_id: String }, + DeleteRevisionByUid { + uid: String, + revision_id: String, + }, /// Write revision `revision_id` of the file at `path` to the absolute local /// path `dest`, leaving the file's current content untouched. Replies with /// [`Response::Ok`]. @@ -699,15 +852,21 @@ pub enum Request { /// with [`Response::Entries`]; like [`Request::ListSharedWithMe`] the entries /// carry a `uid` and an empty `path`, since the subtree lives outside the /// mount. Lets a front-end browse into a shared folder. - ListSharedFolder { uid: String }, + ListSharedFolder { + uid: String, + }, /// Download a file shared with me into the content cache, addressed by `uid`. /// Replies with [`Response::FilePath`] so the front-end can open it with the /// default app. The by-uid twin of [`Request::OpenFile`], which can only /// address nodes inside the mount. - OpenSharedFile { uid: String }, + OpenSharedFile { + uid: String, + }, /// Leave a shared node by its `uid`, giving up my access. Replies with /// [`Response::Ok`]. - LeaveShared { uid: String }, + LeaveShared { + uid: String, + }, // ---- incoming invitations --------------------------------------------- /// List invitations addressed to me, pending accept or reject. Replies with @@ -715,9 +874,13 @@ pub enum Request { ListInvitations, /// Accept the invitation `id`, gaining access to the shared node. Replies with /// [`Response::Ok`]. - AcceptInvitation { id: String }, + AcceptInvitation { + id: String, + }, /// Reject the invitation `id`, declining access. Replies with [`Response::Ok`]. - RejectInvitation { id: String }, + RejectInvitation { + id: String, + }, // ---- bookmarks -------------------------------------------------------- /// List public links saved to my account. Replies with [`Response::Bookmarks`]. @@ -729,7 +892,9 @@ pub enum Request { password: Option, }, /// Remove a saved bookmark by its `token`. Replies with [`Response::Ok`]. - DeleteBookmark { token: String }, + DeleteBookmark { + token: String, + }, // ---- account ---------------------------------------------------------- /// Total account storage usage (used/total, all Proton products, not just @@ -743,7 +908,9 @@ pub enum Request { /// daemon performs (uploads, downloads, deletes, renames, shares, sync /// passes, …), so a front-end can show a running "what happened" feed /// without re-deriving it from anywhere. - ListActivity { limit: usize }, + ListActivity { + limit: usize, + }, // ---- push ------------------------------------------------------------- /// Keep the connection open and stream [`Event`] lines instead of one @@ -761,6 +928,10 @@ pub enum Topic { Files, /// The photos timeline or albums. Photos, + /// The visible set of gallery media changed. + GalleryVisibility, + /// A remote Gallery visibility update arrived or its state became unavailable. + GalleryVisibilitySynced, Trash, /// Shares, links, invitations and saved links, in either direction. Shares, @@ -785,9 +956,11 @@ impl Topic { /// Every topic a front-end can act on. A new subscription is told all of /// them have changed, so it catches up on whatever happened while it was /// not connected. - pub const ALL: [Topic; 10] = [ + pub const ALL: [Topic; 12] = [ Topic::Files, Topic::Photos, + Topic::GalleryVisibility, + Topic::GalleryVisibilitySynced, Topic::Trash, Topic::Shares, Topic::Devices, @@ -1831,6 +2004,56 @@ pub struct MappingProgress { pub total: usize, } +/// Actions on saved Drive folder galleries. +#[derive(Serialize, Deserialize, Debug, Clone)] +pub enum GalleryAction { + Unlock { + passphrase: String, + }, + Lock, + List { + album: Option, + offset: usize, + limit: usize, + }, + Folders { + parent: Option, + }, + Add { + uid: String, + }, + Remove { + gallery: String, + }, + Refresh, + Cover { + album: GalleryPlace, + uid: String, + }, +} + +#[derive(Serialize, Deserialize, Debug, Clone)] +pub struct GalleryPlace { + pub gallery: String, + pub album: String, +} + +#[derive(Serialize, Deserialize, Debug, Clone)] +pub struct GalleryFolder { + pub uid: String, + pub name: String, +} + +#[derive(Serialize, Deserialize, Debug, Clone)] +pub struct GalleryAlbum { + pub place: GalleryPlace, + pub folder: GalleryFolder, + pub cover: Option, + pub items: u64, + pub folders: u64, + pub hidden: bool, +} + /// One photo in a [`Request::PhotosTimeline`] page. #[derive(Serialize, Deserialize, Debug, Clone)] pub struct PhotoItem { @@ -2222,7 +2445,9 @@ pub enum Response { version: String, }, /// A human-readable success message. - Ok { message: String }, + Ok { + message: String, + }, /// Health report for the metadata database and content cache (reply to /// [`Request::CacheInspect`]). CacheReport { @@ -2252,10 +2477,14 @@ pub enum Response { integrity_running: bool, }, /// The pin registry. - Pins { pins: Vec }, + Pins { + pins: Vec, + }, /// A directory listing (reply to [`Request::ListDir`]) or a trash listing /// (reply to [`Request::ListTrash`]). - Entries { entries: Vec }, + Entries { + entries: Vec, + }, /// A page of the photos timeline. `available` is false when the account /// has no photos volume. Photos { @@ -2268,6 +2497,22 @@ pub enum Response { #[serde(default)] counts: Option<(usize, usize, usize)>, }, + GalleryFolders { + folders: Vec, + }, + GalleryPage { + albums: Vec, + items: Vec, + total: usize, + }, + GalleryVideo { + url: String, + token: String, + size: u64, + }, + GalleryThumbnail { + data: Option, + }, /// The account's photo albums (reply to [`Request::PhotoAlbums`]). /// `available` is false when the account has no photos volume, matching /// [`Response::Photos`]. @@ -2276,7 +2521,9 @@ pub enum Response { items: Vec, }, /// What the daemon is doing right now (reply to [`Request::Diagnostics`]). - Diagnostics { diagnostics: Diagnostics }, + Diagnostics { + diagnostics: Diagnostics, + }, /// How the Takeout import is doing (reply to [`Request::ImportStatus`]). /// `running` is false once it has finished, when `summary` is the final /// report; `summary` is `None` when no import has run this session. @@ -2304,10 +2551,14 @@ pub enum Response { }, /// The months the timeline spans (reply to [`Request::PhotoMonths`]), /// newest first. - PhotoMonths { months: Vec }, + PhotoMonths { + months: Vec, + }, /// The duplicate sets (reply to [`Request::PhotoDuplicates`]), newest /// first. Each set lists the copy worth keeping first. - PhotoDuplicates { sets: Vec> }, + PhotoDuplicates { + sets: Vec>, + }, /// The sets of alike shots (reply to [`Request::PhotoSimilar`]), newest /// first, each in capture order; and how far hashing has got, `None` /// once no pass is running. `uncompared` counts the shots left out @@ -2329,9 +2580,13 @@ pub enum Response { }, /// The photos of one town, each with its location (reply to /// [`Request::PlaceLocations`]). - PhotoLocations { items: Vec }, + PhotoLocations { + items: Vec, + }, /// Thumbnails for a [`Request::PhotoThumbs`] batch. - Thumbs { items: Vec }, + Thumbs { + items: Vec, + }, /// Per-node outcome of a [`Request::TrashNodes`] batch. Reported per uid /// rather than as one verdict: the server answers each node separately, and /// a front-end that removed all of them on a partial success would show a @@ -2341,7 +2596,9 @@ pub enum Response { failed: Vec, }, /// The album a [`Request::CreateAlbum`] made. - AlbumCreated { uid: String }, + AlbumCreated { + uid: String, + }, /// Outcome of a [`Request::AddToAlbum`] or [`Request::RemoveFromAlbum`], /// per photo like [`Response::Trashed`]: `changed` photos were added or /// removed, `failed` ones were not. @@ -2355,20 +2612,33 @@ pub enum Response { FileThumbsStale, /// Daemon-issued generation reserved by /// [`Request::ReserveFileThumbGeneration`]. - FileThumbGeneration { generation: u64 }, + FileThumbGeneration { + generation: u64, + }, /// Current recursive thumbnail-build progress. - ThumbnailBuild { status: ThumbnailBuildStatus }, + ThumbnailBuild { + status: ThumbnailBuildStatus, + }, /// Whether a photos-timeline refresh is still running (reply to /// [`Request::PhotosRefreshStatus`]). - PhotosRefresh { running: bool }, + PhotosRefresh { + running: bool, + }, /// An on-disk path the front-end can open (e.g. a downloaded photo). - FilePath { path: String }, + FilePath { + path: String, + }, /// Full-text search results (reply to [`Request::Search`]). - SearchResults { hits: Vec }, + SearchResults { + hits: Vec, + }, /// Local-file search results (reply to [`Request::SearchLocal`]). `indexing` /// is true while a scan of the machine is still running, so a front-end can /// say "still indexing" instead of "no matches" on a cold first launch. - LocalResults { hits: Vec, indexing: bool }, + LocalResults { + hits: Vec, + indexing: bool, + }, /// Drive and local-file search results returned together (reply to /// [`Request::SearchV2`]). `local_indexing` distinguishes a genuinely empty /// local result set from one observed while the initial scan is running. @@ -2387,17 +2657,29 @@ pub enum Response { jobs: Vec, }, /// The account's devices (reply to [`Request::ListDevices`]). - Devices { items: Vec }, + Devices { + items: Vec, + }, /// Every local Proton Drive location (reply to [`Request::ListLocations`]). - Locations { items: Vec }, + Locations { + items: Vec, + }, /// This device's synced folders (reply to [`Request::ListSyncFolders`]). - SyncFolders { items: Vec }, + SyncFolders { + items: Vec, + }, /// The upload/change queue (reply to [`Request::ListPendingOps`]). - PendingOps { items: Vec }, + PendingOps { + items: Vec, + }, /// Conflict copies (reply to [`Request::ListConflicts`]). - Conflicts { items: Vec }, + Conflicts { + items: Vec, + }, /// Folders offered for restore (reply to [`Request::ListRestorableFolders`]). - RestorableFolders { items: Vec }, + RestorableFolders { + items: Vec, + }, /// A node's share: members + pending invitations, and its public link if any /// (reply to [`Request::ListShare`]). Share { @@ -2407,28 +2689,46 @@ pub enum Response { /// A freshly created or changed public link, carrying the shareable URL /// (reply to [`Request::CreatePublicLink`] and /// [`Request::UpdatePublicLink`]). - PublicLink { link: PublicLinkInfo }, + PublicLink { + link: PublicLinkInfo, + }, /// What a folder holds on Proton Drive (reply to [`Request::FolderSize`]): /// the bytes on storage and the number of items below it, folders and /// trashed items included. - FolderSize { size: u64, items: u64 }, + FolderSize { + size: u64, + items: u64, + }, /// Invitations addressed to me (reply to [`Request::ListInvitations`]). - Invitations { items: Vec }, + Invitations { + items: Vec, + }, /// Saved public links (reply to [`Request::ListBookmarks`]). - Bookmarks { items: Vec }, + Bookmarks { + items: Vec, + }, /// Account storage usage in bytes (reply to [`Request::AccountQuota`]). /// `max_space` is the total; `used_space` what is consumed. `max_space == 0` /// means the total is unknown, which a front-end shows as a plain used figure /// rather than a full bar. - AccountQuota { max_space: i64, used_space: i64 }, + AccountQuota { + max_space: i64, + used_space: i64, + }, /// Nodes I have shared with others (reply to [`Request::ListSharedByMe`]). - SharedByMe { items: Vec }, + SharedByMe { + items: Vec, + }, /// A file's version history, newest first (reply to /// [`Request::ListRevisions`]). - Revisions { items: Vec }, + Revisions { + items: Vec, + }, /// The daemon's recent activity, newest first (reply to /// [`Request::ListActivity`]). - Activity { items: Vec }, + Activity { + items: Vec, + }, /// The request failed. `message` is for the user; `kind` is for the code — /// a front-end decides its copy and whether to offer a retry from `kind`, /// never by matching on the text. @@ -2527,6 +2827,8 @@ impl Request { pub fn read_timeout(&self) -> Duration { if self.is_poll() { POLL_READ_TIMEOUT + } else if matches!(self, Request::DriveGallery { .. }) { + Duration::from_secs(300) } else { READ_TIMEOUT } diff --git a/crates/pdfs-core/src/db/albums.rs b/crates/pdfs-core/src/db/albums.rs index f41c01c..19b76c3 100644 --- a/crates/pdfs-core/src/db/albums.rs +++ b/crates/pdfs-core/src/db/albums.rs @@ -163,33 +163,47 @@ impl Db { album_uid: &str, offset: usize, limit: usize, + ) -> Result> { + self.album_photos_page_visible(album_uid, offset, limit, "[]") + } + + pub fn album_photos_page_visible( + &self, + album_uid: &str, + offset: usize, + limit: usize, + excluded: &str, ) -> Result> { let conn = self.read(); let mut stmt = conn.prepare( "SELECT uid, capture_time, name, ratio, thumb_state, kind FROM album_photos - WHERE album_uid = ?1 ORDER BY seq LIMIT ?2 OFFSET ?3", + WHERE album_uid = ?1 AND uid NOT IN (SELECT value FROM json_each(?4)) + ORDER BY seq LIMIT ?2 OFFSET ?3", )?; let rows = stmt - .query_map(params![album_uid, limit as i64, offset as i64], |r| { - Ok(StoredPhoto { - uid: r.get(0)?, - capture_time: r.get(1)?, - name: r.get(2)?, - ratio: r.get(3)?, - thumb_state: r.get(4)?, - kind: crate::control::PhotoKind::from_i64(r.get(5)?), - // Album rows have no favorite state of their own: an album - // photo on someone else's volume is not in our timeline, and - // favouriting one is not supported yet anyway. - favorite: false, - // Nor are album rows grouped: an album is a list the user - // made, and it shows exactly what they put in it. - group_size: 1, - has_raw: false, - // Album rows carry no location. - place_id: None, - }) - })? + .query_map( + params![album_uid, limit as i64, offset as i64, excluded], + |r| { + Ok(StoredPhoto { + uid: r.get(0)?, + capture_time: r.get(1)?, + name: r.get(2)?, + ratio: r.get(3)?, + thumb_state: r.get(4)?, + kind: crate::control::PhotoKind::from_i64(r.get(5)?), + // Album rows have no favorite state of their own: an album + // photo on someone else's volume is not in our timeline, and + // favouriting one is not supported yet anyway. + favorite: false, + // Nor are album rows grouped: an album is a list the user + // made, and it shows exactly what they put in it. + group_size: 1, + has_raw: false, + // Album rows carry no location. + place_id: None, + }) + }, + )? .collect::>()?; Ok(rows) } diff --git a/crates/pdfs-core/src/db/photos.rs b/crates/pdfs-core/src/db/photos.rs index d2562c7..dda2c27 100644 --- a/crates/pdfs-core/src/db/photos.rs +++ b/crates/pdfs-core/src/db/photos.rs @@ -513,24 +513,42 @@ impl Db { range: Option<(i64, i64)>, favorites: bool, not_in_album: bool, + ) -> Result> { + self.photos_page_visible(offset, limit, kind, range, favorites, not_in_album, "[]") + } + + #[allow(clippy::too_many_arguments)] + pub fn photos_page_visible( + &self, + offset: usize, + limit: usize, + kind: Option, + range: Option<(i64, i64)>, + favorites: bool, + not_in_album: bool, + excluded: &str, ) -> Result> { let conn = self.read(); // Built up so any combination of the optional filters is one indexed // query rather than a statement per case. let mut sql = String::from(PHOTO_SELECT); - let mut binds: Vec = Vec::new(); + let mut binds: Vec = Vec::new(); let mut conds: Vec = Vec::new(); + if excluded != "[]" { + binds.push(excluded.to_owned().into()); + conds.push("p.uid NOT IN (SELECT value FROM json_each(?1))".to_owned()); + } if kind != Some(crate::control::PhotoKind::Raw) { conds.push("p.uid = COALESCE(p.group_key, p.uid)".to_string()); } if let Some(k) = kind { - binds.push(k.as_i64()); + binds.push((k.as_i64()).into()); conds.push(format!("p.kind = ?{}", binds.len())); } if let Some((from, to)) = range { - binds.push(from); + binds.push((from).into()); conds.push(format!("p.capture_time >= ?{}", binds.len())); - binds.push(to); + binds.push((to).into()); conds.push(format!("p.capture_time < ?{}", binds.len())); } if favorites { @@ -549,9 +567,9 @@ impl Db { sql.push_str(" WHERE "); sql.push_str(&conds.join(" AND ")); } - binds.push(limit as i64); + binds.push((limit as i64).into()); let limit_pos = binds.len(); - binds.push(offset as i64); + binds.push((offset as i64).into()); let offset_pos = binds.len(); sql.push_str(&format!( " ORDER BY p.seq LIMIT ?{limit_pos} OFFSET ?{offset_pos}" @@ -580,6 +598,25 @@ impl Db { Ok(rows) } + /// Include associated files so a public preview cannot reveal a hidden + /// RAW, JPEG or Live Photo through another part of the same shot. + pub fn photo_group_members_for(&self, uids: &HashSet) -> Result> { + if uids.is_empty() { + return Ok(HashSet::new()); + } + let ids = serde_json::to_string(uids).expect("file identifiers serialize"); + let conn = self.read(); + let mut query = conn.prepare( + "SELECT uid FROM photos WHERE COALESCE(group_key, uid) IN ( + SELECT COALESCE(group_key, uid) FROM photos + WHERE uid IN (SELECT value FROM json_each(?1)) + )", + )?; + Ok(query + .query_map([ids], |row| row.get(0))? + .collect::>()?) + } + /// The whole persisted timeline, in stored order — every file, not one row /// per group. Only for whole-library passes (the photo re-date); the gallery /// pages with [`Db::photos_page`]. @@ -601,27 +638,33 @@ impl Db { pub fn photos_months( &self, kind: Option, + ) -> Result> { + self.photos_months_visible(kind, "[]") + } + + pub fn photos_months_visible( + &self, + kind: Option, + excluded: &str, ) -> Result> { let conn = self.read(); // The scrubber has to agree with the page it scrubs, so it counts what // the page shows: groups everywhere except on the Raw tab. - let (filter, binds): (&str, Vec) = match kind { - Some(crate::control::PhotoKind::Raw) => (" WHERE kind = 2", Vec::new()), - Some(k) => ( - " WHERE uid = COALESCE(group_key, uid) AND kind = ?1", - vec![k.as_i64()], - ), - None => (" WHERE uid = COALESCE(group_key, uid)", Vec::new()), + let filter = match kind { + Some(crate::control::PhotoKind::Raw) => "kind = ?2", + Some(_) => "uid = COALESCE(group_key, uid) AND kind = ?2", + None => "uid = COALESCE(group_key, uid) AND ?2 IS NULL", }; let sql = format!( "SELECT CAST(strftime('%Y', capture_time, 'unixepoch', 'localtime') AS INTEGER) AS y, \ CAST(strftime('%m', capture_time, 'unixepoch', 'localtime') AS INTEGER) AS m, \ COUNT(*) \ - FROM photos{filter} GROUP BY y, m ORDER BY y DESC, m DESC" + FROM photos WHERE {filter} AND uid NOT IN (SELECT value FROM json_each(?1)) + GROUP BY y, m ORDER BY y DESC, m DESC" ); let mut stmt = conn.prepare(&sql)?; let rows = stmt - .query_map(rusqlite::params_from_iter(binds), |r| { + .query_map(params![excluded, kind.map(|kind| kind.as_i64())], |r| { Ok(( r.get::<_, i32>(0)?, r.get::<_, i32>(1)?, @@ -637,6 +680,15 @@ impl Db { /// pick the date, and its own year is left out, because today's photos are /// what the timeline already opens on. One row per group, like the timeline. pub fn photos_on_this_day(&self, today: i64, limit: usize) -> Result> { + self.photos_on_this_day_visible(today, limit, "[]") + } + + pub fn photos_on_this_day_visible( + &self, + today: i64, + limit: usize, + excluded: &str, + ) -> Result> { let conn = self.read(); let sql = format!( "{PHOTO_SELECT} WHERE p.uid = COALESCE(p.group_key, p.uid) \ @@ -644,11 +696,12 @@ impl Db { = strftime('%m-%d', ?1, 'unixepoch', 'localtime') \ AND strftime('%Y', p.capture_time, 'unixepoch', 'localtime') \ < strftime('%Y', ?1, 'unixepoch', 'localtime') \ + AND p.uid NOT IN (SELECT value FROM json_each(?3)) ORDER BY p.seq LIMIT ?2" ); let mut stmt = conn.prepare(&sql)?; let rows = stmt - .query_map(params![today, limit as i64], stored_photo)? + .query_map(params![today, limit as i64, excluded], stored_photo)? .collect::>()?; Ok(rows) } @@ -657,6 +710,10 @@ impl Db { /// cover, most photographed first. Counted per group, like the timeline; /// photos without a location, or taken far from any town, are in none. pub fn photo_places(&self) -> Result> { + self.photo_places_visible("[]") + } + + pub fn photo_places_visible(&self, excluded: &str) -> Result> { let rows: Vec<(u32, usize, String)> = { let conn = self.read(); // SQLite fills the bare `uid` from the row `MIN(seq)` picked, which @@ -664,9 +721,10 @@ impl Db { let mut stmt = conn.prepare( "SELECT place_id, COUNT(*), uid, MIN(seq) FROM photos \ WHERE uid = COALESCE(group_key, uid) AND place_id IS NOT NULL \ + AND uid NOT IN (SELECT value FROM json_each(?1)) GROUP BY place_id ORDER BY COUNT(*) DESC, MIN(seq)", )?; - stmt.query_map([], |r| { + stmt.query_map([excluded], |r| { Ok((r.get(0)?, r.get::<_, i64>(1)? as usize, r.get(2)?)) })? .collect::>()? @@ -695,15 +753,29 @@ impl Db { id: u32, offset: usize, limit: usize, + ) -> Result> { + self.photos_at_place_visible(id, offset, limit, "[]") + } + + pub fn photos_at_place_visible( + &self, + id: u32, + offset: usize, + limit: usize, + excluded: &str, ) -> Result> { let conn = self.read(); let sql = format!( - "{PHOTO_SELECT} WHERE p.uid = COALESCE(p.group_key, p.uid) AND p.place_id = ?1 \ + "{PHOTO_SELECT} WHERE p.uid = COALESCE(p.group_key, p.uid) AND p.place_id = ?1 + AND p.uid NOT IN (SELECT value FROM json_each(?4)) ORDER BY p.seq LIMIT ?2 OFFSET ?3" ); let mut stmt = conn.prepare(&sql)?; let rows = stmt - .query_map(params![id, limit as i64, offset as i64], stored_photo)? + .query_map( + params![id, limit as i64, offset as i64, excluded], + stored_photo, + )? .collect::>()?; Ok(rows) } @@ -884,6 +956,10 @@ impl Db { /// Per-tab counts for the Photos page subtitle: `(photos, videos, raw)`. pub fn photos_counts(&self) -> Result<(usize, usize, usize)> { + self.photos_counts_visible("[]") + } + + pub fn photos_counts_visible(&self, excluded: &str) -> Result<(usize, usize, usize)> { use crate::control::PhotoKind; let conn = self.read(); // Photos and Videos count groups — one shot is one entry, however many @@ -891,9 +967,12 @@ impl Db { // them individually. let mut stmt = conn.prepare( "SELECT kind, COUNT(*) FROM photos \ - WHERE uid = COALESCE(group_key, uid) OR kind = 2 GROUP BY kind", + WHERE (uid = COALESCE(group_key, uid) OR kind = 2) + AND uid NOT IN (SELECT value FROM json_each(?1)) GROUP BY kind", )?; - let rows = stmt.query_map([], |r| Ok((r.get::<_, i64>(0)?, r.get::<_, i64>(1)?)))?; + let rows = stmt.query_map([excluded], |r| { + Ok((r.get::<_, i64>(0)?, r.get::<_, i64>(1)?)) + })?; let (mut photos, mut videos, mut raw) = (0usize, 0usize, 0usize); for row in rows { let (kind, n) = row?; diff --git a/crates/pdfs-core/src/db/tests.rs b/crates/pdfs-core/src/db/tests.rs index 68a941e..da34435 100644 --- a/crates/pdfs-core/src/db/tests.rs +++ b/crates/pdfs-core/src/db/tests.rs @@ -337,6 +337,10 @@ fn places_group_photos_by_the_nearest_town() { .map(|p| p.uid) .collect(); assert_eq!(berlin, ["b2", "b1-jpeg"]); + let visible = db.photo_places_visible(r#"["b2","p1"]"#).unwrap(); + assert_eq!(visible.len(), 1); + assert_eq!(visible[0].count, 1); + assert_eq!(visible[0].cover.uid, "b1-jpeg"); } /// A town's photos come with where each was taken, one per RAW+JPEG shot. @@ -7165,6 +7169,29 @@ fn a_raw_and_its_jpeg_are_one_entry_in_the_grid() { ["jpeg", "raw"] ); assert_eq!(db.photos_group("alone").unwrap().len(), 1); + + let hidden = db + .photo_group_members_for(&["raw".to_owned()].into_iter().collect()) + .unwrap(); + assert_eq!( + hidden, + ["raw".to_owned(), "jpeg".to_owned()].into_iter().collect() + ); + let excluded = serde_json::to_string(&hidden).unwrap(); + assert_eq!(db.photos_counts_visible(&excluded).unwrap(), (1, 0, 0)); + let months = db.photos_months_visible(None, &excluded).unwrap(); + assert_eq!(months.len(), 1); + assert_eq!(months[0].2, 1); + let public = db + .photos_page_visible(0, 1, None, None, false, false, &excluded) + .unwrap(); + assert_eq!( + public + .iter() + .map(|photo| photo.uid.as_str()) + .collect::>(), + ["alone"] + ); } /// Pixel names the two files of one raw capture after the role each plays, so diff --git a/crates/pdfs-fuse/Cargo.toml b/crates/pdfs-fuse/Cargo.toml index 6a36a0e..28c1d0a 100644 --- a/crates/pdfs-fuse/Cargo.toml +++ b/crates/pdfs-fuse/Cargo.toml @@ -14,6 +14,13 @@ pdfs-core.workspace = true zip.workspace = true sha1.workspace = true proton-drive-rs.workspace = true +pg-app.workspace = true +pg-core.workspace = true +hyper = { version = "1", features = ["http1", "server"] } +hyper-util = { version = "0.1", features = ["tokio"] } +http-body-util = "0.1" +getrandom = "0.4" +zeroize.workspace = true futures.workspace = true async-trait.workspace = true tokio.workspace = true diff --git a/crates/pdfs-fuse/src/albums.rs b/crates/pdfs-fuse/src/albums.rs index b5c7b1b..1c24e08 100644 --- a/crates/pdfs-fuse/src/albums.rs +++ b/crates/pdfs-fuse/src/albums.rs @@ -154,6 +154,7 @@ impl Core { album: &NodeUid, offset: usize, limit: usize, + excluded: &str, ) -> CoreResult> { let key = album.to_string(); let stamp = format!("{ALBUM_SYNCED_PREFIX}{key}"); @@ -172,7 +173,7 @@ impl Core { let page = self .db - .album_photos_page(&key, offset, limit) + .album_photos_page_visible(&key, offset, limit, excluded) .map_err(CoreError::from)?; Ok(page.into_iter().map(|p| self.photo_item(p)).collect()) } diff --git a/crates/pdfs-fuse/src/control.rs b/crates/pdfs-fuse/src/control.rs index 0db3cf0..3878879 100644 --- a/crates/pdfs-fuse/src/control.rs +++ b/crates/pdfs-fuse/src/control.rs @@ -396,6 +396,11 @@ fn touched_topics(request: &CtlRequest) -> &'static [Topic] { use CtlRequest as R; match request { R::Pin { .. } | R::Unpin { .. } => &[Topic::Files], + R::DriveGallery { + action: + pdfs_core::control::GalleryAction::Lock + | pdfs_core::control::GalleryAction::Unlock { .. }, + } => &[Topic::GalleryVisibility], R::CreateAlbum { .. } | R::RenameAlbum { .. } | R::DeleteAlbum { .. } @@ -552,6 +557,33 @@ fn handle_control_conn(core: &Core, username: &str, mountpoint: &Path, stream: U // Registered before the request is even parsed, so a handler that wedges // inside the daemon shows up by name in `pdfs diagnostics`. let _inflight = super::diagnostics::InflightGuard::new(super::diagnostics::request_kind(&line)); + let visibility = if matches!( + &request, + Ok(CtlRequest::PhotosTimeline { .. } + | CtlRequest::PhotoDuplicates + | CtlRequest::PhotoSimilar + | CtlRequest::PhotoPlaces + | CtlRequest::PlacePhotos { .. } + | CtlRequest::PlaceLocations { .. } + | CtlRequest::PhotosOnThisDay { .. } + | CtlRequest::PhotoGroup { .. } + | CtlRequest::PhotoAlbums + | CtlRequest::AlbumPhotos { .. } + | CtlRequest::PhotoMonths { .. } + | CtlRequest::PhotoThumbs { .. } + | CtlRequest::OpenGalleryImage { .. } + | CtlRequest::OpenPhoto { .. }) + ) { + core.gallery_visibility() + } else { + Ok(std::sync::Arc::default()) + }; + let visibility = match visibility { + Ok(visibility) => visibility, + Err(error) => return write_response(stream, CtlResponse::error(error)), + }; + let excluded = + serde_json::to_string(&visibility.media).expect("a set of file identifiers serializes"); let response = match request { Ok(CtlRequest::Status) => status_response(core, username, mountpoint), Ok(CtlRequest::Subscribe) => { @@ -668,11 +700,12 @@ fn handle_control_conn(core: &Core, username: &str, mountpoint: &Path, stream: U range, favorites, not_in_album, + &excluded, ) { Ok(Some(items)) => CtlResponse::Photos { available: true, items, - counts: core.db.photos_counts().ok(), + counts: core.db.photos_counts_visible(&excluded).ok(), }, Ok(None) => CtlResponse::Photos { available: false, @@ -693,7 +726,7 @@ fn handle_control_conn(core: &Core, username: &str, mountpoint: &Path, stream: U }, Err(e) => CtlResponse::error(e), }, - Ok(CtlRequest::PhotoPlaces) => match core.photo_places() { + Ok(CtlRequest::PhotoPlaces) => match core.photo_places(&excluded) { Ok(items) => CtlResponse::Places { items, mapping: core.timeline_progress(), @@ -701,7 +734,7 @@ fn handle_control_conn(core: &Core, username: &str, mountpoint: &Path, stream: U Err(e) => CtlResponse::error(e), }, Ok(CtlRequest::PlacePhotos { id, offset, limit }) => { - match core.place_photos(id, offset, clamp_limit(limit)) { + match core.place_photos(id, offset, clamp_limit(limit), &excluded) { Ok(items) => CtlResponse::Photos { available: true, items, @@ -715,7 +748,7 @@ fn handle_control_conn(core: &Core, username: &str, mountpoint: &Path, stream: U Err(e) => CtlResponse::error(e), }, Ok(CtlRequest::PhotosOnThisDay { limit }) => { - match core.photos_on_this_day(clamp_limit(limit)) { + match core.photos_on_this_day(clamp_limit(limit), &excluded) { Ok(items) => CtlResponse::Photos { available: true, items, @@ -760,7 +793,10 @@ fn handle_control_conn(core: &Core, username: &str, mountpoint: &Path, stream: U // An album page is a timeline page as far as the front-end is // concerned, so it comes back in the same reply — with `counts` // unset, which describe the whole timeline rather than this album. - Some(album) => match core.album_photos(&album, offset, clamp_limit(limit)) { + Some(album) => match visibility + .permits(&uid) + .and_then(|()| core.album_photos(&album, offset, clamp_limit(limit), &excluded)) + { Ok(items) => CtlResponse::Photos { available: true, items, @@ -802,17 +838,23 @@ fn handle_control_conn(core: &Core, username: &str, mountpoint: &Path, stream: U core.remove_from_album(album, photos) }) } - Ok(CtlRequest::PhotoMonths { kind }) => match core.db.photos_months(kind) { - Ok(months) => CtlResponse::PhotoMonths { - months: months - .into_iter() - .map(|(year, month, count)| PhotoMonth { year, month, count }) - .collect(), - }, - Err(e) => CtlResponse::error(e.into()), - }, + Ok(CtlRequest::PhotoMonths { kind }) => { + match core.db.photos_months_visible(kind, &excluded) { + Ok(months) => CtlResponse::PhotoMonths { + months: months + .into_iter() + .map(|(year, month, count)| PhotoMonth { year, month, count }) + .collect(), + }, + Err(e) => CtlResponse::error(e.into()), + } + } Ok(CtlRequest::PhotoThumbs { uids }) => { - let parsed: Vec = uids.iter().filter_map(|u| parse_uid(u)).collect(); + let parsed: Vec = uids + .iter() + .filter(|uid| !visibility.media.contains(*uid)) + .filter_map(|u| parse_uid(u)) + .collect(); CtlResponse::Thumbs { items: core.photo_thumbs(&parsed), } @@ -862,7 +904,7 @@ fn handle_control_conn(core: &Core, username: &str, mountpoint: &Path, stream: U running: core.timeline_refreshing(), }, Ok(CtlRequest::OpenPhoto { uid }) => match parse_uid(&uid) { - Some(u) => match core.open_photo(&u) { + Some(u) => match visibility.permits(&uid).and_then(|()| core.open_photo(&u)) { Ok(p) => CtlResponse::FilePath { path: p.display().to_string(), }, @@ -870,6 +912,27 @@ fn handle_control_conn(core: &Core, username: &str, mountpoint: &Path, stream: U }, None => CtlResponse::error(CoreError::invalid(format!("bad uid: {uid}"))), }, + Ok(CtlRequest::DriveGallery { action }) => core + .drive_gallery(action) + .unwrap_or_else(CtlResponse::error), + Ok(CtlRequest::OpenGalleryVideo { uid }) => core + .open_gallery_video(&uid) + .unwrap_or_else(CtlResponse::error), + Ok(CtlRequest::OpenGalleryImage { uid }) => match visibility + .permits(&uid) + .and_then(|()| core.open_shared_file(&uid)) + { + Ok(path) => CtlResponse::FilePath { + path: path.display().to_string(), + }, + Err(error) => CtlResponse::error(error), + }, + Ok(CtlRequest::CloseGalleryVideo { token }) => core + .close_gallery_video(&token) + .unwrap_or_else(CtlResponse::error), + Ok(CtlRequest::GalleryThumbnail { uid }) => core + .gallery_thumbnail(&uid) + .unwrap_or_else(CtlResponse::error), // The scan alone walks every archive's central directory, so even the // dry run goes to a background thread and is read back through // `ImportStatus` rather than answered inline. @@ -1929,9 +1992,14 @@ fn handle_control_conn(core: &Core, username: &str, mountpoint: &Path, stream: U // The request did not parse: the caller sent something malformed. Err(e) => CtlResponse::error(CoreError::invalid(format!("bad request: {e}"))), }; + let response = filter_gallery_response(response, &visibility); if !touched.is_empty() && !matches!(response, CtlResponse::Error { .. }) { core.events.publish(touched); } + write_response(stream, response); +} + +fn write_response(mut stream: UnixStream, response: CtlResponse) { let mut out = match serde_json::to_vec(&response) { Ok(v) => v, Err(e) => { @@ -1940,10 +2008,40 @@ fn handle_control_conn(core: &Core, username: &str, mountpoint: &Path, stream: U } }; out.push(b'\n'); - let mut stream = stream; let _ = stream.write_all(&out); } +fn filter_gallery_response( + mut response: CtlResponse, + visibility: &super::gallery::Visibility, +) -> CtlResponse { + let visible = |item: &pdfs_core::control::PhotoItem| !visibility.media.contains(&item.uid); + match &mut response { + CtlResponse::Photos { items, .. } => items.retain(visible), + CtlResponse::Albums { items, .. } => { + items.retain(|item| !visibility.albums.contains(&item.uid)); + for album in items { + if album + .cover_uid + .as_ref() + .is_some_and(|uid| visibility.media.contains(uid)) + { + album.cover_uid = None; + } + } + } + CtlResponse::PhotoDuplicates { sets } | CtlResponse::PhotoSimilar { sets, .. } => { + for set in sets.iter_mut() { + set.retain(visible); + } + sets.retain(|set| set.len() > 1); + } + CtlResponse::PhotoLocations { items } => items.retain(|located| visible(&located.photo)), + _ => {} + } + response +} + /// Listen on the control socket, serving one command per connection, each on its /// own thread. Runs on its own thread; returns only if the listener itself fails. /// diff --git a/crates/pdfs-fuse/src/gallery.rs b/crates/pdfs-fuse/src/gallery.rs new file mode 100644 index 0000000..6ffaa1f --- /dev/null +++ b/crates/pdfs-fuse/src/gallery.rs @@ -0,0 +1,431 @@ +//! Host Proton Gallery's account and catalog services in the Drive daemon. + +mod video; + +use std::collections::HashSet; +use std::path::PathBuf; +use std::sync::{ + Arc, + atomic::{AtomicBool, Ordering}, +}; +use std::time::{Duration, Instant}; + +use pdfs_core::control::{ + GalleryAction, GalleryAlbum, GalleryFolder, GalleryPlace, PhotoItem, PhotoKind, Response, +}; +use pdfs_core::{CoreError, CoreResult}; +use pg_app::{App, View}; +use pg_core::CancellationToken; +use pg_core::model::{AssetKey, SourceId}; +use proton_drive_rs::proton_sdk::session::ProtonApiSession; +use tokio::sync::{Mutex, OnceCell}; + +use super::{Core, NodeUid, parse_uid}; + +pub(super) struct Gallery { + root: PathBuf, + session: ProtonApiSession, + cancel: CancellationToken, + app: OnceCell, + checked: Mutex>)>>, + unlocked: AtomicBool, + video: video::Server, +} + +#[derive(Default, PartialEq, Eq)] +pub(super) struct Visibility { + pub(super) media: HashSet, + pub(super) albums: HashSet, +} + +impl Visibility { + pub(super) fn permits(&self, uid: &str) -> CoreResult<()> { + if self.media.contains(uid) || self.albums.contains(uid) { + return Err(CoreError::invalid("Unlock hidden albums to open this item")); + } + Ok(()) + } +} + +impl Gallery { + pub(super) fn new(root: PathBuf, session: ProtonApiSession) -> Self { + Self { + root, + session, + cancel: CancellationToken::new(), + app: OnceCell::new(), + checked: Mutex::new(None), + unlocked: AtomicBool::new(false), + video: video::Server::default(), + } + } + + pub(super) fn cancel(&self) { + self.cancel.cancel(); + self.video.close_all(); + } + + async fn app(&self, core: &Core) -> CoreResult<&App> { + self.app + .get_or_try_init(|| async { + App::open_hosted( + self.root.clone(), + self.session.clone(), + core.client.clone(), + self.cancel.child_token(), + ) + .await + .map_err(gallery_error) + }) + .await + } + + async fn ensure_visibility( + &self, + core: &Core, + app: &App, + force: bool, + ) -> CoreResult> { + if self.cancel.is_cancelled() { + return Err(CoreError::remote("The Gallery session expired")); + } + let mut checked = self.checked.lock().await; + if !force + && let Some((instant, Some(visibility))) = checked.as_ref() + && instant.elapsed() < Duration::from_secs(60) + { + return Ok(visibility.clone()); + } + let previous = checked.as_ref().map(|(_, visibility)| visibility.as_ref()); + let visibility = async { + let account = self.account()?; + app.refresh_gallery_configuration(false) + .await + .map_err(gallery_error)?; + let mut visibility = Visibility::default(); + for (volume, node) in app + .catalog + .hidden_assets(account.clone()) + .await + .map_err(gallery_error)? + { + visibility + .media + .insert(NodeUid::new(volume.into(), node.into()).to_string()); + } + visibility.media.extend( + core.db + .photo_group_members_for(&visibility.media) + .map_err(CoreError::from)?, + ); + for album in app + .catalog + .hidden_configuration_albums(account) + .await + .map_err(gallery_error)? + { + visibility.albums.insert( + NodeUid::new(album.volume.as_str().into(), album.node.as_str().into()) + .to_string(), + ); + } + Ok::<_, CoreError>(Arc::new(visibility)) + } + .await; + let current = visibility.as_ref().ok(); + if previous.is_some_and(|previous| previous != current) { + self.video.close_all(); + core.events + .publish(&[pdfs_core::control::Topic::GalleryVisibilitySynced]); + } + *checked = Some((Instant::now(), current.cloned())); + visibility + } + + fn account(&self) -> CoreResult { + pg_core::model::AccountId::new(self.session.user_id().as_str()).map_err(gallery_error) + } + + fn lock(&self) { + self.unlocked.store(false, Ordering::SeqCst); + self.video.close_all(); + } + + fn unlocked(&self) -> bool { + self.unlocked.load(Ordering::SeqCst) + } + + pub(super) async fn poll(self: Arc, core: Core) { + loop { + tokio::select! { + biased; + _ = self.cancel.cancelled() => break, + _ = tokio::time::sleep(Duration::from_secs(60)) => {} + } + if let Some(app) = self.app.get() { + let _ = self.ensure_visibility(&core, app, false).await; + } + } + } + + fn asset(&self, uid: &NodeUid) -> CoreResult { + Ok(AssetKey { + account: self.account()?, + volume: pg_core::model::VolumeId::new(uid.volume_id.as_str()).map_err(gallery_error)?, + node: pg_core::model::NodeId::new(uid.link_id.as_str()).map_err(gallery_error)?, + }) + } +} + +fn gallery_error(error: impl std::fmt::Display) -> CoreError { + CoreError::remote(error.to_string()) +} + +fn uid(value: &str) -> CoreResult { + parse_uid(value).ok_or_else(|| CoreError::invalid("Invalid gallery node")) +} + +fn done() -> Response { + Response::Ok { + message: "Gallery updated".into(), + } +} + +fn asset_uid(asset: &AssetKey) -> String { + NodeUid::new(asset.volume.as_str().into(), asset.node.as_str().into()).to_string() +} + +impl Core { + pub(super) fn gallery_visibility(&self) -> CoreResult> { + if self.gallery.is_none() { + return Ok(Arc::default()); + } + let gallery = self.gallery_host()?; + self.rt.block_on(async { + let app = gallery.app(self).await?; + let visibility = gallery.ensure_visibility(self, app, false).await?; + Ok(if gallery.unlocked() { + Arc::default() + } else { + visibility + }) + }) + } + + fn gallery_host(&self) -> CoreResult<&Gallery> { + self.gallery + .as_deref() + .filter(|gallery| !gallery.cancel.is_cancelled()) + .ok_or_else(|| CoreError::remote("The Gallery session is unavailable")) + } + + pub(super) fn drive_gallery(&self, action: GalleryAction) -> CoreResult { + let gallery = self.gallery_host()?; + let action = match action { + GalleryAction::Unlock { passphrase } => { + let passphrase = zeroize::Zeroizing::new(passphrase); + pdfs_core::auth::unlock_gallery(gallery.session.username(), &passphrase) + .map_err(gallery_error)?; + gallery.unlocked.store(true, Ordering::SeqCst); + return Ok(done()); + } + GalleryAction::Lock => { + gallery.lock(); + return Ok(done()); + } + other => other, + }; + self.rt.block_on(async { + let app = gallery.app(self).await?; + gallery + .ensure_visibility(self, app, matches!(action, GalleryAction::Refresh)) + .await?; + let unlocked = gallery.unlocked(); + match action { + GalleryAction::Unlock { .. } | GalleryAction::Lock => unreachable!(), + GalleryAction::List { + album, + offset, + limit, + } => { + let parent = album + .as_ref() + .map(|a| (a.gallery.as_str(), a.album.as_str())); + let albums = if offset == 0 { + app.drive_albums(parent, unlocked) + .await + .map_err(gallery_error)? + .into_iter() + .map(|entry| GalleryAlbum { + place: GalleryPlace { + gallery: entry.gallery.to_string(), + album: entry.source.id.to_string(), + }, + folder: GalleryFolder { + uid: NodeUid::new( + entry.source.volume.as_str().into(), + entry.source.root.as_str().into(), + ) + .to_string(), + name: entry.settings.title.unwrap_or(entry.source.label), + }, + cover: entry.cover.map(|asset| asset_uid(&asset.key)), + items: entry.direct_items, + folders: entry.child_albums, + hidden: entry.settings.hidden, + }) + .collect() + } else { + Vec::new() + }; + let (items, total) = if let Some(GalleryPlace { gallery, album }) = album { + let view = app + .outline_with_visibility( + View::DriveAlbum { gallery, album }, + false, + unlocked, + ) + .await + .map_err(gallery_error)?; + let total = view.len(); + let items = app + .outline_items(&view, offset.min(total), limit.clamp(1, 250)) + .await + .map_err(gallery_error)? + .into_iter() + .flatten() + .map(|item| PhotoItem { + uid: asset_uid(&item.key), + capture_time: item.sort_time, + thumb_path: None, + name: Some(item.name), + ratio: item.aspect_ratio, + no_thumb: false, + kind: if item.is_video { + PhotoKind::Video + } else { + PhotoKind::Photo + }, + favorite: item.favorite, + group_size: 1, + has_raw: false, + place_id: None, + }) + .collect(); + (items, total) + } else { + (Vec::new(), 0) + }; + Ok(Response::GalleryPage { + albums, + items, + total, + }) + } + GalleryAction::Folders { parent } => { + let list = app + .browse_drive_folders(parent.as_deref().map(uid).transpose()?) + .await + .map_err(gallery_error)?; + Ok(Response::GalleryFolders { + folders: list + .children + .into_iter() + .map(|folder| GalleryFolder { + uid: folder.uid.to_string(), + name: folder.name, + }) + .collect(), + }) + } + GalleryAction::Add { uid: node } => { + app.add_drive_folder(uid(&node)?) + .await + .map_err(gallery_error)?; + gallery.ensure_visibility(self, app, true).await?; + Ok(done()) + } + GalleryAction::Remove { gallery: id } => { + app.forget_drive_gallery(SourceId::new(id).map_err(gallery_error)?) + .await + .map_err(gallery_error)?; + gallery.ensure_visibility(self, app, true).await?; + Ok(done()) + } + GalleryAction::Refresh => { + for album in app.drive_albums(None, true).await.map_err(gallery_error)? { + let root = NodeUid::new( + album.source.volume.as_str().into(), + album.source.root.as_str().into(), + ); + app.scan_drive_folder(root).await.map_err(gallery_error)?; + } + gallery.ensure_visibility(self, app, true).await?; + Ok(done()) + } + GalleryAction::Cover { album, uid: node } => { + let id = SourceId::new(&album.album).map_err(gallery_error)?; + app.outline(View::DriveAlbum { + gallery: album.gallery, + album: album.album, + }) + .await + .map_err(gallery_error)?; + let mut settings = app + .catalog + .album_settings(id.clone()) + .await + .map_err(gallery_error)?; + settings.cover = Some(gallery.asset(&uid(&node)?)?); + app.catalog + .set_album_settings(id, settings) + .await + .map_err(gallery_error)?; + gallery.ensure_visibility(self, app, true).await?; + Ok(done()) + } + } + }) + } + + pub(super) fn open_gallery_video(&self, node: &str) -> CoreResult { + let gallery = self.gallery_host()?; + let uid = uid(node)?; + self.rt.block_on(async { + let app = gallery.app(self).await?; + let visibility = gallery.ensure_visibility(self, app, false).await?; + if !gallery.unlocked() { + visibility.permits(node)?; + } + let stream = app + .stream_video(&gallery.asset(&uid)?) + .await + .map_err(gallery_error)?; + gallery.video.open(stream, &gallery.cancel).await + }) + } + + pub(super) fn close_gallery_video(&self, token: &str) -> CoreResult { + self.gallery_host()?.video.close(token); + Ok(done()) + } + + pub(super) fn gallery_thumbnail(&self, node: &str) -> CoreResult { + use base64::{Engine, engine::general_purpose::STANDARD}; + let gallery = self.gallery_host()?; + let asset = gallery.asset(&uid(node)?)?; + self.rt.block_on(async { + let app = gallery.app(self).await?; + let visibility = gallery.ensure_visibility(self, app, false).await?; + if !gallery.unlocked() { + visibility.permits(node)?; + } + let data = app + .thumbnail(&asset) + .await + .map_err(gallery_error)? + .map(|bytes| STANDARD.encode(bytes)); + Ok(Response::GalleryThumbnail { data }) + }) + } +} diff --git a/crates/pdfs-fuse/src/gallery/video.rs b/crates/pdfs-fuse/src/gallery/video.rs new file mode 100644 index 0000000..35a9a4f --- /dev/null +++ b/crates/pdfs-fuse/src/gallery/video.rs @@ -0,0 +1,205 @@ +use std::{collections::VecDeque, io, sync::Arc, time::Duration}; + +use base64::{Engine, engine::general_purpose::URL_SAFE_NO_PAD}; +use http_body_util::{BodyExt, Empty, StreamBody, combinators::UnsyncBoxBody}; +use hyper::{ + Method, Request, Response, StatusCode, + body::{Bytes, Frame, Incoming}, + header, + server::conn::http1, + service::service_fn, +}; +use hyper_util::rt::TokioIo; +use pdfs_core::{CoreResult, control::Response as ControlResponse}; +use pg_app::video::VideoStream; +use pg_core::CancellationToken; +use tokio::net::TcpListener; + +type Body = UnsyncBoxBody; + +const LEASE: Duration = Duration::from_secs(4 * 60 * 60); +const MAX_STREAMS: usize = 4; +const CHUNK: u32 = 256 * 1024; + +#[derive(Default)] +pub(super) struct Server { + active: parking_lot::Mutex>, +} + +impl Server { + pub(super) fn close(&self, token: &str) { + let mut active = self.active.lock(); + if let Some(index) = active.iter().position(|(id, _)| id == token) + && let Some((_, cancel)) = active.remove(index) + { + cancel.cancel(); + } + } + + pub(super) fn close_all(&self) { + for (_, cancel) in self.active.lock().drain(..) { + cancel.cancel(); + } + } + + pub(super) async fn open( + &self, + stream: Arc, + account: &CancellationToken, + ) -> CoreResult { + let listener = TcpListener::bind((std::net::Ipv4Addr::LOCALHOST, 0)) + .await + .map_err(super::gallery_error)?; + let address = listener.local_addr().map_err(super::gallery_error)?; + let mut nonce = [0; 32]; + getrandom::fill(&mut nonce).map_err(super::gallery_error)?; + let token = URL_SAFE_NO_PAD.encode(nonce); + let path: Arc = format!("/{token}").into(); + let cancel = account.child_token(); + { + let mut active = self.active.lock(); + active.retain(|(_, cancel)| !cancel.is_cancelled()); + if active.len() >= MAX_STREAMS + && let Some((_, oldest)) = active.pop_front() + { + oldest.cancel(); + } + active.push_back((token.clone(), cancel.clone())); + } + let size = stream.length(); + tokio::spawn(async move { + let mut connections = tokio::task::JoinSet::new(); + let lifetime = tokio::time::sleep(LEASE); + tokio::pin!(lifetime); + loop { + tokio::select! { + biased; + _ = cancel.cancelled() => break, + _ = &mut lifetime => break, + _ = connections.join_next(), if !connections.is_empty() => {}, + incoming = listener.accept(), if connections.len() < 8 => { + let Ok((socket, _)) = incoming else { break }; + let stream = stream.clone(); + let path = path.clone(); + connections.spawn(async move { + let service = service_fn(move |request| reply(request, stream.clone(), path.clone())); + let _ = http1::Builder::new() + .timer(hyper_util::rt::TokioTimer::new()) + .header_read_timeout(Duration::from_secs(10)) + .keep_alive(false) + .serve_connection(TokioIo::new(socket), service).await; + }); + } + } + } + stream.stop(); + cancel.cancel(); + connections.abort_all(); + }); + Ok(ControlResponse::GalleryVideo { + url: format!("http://{address}/{token}"), + token, + size, + }) + } +} + +fn range(value: Option<&str>, size: u64) -> Option<(u64, u64)> { + let Some(value) = value else { + return Some((0, size)); + }; + let (first, last) = value.strip_prefix("bytes=")?.split_once('-')?; + if first.is_empty() { + let suffix = last.parse::().ok()?.min(size); + return (suffix > 0).then_some((size - suffix, size)); + } + let start = first.parse::().ok()?; + let end = if last.is_empty() { + size + } else { + last.parse::().ok()?.saturating_add(1).min(size) + }; + (start < end).then_some((start, end)) +} + +fn empty() -> Body { + Empty::new().map_err(|never| match never {}).boxed_unsync() +} + +async fn reply( + request: Request, + stream: Arc, + path: Arc, +) -> Result, hyper::http::Error> { + let response = Response::builder().header(header::CACHE_CONTROL, "no-store"); + if request + .uri() + .path_and_query() + .is_none_or(|actual| actual.as_str() != path.as_ref()) + { + return response.status(StatusCode::NOT_FOUND).body(empty()); + } + if !matches!(*request.method(), Method::HEAD | Method::GET) { + return response + .status(StatusCode::METHOD_NOT_ALLOWED) + .body(empty()); + } + let size = stream.length(); + let requested = request.headers().get(header::RANGE); + let parsed = match requested { + Some(value) => value + .to_str() + .ok() + .and_then(|value| range(Some(value), size)), + None => range(None, size), + }; + let Some((start, end)) = parsed else { + return response + .status(StatusCode::RANGE_NOT_SATISFIABLE) + .header(header::CONTENT_RANGE, format!("bytes */{size}")) + .body(empty()); + }; + let response = response + .header(header::ACCEPT_RANGES, "bytes") + .header(header::CONTENT_LENGTH, end - start) + .header(header::CONTENT_TYPE, "application/octet-stream"); + let response = if requested.is_some() { + response.status(StatusCode::PARTIAL_CONTENT).header( + header::CONTENT_RANGE, + format!("bytes {start}-{}/{size}", end - 1), + ) + } else { + response + }; + if request.method() == Method::HEAD { + return response.body(empty()); + } + let body = futures::stream::try_unfold((stream, start), move |(stream, at)| async move { + if at == end { + return Ok(None); + } + let read = (end - at).min(u64::from(CHUNK)) as u32; + let bytes = stream.read(at, read).await.map_err(io::Error::other)?; + if bytes.is_empty() { + return Err(io::Error::from(io::ErrorKind::UnexpectedEof)); + } + let next = at + bytes.len() as u64; + Ok(Some((Frame::data(Bytes::from(bytes)), (stream, next)))) + }); + response.body(BodyExt::boxed_unsync(StreamBody::new(body))) +} + +#[cfg(test)] +mod tests { + use super::range; + + #[test] + fn resolves_seek_ranges_and_rejects_invalid_ranges() { + assert_eq!(range(None, 10), Some((0, 10))); + assert_eq!(range(Some("bytes=3-5"), 10), Some((3, 6))); + assert_eq!(range(Some("bytes=9-"), 10), Some((9, 10))); + assert_eq!(range(Some("bytes=-3"), 10), Some((7, 10))); + assert_eq!(range(Some("bytes=10-"), 10), None); + assert_eq!(range(Some("bytes=0-1,3-4"), 10), None); + } +} diff --git a/crates/pdfs-fuse/src/lib.rs b/crates/pdfs-fuse/src/lib.rs index ee73dd4..5418b08 100644 --- a/crates/pdfs-fuse/src/lib.rs +++ b/crates/pdfs-fuse/src/lib.rs @@ -91,6 +91,7 @@ mod drive; use drive::{DriveApi, RevisionRead}; mod events; mod filesystem; +mod gallery; mod keeper; mod link; pub use filesystem::ProtonFs; @@ -499,6 +500,7 @@ struct Core { /// The concrete client, for what [`DriveApi`] does not cover: sharing, /// Photos, devices, invitations and public links. client: ProtonDriveClient, + gallery: Option>, rt: tokio::runtime::Handle, /// The daemon's My Files root. Forked on-demand sessions retain this value /// so ownership checks never mistake their own mount root for account scope. diff --git a/crates/pdfs-fuse/src/link.rs b/crates/pdfs-fuse/src/link.rs index 517d175..7b65347 100644 --- a/crates/pdfs-fuse/src/link.rs +++ b/crates/pdfs-fuse/src/link.rs @@ -232,6 +232,9 @@ impl Core { /// Unless the keyring holds a newer session than the refused one: then /// the mount ends, for the daemon to mount again on that one. pub(crate) fn mark_session_expired(&self, what: &str, error: &dyn std::fmt::Display) { + if let Some(gallery) = &self.gallery { + gallery.cancel(); + } if self.link.resume_stored.load(Ordering::Relaxed) { return self.mark_offline(what, error); } diff --git a/crates/pdfs-fuse/src/mount.rs b/crates/pdfs-fuse/src/mount.rs index 1051512..a989f02 100644 --- a/crates/pdfs-fuse/src/mount.rs +++ b/crates/pdfs-fuse/src/mount.rs @@ -310,6 +310,7 @@ enum Start { pub struct MountOptions { /// Proton account the session belongs to, for display and per-user paths. pub username: String, + pub gallery_session: Option, /// What the background conflict sweep may do. See `docs/BUGS.md` B71. pub sweep_mode: SweepMode, /// Upload and download caps in bytes per second (`0` = no cap). @@ -456,6 +457,7 @@ pub(crate) fn mount_with( ) -> std::io::Result { let MountOptions { username, + gallery_session, sweep_mode, upload_limit, download_limit, @@ -480,9 +482,13 @@ pub(crate) fn mount_with( let (sync_tx, sync_rx) = std::sync::mpsc::channel::(); let paused_until = pause::load_paused_until(&db); + let gallery_dir = control_socket.with_file_name("gallery-catalog"); + let gallery = + gallery_session.map(|session| Arc::new(super::gallery::Gallery::new(gallery_dir, session))); let core = Core { drive, client, + gallery, rt: rt.clone(), maintenance: Arc::new(Mutex::new(Default::default())), primary_root_uid: root.uid.clone(), @@ -636,6 +642,9 @@ pub(crate) fn mount_with( // Keep the launcher prompt's "This computer" index fresh. Its own thread: // the walk is I/O-heavy and must never sit in front of a FUSE callback. if matches!(host, Host::Daemon) { + if let Some(gallery) = &core.gallery { + rt.spawn(gallery.clone().poll(core.clone())); + } let db = core.db.clone(); let indexing = core.indexing.clone(); let transfers = core.transfers.clone(); @@ -954,6 +963,9 @@ fn keep_or_abandon( /// Signal every worker to stop, then join them up to [`WORKER_JOIN_DEADLINE`]. fn halt_workers(core: &Core, control_socket: &Path, workers: Vec>) { core.shutdown.stop(); + if let Some(gallery) = &core.gallery { + gallery.cancel(); + } core.wake_drain(); let _ = core.sync_tx.send(sync::SyncMsg::Stop); // Connect while the socket still exists — that is the whole point of the diff --git a/crates/pdfs-fuse/src/photos.rs b/crates/pdfs-fuse/src/photos.rs index 9d055d3..b8d1e16 100644 --- a/crates/pdfs-fuse/src/photos.rs +++ b/crates/pdfs-fuse/src/photos.rs @@ -1175,6 +1175,7 @@ impl Core { .unwrap_or_default() } + #[allow(clippy::too_many_arguments)] pub(crate) fn photos_timeline( &self, offset: usize, @@ -1183,6 +1184,7 @@ impl Core { range: Option<(i64, i64)>, favorites: bool, not_in_album: bool, + excluded: &str, ) -> CoreResult>> { let count = self.db.photos_count().map_err(CoreError::from)?; if count == 0 { @@ -1208,7 +1210,15 @@ impl Core { let page = self .db - .photos_page(offset, limit, kind, range, favorites, not_in_album) + .photos_page_visible( + offset, + limit, + kind, + range, + favorites, + not_in_album, + excluded, + ) .map_err(CoreError::from)?; Ok(Some(page.into_iter().map(|p| self.photo_item(p)).collect())) } @@ -1365,8 +1375,11 @@ impl Core { /// The towns the photos were taken in, as wire items. A town the bundled /// table no longer knows (the stored id came from an older table) is left /// out rather than shown without a name. - pub(crate) fn photo_places(&self) -> CoreResult> { - let places = self.db.photo_places().map_err(CoreError::from)?; + pub(crate) fn photo_places(&self, excluded: &str) -> CoreResult> { + let places = self + .db + .photo_places_visible(excluded) + .map_err(CoreError::from)?; Ok(places .into_iter() .filter_map(|place| { @@ -1390,10 +1403,11 @@ impl Core { id: u32, offset: usize, limit: usize, + excluded: &str, ) -> CoreResult> { let photos = self .db - .photos_at_place(id, offset, limit) + .photos_at_place_visible(id, offset, limit, excluded) .map_err(CoreError::from)?; Ok(photos.into_iter().map(|p| self.photo_item(p)).collect()) } @@ -1417,13 +1431,17 @@ impl Core { /// Photos taken on today's date in earlier years, as wire items. Served /// from the stored timeline only: the strip is a nicety, not worth a wait /// on the network, and the timeline's own load keeps that store fresh. - pub(crate) fn photos_on_this_day(&self, limit: usize) -> CoreResult> { + pub(crate) fn photos_on_this_day( + &self, + limit: usize, + excluded: &str, + ) -> CoreResult> { let now = std::time::SystemTime::now() .duration_since(std::time::UNIX_EPOCH) .map_or(0, |d| d.as_secs() as i64); let photos = self .db - .photos_on_this_day(now, limit) + .photos_on_this_day_visible(now, limit, excluded) .map_err(CoreError::from)?; Ok(photos.into_iter().map(|p| self.photo_item(p)).collect()) } diff --git a/crates/pdfs-fuse/src/sim/daemon.rs b/crates/pdfs-fuse/src/sim/daemon.rs index 3a1cd9c..c6579e6 100644 --- a/crates/pdfs-fuse/src/sim/daemon.rs +++ b/crates/pdfs-fuse/src/sim/daemon.rs @@ -89,6 +89,7 @@ impl Daemon { db, MountOptions { username: "sim".into(), + gallery_session: None, sweep_mode: AppConfig::default().resolved_conflict_sweep(), upload_limit: 0, download_limit: 0, diff --git a/crates/pdfs-gui/Cargo.toml b/crates/pdfs-gui/Cargo.toml index d876395..ddee5ac 100644 --- a/crates/pdfs-gui/Cargo.toml +++ b/crates/pdfs-gui/Cargo.toml @@ -22,6 +22,8 @@ name = "pdfs-prompt" path = "src/prompt.rs" [dependencies] +pg-core.workspace = true +base64.workspace = true pdfs-core.workspace = true tracing.workspace = true tracing-subscriber.workspace = true diff --git a/crates/pdfs-gui/resources/style.css b/crates/pdfs-gui/resources/style.css index 0a242f9..ddbf362 100644 --- a/crates/pdfs-gui/resources/style.css +++ b/crates/pdfs-gui/resources/style.css @@ -123,6 +123,7 @@ scale.browser-status-meter trough { min-width: 140px; min-height: 6px; } .album-cover { border-radius: 16px; background: alpha(currentColor, 0.06); box-shadow: 0 4px 16px rgba(0, 0, 0, 0.32); transition: box-shadow 180ms ease; } .album-card:hover .album-cover { box-shadow: 0 10px 26px rgba(0, 0, 0, 0.5); } .album-card:hover .photo-thumb { transform: scale(1.05); } +listview.drive-gallery-rows > row { padding: 0; } .view-switch button, .view-switch toggle { padding-left: 12px; padding-right: 12px; } /* Shared with Me: what a share lets me do, as a tinted pill beside the name. */ diff --git a/crates/pdfs-gui/src/app/events.rs b/crates/pdfs-gui/src/app/events.rs index 65e33f1..6cb1219 100644 --- a/crates/pdfs-gui/src/app/events.rs +++ b/crates/pdfs-gui/src/app/events.rs @@ -133,6 +133,32 @@ fn follow_changes(ui: &Rc, state: &FeedState, topics: &[Topic]) { refresh_file_thumbnails(ui); } let page = ui.stack.visible_child_name(); + if changed(Topic::GalleryVisibilitySynced) + && let Some(browser) = ui.drive_galleries.borrow().upgrade() + { + browser.refresh_visibility(); + } + if changed(Topic::GalleryVisibility) || changed(Topic::GalleryVisibilitySynced) { + for window in gtk4::Window::list_toplevels() { + if let Ok(window) = window.downcast::() + && window.has_css_class("photo-viewer-window") + { + window.close(); + } + } + ui.gallery.photo_tex.borrow_mut().clear(); + ui.gallery.photo_tex_order.borrow_mut().clear(); + ui.gallery.model.remove_all(); + ui.gallery.groups.remove_all(); + ui.gallery.timeline_stale.set(true); + if page.as_deref() == Some("gallery") { + match ui.gallery.content.visible_child_name().as_deref() { + Some("albums") => load_albums(ui), + Some("places") => load_places(ui), + _ => load_gallery(ui, false), + } + } + } // A timeline out of sight is read again when the user comes back to it; // one on screen is left alone (below). if changed(Topic::Photos) && (page.as_deref() != Some("gallery") || !photo_grid_shown(ui)) { diff --git a/crates/pdfs-gui/src/app/main.rs b/crates/pdfs-gui/src/app/main.rs index d3233a3..55d237f 100644 --- a/crates/pdfs-gui/src/app/main.rs +++ b/crates/pdfs-gui/src/app/main.rs @@ -160,6 +160,7 @@ struct Ui { pub(crate) details: DetailsState, pub(crate) trash: TrashState, pub(crate) gallery: GalleryState, + drive_galleries: RefCell>, pub(crate) shared: SharedState, pub(crate) shared_by_me: SharedByMeState, pub(crate) devices: DevicesState, @@ -459,6 +460,7 @@ fn build_window(app: &adw::Application) { nav: split.clone(), narrow: Cell::new(false), file_thumbs: FileThumbnailState::new(), + drive_galleries: RefCell::default(), login: login_widgets, status: StatusState { status_inflight: Cell::new(false), @@ -760,6 +762,10 @@ fn build_window(app: &adw::Application) { &gallery_widgets.scroll, &gallery_widgets.square_action, ); + gallery_widgets.drive_galleries.connect_clicked({ + let ui = ui.clone(); + move |_| pages::drive_galleries::open(&ui) + }); wire_gallery_empty( &ui, &gallery_widgets.empty_upload, diff --git a/crates/pdfs-gui/src/app/pages/drive_galleries.rs b/crates/pdfs-gui/src/app/pages/drive_galleries.rs new file mode 100644 index 0000000..00fa925 --- /dev/null +++ b/crates/pdfs-gui/src/app/pages/drive_galleries.rs @@ -0,0 +1,822 @@ +use crate::*; +use base64::{Engine, engine::general_purpose::STANDARD}; +use pdfs_core::control::{GalleryAction, GalleryAlbum, GalleryFolder, GalleryPlace}; + +const PAGE: usize = 150; + +#[derive(Clone)] +enum Row { + Albums(Vec, i32), + Heading(String), + Media(Vec<(PhotoItem, (i32, i32))>), + Folder(GalleryFolder), +} + +struct Place { + album: GalleryAlbum, + parent_offset: f64, +} + +pub(crate) struct Browser { + ui: Rc, + window: glib::WeakRef, + rows: gio::ListStore, + scroll: gtk4::ScrolledWindow, + title: adw::WindowTitle, + status: gtk4::Label, + choose: gtk4::Button, + trail: RefCell>, + chooser: RefCell>>, + cover: RefCell>, + albums: RefCell>, + items: RefCell>, + width: Cell, + generation: Cell, + total: Cell, + loading: Cell, + unlocked: Cell, + thumbnail_slots: tokio::sync::Semaphore, +} + +impl Browser { + pub(crate) fn close(&self) { + if let Some(window) = self.window.upgrade() { + window.close(); + } + } + + pub(crate) fn refresh_visibility(self: &Rc) { + if self.chooser.borrow().is_none() { + self.trail.borrow_mut().clear(); + self.cover.borrow_mut().take(); + self.load(0, 0.0); + } + } + + fn current(&self) -> Option { + self.trail.borrow().last().map(|place| place.album.clone()) + } + + fn next_request(&self) -> u64 { + let next = self.generation.get().wrapping_add(1); + self.generation.set(next); + next + } + + fn load(self: &Rc, offset: usize, restore: f64) { + self.choose.set_visible(false); + self.loading.set(true); + let generation = if offset == 0 { + self.total.set(0); + self.albums.borrow_mut().clear(); + self.items.borrow_mut().clear(); + self.rows.remove_all(); + self.next_request() + } else { + self.generation.get() + }; + let album = self.current(); + self.title.set_title( + album + .as_ref() + .map_or_else(|| gettext("Drive Galleries"), |a| a.folder.name.clone()) + .as_str(), + ); + self.status.set_label(&gettext("Loading…")); + let rx = spawn_request( + self.ui.dirs.control_socket(), + Request::DriveGallery { + action: GalleryAction::List { + album: album.map(|a| a.place), + offset, + limit: PAGE, + }, + }, + ); + let browser = self.clone(); + glib::spawn_future_local(async move { + let result = rx.recv().await; + if browser.generation.get() != generation { + return; + } + browser.loading.set(false); + match result { + Ok(Ok(Response::GalleryPage { + albums, + items, + total, + })) => { + if offset == 0 { + *browser.albums.borrow_mut() = albums; + } + browser.items.borrow_mut().extend(items); + browser.total.set(total); + let empty = total == 0 && browser.albums.borrow().is_empty(); + let message = if browser.cover.borrow().is_some() { + gettext("Choose a photo or video as the album cover.") + } else if empty { + gettext("This gallery is empty.") + } else { + String::new() + }; + browser.status.set_label(&message); + browser.rebuild(); + if restore > 0.0 { + let scroll = browser.scroll.clone(); + glib::idle_add_local_once(move || scroll.vadjustment().set_value(restore)); + } + } + Ok(Ok(Response::Error { message, .. })) => browser.status.set_label(&message), + _ => browser + .status + .set_label(&gettext("Couldn't reach Proton Drive.")), + } + }); + } + + fn browse_folders(self: &Rc) { + let Some(trail) = self.chooser.borrow().clone() else { + return; + }; + let generation = self.next_request(); + let parent = trail.last().map(|folder| folder.uid.clone()); + self.choose.set_visible(parent.is_some()); + self.title.set_title(&gettext("Choose a Drive Folder")); + self.rows.remove_all(); + let rx = spawn_request( + self.ui.dirs.control_socket(), + Request::DriveGallery { + action: GalleryAction::Folders { parent }, + }, + ); + let browser = self.clone(); + glib::spawn_future_local(async move { + let result = rx.recv().await; + if browser.generation.get() != generation { + return; + } + match result { + Ok(Ok(Response::GalleryFolders { folders })) => { + browser + .status + .set_label(&gettext("Open a folder, then choose Add This Folder.")); + for folder in folders { + browser + .rows + .append(&BoxedAnyObject::new(Row::Folder(folder))); + } + } + Ok(Ok(Response::Error { message, .. })) => browser.status.set_label(&message), + _ => browser + .status + .set_label(&gettext("Couldn't reach Proton Drive.")), + } + }); + } + + fn change(self: &Rc, action: GalleryAction) { + let unlock = matches!(action, GalleryAction::Unlock { .. }); + let lock = matches!(action, GalleryAction::Lock); + if lock { + self.trail.borrow_mut().clear(); + self.cover.borrow_mut().take(); + self.items.borrow_mut().clear(); + self.rows.remove_all(); + } + let generation = self.next_request(); + self.status.set_label(&gettext("Updating gallery…")); + let rx = spawn_request( + self.ui.dirs.control_socket(), + Request::DriveGallery { action }, + ); + let browser = self.clone(); + glib::spawn_future_local(async move { + let result = rx.recv().await; + if browser.generation.get() != generation { + if unlock && matches!(result, Ok(Ok(Response::Ok { .. }))) { + browser.lock(); + } + return; + } + match result { + Ok(Ok(Response::Ok { .. })) => { + if unlock || lock { + browser.unlocked.set(unlock); + } + browser.chooser.borrow_mut().take(); + browser.load(0, 0.0); + } + Ok(Ok(Response::Error { message, .. })) => browser.status.set_label(&message), + _ => browser + .status + .set_label(&gettext("Couldn't reach Proton Drive.")), + } + }); + } + + fn lock(&self) { + let _ = spawn_request( + self.ui.dirs.control_socket(), + Request::DriveGallery { + action: GalleryAction::Lock, + }, + ); + } + + fn prompt_unlock(self: &Rc) { + let Some(parent) = self.window.upgrade() else { + return; + }; + let dialog = adw::AlertDialog::builder() + .heading(gettext("Unlock Hidden Albums")) + .body(gettext("Enter your Gallery passphrase. On first use, choose one with at least 12 characters.")) + .build(); + let password = gtk4::PasswordEntry::builder().show_peek_icon(true).build(); + dialog.set_extra_child(Some(&password)); + dialog.add_response("cancel", &gettext("Cancel")); + dialog.add_response("unlock", &gettext("Unlock")); + dialog.set_response_appearance("unlock", adw::ResponseAppearance::Suggested); + dialog.set_default_response(Some("unlock")); + let browser = Rc::downgrade(self); + dialog.connect_response(None, move |_, response| { + let passphrase = password.text().to_string(); + password.set_text(""); + if response == "unlock" + && let Some(browser) = browser.upgrade() + { + browser.change(GalleryAction::Unlock { passphrase }); + } + }); + dialog.present(Some(&parent)); + } + + fn back(self: &Rc) { + let choosing = self.chooser.borrow().is_some(); + if choosing { + let went_up = self + .chooser + .borrow_mut() + .as_mut() + .and_then(Vec::pop) + .is_some(); + if went_up { + self.browse_folders(); + } else { + self.chooser.borrow_mut().take(); + self.load(0, 0.0); + } + return; + } + let at_target = self + .cover + .borrow() + .as_ref() + .zip(self.current()) + .is_some_and(|(target, current)| target.album == current.place.album); + if at_target { + self.cover.borrow_mut().take(); + self.status.set_label(""); + return; + } + let previous = self.trail.borrow_mut().pop(); + if let Some(previous) = previous { + self.load(0, previous.parent_offset); + } else if let Some(window) = self.window.upgrade() { + window.close(); + } + } + + fn rebuild(&self) { + if self.chooser.borrow().is_some() { + return; + } + let width = (self.width.get() - 24).max(240); + let columns = ((width + 8) / 216).max(1); + let card = (width - 8 * (columns - 1)) / columns; + let mut rows = Vec::new(); + for albums in self.albums.borrow().chunks(columns as usize) { + rows.push(BoxedAnyObject::new(Row::Albums(albums.to_vec(), card))); + } + let items = self.items.borrow(); + let period = |item: &PhotoItem| { + glib::DateTime::from_unix_local(item.capture_time) + .ok() + .and_then(|date| date.format("%B %Y").ok()) + .map(|value| value.to_string()) + .unwrap_or_else(|| gettext("Unknown date")) + }; + for section in items.chunk_by(|a, b| period(a) == period(b)) { + rows.push(BoxedAnyObject::new(Row::Heading(period(§ion[0])))); + let ratios: Vec<_> = section + .iter() + .map(|item| item.ratio.unwrap_or(1.0)) + .collect(); + let mut items = section.iter(); + for sizes in super::photos::plan_justified(&ratios, width, 180) { + rows.push(BoxedAnyObject::new(Row::Media( + items.by_ref().cloned().zip(sizes).collect(), + ))); + } + } + self.rows.splice(0, self.rows.n_items(), &rows); + } + + fn preview(self: &Rc, item: PhotoItem) { + let video = item.kind == PhotoKind::Video; + let request = if video { + Request::OpenGalleryVideo { uid: item.uid } + } else { + Request::OpenGalleryImage { uid: item.uid } + }; + let reply = spawn_request(self.ui.dirs.control_socket(), request); + let browser = self.clone(); + let generation = self.generation.get(); + glib::spawn_future_local(async move { + let result = reply.recv().await; + let close = |token| { + let _ = spawn_request( + browser.ui.dirs.control_socket(), + Request::CloseGalleryVideo { token }, + ); + }; + let parent = browser + .window + .upgrade() + .filter(|_| generation == browser.generation.get()); + let Some(parent) = parent else { + if let Ok(Ok(Response::GalleryVideo { token, .. })) = result { + close(token); + } + return; + }; + let preview = gtk4::Window::builder() + .transient_for(&parent) + .destroy_with_parent(true) + .title(item.name.unwrap_or_else(|| gettext("Preview"))) + .default_width(850) + .default_height(600) + .build(); + preview.add_css_class("photo-viewer-window"); + match result { + Ok(Ok(Response::GalleryVideo { url, token, .. })) => { + let player = gtk4::Video::builder().autoplay(true).build(); + player.set_file(Some(&gio::File::for_uri(&url))); + preview.set_child(Some(&player)); + let socket = browser.ui.dirs.control_socket(); + preview.connect_close_request(move |_| { + player.set_media_stream(gtk4::MediaStream::NONE); + let _ = spawn_request( + socket.clone(), + Request::CloseGalleryVideo { + token: token.clone(), + }, + ); + glib::Propagation::Proceed + }); + } + Ok(Ok(Response::FilePath { path })) => { + let picture = gtk4::Picture::for_filename(path); + preview.set_child(Some(&picture)); + } + Ok(Ok(Response::Error { message, .. })) => { + browser.status.set_label(&message); + return; + } + _ => { + browser + .status + .set_label(&gettext("Couldn't open the file.")); + return; + } + } + preview.present(); + }); + } +} + +pub(crate) fn open(ui: &Rc) { + if let Some(browser) = ui.drive_galleries.borrow().upgrade() + && let Some(window) = browser.window.upgrade() + { + window.present(); + return; + } + let Some(parent) = ui_window(ui) else { return }; + let window = gtk4::Window::builder() + .transient_for(&parent) + .default_width(1020) + .default_height(760) + .build(); + let title = adw::WindowTitle::new(&gettext("Drive Galleries"), ""); + let header = adw::HeaderBar::builder().title_widget(&title).build(); + let back = gtk4::Button::from_icon_name("go-previous-symbolic"); + back.set_tooltip_text(Some(&gettext("Back"))); + header.pack_start(&back); + let add = gtk4::Button::with_label(&gettext("Add Gallery")); + let choose = gtk4::Button::with_label(&gettext("Add This Folder")); + choose.set_visible(false); + header.pack_end(&add); + header.pack_end(&choose); + let more = gtk4::Button::from_icon_name("view-more-symbolic"); + more.set_tooltip_text(Some(&gettext("Gallery Options"))); + header.pack_end(&more); + let rows = gio::ListStore::new::(); + let factory = gtk4::SignalListItemFactory::new(); + let list = gtk4::ListView::builder() + .model(>k4::NoSelection::new(Some(rows.clone()))) + .factory(&factory) + .build(); + list.add_css_class("drive-gallery-rows"); + let scroll = gtk4::ScrolledWindow::builder() + .vexpand(true) + .hscrollbar_policy(gtk4::PolicyType::External) + .child(&list) + .build(); + let status = gtk4::Label::new(None); + status.set_wrap(true); + let content = gtk4::Box::new(gtk4::Orientation::Vertical, 0); + content.append(&header); + content.append(&status); + content.append(&scroll); + window.set_child(Some(&content)); + let browser = Rc::new(Browser { + ui: ui.clone(), + window: window.downgrade(), + rows, + scroll: scroll.clone(), + title, + status, + choose: choose.clone(), + trail: RefCell::new(Vec::new()), + chooser: RefCell::new(None), + cover: RefCell::new(None), + albums: RefCell::new(Vec::new()), + items: RefCell::new(Vec::new()), + width: Cell::new(0), + generation: Cell::new(0), + total: Cell::new(0), + loading: Cell::new(false), + unlocked: Cell::new(false), + thumbnail_slots: tokio::sync::Semaphore::new(8), + }); + *ui.drive_galleries.borrow_mut() = Rc::downgrade(&browser); + window.connect_close_request({ + let browser = browser.clone(); + move |_| { + *browser.ui.drive_galleries.borrow_mut() = std::rc::Weak::new(); + browser.next_request(); + if browser.unlocked.get() { + browser.lock(); + } + glib::Propagation::Proceed + } + }); + let weak = Rc::downgrade(&browser); + factory.connect_bind(move |_, item| { + let Some(browser) = weak.upgrade() else { + return; + }; + let Some(list_item) = item.downcast_ref::() else { + return; + }; + let Some(data) = list_item.item().and_downcast::() else { + return; + }; + let row = data.borrow::(); + let line = gtk4::Box::new(gtk4::Orientation::Horizontal, 8); + line.set_margin_start(12); + line.set_margin_end(12); + line.set_margin_bottom(8); + match &*row { + Row::Heading(label) => { + let label = gtk4::Label::new(Some(label)); + label.add_css_class("heading"); + line.append(&label); + } + Row::Folder(folder) => { + let button = gtk4::Button::with_label(&folder.name); + button.set_hexpand(true); + button.connect_clicked({ + let weak = Rc::downgrade(&browser); + let folder = folder.clone(); + move |_| { + if let Some(browser) = weak.upgrade() { + if let Some(trail) = browser.chooser.borrow_mut().as_mut() { + trail.push(folder.clone()); + } + browser.browse_folders(); + } + } + }); + line.append(&button); + } + Row::Albums(albums, width) => { + for album in albums { + let items = ngettext_f("{n} item", "{n} items", album.items, &[]); + let mut detail = if album.folders > 0 { + let folders = ngettext_f("{n} folder", "{n} folders", album.folders, &[]); + format!("{items} · {folders}") + } else { + items + }; + if album.hidden { + detail = format!("{detail} · {}", gettext("Hidden")); + } + let button = tile( + &browser, + &album.folder.name, + album.cover.as_deref(), + *width, + 130, + Some(&detail), + false, + ); + button.connect_clicked({ + let weak = Rc::downgrade(&browser); + let album = album.clone(); + move |_| { + if let Some(browser) = weak.upgrade() { + browser.trail.borrow_mut().push(Place { + album: album.clone(), + parent_offset: browser.scroll.vadjustment().value(), + }); + browser.load(0, 0.0); + } + } + }); + line.append(&button); + } + } + Row::Media(items) => { + line.set_spacing(super::photos::TILE_GAP); + for (item, (width, height)) in items { + let button = tile( + &browser, + item.name.as_deref().unwrap_or(""), + Some(&item.uid), + *width, + *height, + None, + item.kind == PhotoKind::Video, + ); + button.connect_clicked({ + let weak = Rc::downgrade(&browser); + let item = item.clone(); + move |_| { + if let Some(browser) = weak.upgrade() { + let cover = browser.cover.borrow_mut().take(); + if let Some(album) = cover { + browser.change(GalleryAction::Cover { + album, + uid: item.uid.clone(), + }); + } else { + browser.preview(item.clone()); + } + } + } + }); + line.append(&button); + } + } + } + list_item.set_child(Some(&line)); + }); + factory.connect_unbind(|_, item| { + if let Some(item) = item.downcast_ref::() { + item.set_child(gtk4::Widget::NONE); + } + }); + back.connect_clicked({ + let weak = Rc::downgrade(&browser); + move |_| { + if let Some(browser) = weak.upgrade() { + browser.back(); + } + } + }); + add.connect_clicked({ + let weak = Rc::downgrade(&browser); + let choose = choose.clone(); + move |_| { + if let Some(browser) = weak.upgrade() { + choose.set_visible(true); + *browser.chooser.borrow_mut() = Some(Vec::new()); + browser.browse_folders(); + } + } + }); + choose.connect_clicked({ + let weak = Rc::downgrade(&browser); + move |button| { + if let Some(browser) = weak.upgrade() { + let uid = browser + .chooser + .borrow() + .as_ref() + .and_then(|trail| trail.last()) + .map(|f| f.uid.clone()); + if let Some(uid) = uid { + button.set_visible(false); + browser.change(GalleryAction::Add { uid }); + } + } + } + }); + more.connect_clicked({ + let weak = Rc::downgrade(&browser); + move |button| { + if let Some(browser) = weak.upgrade() { + let mut menu = ActionMenu::new(); + menu.item(&gettext("Refresh"), { + let browser = browser.clone(); + move || browser.change(GalleryAction::Refresh) + }); + if browser.unlocked.get() { + menu.item(&gettext("Lock Hidden Albums"), { + let browser = browser.clone(); + move || browser.change(GalleryAction::Lock) + }); + } else { + menu.item(&gettext("Unlock Hidden Albums"), { + let browser = browser.clone(); + move || browser.prompt_unlock() + }); + } + if let Some(album) = browser.current() { + menu.item(&gettext("Choose Cover"), { + let browser = browser.clone(); + let place = album.place.clone(); + move || { + *browser.cover.borrow_mut() = Some(place.clone()); + browser.status.set_label(&gettext( + "Choose a photo or video from this album or a subfolder.", + )); + } + }); + menu.item(&gettext("Public Link"), { + let browser = browser.clone(); + let folder = album.folder.clone(); + move || { + open_share_dialog_over( + &browser.ui, + &DirEntry { + uid: folder.uid.clone(), + name: folder.name.clone(), + is_dir: true, + ..DirEntry::default() + }, + browser.window.upgrade(), + ) + } + }); + if browser.trail.borrow().len() == 1 { + menu.item(&gettext("Remove Gallery"), { + let browser = browser.clone(); + move || { + browser.trail.borrow_mut().clear(); + browser.change(GalleryAction::Remove { + gallery: album.place.gallery.clone(), + }); + } + }); + } + } + menu.popup_at( + button, + f64::from(button.width()) / 2.0, + f64::from(button.height()), + ); + } + } + }); + scroll.vadjustment().connect_value_changed({ + let weak = Rc::downgrade(&browser); + move |adj| { + if let Some(browser) = weak.upgrade() { + let offset = browser.items.borrow().len(); + if browser.chooser.borrow().is_none() + && !browser.loading.get() + && offset < browser.total.get() + && adj.value() + adj.page_size() + 800.0 >= adj.upper() + { + browser.load(offset, 0.0); + } + } + } + }); + scroll.add_tick_callback({ + let weak = Rc::downgrade(&browser); + move |scroll, _| { + let Some(browser) = weak.upgrade() else { + return glib::ControlFlow::Break; + }; + let width = scroll.width(); + if width > 0 && browser.width.replace(width) != width { + browser.rebuild(); + } + glib::ControlFlow::Continue + } + }); + window.present(); + browser.load(0, 0.0); +} + +fn tile( + browser: &Rc, + title: &str, + uid: Option<&str>, + width: i32, + height: i32, + detail: Option<&str>, + video: bool, +) -> gtk4::Button { + let picture = gtk4::Picture::builder() + .content_fit(gtk4::ContentFit::Cover) + .can_shrink(true) + .width_request(if detail.is_some() { + (width - 24).max(1) + } else { + width + }) + .height_request(height) + .build(); + let label = gtk4::Label::new(Some(title)); + label.set_ellipsize(gtk4::pango::EllipsizeMode::End); + label.set_max_width_chars((width / 9).max(1)); + let box_ = gtk4::Box::new(gtk4::Orientation::Vertical, 4); + let cover = gtk4::Overlay::new(); + cover.set_child(Some(&picture)); + let icon = gtk4::Image::from_icon_name(if detail.is_some() { + "folder-symbolic" + } else { + "image-x-generic-symbolic" + }); + icon.set_halign(gtk4::Align::Center); + icon.set_valign(gtk4::Align::Center); + icon.set_pixel_size(32); + icon.add_css_class("dim-label"); + cover.add_overlay(&icon); + cover.set_overflow(gtk4::Overflow::Hidden); + let button = gtk4::Button::builder().tooltip_text(title).build(); + if let Some(detail) = detail { + box_.append(&cover); + box_.append(&label); + let caption = gtk4::Label::new(Some(detail)); + caption.add_css_class("dim-label"); + caption.add_css_class("caption"); + caption.set_ellipsize(gtk4::pango::EllipsizeMode::End); + box_.append(&caption); + button.set_width_request(width); + button.set_child(Some(&box_)); + } else { + button.add_css_class("photo-tile"); + cover.add_css_class("photo-placeholder"); + label.add_css_class("photo-caption"); + label.set_valign(gtk4::Align::End); + cover.add_overlay(&label); + if video { + let play = gtk4::Image::from_icon_name("media-playback-start-symbolic"); + play.add_css_class("photo-video-badge"); + play.add_css_class("photo-video-badge-small"); + play.set_halign(gtk4::Align::End); + play.set_valign(gtk4::Align::Start); + play.set_margin_end(8); + play.set_margin_top(8); + cover.add_overlay(&play); + } + button.set_child(Some(&cover)); + } + if let Some(uid) = uid { + let browser = browser.clone(); + let generation = browser.generation.get(); + let uid = uid.to_owned(); + let picture = picture.downgrade(); + let icon = icon.downgrade(); + glib::spawn_future_local(async move { + let Ok(_permit) = browser.thumbnail_slots.acquire().await else { + return; + }; + if picture.upgrade().is_none() || generation != browser.generation.get() { + return; + } + let request = spawn_request( + browser.ui.dirs.control_socket(), + Request::GalleryThumbnail { uid }, + ); + let response = request.recv().await; + if generation == browser.generation.get() + && let (Some(picture), Ok(Ok(Response::GalleryThumbnail { data: Some(data) }))) = + (picture.upgrade(), response) + && let Ok(bytes) = STANDARD.decode(data) + && let Ok(texture) = gtk4::gdk::Texture::from_bytes(&glib::Bytes::from_owned(bytes)) + { + picture.set_paintable(Some(&texture)); + if let Some(icon) = icon.upgrade() { + icon.set_visible(false); + } + } + }); + } + button +} diff --git a/crates/pdfs-gui/src/app/pages/login.rs b/crates/pdfs-gui/src/app/pages/login.rs index e7b0dc8..b8c4122 100644 --- a/crates/pdfs-gui/src/app/pages/login.rs +++ b/crates/pdfs-gui/src/app/pages/login.rs @@ -683,6 +683,10 @@ pub(crate) fn sign_out(ui: &Rc) { ), &gettext("Sign Out"), move || { + let galleries = ui.drive_galleries.borrow().upgrade(); + if let Some(galleries) = galleries { + galleries.close(); + } // systemctl and the keyring both block, so run them on a worker. let ui = ui.clone(); glib::spawn_future_local(async move { diff --git a/crates/pdfs-gui/src/app/pages/mod.rs b/crates/pdfs-gui/src/app/pages/mod.rs index fd1a8bf..0de5bc0 100644 --- a/crates/pdfs-gui/src/app/pages/mod.rs +++ b/crates/pdfs-gui/src/app/pages/mod.rs @@ -3,6 +3,7 @@ pub(crate) mod activity_text; pub(crate) mod albums; pub(crate) mod browser; pub(crate) mod devices; +pub(crate) mod drive_galleries; pub(crate) mod duplicates; pub(crate) mod locations; pub(crate) mod login; diff --git a/crates/pdfs-gui/src/app/pages/photo_viewer.rs b/crates/pdfs-gui/src/app/pages/photo_viewer.rs index 793c136..c857bde 100644 --- a/crates/pdfs-gui/src/app/pages/photo_viewer.rs +++ b/crates/pdfs-gui/src/app/pages/photo_viewer.rs @@ -31,6 +31,8 @@ pub(crate) struct Viewer { pub(crate) scroller: gtk4::ScrolledWindow, pub(crate) picture: gtk4::Picture, pub(crate) video: gtk4::Video, + video_token: RefCell>, + load_generation: Cell, pub(crate) spinner: Spinner, pub(crate) status: gtk4::Label, pub(crate) title: gtk4::Label, @@ -272,12 +274,14 @@ fn viewer_item(ui: &Rc, viewer: &Rc, uid: &str) -> Option /// full-size file, and swap it in — plus its EXIF — when it lands. A video /// plays in place once its file is down. pub(crate) fn load_photo(ui: &Rc, viewer: &Rc, uid: String) { + let generation = viewer.load_generation.get().wrapping_add(1); + viewer.load_generation.set(generation); viewer.spinner.set_visible(true); viewer.status.set_visible(false); viewer.loading.set(true); *viewer.path.borrow_mut() = None; clear_info(viewer); - stop_video(viewer); + stop_video(ui, viewer); viewer.media.set_visible_child_name("photo"); sync_strip(viewer); reset_zoom(viewer); @@ -302,17 +306,22 @@ pub(crate) fn load_photo(ui: &Rc, viewer: &Rc, uid: String) { None => viewer.picture.set_paintable(gtk4::gdk::Paintable::NONE), } - let rx = spawn_request( - ui.dirs.control_socket(), - Request::OpenPhoto { uid: uid.clone() }, - ); + let request = if is_video { + Request::OpenGalleryVideo { uid: uid.clone() } + } else { + Request::OpenPhoto { uid: uid.clone() } + }; + let rx = spawn_request(ui.dirs.control_socket(), request); let viewer = viewer.clone(); let ui = ui.clone(); glib::spawn_future_local(async move { let result = rx.recv().await; // The user may have moved on while this was in flight; that photo's own // request owns the viewer now. - if *viewer.uid.borrow() != uid { + if viewer.load_generation.get() != generation { + if let Ok(Ok(Response::GalleryVideo { token, .. })) = result { + close_video(&ui, token); + } return; } viewer.spinner.set_visible(false); @@ -326,6 +335,14 @@ pub(crate) fn load_photo(ui: &Rc, viewer: &Rc, uid: String) { viewer.status.set_visible(true); }; let path = match result { + Ok(Ok(Response::GalleryVideo { url, token, size })) => { + *viewer.video_token.borrow_mut() = Some(token); + viewer.video.set_file(Some(&gio::File::for_uri(&url))); + viewer.media.set_visible_child_name("video"); + sync_strip(&viewer); + show_info(&viewer, Some(size), ExifInfo::default()); + return; + } Ok(Ok(Response::FilePath { path })) => path, Ok(Ok(Response::Error { message, .. })) => return fail(&message), Ok(Ok(_)) => return fail(&gettext("Unexpected reply from the Proton Drive service.")), @@ -481,8 +498,18 @@ fn next_slide(ui: &Rc, viewer: &Rc) { /// Stop whatever the player was playing, so stepping off a video (or closing /// the lightbox) doesn't leave its sound running. -fn stop_video(viewer: &Rc) { +fn close_video(ui: &Ui, token: String) { + let _reply = spawn_request( + ui.dirs.control_socket(), + Request::CloseGalleryVideo { token }, + ); +} + +fn stop_video(ui: &Ui, viewer: &Rc) { viewer.video.set_media_stream(gtk4::MediaStream::NONE); + if let Some(token) = viewer.video_token.borrow_mut().take() { + close_video(ui, token); + } } /// Warm the cache with the photo `delta` steps away, so stepping there is @@ -1473,6 +1500,8 @@ pub(crate) fn open_photo_viewer(ui: &Rc, initial_uid: String) -> gtk4::Windo scroller: scroller.clone(), picture: picture.clone(), video, + video_token: RefCell::new(None), + load_generation: Cell::new(0), spinner, status: status_label, title: title_label, @@ -1700,7 +1729,10 @@ pub(crate) fn open_photo_viewer(ui: &Rc, initial_uid: String) -> gtk4::Windo } if let Some(viewer) = keep.borrow_mut().take() { reveal_photo(&ui_close, &viewer.uid.borrow()); - stop_video(&viewer); + viewer + .load_generation + .set(viewer.load_generation.get().wrapping_add(1)); + stop_video(&ui_close, &viewer); disarm_slide(&viewer); if let Some(source) = viewer.chrome_source.borrow_mut().take() { source.remove(); @@ -1952,7 +1984,7 @@ fn open_viewer_menu(ui: &Rc, viewer: &Rc) { } menu.section(); // These need the full-size file, which may still be downloading. - if viewer.path.borrow().is_some() { + if viewer.path.borrow().is_some() || viewer.video_token.borrow().is_some() { let still = viewer.media.visible_child_name().as_deref() == Some("photo"); if still { // Translators: menu item that puts the photo on the clipboard as an image. @@ -1999,17 +2031,45 @@ fn open_viewer_menu(ui: &Rc, viewer: &Rc) { }); } -fn save_shown_photo(_ui: &Rc, viewer: &Rc) { - if let Some(path) = viewer.path.borrow().as_deref() { - let name = viewer.name.borrow(); - save_photo_to_disk(viewer, path, name.as_deref().unwrap_or("photo")); - } +fn save_shown_photo(ui: &Rc, viewer: &Rc) { + with_viewer_file(ui, viewer, |viewer, path, name| { + save_photo_to_disk(viewer, path, name.unwrap_or("photo")) + }); } -fn open_shown_photo(_ui: &Rc, viewer: &Rc) { +fn open_shown_photo(ui: &Rc, viewer: &Rc) { + with_viewer_file(ui, viewer, |viewer, path, name| { + open_with(&viewer.window, path, name) + }); +} + +fn with_viewer_file( + ui: &Rc, + viewer: &Rc, + use_file: impl FnOnce(&Rc, &str, Option<&str>) + 'static, +) { + let name = viewer.name.borrow().clone(); if let Some(path) = viewer.path.borrow().as_deref() { - open_with(&viewer.window, path, viewer.name.borrow().as_deref()); + use_file(viewer, path, name.as_deref()); + return; } + if viewer.video_token.borrow().is_none() { + return; + } + let uid = viewer.uid.borrow().clone(); + let viewer = viewer.clone(); + let rx = spawn_request(ui.dirs.control_socket(), Request::OpenPhoto { uid }); + glib::spawn_future_local(async move { + match rx.recv().await { + Ok(Ok(Response::FilePath { path })) => use_file(&viewer, &path, name.as_deref()), + Ok(Ok(Response::Error { message, .. })) => { + viewer.toasts.add_toast(adw::Toast::new(&message)) + } + _ => viewer + .toasts + .add_toast(adw::Toast::new(&gettext("Couldn't open the file."))), + } + }); } fn add_shown_photo_to_album(ui: &Rc, viewer: &Rc) { diff --git a/crates/pdfs-gui/src/app/pages/photos.rs b/crates/pdfs-gui/src/app/pages/photos.rs index 5699eda..3b39453 100644 --- a/crates/pdfs-gui/src/app/pages/photos.rs +++ b/crates/pdfs-gui/src/app/pages/photos.rs @@ -467,6 +467,7 @@ impl GalleryRow { /// The widgets [`build_gallery_page`] hands back to [`build_window`]. pub(crate) struct GalleryWidgets { + pub(crate) drive_galleries: gtk4::Button, /// Flat, newest-first list of every loaded photo. Backs the lightbox's /// prev/next navigation; the visible sections are derived from it. pub(crate) model: gio::ListStore, @@ -940,10 +941,13 @@ pub(crate) fn build_gallery_page() -> (gtk4::Widget, GalleryWidgets) { header.pack_end(&more); header.pack_end(&select_btn); header.pack_end(&selection.cancel); + let drive_galleries = gtk4::Button::with_label(&gettext("Drive Galleries")); + header.pack_end(&drive_galleries); ( frame.upcast(), GalleryWidgets { + drive_galleries, model, groups, content, @@ -2203,16 +2207,15 @@ pub(crate) fn justify_rows(ui: &Rc, photos: &[PhotoItem], width: i32) -> Vec /// The narrowest and the widest shape a tile may take, as width over height. /// A panorama at its own shape would be a ribbon, and a screenshot of a phone /// a thread; past these the thumbnail is cropped to fit. -pub(crate) const TILE_RATIO_MIN: f64 = 0.5; -pub(crate) const TILE_RATIO_MAX: f64 = 2.5; +#[cfg(test)] +const TILE_RATIO_MIN: f64 = 0.5; +#[cfg(test)] +const TILE_RATIO_MAX: f64 = 2.5; /// The shape a photo's tile takes: its own, clamped, or square while the /// daemon has not seen a thumbnail of it yet. pub(crate) fn tile_ratio(ratio: Option) -> f64 { - ratio - .filter(|ratio| ratio.is_finite() && *ratio > 0.0) - .unwrap_or(1.0) - .clamp(TILE_RATIO_MIN, TILE_RATIO_MAX) + pg_core::grid::tile_ratio(ratio.unwrap_or(1.0)) } /// The justified layout math: tiles of the given shapes, in order, broken into @@ -2225,64 +2228,33 @@ pub(crate) fn tile_ratio(ratio: Option) -> f64 { /// two photos from one day stay two photos at the target height, not two /// photos as tall as the window. pub(crate) fn plan_justified(ratios: &[f64], width: i32, target: i32) -> Vec> { - let width = width.max(1); - let target = f64::from(target.clamp(ROW_MIN, ROW_MAX)); - let gap = f64::from(TILE_GAP); - // The height that makes `ratios` span the width exactly. - let fit = |ratios: &[f64]| { - let gaps = gap * (ratios.len() as f64 - 1.0); - (f64::from(width) - gaps).max(1.0) / ratios.iter().sum::() + let Ok(grid) = pg_core::grid::plan_sections( + ratios, + &[], + width.clamp(1, 32_768) as u32, + target.clamp(ROW_MIN, ROW_MAX) as u32, + TILE_GAP as u32, + ) else { + return Vec::new(); }; - let mut rows = Vec::new(); - let mut start = 0; - while start < ratios.len() { - let mut end = start + 1; - while end < ratios.len() && fit(&ratios[start..end]) > target { - end += 1; - } - let full = fit(&ratios[start..end]) <= target; - // Giving the last photo back leaves the row taller than the target; - // keeping it, shorter. Whichever misses by less wins. - if full - && end - start > 1 - && fit(&ratios[start..end - 1]) - target < target - fit(&ratios[start..end]) - { - end -= 1; - } - let row = &ratios[start..end]; - rows.push(if full { - size_row(row, fit(row), Some(width)) - } else { - size_row(row, target, None) - }); - start = end; - } - rows -} - -/// Tile sizes for one row of shapes at `height`. With `span`, the widths are -/// rounded so the row, gaps included, is exactly that wide: each tile ends -/// where its share of the row ends, so no rounding error piles up at the end. -fn size_row(ratios: &[f64], height: f64, span: Option) -> Vec<(i32, i32)> { - let tile_height = (height.round() as i32).max(1); - let Some(span) = span else { - return ratios - .iter() - .map(|ratio| (((ratio * height).round() as i32).max(1), tile_height)) - .collect(); - }; - let content = f64::from(span - TILE_GAP * (ratios.len() as i32 - 1)); - let total: f64 = ratios.iter().sum(); - let mut sizes = Vec::with_capacity(ratios.len()); - let mut done = 0.0; - let mut left = 0; - for ratio in ratios { - done += ratio; - let right = (content * done / total).round() as i32; - sizes.push(((right - left).max(1), tile_height)); - left = right; - } - sizes + let ends = grid + .row_starts + .iter() + .copied() + .skip(1) + .chain(std::iter::once(grid.widths.len() as u32)); + grid.row_starts + .iter() + .copied() + .zip(ends) + .zip(grid.row_heights) + .map(|((start, end), height)| { + grid.widths[start as usize..end as usize] + .iter() + .map(|width| (*width as i32, height as i32)) + .collect() + }) + .collect() } /// The layout math: how many square tiles of about `target` px fit across diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md index eb3ac26..4ccd367 100644 --- a/docs/CHANGELOG.md +++ b/docs/CHANGELOG.md @@ -11,6 +11,19 @@ scratch (user data in `staging/` and `recovery/` is never touched by this). ## [Unreleased] +### Added + +- Open **Drive Galleries** from Photos to browse saved My files folders and their + subfolders, choose album covers, and manage public links. Saved galleries and + covers sync with Proton Gallery on desktop and Android. + +### Changed + +- Photos uses Proton Gallery's justified row planner. The Photos viewer starts + and seeks through supported videos without caching the whole original. +- Gallery-hidden albums and their contents are filtered from Photos and Drive + Galleries. Unlock them with the local Gallery passphrase. + ## [3.8.1] — 2026-11-19 Schema: **45**. No database migration in this release. diff --git a/packaging/copr/README.md b/packaging/copr/README.md index 67292d8..dc11962 100644 --- a/packaging/copr/README.md +++ b/packaging/copr/README.md @@ -8,7 +8,7 @@ release assets: | Source | What it is | | --- | --- | | `Source0` | GitHub's archive of the `v` tag | -| `Source1` | `proton-drive-linux-vendor-.tar.xz`: every crate from `Cargo.lock`, made by `cargo vendor` in `release.yml` | +| `Source1` | `proton-drive-linux-vendor-.tar.xz`: the crates and source mappings generated by `cargo vendor` in `release.yml` | With the vendored crates the build needs no network, so the COPR project keeps network access off. diff --git a/packaging/nix/package.nix b/packaging/nix/package.nix index c2bce34..e9f4b4a 100644 --- a/packaging/nix/package.nix +++ b/packaging/nix/package.nix @@ -44,7 +44,10 @@ rustPlatform.buildRustPackage { ]; }; - cargoLock.lockFile = ../../Cargo.lock; + cargoLock = { + lockFile = ../../Cargo.lock; + allowBuiltinFetchGit = true; + }; cargoBuildFlags = [ "--bin" diff --git a/packaging/proton-drive-linux.spec b/packaging/proton-drive-linux.spec index d383a70..4cc1ac9 100644 --- a/packaging/proton-drive-linux.spec +++ b/packaging/proton-drive-linux.spec @@ -2,7 +2,7 @@ # # - From a checkout (local builds and the release workflow). From the repository root: # rpmbuild -bb packaging/proton-drive-linux.spec --define "git_dir $PWD" ... -# %build needs network so cargo can fetch crates.io (same trade-off as the Arch PKGBUILD). +# %build needs network so Cargo can fetch crates.io and Git dependencies. # - From the release tarballs (COPR, .github/workflows/copr.yml), when git_dir is not # defined. Source1 holds every crate, so the build runs offline. @@ -72,16 +72,19 @@ system tray and search launcher. Unofficial and not affiliated with Proton AG. test -f %{git_dir}/Cargo.toml cp -a %{git_dir}/LICENSE . %else -# -a 1 unpacks the vendored crates into vendor/ inside the source tree. +# -a 1 unpacks the vendored crates and their source mappings. %autosetup -n %{name}-%{version} -a 1 -mkdir -p .cargo -cat > .cargo/config.toml <<'EOF' +# Older vendor tarballs contained only crates.io dependencies. +if [ ! -f .cargo/config.toml ]; then + mkdir -p .cargo + cat > .cargo/config.toml <<'EOF' [source.crates-io] replace-with = "vendored-sources" [source.vendored-sources] directory = "vendor" EOF +fi %endif %build diff --git a/po/POTFILES.in b/po/POTFILES.in index 3b066df..c411c36 100644 --- a/po/POTFILES.in +++ b/po/POTFILES.in @@ -6,6 +6,7 @@ crates/pdfs-gui/src/app/pages/activity_text.rs crates/pdfs-gui/src/app/pages/albums.rs crates/pdfs-gui/src/app/pages/browser.rs crates/pdfs-gui/src/app/pages/devices.rs +crates/pdfs-gui/src/app/pages/drive_galleries.rs crates/pdfs-gui/src/app/pages/duplicates.rs crates/pdfs-gui/src/app/pages/locations.rs crates/pdfs-gui/src/app/pages/login.rs