Skip to content

Native iCloud apps for Windows and Linux, built in Rust. Notes, Reminders, Calendar, Contacts, Drive and Photos, offline and in sync with your iPhone.

Photos folder: add photos by copying them in, delete to Recently Deleted

Yashwanth Kamireddi99c8b13662db
diff --git a/Cargo.lock b/Cargo.lock
index fab1075..f860ab2 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -3734,6 +3734,7 @@ dependencies = [
"futures-util",
"image",
"jiff",
+ "keyring",
"plist",
"quince-auth",
"quince-core",
diff --git a/crates/quince-core/src/photos.rs b/crates/quince-core/src/photos.rs
index b8cc802..66a75bd 100644
--- a/crates/quince-core/src/photos.rs
+++ b/crates/quince-core/src/photos.rs
@@ -519,6 +519,23 @@ impl Library {
Ok(rows.collect::<std::result::Result<_, _>>()?)
}
+ /// The latest upload of the file at `path`, whatever its state: a file added through the
+ /// Photos folder is sent once, even when the folder sends it again after a restart.
+ pub fn upload_at(&self, path: &str) -> Result<Option<Upload>> {
+ let id: Option<String> = self
+ .conn
+ .query_row(
+ "SELECT id FROM photo_uploads WHERE path = ?1 ORDER BY added_at DESC, rowid DESC LIMIT 1",
+ params![path],
+ |r| r.get(0),
+ )
+ .optional()?;
+ match id {
+ Some(id) => self.upload(&id),
+ None => Ok(None),
+ }
+ }
+
/// One upload, by id, whatever its state: what the upload panel shows a picture of.
pub fn upload(&self, id: &str) -> Result<Option<Upload>> {
Ok(self
diff --git a/crates/quince-vfs/src/fuse.rs b/crates/quince-vfs/src/fuse.rs
index c1a8b21..3ddb510 100644
--- a/crates/quince-vfs/src/fuse.rs
+++ b/crates/quince-vfs/src/fuse.rs
@@ -59,8 +59,11 @@ struct Inner {
writes: Option<Arc<Writes>>,
/// The account's storage as last asked, `(used, total)`.
space: Mutex<Option<((u64, u64), std::time::Instant)>>,
- /// Nothing in it can be changed (the Photos folder, for now).
+ /// Nothing in it can be changed.
read_only: bool,
+ /// New files can be added and anything deleted, nothing else (the Photos folder: a photo is
+ /// added or deleted, never rewritten in place, renamed or given a folder).
+ add_only: bool,
}
pub struct DriveFs(Arc<Inner>);
@@ -89,6 +92,7 @@ impl DriveFs {
writes: None,
space: Mutex::new(None),
read_only: false,
+ add_only: false,
}))
}
@@ -117,6 +121,14 @@ impl DriveFs {
self
}
+ /// New files can be added (into folders the remote `accepts`) and files deleted; nothing
+ /// is rewritten, renamed, moved or made a folder — "read-only file system" to all of that.
+ #[must_use]
+ pub fn add_only(mut self) -> Self {
+ self.inner_mut().add_only = true;
+ self
+ }
+
/// Files can be written, their bytes kept in `dir` until Apple has them. What was waiting
/// when the folder last went away is picked up again and sent.
///
@@ -299,7 +311,8 @@ impl Inner {
perm: match (dir, self.writes.is_some() && !self.read_only) {
(true, _) if self.read_only => 0o555,
(true, _) => 0o755,
- (false, true) => 0o644,
+ (false, true) if !self.add_only => 0o644,
+ (false, true) => 0o444,
(false, false) => 0o444,
},
nlink: if dir { 2 } else { 1 },
@@ -397,6 +410,9 @@ impl Inner {
/// A file of Apple's made writable: its bytes copied here (unless they are about to be
/// thrown away), to be sent back in its place.
fn begin_writing(&self, ino: u64, item: &DriveItem, keep: bool) -> Result<(), Errno> {
+ if self.add_only {
+ return Err(Errno::EROFS);
+ }
let writes = self.writes.as_ref().ok_or(Errno::EROFS)?;
if self.pending(ino).is_some() {
return Ok(());
@@ -540,14 +556,26 @@ impl Inner {
&& std::fs::copy(writes.staging(ino, &p.name), &out).is_ok();
me.with_pending(ino, |p| p.sending = true);
let result = if copied {
- let r = writes::send(
- me.remote.as_ref(),
- &folder,
- &out,
- p.replaces.as_ref(),
- ours.as_ref(),
- )
- .await;
+ // Where only adding is, a send is an addition and nothing else: never a
+ // replacement of a file found under the same name.
+ let r = if me.add_only {
+ me.remote
+ .upload(&folder, &out)
+ .await
+ .map(|item| writes::Sent {
+ item,
+ conflicted: false,
+ })
+ } else {
+ writes::send(
+ me.remote.as_ref(),
+ &folder,
+ &out,
+ p.replaces.as_ref(),
+ ours.as_ref(),
+ )
+ .await
+ };
let _ = std::fs::remove_dir_all(&out_dir);
r
} else {
@@ -688,6 +716,17 @@ impl Inner {
}
}
let pending = me.pending(ino);
+ // Added and not yet sent, under another name or among other new files — a copy's
+ // temporary name made its own — is all that can be renamed where only adding is.
+ if me.add_only
+ && (pending.is_none()
+ || target
+ .as_ref()
+ .is_some_and(|(t, _)| me.pending(*t).is_none())
+ || !me.remote.accepts(&to))
+ {
+ return Err(Errno::EROFS);
+ }
match (pending, target) {
// A file written here taking another's name — an editor's save: what it replaces
// (Apple's file, or another being written) goes, and Apple's into Recently Deleted
@@ -986,6 +1025,9 @@ impl Filesystem for DriveFs {
let Some(name) = name.to_str() else {
return reply.error(Errno::EINVAL);
};
+ if inner.add_only && !inner.remote.accepts(&folder) {
+ return reply.error(Errno::EROFS);
+ }
if let Ok((ino, item)) = inner.child(parent.0, OsStr::new(name)) {
if flags & libc::O_EXCL != 0 {
return reply.error(Errno::EEXIST);
@@ -1220,7 +1262,7 @@ impl Filesystem for DriveFs {
_umask: u32,
reply: ReplyEntry,
) {
- if self.0.read_only {
+ if self.0.read_only || self.0.add_only {
return reply.error(Errno::EROFS);
}
let inner = &self.0;
@@ -1253,7 +1295,7 @@ impl Filesystem for DriveFs {
}
fn rmdir(&self, _req: &Request, parent: INodeNo, name: &OsStr, reply: ReplyEmpty) {
- if self.0.read_only {
+ if self.0.read_only || self.0.add_only {
return reply.error(Errno::EROFS);
}
match self.0.remove(parent.0, name, true) {
diff --git a/crates/quince-vfs/src/lib.rs b/crates/quince-vfs/src/lib.rs
index 1627ffd..9d59eef 100644
--- a/crates/quince-vfs/src/lib.rs
+++ b/crates/quince-vfs/src/lib.rs
@@ -43,6 +43,11 @@ pub trait Remote: Send + Sync + 'static {
fn upload(&self, _folder: &DriveItem, _path: &Path) -> Fut<DriveItem> {
Box::pin(async { Err("read-only".to_string()) })
}
+ /// Whether new files may be written into `folder`. Every folder by default; a folder that
+ /// is a view, not a place (the Photos folder's Favorites), says no.
+ fn accepts(&self, _folder: &DriveItem) -> bool {
+ true
+ }
/// An item deleted — into Apple's Recently Deleted, where it can be put back for 30 days.
fn delete(&self, _item: &DriveItem) -> Fut<()> {
Box::pin(async { Err("read-only".to_string()) })
diff --git a/probe/Cargo.toml b/probe/Cargo.toml
index 603161e..5f06d53 100644
--- a/probe/Cargo.toml
+++ b/probe/Cargo.toml
@@ -6,6 +6,7 @@ license.workspace = true
publish = false
[dependencies]
+keyring = { version = "3", default-features = false, features = ["sync-secret-service", "crypto-rust"] }
futures-util = "0.3"
image = { version = "0.25", default-features = false, features = ["png", "jpeg"] }
sha1 = "0.10"
diff --git a/probe/examples/keyring_pipe.rs b/probe/examples/keyring_pipe.rs
new file mode 100644
index 0000000..024b3ce
--- /dev/null
+++ b/probe/examples/keyring_pipe.rs
@@ -0,0 +1,19 @@
+//! For the isolated real-app harness: the app's keyring entry copied over a pipe into another
+//! session's keyring, never through a file. `get` prints it (run in the real session), `set`
+//! reads it from stdin (run inside the isolated one).
+use anyhow::{anyhow, Result};
+use std::io::{Read, Write};
+
+fn main() -> Result<()> {
+ let entry = keyring::Entry::new("dev.quince.client", "session")?;
+ match std::env::args().nth(1).as_deref() {
+ Some("get") => std::io::stdout().write_all(entry.get_password()?.as_bytes())?,
+ Some("set") => {
+ let mut secret = String::new();
+ std::io::stdin().read_to_string(&mut secret)?;
+ entry.set_password(&secret)?;
+ }
+ _ => return Err(anyhow!("get or set")),
+ }
+ Ok(())
+}
diff --git a/probe/examples/photos_folder_add_live.rs b/probe/examples/photos_folder_add_live.rs
new file mode 100644
index 0000000..26bc2cf
--- /dev/null
+++ b/probe/examples/photos_folder_add_live.rs
@@ -0,0 +1,273 @@
+//! Live: the Photos folder's add-only mode (quince-vfs `add_only`) against real iCloud Photos,
+//! through the same uploader and delete the app uses. Mounts a small Photos folder — Library
+//! (takes new photos) and Favorites (a view: takes nothing) — then, as any program would:
+//!
+//! - copies the test JPEG into Library: it goes up and is confirmed in the library;
+//! - tries what a Photos folder must refuse: a folder made, a photo written over, renamed, a
+//! file put in Favorites — each "read-only file system";
+//! - deletes it: into Recently Deleted, confirmed from Apple.
+//!
+//! The file must be named quince-upload-test.jpg (photos_expunge deletes it for good after).
+use anyhow::{anyhow, Result};
+use quince_core::drive::DriveItem;
+use quince_icloud::photos::{Flag, CONTAINER, ZONE};
+use quince_vfs::{fuse, Cache, Fut, Remote, Store, ROOT};
+use std::collections::HashMap;
+use std::sync::{Arc, Mutex};
+
+const LIBRARY: &str = "PH::library";
+const FAVORITES: &str = "PH::favorites";
+
+struct Ctx {
+ http: reqwest::Client,
+ ck: String,
+ up: String,
+ dsid: String,
+ params: Vec<(String, String)>,
+}
+
+#[derive(Clone)]
+struct Photos {
+ ctx: Arc<Ctx>,
+ /// What this run added, as the library would list it.
+ added: Arc<Mutex<HashMap<String, DriveItem>>>,
+}
+
+fn folder(id: &str, name: &str) -> DriveItem {
+ DriveItem {
+ drivewsid: id.into(),
+ parent_id: Some(ROOT.into()),
+ name: name.into(),
+ extension: None,
+ kind: "FOLDER".into(),
+ size: None,
+ child_count: None,
+ created_at: None,
+ modified_at: None,
+ etag: None,
+ }
+}
+
+impl Photos {
+ fn children(&self, id: &str) -> Vec<DriveItem> {
+ match id {
+ ROOT => vec![folder(LIBRARY, "Library"), folder(FAVORITES, "Favorites")],
+ LIBRARY => self.added.lock().unwrap().values().cloned().collect(),
+ _ => vec![],
+ }
+ }
+}
+
+impl Store for Photos {
+ fn children(&self, folder: &str) -> Option<Vec<DriveItem>> {
+ Some(Photos::children(self, folder))
+ }
+}
+
+impl Remote for Photos {
+ fn list(&self, folder: &str) -> Fut<Vec<DriveItem>> {
+ let items = self.children(folder);
+ Box::pin(async move { Ok(items) })
+ }
+ fn read(&self, _: &DriveItem, _: u64, _: u64) -> Fut<Vec<u8>> {
+ Box::pin(async { Err("not read here".to_string()) })
+ }
+ fn accepts(&self, folder: &DriveItem) -> bool {
+ folder.drivewsid == LIBRARY
+ }
+ fn upload(&self, folder: &DriveItem, path: &std::path::Path) -> Fut<DriveItem> {
+ let (me, folder, path) = (self.clone(), folder.drivewsid.clone(), path.to_path_buf());
+ Box::pin(async move {
+ let name = path.file_name().unwrap().to_string_lossy().into_owned();
+ let c = &me.ctx;
+ let outcome = quince_icloud::photos_upload::upload(
+ &c.http,
+ &c.up,
+ &c.dsid,
+ &path,
+ &name,
+ 1_792_521_600_000,
+ "Asia/Kolkata",
+ -330,
+ &uuid::Uuid::new_v4().to_string(),
+ Arc::new(|_| {}),
+ )
+ .await
+ .map_err(|e| e.to_string())?;
+ let quince_icloud::photos_upload::Outcome::Uploaded(u) = outcome else {
+ return Err(format!("refused: {outcome:?}"));
+ };
+ println!("uploaded through the folder: asset {}", u.asset);
+ let (stem, ext) = name.rsplit_once('.').unwrap();
+ let item = DriveItem {
+ drivewsid: format!("PHOTO::{}", u.asset),
+ parent_id: Some(folder),
+ name: stem.into(),
+ extension: Some(ext.into()),
+ kind: "FILE".into(),
+ size: std::fs::metadata(&path).ok().map(|m| m.len() as i64),
+ child_count: None,
+ created_at: None,
+ modified_at: None,
+ etag: None,
+ };
+ me.added.lock().unwrap().insert(u.asset, item.clone());
+ Ok(item)
+ })
+ }
+ fn delete(&self, item: &DriveItem) -> Fut<()> {
+ let (me, item) = (self.clone(), item.clone());
+ Box::pin(async move {
+ let asset = item.drivewsid.trim_start_matches("PHOTO::").to_string();
+ let c = &me.ctx;
+ let zc = quince_icloud::cloudkit::ZoneClient::new(
+ &c.http,
+ &c.ck,
+ CONTAINER,
+ c.params.clone(),
+ );
+ let rec = zc
+ .lookup_record(ZONE, &asset)
+ .await
+ .map_err(|e| e.to_string())?
+ .ok_or("gone")?;
+ quince_icloud::photos::set_flag(
+ &c.http,
+ &c.ck,
+ c.params.clone(),
+ &asset,
+ rec["recordChangeTag"].as_str(),
+ Flag::Deleted,
+ true,
+ )
+ .await
+ .map_err(|e| e.to_string())?;
+ me.added.lock().unwrap().remove(&asset);
+ Ok(())
+ })
+ }
+}
+
+/// EROFS, "read-only file system" (30 on Linux).
+fn erofs<T>(what: &str, r: std::io::Result<T>) {
+ let ok = matches!(&r, Err(e) if e.raw_os_error() == Some(30));
+ println!("{} {what}: {:?}", if ok { "PASS" } else { "FAIL" }, r.err());
+}
+
+fn main() -> Result<()> {
+ let mut args = std::env::args().skip(1);
+ let (jpeg, at) = (
+ std::path::PathBuf::from(args.next().ok_or_else(|| anyhow!("jpeg"))?),
+ std::path::PathBuf::from(args.next().ok_or_else(|| anyhow!("mount point"))?),
+ );
+ let rt = tokio::runtime::Runtime::new()?;
+ let dir = std::path::PathBuf::from(std::env::var("HOME")?).join(".local/share/quince-probe");
+ let ctx = rt.block_on(async {
+ let mut client = quince_auth::Client::new(&dir)?;
+ if !client.resume().await? {
+ return Err(anyhow!("no session"));
+ }
+ let s = client.session();
+ let p = client.service_params();
+ Ok::<_, anyhow::Error>(Ctx {
+ http: client.http().clone(),
+ ck: s
+ .service_url("ckdatabasews")
+ .ok_or_else(|| anyhow!("no ck"))?,
+ up: s
+ .service_url("photosupload")
+ .ok_or_else(|| anyhow!("no upload"))?,
+ dsid: p
+ .iter()
+ .find(|(k, _)| k == "dsid")
+ .map(|(_, v)| v.clone())
+ .unwrap_or_default(),
+ params: p,
+ })
+ })?;
+ let photos = Photos {
+ ctx: Arc::new(ctx),
+ added: Arc::default(),
+ };
+ let scratch = std::env::temp_dir().join(format!("quince-photos-add-{}", std::process::id()));
+ std::fs::create_dir_all(&at)?;
+ let fs = fuse::DriveFs::new(
+ Arc::new(photos.clone()),
+ Arc::new(photos.clone()),
+ Arc::new(Cache::new(&scratch.join("cache"))?),
+ rt.handle().clone(),
+ )
+ .add_only()
+ .with_writes(&scratch.join("writes"))?;
+ let writes = fs.writes().ok_or_else(|| anyhow!("no writes"))?;
+ let session = fuse::mount(fs, &at)?;
+ let lib = at.join("Library");
+ let target = lib.join("quince-upload-test.jpg");
+
+ std::fs::copy(&jpeg, &target)?;
+ println!("copied in");
+ let started = std::time::Instant::now();
+ while writes.waiting().files > 0 && started.elapsed().as_secs() < 120 {
+ std::thread::sleep(std::time::Duration::from_millis(500));
+ }
+ let asset = photos.added.lock().unwrap().keys().next().cloned();
+ println!(
+ "{} sent within {:.1}s",
+ if asset.is_some() { "PASS" } else { "FAIL" },
+ started.elapsed().as_secs_f64()
+ );
+ let asset = asset.ok_or_else(|| anyhow!("never sent"))?;
+ let found = rt.block_on(async {
+ let c = &photos.ctx;
+ quince_icloud::cloudkit::ZoneClient::new(&c.http, &c.ck, CONTAINER, c.params.clone())
+ .lookup_record(ZONE, &asset)
+ .await
+ })?;
+ println!(
+ "{} in iCloud Photos",
+ if found.is_some() { "PASS" } else { "FAIL" }
+ );
+ println!(
+ "{} listed in Library as {:?}",
+ if target.exists() { "PASS" } else { "FAIL" },
+ std::fs::read_dir(&lib)?
+ .flatten()
+ .map(|e| e.file_name())
+ .collect::<Vec<_>>()
+ );
+
+ erofs("no folders made", std::fs::create_dir(lib.join("New")));
+ erofs(
+ "a photo never written over",
+ std::fs::OpenOptions::new().write(true).open(&target),
+ );
+ erofs(
+ "nor renamed",
+ std::fs::rename(&target, lib.join("other.jpg")),
+ );
+ erofs(
+ "nothing put in a view",
+ std::fs::write(at.join("Favorites").join("x.jpg"), b"x"),
+ );
+
+ std::fs::remove_file(&target)?;
+ let after = rt.block_on(async {
+ let c = &photos.ctx;
+ quince_icloud::cloudkit::ZoneClient::new(&c.http, &c.ck, CONTAINER, c.params.clone())
+ .lookup_record(ZONE, &asset)
+ .await
+ })?;
+ let deleted = after
+ .as_ref()
+ .and_then(|r| r.pointer("/fields/isDeleted/value"))
+ .and_then(serde_json::Value::as_i64)
+ == Some(1);
+ println!(
+ "{} deleted through the folder: in Recently Deleted",
+ if deleted { "PASS" } else { "FAIL" }
+ );
+ drop(session);
+ let _ = std::fs::remove_dir_all(&scratch);
+ println!("ASSET {asset}");
+ Ok(())
+}
diff --git a/src-tauri/src/main.rs b/src-tauri/src/main.rs
index 0be2b4c..661d56e 100644
--- a/src-tauri/src/main.rs
+++ b/src-tauri/src/main.rs
@@ -511,7 +511,7 @@ pub const ACCOUNT_KEY: &str = "account";
/// What of an account lives in the data folder beside the session: its library, and every
/// cache and queue made from it. Moved as one when another account signs in.
-const ACCOUNT_FILES: [&str; 11] = [
+const ACCOUNT_FILES: [&str; 12] = [
"library.db",
"library.db-wal",
"library.db-shm",
@@ -519,6 +519,7 @@ const ACCOUNT_FILES: [&str; 11] = [
"photos-folder-cache",
"drive-cache",
"drive-writes",
+ "photos-folder-writes",
"thumbnails",
"note-files",
"note-media",
diff --git a/src-tauri/src/mount.rs b/src-tauri/src/mount.rs
index be42bdd..7abbca9 100644
--- a/src-tauri/src/mount.rs
+++ b/src-tauri/src/mount.rs
@@ -367,13 +367,16 @@ fn start(app: &AppHandle, which: Which, at: &std::path::Path) -> Result<(), Stri
// Read through the app's own photo cache; the folder keeps no second copy.
let unused = crate::state_dir(app).join("photos-folder-cache");
let cache = Arc::new(quince_vfs::Cache::new(&unused).map_err(|e| e.to_string())?);
+ // Photos added here wait beside the library (owner-only) until Photos has them.
quince_vfs::fuse::DriveFs::new(
Arc::new(crate::mount_photos::PhotosRemote(app.clone())),
Arc::new(crate::mount_photos::PhotosStore(app.clone())),
cache,
rt,
)
- .read_only()
+ .add_only()
+ .with_writes(&crate::state_dir(app).join("photos-folder-writes"))
+ .map_err(|e| e.to_string())?
}
};
// Pictures go where every file manager looks for thumbnails, so none of them downloads a
@@ -467,25 +470,28 @@ pub fn resume(app: &AppHandle) {
/// Files written in the iCloud Drive folder and not yet sent: from the folder while it is up,
/// from what it wrote down when it went away while it is not.
pub fn unsent_files(data_dir: &std::path::Path) -> usize {
- if let Some(w) = WRITES
+ let journal = |name: &str| {
+ let dir = data_dir.join(name);
+ if !dir.exists() {
+ return 0;
+ }
+ quince_vfs::writes::Writes::new(&dir)
+ .map(|w| {
+ w.load()
+ .iter()
+ .filter(|(_, p)| !quince_vfs::writes::stays_local(&p.name))
+ .count()
+ })
+ .unwrap_or(0)
+ };
+ let drive = WRITES
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.as_ref()
- {
- return w.waiting().files as usize;
- }
- let dir = data_dir.join("drive-writes");
- if !dir.exists() {
- return 0;
- }
- quince_vfs::writes::Writes::new(&dir)
- .map(|w| {
- w.load()
- .iter()
- .filter(|(_, p)| !quince_vfs::writes::stays_local(&p.name))
- .count()
- })
- .unwrap_or(0)
+ .map(|w| w.waiting().files as usize);
+ // The Photos folder's are counted from what it wrote down; once sending, they are in
+ // Photos' upload queue as well, and counted there.
+ drive.unwrap_or_else(|| journal("drive-writes")) + journal("photos-folder-writes")
}
/// Every thumbnail the folders left where file managers look for them, removed — with the
diff --git a/src-tauri/src/mount_photos.rs b/src-tauri/src/mount_photos.rs
index b223678..6453fb7 100644
--- a/src-tauri/src/mount_photos.rs
+++ b/src-tauri/src/mount_photos.rs
@@ -1,4 +1,4 @@
-//! iCloud Photos as a folder (quince-vfs, read-only for now), laid out as people look for
+//! iCloud Photos as a folder (quince-vfs), laid out as people look for
//! photos: by when they were taken, in their albums, the favourites, the videos.
//!
//! Library/2026/10 October/IMG_1234.HEIC
@@ -11,6 +11,10 @@
//! read from the app's own photo cache (fetched once if they are not there), never copied a
//! second time; thumbnails are the app's own, so a file manager browsing downloads nothing.
//! Hidden and Recently Deleted are never shown.
+//!
+//! Photos are added and deleted here, never rewritten in place (quince-vfs `add_only`): a
+//! file put in the library, or in an album, goes up to iCloud Photos (and into the album); a
+//! file deleted goes to Recently Deleted, or out of the album it was deleted from.
use crate::photos::{cache_path, cached, Size};
use crate::Data;
@@ -223,7 +227,105 @@ impl Store for PhotosStore {
pub struct PhotosRemote(pub AppHandle);
+/// Whether a folder is a place photos can be added: the library at any depth (a photo then
+/// shows under the month it was taken), or an album (it goes into it too). Favorites, Videos,
+/// the albums list and album folders are views, not places.
+fn accepts(app: &AppHandle, folder: &str) -> bool {
+ if folder == LIBRARY || folder.starts_with("PH::y:") || folder.starts_with("PH::m:") {
+ return true;
+ }
+ folder.strip_prefix("PH::album:").is_some_and(|album| {
+ let data = app.state::<Data>();
+ let library = data.0.blocking_lock();
+ library
+ .albums()
+ .unwrap_or_default()
+ .iter()
+ .any(|a| a.id == album && !a.folder)
+ })
+}
+
impl Remote for PhotosRemote {
+ fn accepts(&self, folder: &DriveItem) -> bool {
+ // Asked from the folder's own threads, never the async ones: the lock can block.
+ accepts(&self.0, &folder.drivewsid)
+ }
+
+ fn upload(&self, folder: &DriveItem, path: &std::path::Path) -> Fut<DriveItem> {
+ let (app, folder, path) = (self.0.clone(), folder.drivewsid.clone(), path.to_path_buf());
+ Box::pin(async move {
+ let album = folder.strip_prefix("PH::album:").map(str::to_string);
+ let asset = crate::photos::add_from_folder(&app, &path, album).await?;
+ let made = {
+ let data = app.state::<Data>();
+ let library = data.0.lock().await;
+ library.photo(&asset).map_err(|e| e.to_string())?
+ };
+ Ok(match made {
+ Some(p) => file(&p, &folder),
+ // Not read back yet: named as it was put there, until the next look.
+ None => {
+ let name = path
+ .file_name()
+ .map(|n| n.to_string_lossy().into_owned())
+ .unwrap_or_default();
+ let (stem, ext) = match name.rsplit_once('.') {
+ Some((s, e)) if !s.is_empty() => (s.to_string(), Some(e.to_string())),
+ _ => (name, None),
+ };
+ DriveItem {
+ drivewsid: format!("{FILE}{asset}"),
+ parent_id: Some(folder),
+ name: stem,
+ extension: ext,
+ kind: "FILE".into(),
+ size: std::fs::metadata(&path)
+ .ok()
+ .and_then(|m| i64::try_from(m.len()).ok()),
+ child_count: None,
+ created_at: None,
+ modified_at: None,
+ etag: None,
+ }
+ }
+ })
+ })
+ }
+
+ fn delete(&self, item: &DriveItem) -> Fut<()> {
+ let (app, item) = (self.0.clone(), item.clone());
+ Box::pin(async move {
+ let (id, _) = photo_of(&item).ok_or("not a photo")?;
+ let ids = vec![id.to_string()];
+ // In an album, Delete takes it out of the album, as Photos does; anywhere else it
+ // goes to Recently Deleted, there for 30 days. A Live Photo's still and .MOV go as one.
+ match item
+ .parent_id
+ .as_deref()
+ .and_then(|f| f.strip_prefix("PH::album:"))
+ {
+ Some(album) => crate::photos::photos_album_remove(
+ album.to_string(),
+ ids,
+ app.state(),
+ app.state(),
+ )
+ .await
+ .map_err(|e| e.to_string()),
+ None => crate::photos::photos_set_flag(
+ ids,
+ quince_icloud::photos::Flag::Deleted,
+ true,
+ app.state(),
+ app.state(),
+ )
+ .await
+ .map(|_| ())
+ .map_err(|e| e.to_string()),
+ }
+ })
+ }
+
fn list(&self, folder: &str) -> Fut<Vec<DriveItem>> {
// Nothing to ask Apple: the library is kept in step by the app's own sync.
let (app, folder) = (self.0.clone(), folder.to_string());
diff --git a/src-tauri/src/photos.rs b/src-tauri/src/photos.rs
index 4c0ee4f..6bb012c 100644
--- a/src-tauri/src/photos.rs
+++ b/src-tauri/src/photos.rs
@@ -1775,6 +1775,116 @@ pub async fn photos_upload(
Ok(batch)
}
+/// A file put in the Photos folder, added to Photos (and to `album`, when it was put in one)
+/// through the same queue as the window's own uploads — the tray shows it, a quit resumes it,
+/// Photos' limits refuse it with the reason — answering the photo Apple made once it is there.
+///
+/// Sent from a copy named by its bytes, so the folder sending it again after a restart finds
+/// the upload already made, or under way, and waits on that one instead of making a second.
+pub async fn add_from_folder(
+ app: &AppHandle,
+ path: &std::path::Path,
+ album: Option<String>,
+) -> Result<String, String> {
+ use sha2::Digest;
+ let name = path
+ .file_name()
+ .map(|n| n.to_string_lossy().into_owned())
+ .ok_or("no name")?;
+ // Read in pieces: a video can be many gigabytes, never held whole in memory.
+ let (digest, len) = {
+ let path = path.to_path_buf();
+ tokio::task::spawn_blocking(move || -> std::io::Result<(String, u64)> {
+ use std::io::Read;
+ let mut f = std::fs::File::open(&path)?;
+ let (mut hash, mut buf, mut len) = (sha2::Sha256::new(), vec![0u8; 1 << 20], 0u64);
+ loop {
+ let n = f.read(&mut buf)?;
+ if n == 0 {
+ break;
+ }
+ hash.update(&buf[..n]);
+ len += n as u64;
+ }
+ Ok((format!("{:x}", hash.finalize()), len))
+ })
+ .await
+ .map_err(|e| e.to_string())?
+ .map_err(|e| e.to_string())?
+ };
+ let kept = crate::state_dir(app)
+ .join("photos-folder-writes")
+ .join("outgoing")
+ .join(digest)
+ .join(&name);
+ let at = kept.to_string_lossy().into_owned();
+ let data = app.state::<Data>();
+ let known = data
+ .0
+ .lock()
+ .await
+ .upload_at(&at)
+ .map_err(|e| e.to_string())?;
+ let id = match known {
+ Some(u) if u.state != "failed" && u.state != "cancelled" => u.id,
+ _ => {
+ if let Some(r) = quince_icloud::photos_upload::refusal(&name, len) {
+ return Err(r.words());
+ }
+ if let Some(dir) = kept.parent() {
+ tokio::fs::create_dir_all(dir)
+ .await
+ .map_err(|e| e.to_string())?;
+ }
+ tokio::fs::copy(path, &kept)
+ .await
+ .map_err(|e| e.to_string())?;
+ let u = quince_core::photos::Upload {
+ id: uuid::Uuid::new_v4().to_string(),
+ batch: uuid::Uuid::new_v4().to_string(),
+ path: at,
+ name,
+ state: "waiting".into(),
+ error: None,
+ asset: None,
+ added_at: jiff::Timestamp::now().as_second(),
+ album,
+ };
+ data.0
+ .lock()
+ .await
+ .queue_uploads(std::slice::from_ref(&u))
+ .map_err(|e| e.to_string())?;
+ say(app, &u, "waiting", 0, len, None);
+ u.id
+ }
+ };
+ work(app.clone());
+ // Waited on as the folder waits on any send: it retries a failure with its own backoff.
+ let outcome = loop {
+ let now = data.0.lock().await.upload(&id).map_err(|e| e.to_string())?;
+ match now {
+ Some(u) if u.state == "done" => {
+ break u.asset.ok_or("Apple named no photo".to_string())
+ }
+ Some(u) if u.state == "failed" => {
+ break Err(u.error.unwrap_or_else(|| "It could not be added.".into()))
+ }
+ Some(u) if u.state == "cancelled" => break Err("The upload was cancelled.".into()),
+ None => break Err("The upload is no longer there.".into()),
+ Some(_) => {
+ // A session lapsed stops the queue; started again here, it carries on.
+ work(app.clone());
+ tokio::time::sleep(Duration::from_millis(500)).await;
+ }
+ }
+ };
+ if let Some(dir) = kept.parent() {
+ let _ = tokio::fs::remove_dir_all(dir).await;
+ }
+ outcome
+}
+
/// Stop uploads, by id or a whole batch: what is waiting is not sent, and the file on its way
/// is abandoned mid-send. A photo Apple has already made stays (it is in the library, and can
/// be deleted there).