mirror of
https://github.com/narrrl/proton-drive-linux.git
synced 2026-11-27 03:22:14 +01:00
Compare commits
5
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
69d7441d89 | ||
|
|
45e0b60994 | ||
|
|
96248e41e2 | ||
|
|
ee2f28c5cd | ||
|
|
acc251c3d3 |
No files matched your search
@@ -568,7 +568,7 @@ pub(super) async fn run_event_sync(
|
||||
|
||||
/// Follow the Photos volume and commit changes with its durable event cursor.
|
||||
pub(super) async fn run_photos_event_sync(core: Core) {
|
||||
let photos = core.photos();
|
||||
let photos = core.photos_api();
|
||||
// The photos volume only exists once the user has used Photos at all, and
|
||||
// the daemon may well start before the network does.
|
||||
let scope = loop {
|
||||
@@ -635,7 +635,7 @@ pub(super) async fn run_photos_event_sync(core: Core) {
|
||||
}
|
||||
}
|
||||
if core.db.photos_need_work().unwrap_or(true) {
|
||||
core.spawn_timeline_refresh();
|
||||
core.photos().spawn_timeline_refresh();
|
||||
}
|
||||
core.next_poll(POLL_INTERVAL).await;
|
||||
}
|
||||
|
||||
@@ -68,7 +68,7 @@ fn clamp_limit(limit: usize) -> usize {
|
||||
fn album_change(
|
||||
uid: &str,
|
||||
photos: &[String],
|
||||
change: impl FnOnce(&NodeUid, &[NodeUid]) -> CoreResult<super::albums::AlbumOutcome>,
|
||||
change: impl FnOnce(&NodeUid, &[NodeUid]) -> CoreResult<super::photos::AlbumOutcome>,
|
||||
) -> CtlResponse {
|
||||
let Some(album) = parse_uid(uid) else {
|
||||
return CtlResponse::error(CoreError::invalid(format!("bad album uid: {uid}")));
|
||||
@@ -689,7 +689,9 @@ fn handle_control_conn(core: &Core, username: &str, mountpoint: &Path, stream: U
|
||||
core.invalidate_trash();
|
||||
Ok(())
|
||||
}
|
||||
RefreshScope::Photos { full } if !full && core.timeline_refreshing() => {
|
||||
RefreshScope::Photos { full }
|
||||
if !full && core.photos().timeline_refreshing() =>
|
||||
{
|
||||
// A refresh is already running and will publish exactly the
|
||||
// timeline this request asks for. Doing the work again
|
||||
// cannot make it newer, and the invalidation plus the
|
||||
@@ -709,7 +711,7 @@ fn handle_control_conn(core: &Core, username: &str, mountpoint: &Path, stream: U
|
||||
}
|
||||
// Whatever changed the timeline can just as easily have
|
||||
// changed an album; one scope covers the whole photos view.
|
||||
core.invalidate_albums();
|
||||
core.photos().invalidate_albums();
|
||||
// The refresh is started here, not awaited. A library of
|
||||
// twelve thousand photos is re-read in chunks of
|
||||
// `TIMELINE_ENRICH_CHUNK` nodes, which takes minutes —
|
||||
@@ -717,7 +719,7 @@ fn handle_control_conn(core: &Core, username: &str, mountpoint: &Path, stream: U
|
||||
// returned `Resource temporarily unavailable` to a caller
|
||||
// whose refresh was in fact running fine (B92). The front
|
||||
// end follows it with `PhotosRefreshStatus`.
|
||||
core.spawn_timeline_refresh();
|
||||
core.photos().spawn_timeline_refresh();
|
||||
Ok(())
|
||||
}
|
||||
};
|
||||
@@ -1133,7 +1135,7 @@ fn start_takeout_import(core: &Core, paths: Vec<PathBuf>, dry_run: bool) -> CtlR
|
||||
)));
|
||||
}
|
||||
let count = paths.len();
|
||||
match core.spawn_takeout_import(paths, dry_run) {
|
||||
match core.photos().spawn_takeout_import(paths, dry_run) {
|
||||
Ok(()) => CtlResponse::Ok {
|
||||
message: format!(
|
||||
"{} {count} archive(s)",
|
||||
|
||||
@@ -69,7 +69,7 @@ pub(super) fn answer(ask: &Ask<'_>, request: CtlRequest) -> CtlResponse {
|
||||
range,
|
||||
favorites,
|
||||
not_in_album,
|
||||
} => match core.photos_timeline(
|
||||
} => match core.photos().photos_timeline(
|
||||
offset,
|
||||
clamp_limit(limit),
|
||||
kind,
|
||||
@@ -90,11 +90,11 @@ pub(super) fn answer(ask: &Ask<'_>, request: CtlRequest) -> CtlResponse {
|
||||
},
|
||||
Err(e) => CtlResponse::error(e),
|
||||
},
|
||||
CtlRequest::PhotoDuplicates => match core.photo_duplicates() {
|
||||
CtlRequest::PhotoDuplicates => match core.photos().photo_duplicates() {
|
||||
Ok(sets) => CtlResponse::PhotoDuplicates { sets },
|
||||
Err(e) => CtlResponse::error(e),
|
||||
},
|
||||
CtlRequest::PhotoSimilar => match core.photo_similar() {
|
||||
CtlRequest::PhotoSimilar => match core.photos().photo_similar() {
|
||||
Ok((sets, hashing, uncompared)) => CtlResponse::PhotoSimilar {
|
||||
sets,
|
||||
hashing,
|
||||
@@ -102,15 +102,18 @@ pub(super) fn answer(ask: &Ask<'_>, request: CtlRequest) -> CtlResponse {
|
||||
},
|
||||
Err(e) => CtlResponse::error(e),
|
||||
},
|
||||
CtlRequest::PhotoPlaces => match core.photo_places(excluded) {
|
||||
CtlRequest::PhotoPlaces => match core.photos().photo_places(excluded) {
|
||||
Ok(items) => CtlResponse::Places {
|
||||
items,
|
||||
mapping: core.timeline_progress(),
|
||||
mapping: core.photos().timeline_progress(),
|
||||
},
|
||||
Err(e) => CtlResponse::error(e),
|
||||
},
|
||||
CtlRequest::PlacePhotos { id, offset, limit } => {
|
||||
match core.place_photos(id, offset, clamp_limit(limit), excluded) {
|
||||
match core
|
||||
.photos()
|
||||
.place_photos(id, offset, clamp_limit(limit), excluded)
|
||||
{
|
||||
Ok(items) => CtlResponse::Photos {
|
||||
available: true,
|
||||
items,
|
||||
@@ -119,12 +122,15 @@ pub(super) fn answer(ask: &Ask<'_>, request: CtlRequest) -> CtlResponse {
|
||||
Err(e) => CtlResponse::error(e),
|
||||
}
|
||||
}
|
||||
CtlRequest::PlaceLocations { id } => match core.place_locations(id) {
|
||||
CtlRequest::PlaceLocations { id } => match core.photos().place_locations(id) {
|
||||
Ok(items) => CtlResponse::PhotoLocations { items },
|
||||
Err(e) => CtlResponse::error(e),
|
||||
},
|
||||
CtlRequest::PhotosOnThisDay { limit } => {
|
||||
match core.photos_on_this_day(clamp_limit(limit), excluded) {
|
||||
match core
|
||||
.photos()
|
||||
.photos_on_this_day(clamp_limit(limit), excluded)
|
||||
{
|
||||
Ok(items) => CtlResponse::Photos {
|
||||
available: true,
|
||||
items,
|
||||
@@ -133,7 +139,7 @@ pub(super) fn answer(ask: &Ask<'_>, request: CtlRequest) -> CtlResponse {
|
||||
Err(e) => CtlResponse::error(e),
|
||||
}
|
||||
}
|
||||
CtlRequest::PhotoGroup { uid } => match core.photo_group(&uid) {
|
||||
CtlRequest::PhotoGroup { uid } => match core.photos().photo_group(&uid) {
|
||||
Ok(items) => CtlResponse::Photos {
|
||||
available: true,
|
||||
items,
|
||||
@@ -142,7 +148,7 @@ pub(super) fn answer(ask: &Ask<'_>, request: CtlRequest) -> CtlResponse {
|
||||
Err(e) => CtlResponse::error(e),
|
||||
},
|
||||
CtlRequest::SetPhotoFavorite { uid, favorite } => match parse_uid(&uid) {
|
||||
Some(node_uid) => match core.set_photo_favorite(&node_uid, favorite) {
|
||||
Some(node_uid) => match core.photos().set_photo_favorite(&node_uid, favorite) {
|
||||
Ok(()) => CtlResponse::Ok {
|
||||
message: if favorite {
|
||||
"added to favorites".to_string()
|
||||
@@ -154,7 +160,7 @@ pub(super) fn answer(ask: &Ask<'_>, request: CtlRequest) -> CtlResponse {
|
||||
},
|
||||
None => CtlResponse::error(CoreError::invalid(format!("invalid uid: {uid}"))),
|
||||
},
|
||||
CtlRequest::PhotoAlbums => match core.albums() {
|
||||
CtlRequest::PhotoAlbums => match core.photos().albums() {
|
||||
Ok(Some(items)) => CtlResponse::Albums {
|
||||
available: true,
|
||||
items,
|
||||
@@ -169,10 +175,10 @@ pub(super) fn answer(ask: &Ask<'_>, request: CtlRequest) -> CtlResponse {
|
||||
// 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 visibility
|
||||
.permits(&uid)
|
||||
.and_then(|()| core.album_photos(&album, offset, clamp_limit(limit), excluded))
|
||||
{
|
||||
Some(album) => match visibility.permits(&uid).and_then(|()| {
|
||||
core.photos()
|
||||
.album_photos(&album, offset, clamp_limit(limit), excluded)
|
||||
}) {
|
||||
Ok(items) => CtlResponse::Photos {
|
||||
available: true,
|
||||
items,
|
||||
@@ -182,12 +188,12 @@ pub(super) fn answer(ask: &Ask<'_>, request: CtlRequest) -> CtlResponse {
|
||||
},
|
||||
None => CtlResponse::error(CoreError::invalid(format!("bad album uid: {uid}"))),
|
||||
},
|
||||
CtlRequest::CreateAlbum { name } => match core.create_album(&name) {
|
||||
CtlRequest::CreateAlbum { name } => match core.photos().create_album(&name) {
|
||||
Ok(uid) => CtlResponse::AlbumCreated { uid },
|
||||
Err(e) => CtlResponse::error(e),
|
||||
},
|
||||
CtlRequest::RenameAlbum { uid, name } => match parse_uid(&uid) {
|
||||
Some(album) => match core.rename_album(&album, &name) {
|
||||
Some(album) => match core.photos().rename_album(&album, &name) {
|
||||
Ok(()) => CtlResponse::Ok {
|
||||
message: format!("renamed album to {name}"),
|
||||
},
|
||||
@@ -196,7 +202,7 @@ pub(super) fn answer(ask: &Ask<'_>, request: CtlRequest) -> CtlResponse {
|
||||
None => CtlResponse::error(CoreError::invalid(format!("bad album uid: {uid}"))),
|
||||
},
|
||||
CtlRequest::DeleteAlbum { uid, delete_photos } => match parse_uid(&uid) {
|
||||
Some(album) => match core.delete_album(&album, delete_photos) {
|
||||
Some(album) => match core.photos().delete_album(&album, delete_photos) {
|
||||
Ok(()) => CtlResponse::Ok {
|
||||
message: "album deleted".to_string(),
|
||||
},
|
||||
@@ -205,11 +211,11 @@ pub(super) fn answer(ask: &Ask<'_>, request: CtlRequest) -> CtlResponse {
|
||||
None => CtlResponse::error(CoreError::invalid(format!("bad album uid: {uid}"))),
|
||||
},
|
||||
CtlRequest::AddToAlbum { uid, photos } => album_change(&uid, &photos, |album, photos| {
|
||||
core.add_to_album(album, photos)
|
||||
core.photos().add_to_album(album, photos)
|
||||
}),
|
||||
CtlRequest::RemoveFromAlbum { uid, photos } => {
|
||||
album_change(&uid, &photos, |album, photos| {
|
||||
core.remove_from_album(album, photos)
|
||||
core.photos().remove_from_album(album, photos)
|
||||
})
|
||||
}
|
||||
CtlRequest::PhotoPresence { uid, album } => match core.cached_gallery_visibility() {
|
||||
@@ -235,42 +241,45 @@ pub(super) fn answer(ask: &Ask<'_>, request: CtlRequest) -> CtlResponse {
|
||||
.filter_map(|u| parse_uid(u))
|
||||
.collect();
|
||||
CtlResponse::Thumbs {
|
||||
items: core.photo_thumbs(&parsed),
|
||||
items: core.photos().photo_thumbs(&parsed),
|
||||
}
|
||||
}
|
||||
CtlRequest::FileThumbs { items, generation } => {
|
||||
match core.file_thumbs(&items, generation) {
|
||||
match core.photos().file_thumbs(&items, generation) {
|
||||
Some(items) => CtlResponse::Thumbs { items },
|
||||
None => CtlResponse::FileThumbsStale,
|
||||
}
|
||||
}
|
||||
CtlRequest::ReserveFileThumbGeneration => CtlResponse::FileThumbGeneration {
|
||||
generation: core.reserve_file_thumb_generation(),
|
||||
generation: core.photos().reserve_file_thumb_generation(),
|
||||
},
|
||||
CtlRequest::CancelFileThumbs { generation } => {
|
||||
core.cancel_file_thumbs(generation);
|
||||
core.photos().cancel_file_thumbs(generation);
|
||||
CtlResponse::Ok {
|
||||
message: "thumbnail requests cancelled".to_string(),
|
||||
}
|
||||
}
|
||||
CtlRequest::StartThumbnailBuild { path } => match rel_to_mount(mountpoint, &path) {
|
||||
Ok(rel) => match core.start_thumbnail_build(rel) {
|
||||
Ok(rel) => match core.photos().start_thumbnail_build(rel) {
|
||||
Ok(status) => CtlResponse::ThumbnailBuild { status },
|
||||
Err(error) => CtlResponse::error(error),
|
||||
},
|
||||
Err(error) => CtlResponse::error(error),
|
||||
},
|
||||
CtlRequest::CancelThumbnailBuild => CtlResponse::ThumbnailBuild {
|
||||
status: core.cancel_thumbnail_build(),
|
||||
status: core.photos().cancel_thumbnail_build(),
|
||||
},
|
||||
CtlRequest::ThumbnailBuildStatus => CtlResponse::ThumbnailBuild {
|
||||
status: core.thumbnail_build_status(),
|
||||
status: core.photos().thumbnail_build_status(),
|
||||
},
|
||||
CtlRequest::PhotosRefreshStatus => CtlResponse::PhotosRefresh {
|
||||
running: core.timeline_refreshing(),
|
||||
running: core.photos().timeline_refreshing(),
|
||||
},
|
||||
CtlRequest::OpenPhoto { uid } => match parse_uid(&uid) {
|
||||
Some(u) => match visibility.permits(&uid).and_then(|()| core.open_photo(&u)) {
|
||||
Some(u) => match visibility
|
||||
.permits(&uid)
|
||||
.and_then(|()| core.photos().open_photo(&u))
|
||||
{
|
||||
Ok(p) => CtlResponse::FilePath {
|
||||
path: p.display().to_string(),
|
||||
},
|
||||
@@ -319,7 +328,7 @@ pub(super) fn answer(ask: &Ask<'_>, request: CtlRequest) -> CtlResponse {
|
||||
}
|
||||
}
|
||||
CtlRequest::ImportStatus => {
|
||||
let report = crate::takeout::import_status();
|
||||
let report = crate::photos::takeout::import_status();
|
||||
CtlResponse::ImportStatus {
|
||||
running: report.running,
|
||||
summary: report.summary,
|
||||
@@ -327,12 +336,12 @@ pub(super) fn answer(ask: &Ask<'_>, request: CtlRequest) -> CtlResponse {
|
||||
resumable: report.resumable,
|
||||
}
|
||||
}
|
||||
CtlRequest::ResumeImport => match crate::takeout::resumable_archives() {
|
||||
CtlRequest::ResumeImport => match crate::photos::takeout::resumable_archives() {
|
||||
None => CtlResponse::error(CoreError::not_found("there is no import to resume")),
|
||||
Some(paths) => start_takeout_import(core, paths, false),
|
||||
},
|
||||
CtlRequest::CancelImport => {
|
||||
if crate::takeout::cancel_import() {
|
||||
if crate::photos::takeout::cancel_import() {
|
||||
CtlResponse::Ok {
|
||||
message: "stopping the import".to_string(),
|
||||
}
|
||||
@@ -344,7 +353,7 @@ pub(super) fn answer(ask: &Ask<'_>, request: CtlRequest) -> CtlResponse {
|
||||
dry_run,
|
||||
limit,
|
||||
range,
|
||||
} => match core.spawn_redate(dry_run, limit, range) {
|
||||
} => match core.photos().spawn_redate(dry_run, limit, range) {
|
||||
Ok(()) => CtlResponse::Ok {
|
||||
message: if dry_run {
|
||||
"checking photo dates".to_string()
|
||||
@@ -355,11 +364,11 @@ pub(super) fn answer(ask: &Ask<'_>, request: CtlRequest) -> CtlResponse {
|
||||
Err(e) => CtlResponse::error(e),
|
||||
},
|
||||
CtlRequest::RedateStatus => {
|
||||
let (running, summary) = crate::redate::redate_status();
|
||||
let (running, summary) = crate::photos::redate::redate_status();
|
||||
CtlResponse::RedateStatus { running, summary }
|
||||
}
|
||||
CtlRequest::CancelRedate => {
|
||||
if crate::redate::cancel_redate() {
|
||||
if crate::photos::redate::cancel_redate() {
|
||||
CtlResponse::Ok {
|
||||
message: "stopping the re-date".to_string(),
|
||||
}
|
||||
@@ -383,7 +392,7 @@ pub(super) fn answer(ask: &Ask<'_>, request: CtlRequest) -> CtlResponse {
|
||||
"cannot read {source_path}: {e}"
|
||||
))),
|
||||
Ok((file, len)) => {
|
||||
let photos = core.photos();
|
||||
let photos = core.photos_api();
|
||||
// Unless the caller knows better: the photo's own EXIF,
|
||||
// then the file's modification time, which a copy resets.
|
||||
let capture_time = capture_time.or_else(|| {
|
||||
@@ -401,7 +410,9 @@ pub(super) fn answer(ask: &Ask<'_>, request: CtlRequest) -> CtlResponse {
|
||||
.and_then(pdfs_core::timestamp::modification_time),
|
||||
..Default::default()
|
||||
};
|
||||
let thumbnails = core.upload_thumbnails(Path::new(&source_path), &name);
|
||||
let thumbnails = core
|
||||
.photos()
|
||||
.upload_thumbnails(Path::new(&source_path), &name);
|
||||
let guard =
|
||||
core.transfers
|
||||
.begin(name.clone(), "", TransferDirection::Upload, len);
|
||||
@@ -421,7 +432,7 @@ pub(super) fn answer(ask: &Ask<'_>, request: CtlRequest) -> CtlResponse {
|
||||
// reply lands — so refresh now rather than leaving it to a
|
||||
// background pass that would land just after that reload.
|
||||
core.invalidate_photos();
|
||||
if let Err(e) = core.refresh_timeline_joined() {
|
||||
if let Err(e) = core.photos().refresh_timeline_joined() {
|
||||
warn!(error = %e, "timeline refresh after upload failed");
|
||||
}
|
||||
CtlResponse::Ok {
|
||||
|
||||
@@ -19,83 +19,104 @@ macro_rules! request {
|
||||
}
|
||||
pub(super) use request;
|
||||
|
||||
/// The file a request is about, and how the activity feed names it: the file
|
||||
/// name under the mount, or the uid.
|
||||
struct Target {
|
||||
uid: NodeUid,
|
||||
name: String,
|
||||
}
|
||||
|
||||
impl Target {
|
||||
fn path(core: &Core, rel: &Path) -> CoreResult<Self> {
|
||||
let (_ino, uid) = core.resolve(rel)?;
|
||||
let name = rel
|
||||
.file_name()
|
||||
.map(|n| n.to_string_lossy().into_owned())
|
||||
.unwrap_or_else(|| uid.to_string());
|
||||
Ok(Self { uid, name })
|
||||
}
|
||||
|
||||
fn uid(core: &Core, uid: &str) -> CoreResult<Self> {
|
||||
let uid = core.resolve_anywhere(uid)?;
|
||||
let name = uid.to_string();
|
||||
Ok(Self { uid, name })
|
||||
}
|
||||
}
|
||||
|
||||
/// Answer a request that [`request!`] matches.
|
||||
pub(super) fn answer(ask: &Ask<'_>, request: CtlRequest) -> CtlResponse {
|
||||
let Ask {
|
||||
core, mountpoint, ..
|
||||
} = *ask;
|
||||
let revisions = core.revisions();
|
||||
let at = |path: &str| rel_to_mount(mountpoint, path);
|
||||
let reply = |result: CoreResult<String>| match result {
|
||||
Ok(message) => CtlResponse::Ok { message },
|
||||
Err(e) => CtlResponse::error(e),
|
||||
};
|
||||
match request {
|
||||
CtlRequest::ListRevisions { path } => match rel_to_mount(mountpoint, &path) {
|
||||
Ok(rel) => match core.list_revisions(&rel) {
|
||||
Ok(items) => CtlResponse::Revisions { items },
|
||||
Err(e) => CtlResponse::error(e),
|
||||
},
|
||||
Err(e) => CtlResponse::error(e),
|
||||
},
|
||||
CtlRequest::ListRevisionsByUid { uid } => match core.list_revisions_by_uid(&uid) {
|
||||
Ok(items) => CtlResponse::Revisions { items },
|
||||
Err(e) => CtlResponse::error(e),
|
||||
},
|
||||
CtlRequest::RestoreRevision { path, revision_id } => {
|
||||
match rel_to_mount(mountpoint, &path) {
|
||||
Ok(rel) => match core.restore_revision(&rel, &revision_id) {
|
||||
Ok(()) => CtlResponse::Ok {
|
||||
message: format!("restoring version {revision_id} of {path}"),
|
||||
},
|
||||
Err(e) => CtlResponse::error(e),
|
||||
},
|
||||
CtlRequest::ListRevisions { path } => {
|
||||
match at(&path).and_then(|rel| Target::path(core, &rel)) {
|
||||
Ok(file) => listed(revisions.list(&file.uid)),
|
||||
Err(e) => CtlResponse::error(e),
|
||||
}
|
||||
}
|
||||
CtlRequest::ListRevisionsByUid { uid } => match Target::uid(core, &uid) {
|
||||
Ok(file) => listed(revisions.list(&file.uid)),
|
||||
Err(e) => CtlResponse::error(e),
|
||||
},
|
||||
CtlRequest::RestoreRevision { path, revision_id } => reply(at(&path).and_then(|rel| {
|
||||
let file = Target::path(core, &rel)?;
|
||||
revisions.restore(&file.uid, &revision_id, &file.name)?;
|
||||
// The size and mtime a listing shows describe the revision that
|
||||
// was active a moment ago.
|
||||
core.invalidate_parent_listing(&rel);
|
||||
Ok(format!("restoring version {revision_id} of {path}"))
|
||||
})),
|
||||
CtlRequest::RestoreRevisionByUid { uid, revision_id } => {
|
||||
match core.restore_revision_by_uid(&uid, &revision_id) {
|
||||
Ok(()) => CtlResponse::Ok {
|
||||
message: format!("restoring version {revision_id}"),
|
||||
},
|
||||
Err(e) => CtlResponse::error(e),
|
||||
}
|
||||
reply(Target::uid(core, &uid).and_then(|file| {
|
||||
revisions.restore(&file.uid, &revision_id, &file.name)?;
|
||||
Ok(format!("restoring version {revision_id}"))
|
||||
}))
|
||||
}
|
||||
CtlRequest::DeleteRevision { path, revision_id } => match rel_to_mount(mountpoint, &path) {
|
||||
Ok(rel) => match core.delete_revision(&rel, &revision_id) {
|
||||
Ok(()) => CtlResponse::Ok {
|
||||
message: format!("deleted version {revision_id} of {path}"),
|
||||
},
|
||||
Err(e) => CtlResponse::error(e),
|
||||
},
|
||||
Err(e) => CtlResponse::error(e),
|
||||
},
|
||||
CtlRequest::DeleteRevision { path, revision_id } => reply(at(&path).and_then(|rel| {
|
||||
let file = Target::path(core, &rel)?;
|
||||
revisions.delete(&file.uid, &revision_id, &file.name)?;
|
||||
Ok(format!("deleted version {revision_id} of {path}"))
|
||||
})),
|
||||
CtlRequest::DeleteRevisionByUid { uid, revision_id } => {
|
||||
match core.delete_revision_by_uid(&uid, &revision_id) {
|
||||
Ok(()) => CtlResponse::Ok {
|
||||
message: format!("deleted version {revision_id}"),
|
||||
},
|
||||
Err(e) => CtlResponse::error(e),
|
||||
}
|
||||
reply(Target::uid(core, &uid).and_then(|file| {
|
||||
revisions.delete(&file.uid, &revision_id, &file.name)?;
|
||||
Ok(format!("deleted version {revision_id}"))
|
||||
}))
|
||||
}
|
||||
CtlRequest::SaveRevisionAs {
|
||||
path,
|
||||
revision_id,
|
||||
dest,
|
||||
} => match rel_to_mount(mountpoint, &path) {
|
||||
Ok(rel) => match core.save_revision_as(&rel, &revision_id, Path::new(&dest)) {
|
||||
Ok(written) => CtlResponse::Ok {
|
||||
message: format!("wrote {} to {dest}", human_bytes(written)),
|
||||
},
|
||||
Err(e) => CtlResponse::error(e),
|
||||
},
|
||||
Err(e) => CtlResponse::error(e),
|
||||
},
|
||||
} => reply(at(&path).and_then(|rel| {
|
||||
let file = Target::path(core, &rel)?;
|
||||
let written =
|
||||
revisions.save_as(&file.uid, &revision_id, &file.name, Path::new(&dest))?;
|
||||
Ok(format!("wrote {} to {dest}", human_bytes(written)))
|
||||
})),
|
||||
CtlRequest::SaveRevisionAsByUid {
|
||||
uid,
|
||||
revision_id,
|
||||
dest,
|
||||
} => match core.save_revision_as_by_uid(&uid, &revision_id, Path::new(&dest)) {
|
||||
Ok(written) => CtlResponse::Ok {
|
||||
message: format!("wrote {} to {dest}", human_bytes(written)),
|
||||
},
|
||||
Err(e) => CtlResponse::error(e),
|
||||
},
|
||||
} => reply(Target::uid(core, &uid).and_then(|file| {
|
||||
let written =
|
||||
revisions.save_as(&file.uid, &revision_id, &file.name, Path::new(&dest))?;
|
||||
Ok(format!("wrote {} to {dest}", human_bytes(written)))
|
||||
})),
|
||||
// `control` only hands over what `request!` matches.
|
||||
_ => CtlResponse::error(CoreError::internal("not a revisions request".to_string())),
|
||||
}
|
||||
}
|
||||
|
||||
fn listed(result: CoreResult<Vec<pdfs_core::control::RevisionInfo>>) -> CtlResponse {
|
||||
match result {
|
||||
Ok(items) => CtlResponse::Revisions { items },
|
||||
Err(e) => CtlResponse::error(e),
|
||||
}
|
||||
}
|
||||
@@ -24,15 +24,15 @@ pub(super) use request;
|
||||
pub(super) fn answer(ask: &Ask<'_>, request: CtlRequest) -> CtlResponse {
|
||||
let Ask { core, .. } = *ask;
|
||||
match request {
|
||||
CtlRequest::ListTrash => match core.list_trash() {
|
||||
CtlRequest::ListTrash => match core.trash().list_trash() {
|
||||
Ok(entries) => CtlResponse::Entries { entries },
|
||||
Err(e) => CtlResponse::error(e),
|
||||
},
|
||||
CtlRequest::ListTrashedFolder { uid } => match core.list_trashed_folder(&uid) {
|
||||
CtlRequest::ListTrashedFolder { uid } => match core.trash().list_trashed_folder(&uid) {
|
||||
Ok(entries) => CtlResponse::Entries { entries },
|
||||
Err(e) => CtlResponse::error(e),
|
||||
},
|
||||
CtlRequest::Restore { uids } => match core.restore(&uids) {
|
||||
CtlRequest::Restore { uids } => match core.trash().restore(&uids) {
|
||||
Ok(n) => {
|
||||
core.log_activity(ActivityKind::Restore, format!("{n} item(s)"), "", true);
|
||||
CtlResponse::Ok {
|
||||
@@ -41,7 +41,7 @@ pub(super) fn answer(ask: &Ask<'_>, request: CtlRequest) -> CtlResponse {
|
||||
}
|
||||
Err(e) => CtlResponse::error(e),
|
||||
},
|
||||
CtlRequest::DeleteForever { uids } => match core.delete_forever(&uids) {
|
||||
CtlRequest::DeleteForever { uids } => match core.trash().delete_forever(&uids) {
|
||||
Ok(n) => {
|
||||
core.log_activity(
|
||||
ActivityKind::DeleteForever,
|
||||
@@ -55,7 +55,7 @@ pub(super) fn answer(ask: &Ask<'_>, request: CtlRequest) -> CtlResponse {
|
||||
}
|
||||
Err(e) => CtlResponse::error(e),
|
||||
},
|
||||
CtlRequest::EmptyTrash => match core.empty_trash() {
|
||||
CtlRequest::EmptyTrash => match core.trash().empty_trash() {
|
||||
Ok(n) => {
|
||||
let items = if n == 1 {
|
||||
"1 item".to_string()
|
||||
|
||||
@@ -41,8 +41,8 @@ use proton_drive_rs::{Node, NodeKind};
|
||||
use tracing::{debug, error, info, warn};
|
||||
|
||||
use super::link::{self, is_network_error};
|
||||
use super::photos::sha1_of;
|
||||
use super::state::{Intervals, PendingRevision};
|
||||
use super::takeout::sha1_of;
|
||||
use super::transfers::CountingReader;
|
||||
use super::{
|
||||
Core, DRAIN_BACKOFF_MAX, DRAIN_BACKOFF_MIN, DRAIN_IDLE_POLL, DRAIN_REVISION_DEBOUNCE,
|
||||
|
||||
@@ -475,7 +475,7 @@ impl Core {
|
||||
// a newer blob by the time it is retried (`Core::adoptable_twin`).
|
||||
let sha = staged_sha1(Path::new(blob))?;
|
||||
self.db.note_create_sent(op.id, &sha)?;
|
||||
let thumbnails = self.upload_thumbnails(Path::new(blob), name);
|
||||
let thumbnails = self.photos().upload_thumbnails(Path::new(blob), name);
|
||||
let guard = self
|
||||
.transfers
|
||||
.begin(name, op.uid.clone(), TransferDirection::Upload, meta.len);
|
||||
|
||||
@@ -232,7 +232,7 @@ impl Core {
|
||||
}
|
||||
|
||||
let alt = conflict_name(&name, now_secs());
|
||||
let thumbnails = self.upload_thumbnails(blob, &alt);
|
||||
let thumbnails = self.photos().upload_thumbnails(blob, &alt);
|
||||
let guard =
|
||||
self.transfers
|
||||
.begin(&alt, meta.uid.clone(), TransferDirection::Upload, meta.len);
|
||||
@@ -377,7 +377,7 @@ impl Core {
|
||||
}
|
||||
|
||||
let name = self.node_name(&uid);
|
||||
let thumbnails = self.upload_thumbnails(&blob, &name);
|
||||
let thumbnails = self.photos().upload_thumbnails(&blob, &name);
|
||||
let guard =
|
||||
self.transfers
|
||||
.begin(&name, meta.uid.clone(), TransferDirection::Upload, meta.len);
|
||||
|
||||
@@ -82,7 +82,6 @@ use proton_drive_rs::{
|
||||
};
|
||||
|
||||
mod activity;
|
||||
mod albums;
|
||||
mod attach;
|
||||
mod background;
|
||||
mod conflicts;
|
||||
@@ -121,7 +120,6 @@ mod queue;
|
||||
mod quota;
|
||||
mod reads;
|
||||
mod recovery;
|
||||
mod redate;
|
||||
mod relocate;
|
||||
mod remote;
|
||||
mod requests;
|
||||
@@ -140,7 +138,6 @@ mod supervisor;
|
||||
mod sweep;
|
||||
mod sync;
|
||||
mod systemd;
|
||||
mod takeout;
|
||||
use pdfs_core::transfers;
|
||||
mod upload;
|
||||
mod r#virtual;
|
||||
@@ -587,7 +584,7 @@ struct Core {
|
||||
services: pdfs_core::lifecycle::ServiceBoard,
|
||||
/// Whether a trash refresh is running, and the wake-up for requests waiting
|
||||
/// on its progress.
|
||||
trash: trash::TrashState,
|
||||
trash_jobs: trash::TrashState,
|
||||
/// What the conflict sweep may do, and the copies it already checked this
|
||||
/// run.
|
||||
sweep: sweep::SweepState,
|
||||
@@ -1397,26 +1394,6 @@ impl Core {
|
||||
Ok(out.into_inner())
|
||||
}
|
||||
|
||||
/// Like [`download_file_tracked_to`] for a photo, streaming through the
|
||||
/// photos client's [`download_photo_to`].
|
||||
///
|
||||
/// [`download_file_tracked_to`]: Core::download_file_tracked_to
|
||||
/// [`download_photo_to`]: ProtonPhotosClient::download_photo_to
|
||||
fn download_photo_tracked(
|
||||
&self,
|
||||
photos: &ProtonPhotosClient,
|
||||
uid: &NodeUid,
|
||||
name: &str,
|
||||
total: u64,
|
||||
) -> std::result::Result<Vec<u8>, ProtonError> {
|
||||
let guard = self
|
||||
.transfers
|
||||
.begin(name, uid.to_string(), TransferDirection::Download, total);
|
||||
let mut out = CountingWriter::new(Vec::with_capacity(total as usize), &guard);
|
||||
self.rt.block_on(photos.download_photo_to(uid, &mut out))?;
|
||||
Ok(out.into_inner())
|
||||
}
|
||||
|
||||
/// Fetch a thumbnail of `ttype` for the file at `ino`, served from the cache
|
||||
/// when fresh and otherwise downloaded from the remote and cached. Returns
|
||||
/// `Ok(None)` when the node is not a file or has no thumbnail of that type.
|
||||
@@ -1476,7 +1453,7 @@ impl Core {
|
||||
/// reuses the daemon's single authenticated session rather than logging in
|
||||
/// again (Proton refresh tokens are single-use). Cheap — the Drive client
|
||||
/// is `Clone` over `Arc`-backed state.
|
||||
fn photos(&self) -> ProtonPhotosClient {
|
||||
fn photos_api(&self) -> ProtonPhotosClient {
|
||||
ProtonPhotosClient::from_drive_client(self.client.clone())
|
||||
}
|
||||
|
||||
|
||||
@@ -434,11 +434,17 @@ impl Core {
|
||||
///
|
||||
/// Metadata only: a thumbnail path is attached for photos whose thumbnail is
|
||||
/// already cached, and nothing is downloaded here — the front-end pulls the
|
||||
/// thumbnails it actually paints via [`Core::photo_thumbs`].
|
||||
/// thumbnails it actually paints via [`Photos::photo_thumbs`](crate::photos::Photos::photo_thumbs).
|
||||
pub(super) fn listing_stale(&self, key: &str, ttl: Duration) -> bool {
|
||||
match self.db.state_i64(key).ok().flatten() {
|
||||
Some(ms) => now_ms().saturating_sub(ms) >= ttl.as_millis() as i64,
|
||||
None => true,
|
||||
}
|
||||
listing_stale(&self.db, key, ttl)
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether the listing stamped under `key` is older than `ttl`, or was never
|
||||
/// stamped.
|
||||
pub(crate) fn listing_stale(db: &Db, key: &str, ttl: Duration) -> bool {
|
||||
match db.state_i64(key).ok().flatten() {
|
||||
Some(ms) => now_ms().saturating_sub(ms) >= ttl.as_millis() as i64,
|
||||
None => true,
|
||||
}
|
||||
}
|
||||
@@ -542,7 +542,7 @@ pub(crate) fn mount_with(
|
||||
drain: super::drain::DrainState::new(),
|
||||
pin_work: Arc::new(Mutex::new(Default::default())),
|
||||
sizes: super::sizes::SizeState::new(),
|
||||
trash: super::trash::TrashState::new(),
|
||||
trash_jobs: super::trash::TrashState::new(),
|
||||
shared: super::shared::SharedState::new(),
|
||||
quota: super::quota::QuotaCache::new(),
|
||||
sharing,
|
||||
|
||||
@@ -31,11 +31,20 @@ use proton_drive_rs::proton_sdk::ids::NodeUid;
|
||||
use proton_drive_rs::{NodeKind, PhotoTag, PhotoTagsUpdate, Thumbnail, ThumbnailType};
|
||||
use tracing::{debug, info, warn};
|
||||
|
||||
use super::drive::RevisionRead;
|
||||
use super::ContentCache;
|
||||
use super::drive::{DriveApi, RevisionRead};
|
||||
use super::events::EventHub;
|
||||
use super::shutdown::Shutdown;
|
||||
use super::transfers::{CountingWriter, TransferRegistry};
|
||||
use super::{
|
||||
Core, PHOTOS_AVAILABLE, PHOTOS_SYNCED_MS, TIMELINE_ENRICH_CHUNK, ThumbnailMissCaches,
|
||||
WriteAuthority, link, node_size, now_ms, parse_uid,
|
||||
};
|
||||
use pdfs_core::control::TransferDirection;
|
||||
use pdfs_core::control::{ActivityKind, DirEntry};
|
||||
use pdfs_core::lifecycle::ServiceBoard;
|
||||
use proton_drive_rs::proton_sdk::error::ProtonError;
|
||||
use proton_drive_rs::{ProtonDriveClient, ProtonPhotosClient};
|
||||
|
||||
/// Longest edge, in px, of a thumbnail generated locally for a photo the server
|
||||
/// has none for. Matches the server's own thumbnail scale closely enough that a
|
||||
@@ -129,8 +138,107 @@ const DECODE_BUDGET_BYTES: u64 = 512 * 1024 * 1024;
|
||||
/// The process-wide [`DecodeBudget`] every thumbnail decode draws from.
|
||||
static DECODE_BUDGET: DecodeBudget = DecodeBudget::new(DECODE_BUDGET_BYTES);
|
||||
|
||||
mod albums;
|
||||
pub(crate) mod redate;
|
||||
pub(crate) mod takeout;
|
||||
pub(crate) use albums::AlbumOutcome;
|
||||
pub(crate) use takeout::sha1_of;
|
||||
mod thumbs;
|
||||
mod timeline;
|
||||
mod trash;
|
||||
|
||||
/// The Photos service: the timeline, albums and thumbnails.
|
||||
///
|
||||
/// It holds only the handles it calls, and reaches the filesystem through
|
||||
/// [`PhotosHost`], so it does not depend on [`Core`]. [`Core::photos`] builds
|
||||
/// one on demand, the same way [`Core::syncer`] builds the sync engine. A clone
|
||||
/// shares everything, which is how a refresh or a thumbnail job moves onto a
|
||||
/// background task.
|
||||
#[derive(Clone)]
|
||||
pub(crate) struct Photos {
|
||||
client: ProtonDriveClient,
|
||||
drive: Arc<dyn DriveApi>,
|
||||
rt: tokio::runtime::Handle,
|
||||
cache: Arc<ContentCache>,
|
||||
db: Arc<pdfs_store::db::Db>,
|
||||
shutdown: Arc<Shutdown>,
|
||||
services: ServiceBoard,
|
||||
events: Arc<EventHub>,
|
||||
transfers: Arc<TransferRegistry>,
|
||||
jobs: PhotoJobs,
|
||||
host: Arc<dyn PhotosHost>,
|
||||
}
|
||||
|
||||
/// What the Photos service needs from the filesystem.
|
||||
pub(crate) trait PhotosHost: Send + Sync {
|
||||
/// List a folder of the mount, for the recursive thumbnail build.
|
||||
fn list_dir(&self, rel: &Path) -> CoreResult<Vec<DirEntry>>;
|
||||
/// Record a change this daemon made, so its echo in the event feed is not
|
||||
/// taken for a remote edit.
|
||||
fn note_self_change(&self, uid: &NodeUid);
|
||||
/// Add an entry to the activity log.
|
||||
fn log_activity(&self, kind: ActivityKind, target: String, detail: String, ok: bool);
|
||||
}
|
||||
|
||||
impl PhotosHost for Core {
|
||||
fn list_dir(&self, rel: &Path) -> CoreResult<Vec<DirEntry>> {
|
||||
Core::list_dir(self, rel)
|
||||
}
|
||||
|
||||
fn note_self_change(&self, uid: &NodeUid) {
|
||||
Core::note_self_change(self, uid)
|
||||
}
|
||||
|
||||
fn log_activity(&self, kind: ActivityKind, target: String, detail: String, ok: bool) {
|
||||
Core::log_activity(self, kind, target, detail, ok);
|
||||
}
|
||||
}
|
||||
|
||||
impl Core {
|
||||
/// The Photos service, with this daemon as its host.
|
||||
pub(crate) fn photos(&self) -> Photos {
|
||||
Photos {
|
||||
client: self.client.clone(),
|
||||
drive: self.drive.clone(),
|
||||
rt: self.rt.clone(),
|
||||
cache: self.cache.clone(),
|
||||
db: self.db.clone(),
|
||||
shutdown: self.shutdown.clone(),
|
||||
services: self.services.clone(),
|
||||
events: self.events.clone(),
|
||||
transfers: self.transfers.clone(),
|
||||
jobs: self.photo_jobs.clone(),
|
||||
host: Arc::new(self.clone()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Photos {
|
||||
/// The Photos API over the daemon's single authenticated session.
|
||||
fn photos_api(&self) -> ProtonPhotosClient {
|
||||
ProtonPhotosClient::from_drive_client(self.client.clone())
|
||||
}
|
||||
|
||||
/// Like [`download_file_tracked_to`] for a photo, streaming through the
|
||||
/// photos client's [`download_photo_to`].
|
||||
///
|
||||
/// [`download_file_tracked_to`]: crate::Core::download_file_tracked_to
|
||||
/// [`download_photo_to`]: ProtonPhotosClient::download_photo_to
|
||||
fn download_photo_tracked(
|
||||
&self,
|
||||
photos: &ProtonPhotosClient,
|
||||
uid: &NodeUid,
|
||||
name: &str,
|
||||
total: u64,
|
||||
) -> std::result::Result<Vec<u8>, ProtonError> {
|
||||
let guard = self
|
||||
.transfers
|
||||
.begin(name, uid.to_string(), TransferDirection::Download, total);
|
||||
let mut out = CountingWriter::new(Vec::with_capacity(total as usize), &guard);
|
||||
self.rt.block_on(photos.download_photo_to(uid, &mut out))?;
|
||||
Ok(out.into_inner())
|
||||
}
|
||||
}
|
||||
|
||||
/// What the Photos and thumbnail jobs are doing right now: which refreshes
|
||||
/// and builds are running, how far they got, and which thumbnails are known
|
||||
@@ -149,7 +257,7 @@ pub(crate) struct PhotoJobs {
|
||||
/// The same, for the album listing.
|
||||
pub(crate) albums_refreshing: Arc<AtomicBool>,
|
||||
/// True while the similar-photo pass hashes thumbnails (see
|
||||
/// [`Core::photo_similar`]), so asking again doesn't start a second one.
|
||||
/// [`Photos::photo_similar`]), so asking again doesn't start a second one.
|
||||
pub(crate) similar_hashing: Arc<AtomicBool>,
|
||||
/// Photos whose missing thumbnail is being generated right now. A tile that is
|
||||
/// still on screen asks for its thumbnail again every few seconds, and each of
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
//!
|
||||
//! Both are persisted projections of what the photos volume reports, refreshed
|
||||
//! on the same stale-while-serving rule as the timeline
|
||||
//! ([`crate::photos`]): a listing already on disk is served immediately and
|
||||
//! ([`super`]): a listing already on disk is served immediately and
|
||||
//! refreshed behind the caller, and only an empty one waits on the network.
|
||||
//!
|
||||
//! An album is a folder node carrying album properties, so it has a name like
|
||||
@@ -23,15 +23,16 @@ use proton_drive_rs::NodeKind;
|
||||
use proton_drive_rs::proton_sdk::ids::NodeUid;
|
||||
use tracing::warn;
|
||||
|
||||
use super::{
|
||||
ALBUM_SYNCED_PREFIX, ALBUMS_SYNCED_MS, Core, PHOTOS_AVAILABLE, TIMELINE_ENRICH_CHUNK,
|
||||
TIMELINE_TTL, link, now_ms, parse_uid,
|
||||
use super::Photos;
|
||||
use crate::{
|
||||
ALBUM_SYNCED_PREFIX, ALBUMS_SYNCED_MS, PHOTOS_AVAILABLE, TIMELINE_ENRICH_CHUNK, TIMELINE_TTL,
|
||||
link, listing::listing_stale, now_ms, parse_uid,
|
||||
};
|
||||
|
||||
impl Core {
|
||||
impl Photos {
|
||||
/// The album listing, served from disk and refreshed behind the caller when
|
||||
/// stale. `None` means the account has no photos volume — the same signal
|
||||
/// [`Core::photos_timeline`] gives.
|
||||
/// [`Photos::photos_timeline`] gives.
|
||||
pub(crate) fn albums(&self) -> CoreResult<Option<Vec<AlbumInfo>>> {
|
||||
let count = self.db.albums_count().map_err(CoreError::from)?;
|
||||
if count == 0
|
||||
@@ -44,13 +45,13 @@ impl Core {
|
||||
// Nothing on disk, so this one request waits for the fetch — unless
|
||||
// the account is already known to have no photos volume.
|
||||
let known_empty = self.db.state_i64(PHOTOS_AVAILABLE).ok().flatten() == Some(0);
|
||||
if known_empty && !self.listing_stale(ALBUMS_SYNCED_MS, TIMELINE_TTL) {
|
||||
if known_empty && !listing_stale(&self.db, ALBUMS_SYNCED_MS, TIMELINE_TTL) {
|
||||
return Ok(None);
|
||||
}
|
||||
if !self.rt.block_on(self.refresh_albums())? {
|
||||
return Ok(None);
|
||||
}
|
||||
} else if self.listing_stale(ALBUMS_SYNCED_MS, TIMELINE_TTL) {
|
||||
} else if listing_stale(&self.db, ALBUMS_SYNCED_MS, TIMELINE_TTL) {
|
||||
self.spawn_albums_refresh();
|
||||
}
|
||||
|
||||
@@ -66,7 +67,7 @@ impl Core {
|
||||
.db
|
||||
.photo_projection_generation()
|
||||
.map_err(CoreError::from)?;
|
||||
let photos = self.photos();
|
||||
let photos = self.photos_api();
|
||||
if link::bounded(photos.get_photos_root())
|
||||
.await
|
||||
.map_err(|e| CoreError::from_api(&e, "photos root"))?
|
||||
@@ -132,22 +133,16 @@ impl Core {
|
||||
|
||||
/// Refresh the album listing off the request path. At most one runs at a time.
|
||||
pub(crate) fn spawn_albums_refresh(&self) {
|
||||
if self
|
||||
.photo_jobs
|
||||
.albums_refreshing
|
||||
.swap(true, Ordering::SeqCst)
|
||||
{
|
||||
if self.jobs.albums_refreshing.swap(true, Ordering::SeqCst) {
|
||||
return;
|
||||
}
|
||||
let core = self.clone();
|
||||
let this = self.clone();
|
||||
self.services
|
||||
.spawn_task_job(&self.rt, "pdfs-albums-refresh", async move {
|
||||
let refreshed = core.refresh_albums().await;
|
||||
core.photo_jobs
|
||||
.albums_refreshing
|
||||
.store(false, Ordering::SeqCst);
|
||||
let refreshed = this.refresh_albums().await;
|
||||
this.jobs.albums_refreshing.store(false, Ordering::SeqCst);
|
||||
match refreshed {
|
||||
Ok(_) => core.events.publish(&[Topic::Photos]),
|
||||
Ok(_) => this.events.publish(&[Topic::Photos]),
|
||||
Err(e) => warn!(error = %e, "background album refresh failed"),
|
||||
}
|
||||
});
|
||||
@@ -177,12 +172,12 @@ impl Core {
|
||||
.is_none()
|
||||
{
|
||||
self.rt.block_on(self.refresh_album(album))?;
|
||||
} else if self.listing_stale(&stamp, TIMELINE_TTL) {
|
||||
let core = self.clone();
|
||||
} else if listing_stale(&self.db, &stamp, TIMELINE_TTL) {
|
||||
let this = self.clone();
|
||||
let album = album.clone();
|
||||
self.services
|
||||
.spawn_task_job(&self.rt, "pdfs-album-refresh", async move {
|
||||
if let Err(e) = core.refresh_album(&album).await {
|
||||
if let Err(e) = this.refresh_album(&album).await {
|
||||
warn!(%album, error = %e, "background album refresh failed");
|
||||
}
|
||||
});
|
||||
@@ -235,7 +230,7 @@ impl Core {
|
||||
.db
|
||||
.photo_projection_generation()
|
||||
.map_err(CoreError::from)?;
|
||||
let photos = self.photos();
|
||||
let photos = self.photos_api();
|
||||
let items = link::bounded(photos.enumerate_album(album))
|
||||
.await
|
||||
.map_err(|e| CoreError::from_api(&e, "album"))?;
|
||||
@@ -285,11 +280,11 @@ impl Core {
|
||||
}
|
||||
|
||||
/// Create an album and return its uid. The listing is refreshed before
|
||||
/// answering, so the next [`Core::albums`] already shows it.
|
||||
/// answering, so the next [`Photos::albums`] already shows it.
|
||||
pub(crate) fn create_album(&self, name: &str) -> CoreResult<String> {
|
||||
let uid = self
|
||||
.rt
|
||||
.block_on(self.photos().create_album(name))
|
||||
.block_on(self.photos_api().create_album(name))
|
||||
.map_err(|e| CoreError::from_api(&e, "create album"))?;
|
||||
self.after_album_change(None);
|
||||
Ok(uid.to_string())
|
||||
@@ -297,7 +292,7 @@ impl Core {
|
||||
|
||||
pub(crate) fn rename_album(&self, album: &NodeUid, name: &str) -> CoreResult<()> {
|
||||
self.rt
|
||||
.block_on(self.photos().rename_album(album, name))
|
||||
.block_on(self.photos_api().rename_album(album, name))
|
||||
.map_err(|e| CoreError::from_api(&e, "rename album"))?;
|
||||
self.after_album_change(None);
|
||||
Ok(())
|
||||
@@ -307,7 +302,7 @@ impl Core {
|
||||
/// which only matters for photos that exist in the album alone.
|
||||
pub(crate) fn delete_album(&self, album: &NodeUid, delete_photos: bool) -> CoreResult<()> {
|
||||
self.rt
|
||||
.block_on(self.photos().delete_album(album, delete_photos))
|
||||
.block_on(self.photos_api().delete_album(album, delete_photos))
|
||||
.map_err(|e| CoreError::from_api(&e, "delete album"))?;
|
||||
let key = album.to_string();
|
||||
if let Err(error) = self.db.photos_delete(&[key]) {
|
||||
@@ -325,7 +320,7 @@ impl Core {
|
||||
) -> CoreResult<AlbumOutcome> {
|
||||
let outcomes = self
|
||||
.rt
|
||||
.block_on(self.photos().add_photos_to_album(album, photos))
|
||||
.block_on(self.photos_api().add_photos_to_album(album, photos))
|
||||
.map_err(|e| CoreError::from_api(&e, "add to album"))?;
|
||||
self.after_album_change(Some(album));
|
||||
Ok(album_outcome(outcomes))
|
||||
@@ -340,7 +335,7 @@ impl Core {
|
||||
) -> CoreResult<AlbumOutcome> {
|
||||
let outcomes = self
|
||||
.rt
|
||||
.block_on(self.photos().remove_photos_from_album(album, photos))
|
||||
.block_on(self.photos_api().remove_photos_from_album(album, photos))
|
||||
.map_err(|e| CoreError::from_api(&e, "remove from album"))?;
|
||||
self.after_album_change(Some(album));
|
||||
Ok(album_outcome(outcomes))
|
||||
@@ -363,7 +358,7 @@ impl Core {
|
||||
}
|
||||
|
||||
/// Drop the album listing's and every album's freshness stamp, so the next
|
||||
/// request re-enumerates. Paired with [`Core::invalidate_photos`] — a change
|
||||
/// request re-enumerates. Paired with [`Core::invalidate_photos`](crate::Core::invalidate_photos) — a change
|
||||
/// to the timeline can just as easily be a change to an album.
|
||||
pub(crate) fn invalidate_albums(&self) {
|
||||
let _ = self.db.clear_state(ALBUMS_SYNCED_MS);
|
||||
@@ -27,7 +27,7 @@ use proton_drive_rs::proton_sdk::ids::NodeUid;
|
||||
use proton_drive_rs::{PhotoTag, PhotoTagsUpdate, PhotoUploadMetadata};
|
||||
use tracing::{info, warn};
|
||||
|
||||
use super::Core;
|
||||
use super::Photos;
|
||||
use crate::parse_uid as parse_node_uid;
|
||||
use crate::transfers::CountingReader;
|
||||
|
||||
@@ -84,7 +84,7 @@ struct Candidate {
|
||||
albums: Vec<String>,
|
||||
}
|
||||
|
||||
impl Core {
|
||||
impl Photos {
|
||||
/// Re-date mis-dated photos. Blocking; run on its own thread.
|
||||
///
|
||||
/// `cancel` stops the run at the next photo boundary. A photo is only ever
|
||||
@@ -184,7 +184,7 @@ impl Core {
|
||||
/// trash the original. Every earlier step failing leaves the account exactly
|
||||
/// as it was.
|
||||
fn redate_one(&self, candidate: &Candidate, summary: &mut RedateSummary) -> CoreResult<()> {
|
||||
let photos = self.photos();
|
||||
let photos = self.photos_api();
|
||||
let path = self.open_photo(&candidate.uid)?;
|
||||
let size = std::fs::metadata(&path)
|
||||
.map_err(|e| CoreError::internal(format!("stat {}: {e}", path.display())))?
|
||||
@@ -227,7 +227,7 @@ impl Core {
|
||||
match self.rt.block_on(photos.update_photos(&[update])) {
|
||||
// As in `set_photo_favorite`: claim our own echo, so the tag we
|
||||
// just set does not come back as a remote change.
|
||||
Ok(_) => self.note_self_change(&new_uid),
|
||||
Ok(_) => self.host.note_self_change(&new_uid),
|
||||
Err(e) => {
|
||||
warn!(name = candidate.name, error = %e, "cannot re-favorite re-dated photo")
|
||||
}
|
||||
@@ -287,9 +287,9 @@ impl Core {
|
||||
state.last = None;
|
||||
}
|
||||
|
||||
let core = self.clone();
|
||||
let this = self.clone();
|
||||
if let Err(error) = self.services.spawn_job("pdfs-redate", move || {
|
||||
let outcome = core.redate_photos(dry_run, limit, range, cancel);
|
||||
let outcome = this.redate_photos(dry_run, limit, range, cancel);
|
||||
let mut state = REDATE.lock();
|
||||
state.running = false;
|
||||
state.cancel = None;
|
||||
@@ -47,7 +47,7 @@ use tracing::{info, warn};
|
||||
|
||||
pub(crate) use pdfs_drive::digest::sha1_of;
|
||||
|
||||
use super::Core;
|
||||
use super::Photos;
|
||||
use crate::photos::can_make_thumbnail;
|
||||
use crate::transfers::CountingReader;
|
||||
|
||||
@@ -468,7 +468,7 @@ fn read_entry<R>(
|
||||
Ok(sink(&mut file))
|
||||
}
|
||||
|
||||
impl Core {
|
||||
impl Photos {
|
||||
/// Copy archive entry `entry` into the thumbnail staging folder and return
|
||||
/// its path. The caller removes it.
|
||||
fn stage_takeout_entry(
|
||||
@@ -611,7 +611,7 @@ impl Core {
|
||||
));
|
||||
}
|
||||
|
||||
let photos = self.photos();
|
||||
let photos = self.photos_api();
|
||||
if self
|
||||
.rt
|
||||
.block_on(photos.get_photos_root())
|
||||
@@ -668,7 +668,7 @@ impl Core {
|
||||
report: &Reporter,
|
||||
) -> CoreResult<()> {
|
||||
report.phase(ImportPhase::Checking, 0);
|
||||
let photos = self.photos();
|
||||
let photos = self.photos_api();
|
||||
let names: Vec<String> = planned.iter().map(|p| p.photo.name.clone()).collect();
|
||||
let collisions = self
|
||||
.rt
|
||||
@@ -919,7 +919,7 @@ impl Core {
|
||||
report.step();
|
||||
match done.result {
|
||||
Ok(uid) => {
|
||||
self.note_self_change(&uid);
|
||||
self.host.note_self_change(&uid);
|
||||
summary.uploaded += 1;
|
||||
summary.bytes += done.photo.size;
|
||||
if done.live {
|
||||
@@ -954,7 +954,7 @@ impl Core {
|
||||
tags: Vec<PhotoTag>,
|
||||
main_uid: Option<NodeUid>,
|
||||
) -> CoreResult<NodeUid> {
|
||||
let photos = self.photos();
|
||||
let photos = self.photos_api();
|
||||
let guard = self.transfers.begin(
|
||||
photo.name.clone(),
|
||||
"",
|
||||
@@ -1035,7 +1035,7 @@ impl Core {
|
||||
tags_to_remove: Vec::new(),
|
||||
})
|
||||
.collect();
|
||||
if let Err(e) = self.rt.block_on(self.photos().update_photos(&updates)) {
|
||||
if let Err(e) = self.rt.block_on(self.photos_api().update_photos(&updates)) {
|
||||
warn!(error = %e, "marking imported favorites failed");
|
||||
}
|
||||
}
|
||||
@@ -1049,7 +1049,7 @@ impl Core {
|
||||
summary: &mut ImportSummary,
|
||||
report: &Reporter,
|
||||
) -> CoreResult<()> {
|
||||
let photos = self.photos();
|
||||
let photos = self.photos_api();
|
||||
|
||||
// Existing albums by decrypted name, so a second import of the same
|
||||
// export adds to the album it made the first time instead of a twin.
|
||||
@@ -1152,14 +1152,14 @@ impl Core {
|
||||
state.save();
|
||||
}
|
||||
|
||||
let core = self.clone();
|
||||
let this = self.clone();
|
||||
if let Err(error) = self.services.spawn_job("pdfs-import", move || {
|
||||
// The job is dropped only after the final state is stored: the
|
||||
// job leaving the transfer snapshot is the front-ends' cue to ask
|
||||
// for the result, which must then be there.
|
||||
let job = core.transfers.begin_job("Importing Google Photos");
|
||||
let job = this.transfers.begin_job("Importing Google Photos");
|
||||
let run = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
|
||||
core.import_takeout(&archives, dry_run, &cancel, &job)
|
||||
this.import_takeout(&archives, dry_run, &cancel, &job)
|
||||
}));
|
||||
// A panic must not leave the import marked as running for the
|
||||
// life of the daemon, refusing every later one.
|
||||
@@ -1179,9 +1179,9 @@ impl Core {
|
||||
}
|
||||
drop(job);
|
||||
if !dry_run {
|
||||
core.log_activity(
|
||||
this.host.log_activity(
|
||||
ActivityKind::Upload,
|
||||
"Google Photos import",
|
||||
"Google Photos import".to_string(),
|
||||
activity_line(&summary),
|
||||
summary.complete(),
|
||||
);
|
||||
@@ -4,14 +4,14 @@
|
||||
|
||||
use super::*;
|
||||
|
||||
impl Core {
|
||||
impl Photos {
|
||||
/// [`upload_thumbnails`] for a file about to upload, staging any RAW copy
|
||||
/// under this cache. Blocking.
|
||||
pub(crate) fn upload_thumbnails(&self, path: &Path, name: &str) -> Vec<Thumbnail> {
|
||||
upload_thumbnails(path, name, self.cache.raw_thumbnail_staging_dir())
|
||||
}
|
||||
|
||||
/// [`Core::upload_thumbnails`] on the blocking pool, for async callers.
|
||||
/// [`Photos::upload_thumbnails`] on the blocking pool, for async callers.
|
||||
pub(crate) async fn upload_thumbnails_async(
|
||||
&self,
|
||||
path: PathBuf,
|
||||
@@ -26,7 +26,7 @@ impl Core {
|
||||
/// Thumbnails for `uids`, served from the cache, fetched from the server for
|
||||
/// whatever is missing, and — for the photos the server has no thumbnail for
|
||||
/// at all — *generated locally* from the full file (see
|
||||
/// [`Core::generate_thumbs`]). Requested on demand as tiles scroll into view,
|
||||
/// [`Photos::generate_thumbs`]). Requested on demand as tiles scroll into view,
|
||||
/// so a cold timeline paints immediately and only the photos actually on
|
||||
/// screen cost a round-trip.
|
||||
///
|
||||
@@ -41,7 +41,7 @@ impl Core {
|
||||
self.photo_thumbs_with(requested, true)
|
||||
}
|
||||
|
||||
/// [`Core::photo_thumbs`], with local generation only when `generate` is
|
||||
/// [`Photos::photo_thumbs`], with local generation only when `generate` is
|
||||
/// set. Without it, a photo the server has no thumbnail for is left
|
||||
/// without one rather than downloaded whole.
|
||||
pub(crate) fn photo_thumbs_with(
|
||||
@@ -117,7 +117,7 @@ impl Core {
|
||||
if !want.is_empty() {
|
||||
let mut missing = want.clone();
|
||||
match self.rt.block_on(
|
||||
self.photos()
|
||||
self.photos_api()
|
||||
.enumerate_thumbnails(&want, ThumbnailType::Thumbnail),
|
||||
) {
|
||||
Ok(thumbs) => {
|
||||
@@ -154,7 +154,7 @@ impl Core {
|
||||
}
|
||||
}
|
||||
|
||||
let pending = self.photo_jobs.thumb_gen.lock();
|
||||
let pending = self.jobs.thumb_gen.lock();
|
||||
requested
|
||||
.iter()
|
||||
.zip(uids)
|
||||
@@ -197,7 +197,7 @@ impl Core {
|
||||
}
|
||||
|
||||
/// Thumbnails for image files shown by the regular file browser, Shared and
|
||||
/// Trash pages. Unlike [`Core::photo_thumbs`], these nodes need not be in the
|
||||
/// Trash pages. Unlike [`Photos::photo_thumbs`], these nodes need not be in the
|
||||
/// Photos timeline: the request supplies each file's modification time as
|
||||
/// the cache validity tag.
|
||||
pub(crate) fn file_thumbs(
|
||||
@@ -205,8 +205,8 @@ impl Core {
|
||||
items: &[FileThumbRequest],
|
||||
generation: u64,
|
||||
) -> Option<Vec<PhotoThumb>> {
|
||||
let current = generation != 0
|
||||
&& self.photo_jobs.file_thumb_generation.load(Ordering::SeqCst) == generation;
|
||||
let current =
|
||||
generation != 0 && self.jobs.file_thumb_generation.load(Ordering::SeqCst) == generation;
|
||||
if !current {
|
||||
return None;
|
||||
}
|
||||
@@ -238,7 +238,7 @@ impl Core {
|
||||
.cached_thumbnail_path(uid, ttype, *modified)
|
||||
.is_some()
|
||||
|| self
|
||||
.photo_jobs
|
||||
.jobs
|
||||
.thumbnail_misses
|
||||
.lock()
|
||||
.local_contains(&(uid.clone(), ttype), *modified)
|
||||
@@ -253,7 +253,7 @@ impl Core {
|
||||
self.spawn_generate_thumbs(wanted, &tags, &names, ThumbJob::Files(generation));
|
||||
}
|
||||
|
||||
let pending = self.photo_jobs.thumb_gen.lock();
|
||||
let pending = self.jobs.thumb_gen.lock();
|
||||
Some(
|
||||
items
|
||||
.iter()
|
||||
@@ -279,14 +279,14 @@ impl Core {
|
||||
pub(crate) fn reserve_file_thumb_generation(&self) -> u64 {
|
||||
let next = |current| if current == u64::MAX { 1 } else { current + 1 };
|
||||
let previous = self
|
||||
.photo_jobs
|
||||
.jobs
|
||||
.file_thumb_generation
|
||||
.try_update(Ordering::SeqCst, Ordering::SeqCst, |current| {
|
||||
Some(next(current))
|
||||
})
|
||||
.expect("generation update always succeeds");
|
||||
let generation = next(previous);
|
||||
self.photo_jobs.file_thumb_cancel.notify_waiters();
|
||||
self.jobs.file_thumb_cancel.notify_waiters();
|
||||
generation
|
||||
}
|
||||
|
||||
@@ -295,11 +295,11 @@ impl Core {
|
||||
/// recursive builds do not use this generation and continue normally.
|
||||
pub(crate) fn cancel_file_thumbs(&self, generation: u64) {
|
||||
let previous = self
|
||||
.photo_jobs
|
||||
.jobs
|
||||
.file_thumb_generation
|
||||
.fetch_max(generation, Ordering::SeqCst);
|
||||
if generation > previous {
|
||||
self.photo_jobs.file_thumb_cancel.notify_waiters();
|
||||
self.jobs.file_thumb_cancel.notify_waiters();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -314,7 +314,7 @@ impl Core {
|
||||
job: ThumbJob,
|
||||
) {
|
||||
let fresh: Vec<NodeUid> = {
|
||||
let mut inflight = self.photo_jobs.thumb_gen.lock();
|
||||
let mut inflight = self.jobs.thumb_gen.lock();
|
||||
uids.into_iter()
|
||||
.filter(|uid| inflight.insert(uid.clone()))
|
||||
.collect()
|
||||
@@ -323,16 +323,16 @@ impl Core {
|
||||
return;
|
||||
}
|
||||
|
||||
let core = self.clone();
|
||||
let this = self.clone();
|
||||
let tags = tags.clone();
|
||||
let names = names.clone();
|
||||
// `generate_thumbs` blocks on the runtime itself, so it belongs on the
|
||||
// blocking pool rather than on an async worker.
|
||||
self.rt.spawn_blocking(move || {
|
||||
let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
|
||||
core.generate_thumbs(&fresh, &tags, &names, job)
|
||||
this.generate_thumbs(&fresh, &tags, &names, job)
|
||||
}));
|
||||
let mut inflight = core.photo_jobs.thumb_gen.lock();
|
||||
let mut inflight = this.jobs.thumb_gen.lock();
|
||||
for uid in &fresh {
|
||||
inflight.remove(uid);
|
||||
}
|
||||
@@ -354,13 +354,10 @@ impl Core {
|
||||
pub(super) fn thumb_job_current(&self, job: ThumbJob) -> bool {
|
||||
match job {
|
||||
ThumbJob::Files(generation) => {
|
||||
self.photo_jobs.file_thumb_generation.load(Ordering::SeqCst) == generation
|
||||
self.jobs.file_thumb_generation.load(Ordering::SeqCst) == generation
|
||||
}
|
||||
ThumbJob::Photos => true,
|
||||
ThumbJob::Build => !self
|
||||
.photo_jobs
|
||||
.thumbnail_build_cancelled
|
||||
.load(Ordering::SeqCst),
|
||||
ThumbJob::Build => !self.jobs.thumbnail_build_cancelled.load(Ordering::SeqCst),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -377,12 +374,12 @@ impl Core {
|
||||
for chunk in uids.chunks(THUMB_GEN_CONCURRENCY) {
|
||||
let mut set = tokio::task::JoinSet::new();
|
||||
for uid in chunk {
|
||||
let core = self.clone();
|
||||
let this = self.clone();
|
||||
let client = self.client.clone();
|
||||
let uid = uid.clone();
|
||||
let name = names.get(&uid.to_string()).cloned().unwrap_or_default();
|
||||
set.spawn(async move {
|
||||
if !core.thumb_job_current(job) {
|
||||
if !this.thumb_job_current(job) {
|
||||
return (uid, ThumbAttempt::Cancelled);
|
||||
}
|
||||
let video = is_video_name(&name);
|
||||
@@ -397,19 +394,19 @@ impl Core {
|
||||
// One shared permit pool bounds all thumbnail batches,
|
||||
// rather than multiplying the limit by every control
|
||||
// request the GUI happens to have in flight.
|
||||
let acquire = core.photo_jobs.thumb_gen_budget.clone().acquire_owned();
|
||||
let acquire = this.jobs.thumb_gen_budget.clone().acquire_owned();
|
||||
tokio::pin!(acquire);
|
||||
let _permit = match job {
|
||||
ThumbJob::Files(_) => loop {
|
||||
tokio::select! {
|
||||
permit = &mut acquire => break permit.ok(),
|
||||
_ = core.photo_jobs.file_thumb_cancel.notified() => {
|
||||
if !core.thumb_job_current(job) {
|
||||
_ = this.jobs.file_thumb_cancel.notified() => {
|
||||
if !this.thumb_job_current(job) {
|
||||
return (uid, ThumbAttempt::Cancelled);
|
||||
}
|
||||
}
|
||||
_ = tokio::time::sleep(THUMB_CANCEL_POLL) => {
|
||||
if !core.thumb_job_current(job) {
|
||||
if !this.thumb_job_current(job) {
|
||||
return (uid, ThumbAttempt::Cancelled);
|
||||
}
|
||||
}
|
||||
@@ -418,13 +415,13 @@ impl Core {
|
||||
ThumbJob::Build => loop {
|
||||
tokio::select! {
|
||||
permit = &mut acquire => break permit.ok(),
|
||||
_ = core.photo_jobs.thumbnail_build_cancel.notified() => {
|
||||
if !core.thumb_job_current(job) {
|
||||
_ = this.jobs.thumbnail_build_cancel.notified() => {
|
||||
if !this.thumb_job_current(job) {
|
||||
return (uid, ThumbAttempt::Cancelled);
|
||||
}
|
||||
}
|
||||
_ = tokio::time::sleep(THUMB_CANCEL_POLL) => {
|
||||
if !core.thumb_job_current(job) {
|
||||
if !this.thumb_job_current(job) {
|
||||
return (uid, ThumbAttempt::Cancelled);
|
||||
}
|
||||
}
|
||||
@@ -435,12 +432,12 @@ impl Core {
|
||||
let Some(_permit) = _permit else {
|
||||
return (uid, ThumbAttempt::Unavailable);
|
||||
};
|
||||
if !core.thumb_job_current(job) {
|
||||
if !this.thumb_job_current(job) {
|
||||
return (uid, ThumbAttempt::Cancelled);
|
||||
}
|
||||
|
||||
let download_uid = uid.clone();
|
||||
let drive = core.drive.clone();
|
||||
let drive = this.drive.clone();
|
||||
let audio_name = name.clone();
|
||||
let download = async move {
|
||||
// Photos asked the server in one batch already. A
|
||||
@@ -478,13 +475,13 @@ impl Core {
|
||||
ThumbJob::Files(_) => loop {
|
||||
tokio::select! {
|
||||
result = &mut download => break Some(result),
|
||||
_ = core.photo_jobs.file_thumb_cancel.notified() => {
|
||||
if !core.thumb_job_current(job) {
|
||||
_ = this.jobs.file_thumb_cancel.notified() => {
|
||||
if !this.thumb_job_current(job) {
|
||||
break None;
|
||||
}
|
||||
}
|
||||
_ = tokio::time::sleep(THUMB_CANCEL_POLL) => {
|
||||
if !core.thumb_job_current(job) {
|
||||
if !this.thumb_job_current(job) {
|
||||
break None;
|
||||
}
|
||||
}
|
||||
@@ -493,13 +490,13 @@ impl Core {
|
||||
ThumbJob::Build => loop {
|
||||
tokio::select! {
|
||||
result = &mut download => break Some(result),
|
||||
_ = core.photo_jobs.thumbnail_build_cancel.notified() => {
|
||||
if !core.thumb_job_current(job) {
|
||||
_ = this.jobs.thumbnail_build_cancel.notified() => {
|
||||
if !this.thumb_job_current(job) {
|
||||
break None;
|
||||
}
|
||||
}
|
||||
_ = tokio::time::sleep(THUMB_CANCEL_POLL) => {
|
||||
if !core.thumb_job_current(job) {
|
||||
if !this.thumb_job_current(job) {
|
||||
break None;
|
||||
}
|
||||
}
|
||||
@@ -517,12 +514,12 @@ impl Core {
|
||||
return (uid, ThumbAttempt::Unavailable);
|
||||
}
|
||||
};
|
||||
if !core.thumb_job_current(job) {
|
||||
if !this.thumb_job_current(job) {
|
||||
return (uid, ThumbAttempt::Cancelled);
|
||||
}
|
||||
// Decoding + scaling a 20 MP JPEG is CPU-bound and would
|
||||
// stall the runtime's worker; hand it to the blocking pool.
|
||||
let staging_dir = core.cache.raw_thumbnail_staging_dir().to_path_buf();
|
||||
let staging_dir = this.cache.raw_thumbnail_staging_dir().to_path_buf();
|
||||
let staging = staging_dir.clone();
|
||||
let made = tokio::task::spawn_blocking(move || match fetched {
|
||||
Fetched::Audio(sample) => {
|
||||
@@ -547,12 +544,12 @@ impl Core {
|
||||
// A song without a picture of its own shows its
|
||||
// folder's cover.
|
||||
let made = match made {
|
||||
ScaleAttempt::Undecodable if audio && core.thumb_job_current(job) => {
|
||||
core.folder_cover_thumbnail(&uid, staging).await
|
||||
ScaleAttempt::Undecodable if audio && this.thumb_job_current(job) => {
|
||||
this.folder_cover_thumbnail(&uid, staging).await
|
||||
}
|
||||
made => made,
|
||||
};
|
||||
if !core.thumb_job_current(job) {
|
||||
if !this.thumb_job_current(job) {
|
||||
return (uid, ThumbAttempt::Cancelled);
|
||||
}
|
||||
match made {
|
||||
@@ -583,7 +580,7 @@ impl Core {
|
||||
match self.cache.store_thumbnail(&uid, ttype, tag, &thumb.bytes) {
|
||||
Ok(()) => {
|
||||
summary.made += 1;
|
||||
self.photo_jobs
|
||||
self.jobs
|
||||
.thumbnail_misses
|
||||
.lock()
|
||||
.forget_local(&(uid.clone(), ttype));
|
||||
@@ -600,7 +597,7 @@ impl Core {
|
||||
ThumbAttempt::Undecodable => {
|
||||
summary.undecodable += 1;
|
||||
if let Some(&tag) = tags.get(&uid.to_string()) {
|
||||
self.photo_jobs
|
||||
self.jobs
|
||||
.thumbnail_misses
|
||||
.lock()
|
||||
.remember_local((uid.clone(), ttype), tag);
|
||||
@@ -698,7 +695,7 @@ impl Core {
|
||||
}
|
||||
|
||||
pub(crate) fn thumbnail_build_status(&self) -> ThumbnailBuildStatus {
|
||||
self.photo_jobs.thumbnail_build.lock().clone()
|
||||
self.jobs.thumbnail_build.lock().clone()
|
||||
}
|
||||
|
||||
/// Start one recursive local-thumbnail build. A request for the same root
|
||||
@@ -707,11 +704,11 @@ impl Core {
|
||||
pub(crate) fn start_thumbnail_build(&self, root: PathBuf) -> CoreResult<ThumbnailBuildStatus> {
|
||||
let path = root.to_string_lossy().into_owned();
|
||||
let status = {
|
||||
let mut status = self.photo_jobs.thumbnail_build.lock();
|
||||
let mut status = self.jobs.thumbnail_build.lock();
|
||||
if !thumbnail_build_may_start(&status, &path)? {
|
||||
return Ok(status.clone());
|
||||
}
|
||||
self.photo_jobs
|
||||
self.jobs
|
||||
.thumbnail_build_cancelled
|
||||
.store(false, Ordering::SeqCst);
|
||||
*status = ThumbnailBuildStatus {
|
||||
@@ -727,18 +724,18 @@ impl Core {
|
||||
status.clone()
|
||||
};
|
||||
|
||||
let core = self.clone();
|
||||
let this = self.clone();
|
||||
self.rt.spawn_blocking(move || {
|
||||
if std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
|
||||
core.run_thumbnail_build(root)
|
||||
this.run_thumbnail_build(root)
|
||||
}))
|
||||
.is_err()
|
||||
{
|
||||
let mut status = core.photo_jobs.thumbnail_build.lock();
|
||||
let mut status = this.jobs.thumbnail_build.lock();
|
||||
status.running = false;
|
||||
status.scanning = false;
|
||||
status.message = Some("Thumbnail generation stopped unexpectedly".to_string());
|
||||
core.photo_jobs
|
||||
this.jobs
|
||||
.thumbnail_build_cancelled
|
||||
.store(false, Ordering::SeqCst);
|
||||
warn!(path = %status.path, "recursive thumbnail build panicked");
|
||||
@@ -749,25 +746,25 @@ impl Core {
|
||||
|
||||
pub(crate) fn cancel_thumbnail_build(&self) -> ThumbnailBuildStatus {
|
||||
let (status, cancelled) = {
|
||||
let status = self.photo_jobs.thumbnail_build.lock();
|
||||
let status = self.jobs.thumbnail_build.lock();
|
||||
let cancelled = status.running;
|
||||
if cancelled {
|
||||
self.photo_jobs
|
||||
self.jobs
|
||||
.thumbnail_build_cancelled
|
||||
.store(true, Ordering::SeqCst);
|
||||
}
|
||||
(status.clone(), cancelled)
|
||||
};
|
||||
if cancelled {
|
||||
self.photo_jobs.thumbnail_build_cancel.notify_waiters();
|
||||
self.jobs.thumbnail_build_cancel.notify_waiters();
|
||||
}
|
||||
status
|
||||
}
|
||||
|
||||
pub(crate) fn finish_thumbnail_build(&self) {
|
||||
let mut status = self.photo_jobs.thumbnail_build.lock();
|
||||
let mut status = self.jobs.thumbnail_build.lock();
|
||||
let cancelled = self
|
||||
.photo_jobs
|
||||
.jobs
|
||||
.thumbnail_build_cancelled
|
||||
.swap(false, Ordering::SeqCst);
|
||||
status.running = false;
|
||||
@@ -791,23 +788,19 @@ impl Core {
|
||||
let mut seen_images = HashSet::new();
|
||||
|
||||
while let Some(folder) = folders.pop() {
|
||||
if self
|
||||
.photo_jobs
|
||||
.thumbnail_build_cancelled
|
||||
.load(Ordering::SeqCst)
|
||||
{
|
||||
if self.jobs.thumbnail_build_cancelled.load(Ordering::SeqCst) {
|
||||
self.finish_thumbnail_build();
|
||||
return;
|
||||
}
|
||||
let listing = self.list_dir(&folder);
|
||||
let listing = self.host.list_dir(&folder);
|
||||
{
|
||||
let mut status = self.photo_jobs.thumbnail_build.lock();
|
||||
let mut status = self.jobs.thumbnail_build.lock();
|
||||
status.folders_scanned += 1;
|
||||
}
|
||||
let entries = match listing {
|
||||
Ok(entries) => entries,
|
||||
Err(error) => {
|
||||
let mut status = self.photo_jobs.thumbnail_build.lock();
|
||||
let mut status = self.jobs.thumbnail_build.lock();
|
||||
if status.message.is_none() {
|
||||
status.message = Some(format!(
|
||||
"Some folders could not be read ({}: {error})",
|
||||
@@ -839,18 +832,14 @@ impl Core {
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut status = self.photo_jobs.thumbnail_build.lock();
|
||||
let mut status = self.jobs.thumbnail_build.lock();
|
||||
status.images_found += found_here;
|
||||
status.completed += invalid_here;
|
||||
status.failed += invalid_here;
|
||||
}
|
||||
|
||||
self.photo_jobs.thumbnail_build.lock().scanning = false;
|
||||
if self
|
||||
.photo_jobs
|
||||
.thumbnail_build_cancelled
|
||||
.load(Ordering::SeqCst)
|
||||
{
|
||||
self.jobs.thumbnail_build.lock().scanning = false;
|
||||
if self.jobs.thumbnail_build_cancelled.load(Ordering::SeqCst) {
|
||||
self.finish_thumbnail_build();
|
||||
return;
|
||||
}
|
||||
@@ -862,14 +851,14 @@ impl Core {
|
||||
.cached_thumbnail_path(&uid, ttype, modified)
|
||||
.is_some()
|
||||
{
|
||||
self.photo_jobs.thumbnail_build.lock().completed += 1;
|
||||
self.jobs.thumbnail_build.lock().completed += 1;
|
||||
} else if self
|
||||
.photo_jobs
|
||||
.jobs
|
||||
.thumbnail_misses
|
||||
.lock()
|
||||
.local_contains(&(uid.clone(), ttype), modified)
|
||||
{
|
||||
let mut status = self.photo_jobs.thumbnail_build.lock();
|
||||
let mut status = self.jobs.thumbnail_build.lock();
|
||||
status.completed += 1;
|
||||
status.failed += 1;
|
||||
} else {
|
||||
@@ -878,11 +867,7 @@ impl Core {
|
||||
}
|
||||
|
||||
for chunk in todo.chunks(THUMB_BUILD_CHUNK) {
|
||||
if self
|
||||
.photo_jobs
|
||||
.thumbnail_build_cancelled
|
||||
.load(Ordering::SeqCst)
|
||||
{
|
||||
if self.jobs.thumbnail_build_cancelled.load(Ordering::SeqCst) {
|
||||
self.finish_thumbnail_build();
|
||||
return;
|
||||
}
|
||||
@@ -895,11 +880,7 @@ impl Core {
|
||||
// than downloading the full image twice.
|
||||
let waiting_since = Instant::now();
|
||||
loop {
|
||||
if self
|
||||
.photo_jobs
|
||||
.thumbnail_build_cancelled
|
||||
.load(Ordering::SeqCst)
|
||||
{
|
||||
if self.jobs.thumbnail_build_cancelled.load(Ordering::SeqCst) {
|
||||
self.finish_thumbnail_build();
|
||||
return;
|
||||
}
|
||||
@@ -908,28 +889,28 @@ impl Core {
|
||||
.cached_thumbnail_path(uid, ttype, *modified)
|
||||
.is_some()
|
||||
{
|
||||
self.photo_jobs.thumbnail_build.lock().completed += 1;
|
||||
self.jobs.thumbnail_build.lock().completed += 1;
|
||||
break;
|
||||
}
|
||||
if self
|
||||
.photo_jobs
|
||||
.jobs
|
||||
.thumbnail_misses
|
||||
.lock()
|
||||
.local_contains(&(uid.clone(), ttype), *modified)
|
||||
{
|
||||
let mut status = self.photo_jobs.thumbnail_build.lock();
|
||||
let mut status = self.jobs.thumbnail_build.lock();
|
||||
status.completed += 1;
|
||||
status.failed += 1;
|
||||
break;
|
||||
}
|
||||
if self.photo_jobs.thumb_gen.lock().insert(uid.clone()) {
|
||||
if self.jobs.thumb_gen.lock().insert(uid.clone()) {
|
||||
tags.insert(uid.to_string(), *modified);
|
||||
names.insert(uid.to_string(), name.clone());
|
||||
claimed.push(uid.clone());
|
||||
break;
|
||||
}
|
||||
if waiting_since.elapsed() >= THUMB_BUILD_CLAIM_TIMEOUT {
|
||||
let mut status = self.photo_jobs.thumbnail_build.lock();
|
||||
let mut status = self.jobs.thumbnail_build.lock();
|
||||
status.completed += 1;
|
||||
status.failed += 1;
|
||||
if status.message.is_none() {
|
||||
@@ -950,12 +931,12 @@ impl Core {
|
||||
self.generate_thumbs(&claimed, &tags, &names, ThumbJob::Build)
|
||||
}));
|
||||
{
|
||||
let mut inflight = self.photo_jobs.thumb_gen.lock();
|
||||
let mut inflight = self.jobs.thumb_gen.lock();
|
||||
for uid in &claimed {
|
||||
inflight.remove(uid);
|
||||
}
|
||||
}
|
||||
let mut status = self.photo_jobs.thumbnail_build.lock();
|
||||
let mut status = self.jobs.thumbnail_build.lock();
|
||||
match result {
|
||||
Ok(summary) => {
|
||||
status.completed += summary.processed();
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
|
||||
use super::*;
|
||||
|
||||
impl Core {
|
||||
impl Photos {
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub(crate) fn photos_timeline(
|
||||
&self,
|
||||
@@ -90,7 +90,7 @@ impl Core {
|
||||
/// The SDK reports one outcome per photo rather than failing the call, so the
|
||||
/// single outcome is unwrapped back into this request's result.
|
||||
pub(crate) fn set_photo_favorite(&self, uid: &NodeUid, favorite: bool) -> CoreResult<()> {
|
||||
let photos = self.photos();
|
||||
let photos = self.photos_api();
|
||||
let update = PhotoTagsUpdate {
|
||||
node_uid: uid.clone(),
|
||||
tags_to_add: if favorite {
|
||||
@@ -114,7 +114,7 @@ impl Core {
|
||||
// `NodeUpdated`, which is indistinguishable from the same photo being
|
||||
// favorited on a phone. Claim the echo, or the gallery pays for a
|
||||
// resolve of a node whose one changed field is already stored below.
|
||||
self.note_self_change(uid);
|
||||
self.host.note_self_change(uid);
|
||||
self.db
|
||||
.photos_set_favorite(&uid.to_string(), favorite)
|
||||
.map_err(CoreError::from)?;
|
||||
@@ -142,7 +142,7 @@ impl Core {
|
||||
let sets = self.db.photo_similar().map_err(CoreError::from)?;
|
||||
let (done, total) = self.db.similar_progress().map_err(CoreError::from)?;
|
||||
let hashing = self
|
||||
.photo_jobs
|
||||
.jobs
|
||||
.similar_hashing
|
||||
.load(Ordering::SeqCst)
|
||||
.then_some(MappingProgress { done, total });
|
||||
@@ -155,23 +155,19 @@ impl Core {
|
||||
}
|
||||
|
||||
pub(crate) fn spawn_similar_hashing(&self) {
|
||||
if self.photo_jobs.similar_hashing.swap(true, Ordering::SeqCst) {
|
||||
if self.jobs.similar_hashing.swap(true, Ordering::SeqCst) {
|
||||
return;
|
||||
}
|
||||
let core = self.clone();
|
||||
let this = self.clone();
|
||||
let spawned = self.services.spawn_job("pdfs-similar", move || {
|
||||
if let Err(e) = core.hash_similar() {
|
||||
if let Err(e) = this.hash_similar() {
|
||||
warn!(error = %e, "similar-photo hashing failed");
|
||||
}
|
||||
core.photo_jobs
|
||||
.similar_hashing
|
||||
.store(false, Ordering::SeqCst);
|
||||
this.jobs.similar_hashing.store(false, Ordering::SeqCst);
|
||||
});
|
||||
if let Err(e) = spawned {
|
||||
warn!(error = %e, "could not start similar-photo hashing");
|
||||
self.photo_jobs
|
||||
.similar_hashing
|
||||
.store(false, Ordering::SeqCst);
|
||||
self.jobs.similar_hashing.store(false, Ordering::SeqCst);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -320,100 +316,6 @@ impl Core {
|
||||
out
|
||||
}
|
||||
|
||||
/// Mutation admission for a photo, which [`Core::require_uid_writable`]
|
||||
/// cannot answer on its own.
|
||||
///
|
||||
/// Photos live on the photo volume, and that volume is not part of the FUSE
|
||||
/// tree: a photo has no `nodes` row, so every authority comes back
|
||||
/// [`WriteAuthority::Unknown`] and the plain check refuses the whole
|
||||
/// library. Membership of our own timeline is the authority that does exist
|
||||
/// here — the timeline is enumerated from our photo share, so a uid in it is
|
||||
/// ours to trash. Anything else (an album photo on someone else's volume)
|
||||
/// still fails closed.
|
||||
pub(crate) fn require_photo_writable(&self, uid: &NodeUid) -> Result<(), fuser::Errno> {
|
||||
match self.uid_write_authority(uid) {
|
||||
WriteAuthority::Writable => Ok(()),
|
||||
WriteAuthority::Denied => Err(fuser::Errno::EACCES),
|
||||
WriteAuthority::Unknown => {
|
||||
let key = uid.to_string();
|
||||
let known = self
|
||||
.db
|
||||
.photos_by_uid(std::slice::from_ref(&key))
|
||||
.map(|rows| !rows.is_empty())
|
||||
.unwrap_or(false);
|
||||
if known {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(fuser::Errno::EACCES)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Trash photos by uid, and forget them locally.
|
||||
///
|
||||
/// The gallery is not part of the FUSE mount, so this is the photos-side
|
||||
/// counterpart of [`Core::delete`]: same destination (Proton trash, so the
|
||||
/// Trash page can restore them), addressed by uid because that is all a tile
|
||||
/// has.
|
||||
///
|
||||
/// The server answers per node, and so does this: a batch where one photo
|
||||
/// fails still removes the ones that went, and the caller is told which is
|
||||
/// which. Only what actually left the server is forgotten locally.
|
||||
///
|
||||
/// A photo that is one file of a group takes its whole group with it. The
|
||||
/// gallery shows a RAW+JPEG shot as one tile, so deleting that tile has to
|
||||
/// delete the shot — leaving the RAW behind would put the photo back on the
|
||||
/// Raw tab and nowhere else. `files_only` turns that off, for removing
|
||||
/// one copy of a shot that is stored twice.
|
||||
pub(crate) fn trash_photos(
|
||||
&self,
|
||||
uids: &[NodeUid],
|
||||
files_only: bool,
|
||||
) -> CoreResult<TrashOutcome> {
|
||||
if uids.is_empty() {
|
||||
return Ok((Vec::new(), Vec::new()));
|
||||
}
|
||||
let expanded;
|
||||
let uids = if files_only {
|
||||
uids
|
||||
} else {
|
||||
expanded = self.expand_photo_groups(uids);
|
||||
&expanded
|
||||
};
|
||||
for uid in uids {
|
||||
self.require_photo_writable(uid)
|
||||
.map_err(|errno| self.errno_error(errno, "trash access"))?;
|
||||
}
|
||||
let outcomes = self
|
||||
.rt
|
||||
.block_on(self.drive.trash_nodes(uids))
|
||||
.map_err(|e| CoreError::from_api(&e, "trash"))?;
|
||||
let (trashed, failed) = pdfs_core::batch::split(outcomes);
|
||||
|
||||
let trashed: Vec<String> = trashed.iter().map(|uid| uid.to_string()).collect();
|
||||
for uid in &trashed {
|
||||
if let Some(parsed) = parse_uid(uid) {
|
||||
self.cache.evict(&parsed);
|
||||
self.evict_reader(&parsed);
|
||||
}
|
||||
}
|
||||
// The timeline is served from the database, so removing the rows is what
|
||||
// makes the photos disappear now rather than at the next refresh.
|
||||
if let Err(error) = self.db.photos_delete(&trashed) {
|
||||
warn!(%error, "trashed photos could not be removed from the timeline");
|
||||
}
|
||||
self.invalidate_photos();
|
||||
self.invalidate_albums();
|
||||
self.invalidate_trash();
|
||||
|
||||
let failed = failed
|
||||
.into_iter()
|
||||
.map(|(uid, error)| (uid.to_string(), error.to_string()))
|
||||
.collect();
|
||||
Ok((trashed, failed))
|
||||
}
|
||||
|
||||
/// Commit the lightweight listing before resolving pending nodes. The
|
||||
/// feed generation fences both commits against events received in flight.
|
||||
pub(crate) async fn refresh_timeline(&self) -> CoreResult<bool> {
|
||||
@@ -422,7 +324,7 @@ impl Core {
|
||||
.db
|
||||
.photo_projection_generation()
|
||||
.map_err(CoreError::from)?;
|
||||
let photos = self.photos();
|
||||
let photos = self.photos_api();
|
||||
if self
|
||||
.db
|
||||
.state_i64(PHOTOS_SYNCED_MS)
|
||||
@@ -468,7 +370,7 @@ impl Core {
|
||||
let total = self.db.photos_count().map_err(CoreError::from)?;
|
||||
let skipped = total.saturating_sub(pending.len());
|
||||
let mut resolved = 0;
|
||||
let progress = ProgressGuard(&self.photo_jobs.timeline_progress);
|
||||
let progress = ProgressGuard(&self.jobs.timeline_progress);
|
||||
for (index, chunk) in pending.chunks(TIMELINE_ENRICH_CHUNK).enumerate() {
|
||||
if self.shutdown.is_stopping() {
|
||||
break;
|
||||
@@ -537,12 +439,8 @@ impl Core {
|
||||
/// whole library at once, sharing the session's rate limit and taking
|
||||
/// minutes. Returns whether the account has a photos library.
|
||||
pub(crate) fn refresh_timeline_joined(&self) -> CoreResult<bool> {
|
||||
if self
|
||||
.photo_jobs
|
||||
.timeline_refreshing
|
||||
.swap(true, Ordering::SeqCst)
|
||||
{
|
||||
while self.photo_jobs.timeline_refreshing.load(Ordering::SeqCst)
|
||||
if self.jobs.timeline_refreshing.swap(true, Ordering::SeqCst) {
|
||||
while self.jobs.timeline_refreshing.load(Ordering::SeqCst)
|
||||
&& !self.shutdown.is_stopping()
|
||||
{
|
||||
std::thread::sleep(std::time::Duration::from_millis(200));
|
||||
@@ -555,18 +453,13 @@ impl Core {
|
||||
.state_i64(PHOTOS_SYNCED_MS)
|
||||
.map_err(CoreError::from)?
|
||||
.is_some()
|
||||
|| self
|
||||
.photo_jobs
|
||||
.timeline_refreshing
|
||||
.swap(true, Ordering::SeqCst)
|
||||
|| self.jobs.timeline_refreshing.swap(true, Ordering::SeqCst)
|
||||
{
|
||||
return Ok(self.db.state_i64(PHOTOS_AVAILABLE).ok().flatten() != Some(0));
|
||||
}
|
||||
}
|
||||
let refreshed = self.rt.block_on(self.refresh_timeline());
|
||||
self.photo_jobs
|
||||
.timeline_refreshing
|
||||
.store(false, Ordering::SeqCst);
|
||||
self.jobs.timeline_refreshing.store(false, Ordering::SeqCst);
|
||||
if refreshed.is_ok() {
|
||||
self.events.publish(&[Topic::Photos]);
|
||||
}
|
||||
@@ -574,24 +467,18 @@ impl Core {
|
||||
}
|
||||
|
||||
pub(crate) fn spawn_timeline_refresh(&self) {
|
||||
if self
|
||||
.photo_jobs
|
||||
.timeline_refreshing
|
||||
.swap(true, Ordering::SeqCst)
|
||||
{
|
||||
if self.jobs.timeline_refreshing.swap(true, Ordering::SeqCst) {
|
||||
return;
|
||||
}
|
||||
let core = self.clone();
|
||||
let this = self.clone();
|
||||
self.services
|
||||
.spawn_task_job(&self.rt, "pdfs-timeline-refresh", async move {
|
||||
let refreshed = core.refresh_timeline().await;
|
||||
core.photo_jobs
|
||||
.timeline_refreshing
|
||||
.store(false, Ordering::SeqCst);
|
||||
let refreshed = this.refresh_timeline().await;
|
||||
this.jobs.timeline_refreshing.store(false, Ordering::SeqCst);
|
||||
// Only a refresh that landed: a front-end re-reading after a failed
|
||||
// one would find the timeline still stale and start another.
|
||||
match refreshed {
|
||||
Ok(_) => core.events.publish(&[Topic::Photos]),
|
||||
Ok(_) => this.events.publish(&[Topic::Photos]),
|
||||
Err(e) => warn!(error = %e, "background timeline refresh failed"),
|
||||
}
|
||||
});
|
||||
@@ -600,7 +487,7 @@ impl Core {
|
||||
/// How far the running timeline refresh has got reading photo metadata, or
|
||||
/// `None` when no refresh is reading any.
|
||||
pub(crate) fn timeline_progress(&self) -> Option<MappingProgress> {
|
||||
self.photo_jobs
|
||||
self.jobs
|
||||
.timeline_progress
|
||||
.lock()
|
||||
.map(|(done, total)| MappingProgress { done, total })
|
||||
@@ -609,13 +496,13 @@ impl Core {
|
||||
/// Whether a timeline refresh is running. A front-end that asked for one
|
||||
/// watches this to know when the new timeline is worth re-reading.
|
||||
pub(crate) fn timeline_refreshing(&self) -> bool {
|
||||
self.photo_jobs.timeline_refreshing.load(Ordering::SeqCst)
|
||||
self.jobs.timeline_refreshing.load(Ordering::SeqCst)
|
||||
}
|
||||
|
||||
/// Download a photo's full content into the content cache, returning its
|
||||
/// on-disk path (served from cache when a fresh blob already exists).
|
||||
pub(crate) fn open_photo(&self, uid: &NodeUid) -> CoreResult<PathBuf> {
|
||||
let photos = self.photos();
|
||||
let photos = self.photos_api();
|
||||
let node = self
|
||||
.rt
|
||||
.block_on(photos.get_node(uid))
|
||||
|
||||
@@ -0,0 +1,101 @@
|
||||
//! Trashing photos by uid. This stays on [`Core`] rather than [`Photos`]: it
|
||||
//! checks write authority against the tree, drops open readers and clears the
|
||||
//! trash listing, all of which belong to the filesystem side.
|
||||
|
||||
use super::*;
|
||||
|
||||
impl Core {
|
||||
/// Mutation admission for a photo, which [`Core::require_uid_writable`]
|
||||
/// cannot answer on its own.
|
||||
///
|
||||
/// Photos live on the photo volume, and that volume is not part of the FUSE
|
||||
/// tree: a photo has no `nodes` row, so every authority comes back
|
||||
/// [`WriteAuthority::Unknown`] and the plain check refuses the whole
|
||||
/// library. Membership of our own timeline is the authority that does exist
|
||||
/// here — the timeline is enumerated from our photo share, so a uid in it is
|
||||
/// ours to trash. Anything else (an album photo on someone else's volume)
|
||||
/// still fails closed.
|
||||
pub(crate) fn require_photo_writable(&self, uid: &NodeUid) -> Result<(), fuser::Errno> {
|
||||
match self.uid_write_authority(uid) {
|
||||
WriteAuthority::Writable => Ok(()),
|
||||
WriteAuthority::Denied => Err(fuser::Errno::EACCES),
|
||||
WriteAuthority::Unknown => {
|
||||
let key = uid.to_string();
|
||||
let known = self
|
||||
.db
|
||||
.photos_by_uid(std::slice::from_ref(&key))
|
||||
.map(|rows| !rows.is_empty())
|
||||
.unwrap_or(false);
|
||||
if known {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(fuser::Errno::EACCES)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Trash photos by uid, and forget them locally.
|
||||
///
|
||||
/// The gallery is not part of the FUSE mount, so this is the photos-side
|
||||
/// counterpart of [`Core::delete`]: same destination (Proton trash, so the
|
||||
/// Trash page can restore them), addressed by uid because that is all a tile
|
||||
/// has.
|
||||
///
|
||||
/// The server answers per node, and so does this: a batch where one photo
|
||||
/// fails still removes the ones that went, and the caller is told which is
|
||||
/// which. Only what actually left the server is forgotten locally.
|
||||
///
|
||||
/// A photo that is one file of a group takes its whole group with it. The
|
||||
/// gallery shows a RAW+JPEG shot as one tile, so deleting that tile has to
|
||||
/// delete the shot — leaving the RAW behind would put the photo back on the
|
||||
/// Raw tab and nowhere else. `files_only` turns that off, for removing
|
||||
/// one copy of a shot that is stored twice.
|
||||
pub(crate) fn trash_photos(
|
||||
&self,
|
||||
uids: &[NodeUid],
|
||||
files_only: bool,
|
||||
) -> CoreResult<TrashOutcome> {
|
||||
if uids.is_empty() {
|
||||
return Ok((Vec::new(), Vec::new()));
|
||||
}
|
||||
let expanded;
|
||||
let uids = if files_only {
|
||||
uids
|
||||
} else {
|
||||
expanded = self.photos().expand_photo_groups(uids);
|
||||
&expanded
|
||||
};
|
||||
for uid in uids {
|
||||
self.require_photo_writable(uid)
|
||||
.map_err(|errno| self.errno_error(errno, "trash access"))?;
|
||||
}
|
||||
let outcomes = self
|
||||
.rt
|
||||
.block_on(self.drive.trash_nodes(uids))
|
||||
.map_err(|e| CoreError::from_api(&e, "trash"))?;
|
||||
let (trashed, failed) = pdfs_core::batch::split(outcomes);
|
||||
|
||||
let trashed: Vec<String> = trashed.iter().map(|uid| uid.to_string()).collect();
|
||||
for uid in &trashed {
|
||||
if let Some(parsed) = parse_uid(uid) {
|
||||
self.cache.evict(&parsed);
|
||||
self.evict_reader(&parsed);
|
||||
}
|
||||
}
|
||||
// The timeline is served from the database, so removing the rows is what
|
||||
// makes the photos disappear now rather than at the next refresh.
|
||||
if let Err(error) = self.db.photos_delete(&trashed) {
|
||||
warn!(%error, "trashed photos could not be removed from the timeline");
|
||||
}
|
||||
self.invalidate_photos();
|
||||
self.photos().invalidate_albums();
|
||||
self.invalidate_trash();
|
||||
|
||||
let failed = failed
|
||||
.into_iter()
|
||||
.map(|(uid, error)| (uid.to_string(), error.to_string()))
|
||||
.collect();
|
||||
Ok((trashed, failed))
|
||||
}
|
||||
}
|
||||
@@ -16,7 +16,7 @@
|
||||
//! file rather than trying to describe the new one. The next read repopulates
|
||||
//! from whatever is live by then.
|
||||
//! - **The active revision cannot be deleted**, and the server — not this code —
|
||||
//! is what enforces that. [`Core::delete_revision_for_uid`] refuses locally
|
||||
//! is what enforces that. [`Revisions::delete`] refuses locally
|
||||
//! too, so the user gets a sentence instead of an API code.
|
||||
|
||||
use std::path::Path;
|
||||
@@ -27,7 +27,12 @@ use proton_drive_rs::Revision;
|
||||
use proton_drive_rs::proton_sdk::ids::NodeUid;
|
||||
use tracing::info;
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use proton_drive_rs::ProtonDriveClient;
|
||||
|
||||
use super::Core;
|
||||
use crate::drive::DriveApi;
|
||||
|
||||
/// A [`Revision`] as the control protocol reports it.
|
||||
fn revision_info(revision: Revision) -> RevisionInfo {
|
||||
@@ -45,70 +50,37 @@ fn revision_info(revision: Revision) -> RevisionInfo {
|
||||
}
|
||||
}
|
||||
|
||||
impl Core {
|
||||
/// The version history of the file at mountpoint-relative `rel`.
|
||||
pub(crate) fn list_revisions(&self, rel: &Path) -> CoreResult<Vec<RevisionInfo>> {
|
||||
let (_ino, uid) = self.resolve(rel)?;
|
||||
self.list_revisions_for_uid(&uid)
|
||||
}
|
||||
/// A file's revisions on Drive. Every method takes a node already resolved to
|
||||
/// its uid, and the name the activity feed shows for it.
|
||||
///
|
||||
/// It reaches the filesystem through [`RevisionsHost`]. [`Core::revisions`]
|
||||
/// builds one on demand with the daemon as its host.
|
||||
pub(crate) struct Revisions {
|
||||
client: ProtonDriveClient,
|
||||
drive: Arc<dyn DriveApi>,
|
||||
rt: tokio::runtime::Handle,
|
||||
host: Arc<dyn RevisionsHost>,
|
||||
}
|
||||
|
||||
/// [`Core::list_revisions`] for a node addressed through any daemon location.
|
||||
pub(crate) fn list_revisions_by_uid(&self, uid: &str) -> CoreResult<Vec<RevisionInfo>> {
|
||||
let uid = self.resolve_anywhere(uid)?;
|
||||
self.list_revisions_for_uid(&uid)
|
||||
}
|
||||
/// What [`Revisions`] needs from the filesystem.
|
||||
pub(crate) trait RevisionsHost: Send + Sync {
|
||||
/// Refuse unless this daemon may change the node's content. `what` names
|
||||
/// the operation in the error.
|
||||
fn require_writable(&self, uid: &NodeUid, what: &str) -> CoreResult<()>;
|
||||
/// The node's active revision changed on the server: forget its cached
|
||||
/// content and open readers, and fetch it again if it is kept offline.
|
||||
fn content_replaced(&self, uid: &NodeUid);
|
||||
/// Add an entry to the activity log.
|
||||
fn log_activity(&self, kind: ActivityKind, target: String, detail: String, ok: bool);
|
||||
}
|
||||
|
||||
fn list_revisions_for_uid(&self, uid: &NodeUid) -> CoreResult<Vec<RevisionInfo>> {
|
||||
let revisions = self
|
||||
.rt
|
||||
.block_on(self.client.enumerate_revisions(uid))
|
||||
.map_err(|e| CoreError::from_api(&e, "list revisions"))?;
|
||||
Ok(revisions.into_iter().map(revision_info).collect())
|
||||
}
|
||||
|
||||
/// Make `revision_id` the current content of the file at `rel`.
|
||||
pub(crate) fn restore_revision(&self, rel: &Path, revision_id: &str) -> CoreResult<()> {
|
||||
let (_ino, uid) = self.resolve(rel)?;
|
||||
let name = rel
|
||||
.file_name()
|
||||
.map(|n| n.to_string_lossy().into_owned())
|
||||
.unwrap_or_else(|| uid.to_string());
|
||||
self.restore_revision_for_uid(&uid, revision_id, &name)?;
|
||||
// The size and mtime a listing shows describe the revision that was
|
||||
// active a moment ago.
|
||||
self.invalidate_parent_listing(rel);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// [`Core::restore_revision`] for a node addressed through any daemon
|
||||
/// location.
|
||||
pub(crate) fn restore_revision_by_uid(&self, uid: &str, revision_id: &str) -> CoreResult<()> {
|
||||
let uid = self.resolve_anywhere(uid)?;
|
||||
let name = uid.to_string();
|
||||
self.restore_revision_for_uid(&uid, revision_id, &name)
|
||||
}
|
||||
|
||||
fn restore_revision_for_uid(
|
||||
&self,
|
||||
uid: &NodeUid,
|
||||
revision_id: &str,
|
||||
name: &str,
|
||||
) -> CoreResult<()> {
|
||||
// Restoring rewrites the file's content: the same authority a write
|
||||
// needs, not the one a read needs.
|
||||
impl RevisionsHost for Core {
|
||||
fn require_writable(&self, uid: &NodeUid, what: &str) -> CoreResult<()> {
|
||||
self.require_uid_writable(uid)
|
||||
.map_err(|error| self.errno_error(error, "restore revision"))?;
|
||||
if let Err(e) = self
|
||||
.rt
|
||||
.block_on(self.client.restore_revision(uid, revision_id))
|
||||
{
|
||||
let error = CoreError::from_api(&e, "restore revision");
|
||||
self.log_activity(ActivityKind::Restore, name, &error, false);
|
||||
return Err(error);
|
||||
}
|
||||
// The active revision is changing behind our back — anything describing
|
||||
// the old one (cached blocks, an open reader, the size in a listing) is
|
||||
// stale from here on, and the server may not have applied the swap yet.
|
||||
.map_err(|error| self.errno_error(error, what))
|
||||
}
|
||||
|
||||
fn content_replaced(&self, uid: &NodeUid) {
|
||||
self.cache.evict(uid);
|
||||
self.evict_reader(uid);
|
||||
// A file kept offline gets the restored content back on disk, and
|
||||
@@ -116,9 +88,58 @@ impl Core {
|
||||
if self.cache.is_pinned(uid) {
|
||||
self.recheck_pinned(uid);
|
||||
}
|
||||
self.log_activity(
|
||||
}
|
||||
|
||||
fn log_activity(&self, kind: ActivityKind, target: String, detail: String, ok: bool) {
|
||||
Core::log_activity(self, kind, target, detail, ok);
|
||||
}
|
||||
}
|
||||
|
||||
impl Core {
|
||||
/// The revisions service, with this daemon as its host.
|
||||
pub(crate) fn revisions(&self) -> Revisions {
|
||||
Revisions {
|
||||
client: self.client.clone(),
|
||||
drive: self.drive.clone(),
|
||||
rt: self.rt.clone(),
|
||||
host: Arc::new(self.clone()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Revisions {
|
||||
pub(crate) fn list(&self, uid: &NodeUid) -> CoreResult<Vec<RevisionInfo>> {
|
||||
let revisions = self
|
||||
.rt
|
||||
.block_on(self.client.enumerate_revisions(uid))
|
||||
.map_err(|e| CoreError::from_api(&e, "list revisions"))?;
|
||||
Ok(revisions.into_iter().map(revision_info).collect())
|
||||
}
|
||||
|
||||
pub(crate) fn restore(&self, uid: &NodeUid, revision_id: &str, name: &str) -> CoreResult<()> {
|
||||
// Restoring rewrites the file's content: the same authority a write
|
||||
// needs, not the one a read needs.
|
||||
self.host.require_writable(uid, "restore revision")?;
|
||||
if let Err(e) = self
|
||||
.rt
|
||||
.block_on(self.client.restore_revision(uid, revision_id))
|
||||
{
|
||||
let error = CoreError::from_api(&e, "restore revision");
|
||||
self.host.log_activity(
|
||||
ActivityKind::Restore,
|
||||
name.to_string(),
|
||||
error.to_string(),
|
||||
false,
|
||||
);
|
||||
return Err(error);
|
||||
}
|
||||
// The active revision is changing behind our back — anything describing
|
||||
// the old one (cached blocks, an open reader, the size in a listing) is
|
||||
// stale from here on, and the server may not have applied the swap yet.
|
||||
self.host.content_replaced(uid);
|
||||
self.host.log_activity(
|
||||
ActivityKind::Restore,
|
||||
name,
|
||||
name.to_string(),
|
||||
format!("restored version {revision_id}"),
|
||||
true,
|
||||
);
|
||||
@@ -126,32 +147,8 @@ impl Core {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Permanently delete `revision_id` from the history of the file at `rel`.
|
||||
pub(crate) fn delete_revision(&self, rel: &Path, revision_id: &str) -> CoreResult<()> {
|
||||
let (_ino, uid) = self.resolve(rel)?;
|
||||
let name = rel
|
||||
.file_name()
|
||||
.map(|n| n.to_string_lossy().into_owned())
|
||||
.unwrap_or_else(|| uid.to_string());
|
||||
self.delete_revision_for_uid(&uid, revision_id, &name)
|
||||
}
|
||||
|
||||
/// [`Core::delete_revision`] for a node addressed through any daemon
|
||||
/// location.
|
||||
pub(crate) fn delete_revision_by_uid(&self, uid: &str, revision_id: &str) -> CoreResult<()> {
|
||||
let uid = self.resolve_anywhere(uid)?;
|
||||
let name = uid.to_string();
|
||||
self.delete_revision_for_uid(&uid, revision_id, &name)
|
||||
}
|
||||
|
||||
fn delete_revision_for_uid(
|
||||
&self,
|
||||
uid: &NodeUid,
|
||||
revision_id: &str,
|
||||
name: &str,
|
||||
) -> CoreResult<()> {
|
||||
self.require_uid_writable(uid)
|
||||
.map_err(|error| self.errno_error(error, "delete revision"))?;
|
||||
pub(crate) fn delete(&self, uid: &NodeUid, revision_id: &str, name: &str) -> CoreResult<()> {
|
||||
self.host.require_writable(uid, "delete revision")?;
|
||||
// The server rejects deleting the active revision; saying so here is a
|
||||
// sentence the user can act on instead of an API code, and it costs one
|
||||
// listing the front-end already made to show the version list.
|
||||
@@ -171,9 +168,9 @@ impl Core {
|
||||
self.rt
|
||||
.block_on(self.client.delete_revision(uid, revision_id))
|
||||
.map_err(|e| CoreError::from_api(&e, "delete revision"))?;
|
||||
self.log_activity(
|
||||
self.host.log_activity(
|
||||
ActivityKind::DeleteForever,
|
||||
name,
|
||||
name.to_string(),
|
||||
format!("deleted version {revision_id}"),
|
||||
true,
|
||||
);
|
||||
@@ -181,36 +178,7 @@ impl Core {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Write `revision_id` of the file at `rel` to the absolute local path
|
||||
/// `dest`, leaving the file itself untouched.
|
||||
pub(crate) fn save_revision_as(
|
||||
&self,
|
||||
rel: &Path,
|
||||
revision_id: &str,
|
||||
dest: &Path,
|
||||
) -> CoreResult<u64> {
|
||||
let (_ino, uid) = self.resolve(rel)?;
|
||||
let name = rel
|
||||
.file_name()
|
||||
.map(|n| n.to_string_lossy().into_owned())
|
||||
.unwrap_or_else(|| uid.to_string());
|
||||
self.save_revision_for_uid(&uid, revision_id, &name, dest)
|
||||
}
|
||||
|
||||
/// [`Core::save_revision_as`] for a node addressed through any daemon
|
||||
/// location.
|
||||
pub(crate) fn save_revision_as_by_uid(
|
||||
&self,
|
||||
uid: &str,
|
||||
revision_id: &str,
|
||||
dest: &Path,
|
||||
) -> CoreResult<u64> {
|
||||
let uid = self.resolve_anywhere(uid)?;
|
||||
let name = uid.to_string();
|
||||
self.save_revision_for_uid(&uid, revision_id, &name, dest)
|
||||
}
|
||||
|
||||
fn save_revision_for_uid(
|
||||
pub(crate) fn save_as(
|
||||
&self,
|
||||
uid: &NodeUid,
|
||||
revision_id: &str,
|
||||
@@ -253,13 +221,18 @@ impl Core {
|
||||
// A half-written file looks like a successful export to every
|
||||
// tool that opens it afterwards.
|
||||
let _ = std::fs::remove_file(dest);
|
||||
self.log_activity(ActivityKind::Download, name, &error, false);
|
||||
self.host.log_activity(
|
||||
ActivityKind::Download,
|
||||
name.to_string(),
|
||||
error.to_string(),
|
||||
false,
|
||||
);
|
||||
return Err(error);
|
||||
}
|
||||
};
|
||||
self.log_activity(
|
||||
self.host.log_activity(
|
||||
ActivityKind::Download,
|
||||
name,
|
||||
name.to_string(),
|
||||
format!("saved version {revision_id} to {}", dest.display()),
|
||||
true,
|
||||
);
|
||||
|
||||
@@ -38,7 +38,7 @@ impl SyncHost for Core {
|
||||
}
|
||||
|
||||
fn upload_thumbnails(&self, path: &Path, name: &str) -> Vec<Thumbnail> {
|
||||
Core::upload_thumbnails(self, path, name)
|
||||
self.photos().upload_thumbnails(path, name)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+106
-37
@@ -2,6 +2,7 @@
|
||||
//! listing in the background, restoring from it, deleting from it for good.
|
||||
|
||||
use super::*;
|
||||
use crate::listing::listing_stale;
|
||||
|
||||
/// Whether a trash refresh is running, and the wake-up for requests waiting
|
||||
/// on its progress.
|
||||
@@ -13,7 +14,7 @@ pub(crate) struct TrashState {
|
||||
/// Fires whenever a trash refresh persists a batch or finishes, so a
|
||||
/// `ListTrash` request waiting on a first-ever refresh wakes on progress
|
||||
/// instead of polling or blocking for the whole run. See
|
||||
/// [`Core::await_trash_refresh`].
|
||||
/// [`Trash::await_trash_refresh`].
|
||||
pub(crate) trash_progress: Arc<tokio::sync::Notify>,
|
||||
}
|
||||
|
||||
@@ -26,7 +27,75 @@ impl TrashState {
|
||||
}
|
||||
}
|
||||
|
||||
/// The Drive trash as a service: listing it, refreshing that listing, and
|
||||
/// restoring or deleting from it.
|
||||
///
|
||||
/// It holds only the handles it calls, and reaches the mounted trees through
|
||||
/// [`TrashHost`]. [`Core::trash`] builds one on demand with the daemon as its
|
||||
/// host. A clone shares everything, which is how a refresh moves onto a
|
||||
/// background task.
|
||||
#[derive(Clone)]
|
||||
pub(crate) struct Trash {
|
||||
drive: Arc<dyn DriveApi>,
|
||||
rt: tokio::runtime::Handle,
|
||||
db: Arc<Db>,
|
||||
events: Arc<events::EventHub>,
|
||||
services: pdfs_core::lifecycle::ServiceBoard,
|
||||
writes: writes::WriteState,
|
||||
jobs: TrashState,
|
||||
host: Arc<dyn TrashHost>,
|
||||
}
|
||||
|
||||
/// What the trash needs from the mounted trees.
|
||||
pub(crate) trait TrashHost: Send + Sync {
|
||||
/// Re-enumerate these folders on next access, in every mount, because a
|
||||
/// restored node reappears under one of them.
|
||||
fn invalidate_listings_of(&self, parents: &[NodeUid]);
|
||||
/// Forget nodes the server no longer has, in every mount, with any cached
|
||||
/// content they own.
|
||||
fn drop_local(&self, uids: &[NodeUid]);
|
||||
}
|
||||
|
||||
impl TrashHost for Core {
|
||||
fn invalidate_listings_of(&self, parents: &[NodeUid]) {
|
||||
// Keyed by uid, so it applies to every mount: a restored node reappears
|
||||
// in whichever mounts show its parent, not only the primary one.
|
||||
self.for_each_state(|st| {
|
||||
for parent in parents {
|
||||
if let Some(&ino) = st.by_uid.get(parent) {
|
||||
st.invalidate_listing(ino);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
fn drop_local(&self, uids: &[NodeUid]) {
|
||||
Core::drop_local(self, uids);
|
||||
}
|
||||
}
|
||||
|
||||
impl Core {
|
||||
/// [`Trash::invalidate_trash`], without building the service.
|
||||
pub(super) fn invalidate_trash(&self) {
|
||||
invalidate_trash(&self.db);
|
||||
}
|
||||
|
||||
/// The trash service, with this daemon as its host.
|
||||
pub(crate) fn trash(&self) -> Trash {
|
||||
Trash {
|
||||
drive: self.drive.clone(),
|
||||
rt: self.rt.clone(),
|
||||
db: self.db.clone(),
|
||||
events: self.events.clone(),
|
||||
services: self.services.clone(),
|
||||
writes: self.writes.clone(),
|
||||
jobs: self.trash_jobs.clone(),
|
||||
host: Arc::new(self.clone()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Trash {
|
||||
/// List the account's trash, from the DB. Trashed nodes are outside the
|
||||
/// mounted tree — the FUSE side forgot them when they were trashed — so the
|
||||
/// listing is persisted in its own table rather than derived from `State`, and
|
||||
@@ -36,7 +105,7 @@ impl Core {
|
||||
/// Stale-while-revalidate, like the photos timeline: a persisted listing comes
|
||||
/// back at DB speed and is refreshed in the background past [`TRASH_TTL`].
|
||||
/// Our own trash mutations invalidate it outright (see
|
||||
/// [`Core::invalidate_trash`]), so the TTL only covers changes made elsewhere.
|
||||
/// [`Trash::invalidate_trash`]), so the TTL only covers changes made elsewhere.
|
||||
///
|
||||
/// The refresh always runs *off* the request: a never-fetched trash waits for
|
||||
/// it, but only for [`TRASH_FIRST_WAIT`], and then answers with the batches
|
||||
@@ -44,9 +113,9 @@ impl Core {
|
||||
/// made a large trash unlistable — the refresh outran the front-end's read
|
||||
/// timeout, the user asked again, and each attempt left another full refresh
|
||||
/// grinding in the daemon (`docs/BUGS.md` B72).
|
||||
pub(super) fn list_trash(&self) -> CoreResult<Vec<DirEntry>> {
|
||||
pub(crate) fn list_trash(&self) -> CoreResult<Vec<DirEntry>> {
|
||||
let never_fetched = self.db.state_i64(TRASH_SYNCED_MS).ok().flatten().is_none();
|
||||
if never_fetched || self.listing_stale(TRASH_SYNCED_MS, TRASH_TTL) {
|
||||
if never_fetched || listing_stale(&self.db, TRASH_SYNCED_MS, TRASH_TTL) {
|
||||
self.spawn_trash_refresh();
|
||||
}
|
||||
if never_fetched {
|
||||
@@ -99,7 +168,7 @@ impl Core {
|
||||
|
||||
/// What a trashed folder holds: its children on the server, and the
|
||||
/// stored trash entries trashed inside it before it went.
|
||||
pub(super) fn list_trashed_folder(&self, uid: &str) -> CoreResult<Vec<DirEntry>> {
|
||||
pub(crate) fn list_trashed_folder(&self, uid: &str) -> CoreResult<Vec<DirEntry>> {
|
||||
let folder =
|
||||
parse_uid(uid).ok_or_else(|| CoreError::invalid(format!("invalid uid: {uid}")))?;
|
||||
let children = self
|
||||
@@ -177,7 +246,7 @@ impl Core {
|
||||
/// [`TRASH_MATERIALIZE_CHUNK`] is stored as it lands, so a large trash
|
||||
/// fills the page while it loads. Rows the server no longer lists go once
|
||||
/// the whole listing is in, never earlier.
|
||||
pub(super) async fn refresh_trash(&self) -> CoreResult<()> {
|
||||
pub(crate) async fn refresh_trash(&self) -> CoreResult<()> {
|
||||
let started = Instant::now();
|
||||
let uids = within_trash_call("enumerate trash", self.drive.enumerate_trash_node_uids())
|
||||
.await?
|
||||
@@ -200,7 +269,7 @@ impl Core {
|
||||
let listed: HashSet<String> = uids.iter().map(ToString::to_string).collect();
|
||||
let removed = self.db.trash_retain(&listed).map_err(CoreError::from)?;
|
||||
if removed > 0 {
|
||||
self.trash.trash_progress.notify_waiters();
|
||||
self.jobs.trash_progress.notify_waiters();
|
||||
}
|
||||
let missing: Vec<NodeUid> = uids
|
||||
.into_iter()
|
||||
@@ -235,7 +304,7 @@ impl Core {
|
||||
.collect();
|
||||
materialized += items.len();
|
||||
self.db.trash_upsert(&items).map_err(CoreError::from)?;
|
||||
self.trash.trash_progress.notify_waiters();
|
||||
self.jobs.trash_progress.notify_waiters();
|
||||
self.events.publish(&[Topic::Trash]);
|
||||
debug!(
|
||||
materialized,
|
||||
@@ -258,44 +327,44 @@ impl Core {
|
||||
}
|
||||
|
||||
/// Refresh the trash off the request path. At most one refresh at a time —
|
||||
/// including the one a first-ever [`Core::list_trash`] waits on, so a burst
|
||||
/// including the one a first-ever [`Trash::list_trash`] waits on, so a burst
|
||||
/// of requests against an unfetched trash joins one refresh instead of
|
||||
/// starting one apiece.
|
||||
pub(super) fn spawn_trash_refresh(&self) {
|
||||
if self.trash.trash_refreshing.swap(true, Ordering::SeqCst) {
|
||||
pub(crate) fn spawn_trash_refresh(&self) {
|
||||
if self.jobs.trash_refreshing.swap(true, Ordering::SeqCst) {
|
||||
return;
|
||||
}
|
||||
let core = self.clone();
|
||||
let this = self.clone();
|
||||
self.services
|
||||
.spawn_task_job(&self.rt, "pdfs-trash-refresh", async move {
|
||||
let refreshed = core.refresh_trash().await;
|
||||
core.trash.trash_refreshing.store(false, Ordering::SeqCst);
|
||||
let refreshed = this.refresh_trash().await;
|
||||
this.jobs.trash_refreshing.store(false, Ordering::SeqCst);
|
||||
match refreshed {
|
||||
Ok(_) => core.events.publish(&[Topic::Trash]),
|
||||
Ok(_) => this.events.publish(&[Topic::Trash]),
|
||||
Err(e) => warn!(error = %e, "background trash refresh failed"),
|
||||
}
|
||||
// After the flag, so a waiter that wakes on this sees it cleared.
|
||||
core.trash.trash_progress.notify_waiters();
|
||||
this.jobs.trash_progress.notify_waiters();
|
||||
});
|
||||
}
|
||||
|
||||
/// Wait for the in-flight trash refresh to make progress, for at most
|
||||
/// `budget`. Returns early when it finishes; never cancels it — the refresh
|
||||
/// is a detached task, so giving up here costs the work nothing.
|
||||
pub(super) fn await_trash_refresh(&self, budget: Duration) {
|
||||
pub(crate) fn await_trash_refresh(&self, budget: Duration) {
|
||||
let deadline = Instant::now() + budget;
|
||||
self.rt.block_on(async {
|
||||
while self.trash.trash_refreshing.load(Ordering::SeqCst) {
|
||||
while self.jobs.trash_refreshing.load(Ordering::SeqCst) {
|
||||
let Some(left) = deadline.checked_duration_since(Instant::now()) else {
|
||||
break;
|
||||
};
|
||||
let notified = self.trash.trash_progress.notified();
|
||||
let notified = self.jobs.trash_progress.notified();
|
||||
tokio::pin!(notified);
|
||||
// Register before re-checking the flag: a refresh that finishes
|
||||
// in between must not leave us waiting for a notify that has
|
||||
// already fired.
|
||||
notified.as_mut().enable();
|
||||
if !self.trash.trash_refreshing.load(Ordering::SeqCst) {
|
||||
if !self.jobs.trash_refreshing.load(Ordering::SeqCst) {
|
||||
break;
|
||||
}
|
||||
if tokio::time::timeout(left, notified).await.is_err() {
|
||||
@@ -313,8 +382,8 @@ impl Core {
|
||||
/// trash ourselves. The next Trash page then *waits* for a fresh listing
|
||||
/// rather than painting one from before the mutation — the user just made the
|
||||
/// change and is about to look straight at it.
|
||||
pub(super) fn invalidate_trash(&self) {
|
||||
let _ = self.db.clear_state(TRASH_SYNCED_MS);
|
||||
pub(crate) fn invalidate_trash(&self) {
|
||||
invalidate_trash(&self.db);
|
||||
}
|
||||
|
||||
/// Restore trashed nodes to the folders they were trashed from, together
|
||||
@@ -335,8 +404,8 @@ impl Core {
|
||||
/// The destination parents are read *before* the restore — a restored node
|
||||
/// reappears in a listing the daemon may already have cached, so each one is
|
||||
/// invalidated and re-enumerated on next access.
|
||||
pub(super) fn restore(&self, uids: &[String]) -> CoreResult<usize> {
|
||||
let requested = Self::parse_uids(uids)?;
|
||||
pub(crate) fn restore(&self, uids: &[String]) -> CoreResult<usize> {
|
||||
let requested = Core::parse_uids(uids)?;
|
||||
// A listing we could not read is not a reason to refuse the restore: it
|
||||
// only costs the expansion, and the requested nodes still go back.
|
||||
let relations = self.db.trash_parents().unwrap_or_default();
|
||||
@@ -399,13 +468,7 @@ impl Core {
|
||||
}
|
||||
// Keyed by uid, so it applies to every mount: a restored node reappears
|
||||
// in whichever mounts show its parent, not only the primary one.
|
||||
self.for_each_state(|st| {
|
||||
for parent in &parents {
|
||||
if let Some(&ino) = st.by_uid.get(parent) {
|
||||
st.invalidate_listing(ino);
|
||||
}
|
||||
}
|
||||
});
|
||||
self.host.invalidate_listings_of(&parents);
|
||||
let back: Vec<String> = restored.iter().map(ToString::to_string).collect();
|
||||
let _ = self.db.trash_remove(&back);
|
||||
self.invalidate_trash();
|
||||
@@ -414,8 +477,8 @@ impl Core {
|
||||
|
||||
/// Permanently delete trashed nodes. Irreversible on the server; locally it
|
||||
/// drops any metadata and cached content the node still owns.
|
||||
pub(super) fn delete_forever(&self, uids: &[String]) -> CoreResult<usize> {
|
||||
let parsed = Self::parse_uids(uids)?;
|
||||
pub(crate) fn delete_forever(&self, uids: &[String]) -> CoreResult<usize> {
|
||||
let parsed = Core::parse_uids(uids)?;
|
||||
// Streamed, and each node's local state is dropped as its batch lands.
|
||||
// A permanent delete is irreversible, so the useful property is that a
|
||||
// daemon interrupted mid-batch has already forgotten exactly the nodes
|
||||
@@ -430,7 +493,7 @@ impl Core {
|
||||
let (uid, outcome) = item?;
|
||||
match outcome {
|
||||
Ok(()) => {
|
||||
self.drop_local(std::slice::from_ref(&uid));
|
||||
self.host.drop_local(std::slice::from_ref(&uid));
|
||||
gone.push(uid.to_string());
|
||||
deleted += 1;
|
||||
}
|
||||
@@ -461,7 +524,7 @@ impl Core {
|
||||
/// is what kept the delete from ever being sent (`docs/BUGS.md` B293).
|
||||
/// The stored listing is cleared at once, and the server is asked again
|
||||
/// after [`TRASH_TTL`], so anything it still holds then shows up again.
|
||||
pub(super) fn empty_trash(&self) -> CoreResult<usize> {
|
||||
pub(crate) fn empty_trash(&self) -> CoreResult<usize> {
|
||||
let uids: Vec<String> = self
|
||||
.db
|
||||
.trash_seen()
|
||||
@@ -472,7 +535,7 @@ impl Core {
|
||||
.block_on(within_trash_call("empty trash", self.drive.empty_trash()))?
|
||||
.map_err(|e| CoreError::from_api(&e, "empty trash"))?;
|
||||
let parsed: Vec<NodeUid> = uids.iter().filter_map(|uid| parse_uid(uid)).collect();
|
||||
self.drop_local(&parsed);
|
||||
self.host.drop_local(&parsed);
|
||||
let _ = self.db.trash_replace(&[]);
|
||||
let _ = self.db.set_state_i64(TRASH_SYNCED_MS, now_ms());
|
||||
self.events.publish(&[Topic::Trash]);
|
||||
@@ -480,7 +543,7 @@ impl Core {
|
||||
}
|
||||
}
|
||||
|
||||
/// An entry inside a trashed folder, for [`Core::list_trashed_folder`].
|
||||
/// An entry inside a trashed folder, for [`Trash::list_trashed_folder`].
|
||||
pub(super) fn trashed_entry(
|
||||
uid: String,
|
||||
name: String,
|
||||
@@ -619,3 +682,9 @@ pub(super) fn expand_restore(
|
||||
waves.retain(|wave| !wave.is_empty());
|
||||
waves
|
||||
}
|
||||
|
||||
/// Mark the stored trash listing stale, so the next listing waits for a
|
||||
/// fresh one.
|
||||
fn invalidate_trash(db: &Db) {
|
||||
let _ = db.clear_state(TRASH_SYNCED_MS);
|
||||
}
|
||||
@@ -70,6 +70,7 @@ async fn run_uploads(
|
||||
));
|
||||
}
|
||||
let thumbnails = core
|
||||
.photos()
|
||||
.upload_thumbnails_async(t.path.clone(), t.name.clone())
|
||||
.await;
|
||||
match core
|
||||
|
||||
@@ -772,6 +772,24 @@ only the handles it calls (the client, Drive, the content cache, the transfer li
|
||||
the tree), and every one of its methods takes a node already resolved to its uid. Like the sync
|
||||
engine's `Syncer`, it can be built and tested without the rest of the daemon.
|
||||
|
||||
`photos::Photos` is the timeline, albums, thumbnails, the Google Photos import and the redate
|
||||
job. It holds the handles it calls and the `PhotoJobs` state, and reaches the filesystem through a
|
||||
`PhotosHost` port with three methods: list a folder, for the recursive thumbnail build; note a
|
||||
change made here, so its echo in the event feed is not taken for a remote edit; and add an entry
|
||||
to the activity log. `Core::photos` builds one on demand with the daemon as its
|
||||
host, as `Core::syncer` does for the sync engine. Trashing photos stays on `Core`, because it
|
||||
checks write authority against the tree and drops open readers.
|
||||
|
||||
`trash::Trash` lists the Drive trash, refreshes that listing, and restores or deletes from it. Its
|
||||
`TrashHost` port has two methods, both of which reach every mount: re-enumerate the folders a
|
||||
restored node comes back into, and forget nodes the server no longer has. `Core::trash` builds it
|
||||
on demand.
|
||||
|
||||
`revisions::Revisions` lists, restores, deletes and saves a file's earlier revisions. Like
|
||||
`Sharing`, it only takes a node already resolved to its uid. Its `RevisionsHost` port checks that
|
||||
the node may be written, drops what describes the old content (cached blocks and open readers)
|
||||
and fetches it again if it is kept offline, and adds an activity entry.
|
||||
|
||||
The control socket answers each area's requests in a module of its own under `control/`:
|
||||
sharing, Photos, synced folders and devices, revisions, and the trash and cache. Each module
|
||||
exports a pattern macro naming its requests, and the main match hands them over in one arm, so
|
||||
|
||||
Reference in new issue
Block a user