20 Commits
Author SHA1 Message Date
Alby96andClaude Opus 5.5 6ea611d949 fix(admin): revalidate panel files, count bulk jobs, refresh every loaded row
The phase 3 packages land together, so the panel's pieces must stay in step:

- Admin files are served with Cache-Control: no-cache and their content
  ETag (If-None-Match lists, W/ tags and * honoured). With max-age=3600 a
  browser that loaded the panel before an upgrade could run new modules
  next to cached old ones for up to an hour; now it revalidates each file
  and only what the upgrade changed is sent again.
- The Library's Upload and a sequence's Add photos open upload.js, which
  now ships with the panel: the test requires the module (no 404), the
  dynamic import and the openUpload({ api, sequence, onDone }) calls.
- Bulk jobs over more than 1000 sequences queue one job per 1000; the
  toast now says how many were queued, also when a later chunk failed.
- The live refresh re-reads every loaded row, a thousand per request,
  instead of dropping rows beyond the first 1000 back to Load more.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 11:08:47 +01:00
Alby96 0e52bf0e1b feat(admin): upload photos from the web panel
Owner review 2, R3: the panel can add photos to an existing or a new
sequence without the desktop app. upload.js is a dialog the library pages
open (openUpload({ api, sequence, onDone })): file picker or drag and drop
(folders are counted and left out: whole-folder import stays on the
desktop), per-photo state, a total bar, Cancel that deletes the started
uploads, and a leave-page guard while sending. Each photo is hashed in a
same-origin module worker with an in-house incremental SHA-256 (8 MiB
reads; crypto.subtle cannot hash in pieces), which runs the FIPS 180-4
known answers and a crypto.subtle cross-check before its first hash and
refuses to hash on any mismatch; the server verifies the hash again.
Chunks go through api.putBytes with the session's CSRF header, two files
and two chunks at a time, retrying no answer, 429 and 503; quota, space
and permission refusals stop the run with the server's message, and a
photo deleted from the sequence shows as deleted before.

server/info now lists the photo extensions the archive files, so the
dialog offers and sends only those. The CSP already allows the worker
(worker-src falls back to script-src 'self'); tests pin that, the module
walk follows the worker, and a browser-shaped upload runs end to end
through the cookie session.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
(cherry picked from commit c64c60ab8bb41c102182e284177ac04a56bf1058)
2026-10-27 10:52:40 +01:00
Alby96 aa1d4913a3 feat(admin): Library pages on the web panel (owner review 2, R6)
The web panel now manages the library without editing it: the owner can
browse and view sequences and photos, delete sequences and photos into the
archive's trash, restore or empty the trash and run mass operations, as
R6 asks, on top of the engine endpoints of the previous commit.

- Library page right after the Dashboard: search, Year/Camera/Status/Tag
  filters fed by a new GET /api/v1/sequences/facets, sort, cards or list
  (remembered per browser), lazy cover thumbnails, Load more by cursor,
  multi-select with Shift ranges and "Select all N" of the filter, and a
  sticky bar for the selection: Analyse, Proxies, Thumbnails, Verify,
  Tags (add/remove), Export CSV (client-side) and Delete (dry run, list
  of what moves to the trash, then the move). Filters live in the address,
  so Back from a sequence finds them again.
- Sequence view (#/library?id=): inline title, tags, rating and notes,
  facts, photos in pages of 500 with content-visibility, a photo viewer
  (proxy, arrows, Esc, Exif facts), Set cover, Download original, Delete
  photos (typing the count above 20 photos), Delete sequence, renders to
  download. No video editing controls.
- Trash view (#/library?view=trash, also linked from Archive): entries,
  Restore, and Empty (dry run, list, the localised word typed, the plan's
  fingerprint sent back, the job followed to its end).
- Live updates from sequenceChanged and jobState; keyboard grid (one tab
  stop, arrows, Space, Shift+Space, Enter, Ctrl+A, Esc); RTL, dark theme.
- GET /sequences takes rendered=true|false for the Status filter.
- ui.js: confirmDialog's typed confirmation by name, word or count, with a
  list of what the action concerns; formDialog. api.js: putBytes for the
  web upload, which the Library imports on demand (upload.js, optional).
- New web icons from icons.py (Image for the Library, trash, grid/list,
  arrows, stars, cover); directional glyphs mirror in right-to-left pages.
- Strings in en and it; tests for the facets (both dialects), the rendered
  filter, the menu, the modules and the on-demand upload import.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
(cherry picked from commit 029cf334f66cb6fa1265b96a6f8faff2964c11ea)
2026-10-27 10:51:04 +01:00
Alby96 51782a3ada feat(archive): photo delete, tombstones, trash kinds and emptying, library API
Owner review 2, R6: the web panel manages the library without editing it, so
the engine and the server must delete single photos safely, keep them out of
sync afterwards, and let an administrator restore or finally erase the trash.

- Migration 0008: frame_removals (tombstones by sequence and SHA-256, reason,
  replacement); the sidecar gains "removed" (omitted when empty) and frames a
  reserved "source"; the indexer writes the tombstones on every sync, so a
  rebuild keeps them, and drops a hero frame that is gone.
- FrameTrash: dry run (busy, frames changed, offline, would empty), delete under
  the sequence lease with a write-ahead journal that the next writer undoes
  after a crash, files to trash/photos/<seq>-<time>/originals with a record,
  sidecar without the frames plus tombstones, index sync clearing analyses,
  thumbnails and proxies, proxies renamed to follow their frames, follow-up
  jobs. Restore re-hashes every file, keeps mismatches in the trash, puts the
  same frame records back and drops their tombstones, or files the photos into
  a new sequence through the ingest when theirs is gone.
- Project positions on vanished photos are translated by photo and wait as
  pending frames, so they come back with a restore.
- Trash entries have a kind (sequence, photos, replaced); emptying is a dry run
  with a fingerprint and a new EmptyTrash job (18) that erases exactly the
  planned entries, refuses a stale plan and erases replaced originals only
  while their replacements still hash right.
- Sync honours tombstones: nothing one side deleted is offered back, local
  files are never deleted, replaced photos count as their replacement; the
  server answers an upload of a tombstoned SHA-256 as already there.
- Server: sequence thumbnail, photo delete, bulk delete/retag/jobs, trash
  list/restore/empty endpoints with their error messages; a verify of
  sequences now targets their archive (POST /jobs failed before).
- Desktop trash dialog lists photo entries and empties the trash after a
  typed confirmation through the same job.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
(cherry picked from commit 35bb56690a1d69eae57153d036e1409201cd73f7)
2026-10-27 10:49:34 +01:00
Alby96andClaude Opus 5.5 4b9ba04fe4 docs: changelog section and status for 0.1.0-rc.4
CI / Build and test (pull_request) Successful in 7m2s
CI / Windows tests and installer (pull_request) Skipped
CI / YAML check (pull_request) Successful in 10s
CI / PostgreSQL 16 integration (pull_request) Successful in 5m15s
CI / PostgreSQL 17 integration (pull_request) Successful in 5m3s
CI / Docker image (pull_request) Successful in 1m52s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 10:46:19 +01:00
Alby96andClaude Opus 5.5 ca0fec7fcd docs: decision on locked age limits and their steps
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 10:42:27 +01:00
Alby96andClaude Opus 5.5 d9d799e4d0 i18n: translate the phase 2 strings into the 36 other languages
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 10:42:17 +01:00
Alby96andClaude Opus 5.5 e6e69782ed fix(server): a locked audit retention also fixes the audit step and the switch
The audit retention in force ignored the audit clean-up's steps: with the
audit step unticked nothing was deleted, yet Settings › Logs still showed the
age limit. It is now 0 without that step, and setting a limit (Settings › Logs
or CHRONOS_AUDIT_RETENTION_DAYS at start) ticks the step again, so a saved or
fixed retention always takes effect. While the variable fixes a limit above 0,
an edit that drops the step is 409 setting_locked like turning the schedule off.

The admin panel's Scheduled tab disables what the variable fixes (the row's
switch, the form's Enabled and audit step, the age limit) with the locked
tooltip, and points a setting_locked refusal at the field actually refused.

The Copies kept tooltips now say the backups folder keeps as many copies as
the backup schedule that keeps the most; the LastDone and Newest comments
state the real first-copy rule; Keep audit is documented last-writer-wins.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 10:39:49 +01:00
Alby96andClaude Opus 5.5 94a5466c9f docs: BRIEF, DECISIONS, CHANGELOG and STATUS for owner review 2 phase 2
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 10:29:24 +01:00
Alby96andClaude Opus 5.5 6eb57ba27e fix: backup tooltips name what the schedules keep; true comment on hand-over launches
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 09:58:42 +01:00
Alby96 5cb6809fd0 fix(app): keep Jobs › Scheduled true to the scheduler
Owner review 2, phase 2 (R10) review findings on the desktop:

- Showing the Scheduled tab (and coming back to Jobs on it) reads the
  actions' availability again, as does a Run now answered unavailable;
  rows and an open editor follow, so turning proxies on no longer needs a
  restart.
- A delete the index refuses keeps the row: the failed call no longer
  reads as Deleted (the enum's default), so a live schedule never leaves
  the page.
- SchedulerReady completes false when the index (or the engine) does not
  open, so the tab shows that the schedules do not run instead of an
  empty panel.
- A read of a schedule's last job that started before a live change or a
  later read is ignored, so a finished job no longer shows as running.
- The editor's Action, Unit and Priority dropdowns follow a language
  change, keeping what was chosen.
- Weekly days in the table read from the UI language's first day, as the
  editor's toggles do.
- Backup tooltips no longer promise daily copies with three kept (their
  translations are dropped for retranslation); two tooltips now name the
  real Settings rows (Proxy size; Spazio su disco › Limite della cache).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
(cherry picked from commit c137e2c74cddef299b2e4179ef0417fa4977953c)
2026-10-27 09:58:09 +01:00
Alby96 3f0e6357b1 fix(server): archive.json on its own timer, a live Scheduled tab in one time zone, schedule audit in words
- SchedulerHost reads archive.json every 10 minutes on its own timer. The archive-scan
  runs that used to do it are skipped while a long scan is pending, and the schedule may
  be off or daily, so uploads kept a desktop's old folder template or proxy size.
- Every schedule change and run, a skipped run included, is published as a
  scheduleChanged event. The Scheduled tab reloads on it, so skipped runs, next-run moves
  and other administrators' edits show without waiting for a job.
- The Scheduled tab still draws when the schedule a job links to, or an expanded one, no
  longer exists: its runs are dropped instead of failing the whole load.
- Every time on the Scheduled tab (next run, last result, runs) is in the server's time
  zone, as its "Times in" line says.
- Audit details name a system schedule after its key (system:<key> · name · ...). The
  dashboard and the Logs page show it by its localized name and the recurrence code in
  words, as the Scheduled tab does. Older entries keep their recorded name.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
(cherry picked from commit c20f573d0bdf1cdcf3a86e9702ac76a4bf9508d9)
2026-10-27 09:57:23 +01:00
Alby96 e384564784 fix: logging never fails a job, one backup retention, first copy after the upgrade
Owner review 2, phase 2 review findings (scheduler core).

- Log.Write caught only IOException. Microsoft.Extensions.Logging wraps
  provider failures in an AggregateException, so a log line that could not
  be written (in tests: the process-wide sink of a stopped server whose log
  folder was gone) escaped JobEngine.RunAsync's catch before the failure was
  stored: the job stayed running and the worker faulted. This was the cause
  of the intermittent JobApiTests/ArchiveModuleTests failures. Log.Write now
  drops any non-fatal sink failure, TeeLogSink keeps a line from the other
  sinks, FileLogSink drops a line it cannot write and reopens the file at the
  next one, and LoggerSink drops what the providers throw. The scheduler's
  loop relies on the same guarantee.
- The daily backup loop (RunDailyAsync, IsDue, Interval, CheckInterval) had
  no caller since the index-backup schedule replaced it; it is removed and
  the DatabaseBackups summary describes the schedule.
- The first copy after the upgrade no longer waits a day (or for 03:00):
  SystemSchedule.LastDone seeds a new row due at once when its work was last
  done a period or more before, and both hosts pass the newest copy in the
  backups folder for index-backup.
- Back up now (Settings and Archive), the copy kept before a restore and a
  backup job that keeps fewer prune to the largest Copies kept of the backup
  schedules (DatabaseBackups.KeptAsync), not a fixed three. The four
  tooltips that promised three daily copies are reworded (en, it) and their
  stale translations deleted.
- New tests for the scheduler loop itself: a tick, Wake, a pass that threw,
  and dispose during a pass.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
(cherry picked from commit c5ad0c4c3f636129afe5dd1ce039185516da5621)
2026-10-27 09:56:47 +01:00
Alby96 422f33d5f3 fix(server): show the audit clean-up's real age limit and lock it before the first pass
Settings › Logs › Keep audit showed ServerOptions.AuditRetentionDays, a second
copy of the audit clean-up schedule's age limit. Edits made on Jobs › Scheduled
never reached it, so the panel could say "kept forever" while entries were
being deleted every night. Saving 0 there then changed nothing, because the
endpoint only compared against the stale option value.

- GET and PUT /server/settings now report the schedule's limit in force (0
  while the schedule is off). Saving compares against that value. A value sent
  back unchanged leaves the server.json reset default and the env lock alone. A
  new value sets the schedule and becomes the reset default.
- ApplyAgeAsync also turns the schedule on when it already holds the days but
  is off.
- CHRONOS_AUDIT_RETENTION_DAYS is now applied before the scheduler's first
  pass, through a new Scheduler.StartAsync overload with a beforeFirstPass hook.
  Before, a missed 04:30 run was caught up at start with the stale days, which
  could delete entries the variable says to keep. While the variable fixes a
  limit above 0, turning the schedule off is a 409 setting_locked.
- Corrected the comments in SchedulerHost, ServerOptions, ServerSettingsStore,
  LogSettingsDto, the header of settings.js and ARCHITECTURE.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
(cherry picked from commit 490ed286e9f32745174b13b1963d6ec91955196b)
2026-10-27 09:56:46 +01:00
Alby96 ac121acf7c fix(logs): apply log settings from the first line and name the locking variable
The desktop opened its log files with the default limits and wrote its first
line, which prunes, before Settings › Advanced › Logs were applied. Every start,
and every launch that only hands its file to the running Chronos, deleted logs
older than 14 days and cut the folder to 1 GB whatever the user kept.
AppLogging.Open now builds the sink from the stored settings before that line;
the settings are read again once the launch owns the data folder.

A total below one file deleted each finished file as the next one opened. The
rule now lives in LogFileOptions.TotalBelowFile: the server keeps refusing it,
the desktop raises the total to the file size and its rows no longer offer the
combination.

The desktop log rows threw on negative sizes from an imported or hand-edited
file and showed raw values the files never got; they now show the applied ones.

Upgraded Unraid and compose installs keep CHRONOS_LOG_LEVEL=Information, which
locks both levels. The lock stays; the server now reports which variable fixes
each locked setting (LockedBy), so the panel's tooltip names it exactly and says
to remove it to change the value there. The releases README tells upgraders.

The former-constructor log test no longer fails across midnight UTC.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
(cherry picked from commit 8ba7162bd5926d34c5ec4e40e2a2dad063ee19c3)
2026-10-27 09:56:46 +01:00
Alby96andClaude Opus 5.5 8d66be709c fix: one audit retention, scans at start, live deep analysis and a 6-hour upload sweep
Settle what the R10 scheduler and R11 log packages left open when they were
integrated (owner review 2, phase 2).

- Audit retention has one source of truth, the audit-cleanup schedule's age
  limit. AuditRetentionDays defaults to 0 (the audit log is kept forever, so
  an upgrade deletes nothing; the schedule is seeded off) and accepts 0-3650,
  what a schedule's age limit takes. Saving Settings › Logs › Keep audit sets
  the schedule's limit (on with a limit, off at 0) without a restart;
  CHRONOS_AUDIT_RETENTION_DAYS locks it and Reset goes back to it.
- Both hosts scan right after start again, as their polling did: the server
  after the scheduler starts, the desktop once the archive was reopened and
  again when an unplugged one is back. Scheduler.RunSystemNowAsync runs the
  archive-scan schedule when it is enabled and has not run since the start,
  and skips while its scan is pending.
- Desktop scans follow Settings › Analysis › After a scan at every run: a scan
  schedule without its own deep parameter asks the host
  (IScheduleHost.DeepAnalysisAfterScan), the archive-scan schedule no longer
  freezes the setting, and the editor offers deep only for analyses, so the
  setting's tooltip stays true.
- The server's upload clean-up runs every 6 hours instead of every 30
  minutes, to keep the job history readable; idle uploads still expire after
  UploadRetentionHours.
- The Unraid template and docker-compose leave CHRONOS_LOG_LEVEL empty or
  commented out, and say that setting it locks both log levels, so the admin
  panel can change them.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 02:51:04 +01:00
Alby96 bc786c12c4 feat(app): Jobs › Scheduled and the desktop scheduler
Owner review 2, R10 on the desktop: every timer that queued work out of
sight is now a visible, editable schedule of this PC.

- DesktopScheduleHost implements IScheduleHost: the PC's time zone, the
  archive at Settings › Archive's folder (refreshed from archive.json,
  none while it is offline), and three system schedules: archive-scan
  (every:<ScanIntervalMinutes>m, seeded once from the old setting, no
  catch-up), index-backup (every day with catch-up, replacing
  DatabaseBackups.RunDailyAsync) and housekeeping (daily 04:00 with
  catch-up: job history 90 days and the new cache-trim step).
- AppServices starts the Scheduler after the engine, once the archive was
  reopened; an unplugged archive is looked for every minute and the
  scheduler woken when it is back. The rescan loop and the daily backup
  loop are gone; ApplyJobSettings wakes the scheduler.
- CacheStore.Trim brings the cache to Settings › Storage › Cache limit,
  oldest files first, skipping files in use and the proxies, render-node
  and server-import folders; CacheTrimStep runs it as a clean-up step.
- Jobs gets a Queue | Scheduled segmented control. Scheduled lists the
  schedules (switch, name, action, when, next run, last result) with Run
  now, Edit, Reset (system) or Delete (user's, confirmed), the selected
  schedule's last runs with Show in queue, and an in-window editor that
  checks every field with the scheduler's limits. Jobs a schedule queued
  carry a "Scheduled" pill; the history line follows the housekeeping's
  job-history days.
- JobNotices: a scheduled background run raises a toast only when it
  fails (upkeep stays silent).
- Settings › Archive › Rescan every is removed; ScanIntervalMinutes stays
  only as the seed. Strings in en and it; the others are retranslated.
- The capture shows jobs-scheduled and jobs-schedule-editor on a stopped
  scheduler clock with sample schedules.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
(cherry picked from commit e25d812feb3f417cb9251c748c29e8035fd9b03c)
2026-10-27 02:26:07 +01:00
Alby96 75daab7275 feat(server): scheduled jobs on the server and a Scheduled tab in the admin panel
Owner review 2, R10: nothing may run out of sight, so every timer the server
ran becomes a system schedule the admin panel shows and manages, and
administrators create their own.

- SchedulerHost runs the shared Scheduler on the job engine (started after
  JobEngineHost, stopped before it); ServerScheduleHost gives it the
  container's time zone (UTC with a warning when TZ is unknown), the archive
  refreshed from archive.json at every run (what ArchivePolling did), the
  clean-up steps and the system schedules: archive-scan every 10 minutes
  (no catch-up, also run once at start like the polling), upload-cleanup
  every 30 minutes, index-backup at 03:00 (SQLite only), housekeeping (job
  history) at 04:00 and audit-cleanup at 04:30.
- ArchivePolling and DatabaseBackupService are gone; UploadMaintenance only
  recovers commits at start, its sweep is the "uploads" clean-up step.
- /api/v1/schedules (ManageArchive, audited): list with actions and time
  zone, create, PUT/PATCH, delete (409 schedule_system), run now (409
  schedule_pending), reset (409 schedule_no_defaults), runs paged by cursor;
  invalid fields are 400 invalid_schedule naming the field.
- CHRONOS_AUDIT_RETENTION_DAYS (AuditRetentionDays, default 365) seeds the
  audit clean-up; set by the environment it is applied at every start and
  locked. Job history leaves Settings: it is the housekeeping schedule's age
  limit, and the setting is what a reset restores.
- Admin panel: Jobs has Queue and Scheduled tabs; schedules with when (in
  the panel's language and the server's zone), next run, last result, a
  switch, Run now, Edit, Delete or Reset, their runs linking to the jobs, and
  a side panel for the action, recurrence and parameters; job rows a
  schedule queued carry a Scheduled pill. Strings in en and it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
(cherry picked from commit 808ce94ae29e3bf4522cb4d40dfd76d4f8529c64)
2026-10-27 02:25:01 +01:00
Alby96 e5508e7e69 feat(data): scheduler engine, schedules table and housekeeping jobs
Owner review 2, R10: every timer that queues work becomes a visible schedule,
so the server and the desktop need one shared engine to run them.

- Migration 0007: schedules table (system rows keyed by system_key) and
  jobs.schedule_id; Job.ScheduleId, JobDto.ScheduleId, JobRepository
  HasPendingAsync / ListPendingTargetsAsync / ListByScheduleAsync.
- ScheduleRepository: seeding that keeps user edits, reset, compare-and-set
  claim of a run (one winner across processes), outcomes.
- Scheduling: in-house recurrence (every/daily/weekly/monthly, DST gap moves
  forward, ambiguous time runs once), ScheduleActions resolving scan, verify,
  thumbnails, proxies, analysis, maintenance, backup, cleanup, duplicates and
  orphans into archive jobs, IScheduleHost, and the Scheduler loop (catch-up,
  clock going back, run now, CRUD as API v1 DTOs).
- New job kinds Backup (16) and Cleanup (17) with handlers, shared clean-up
  steps (job history, audit log, trash report that never deletes) and host
  steps through ArchiveServiceOptions; read-only Duplicates and Orphans report
  handlers, so the server can run those kinds too.
- JobEngine no longer purges history at start: the housekeeping schedule's
  job-history step does; JobEngine.CanRun and an EnqueueAsync with scheduleId.
- Protocol DTOs for schedules; job kind names in en and it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
(cherry picked from commit eb0edd2483a493db7c6945d5b494461cabb2a4ad)
2026-10-27 02:08:11 +01:00
Alby96 0e84392f4f feat(logs): log level, retention, size limits and rotation on server and desktop
Owner review 2, R11 asked for more log settings. The file sink now writes daily or
hourly files, continues a full file in numbered parts and prunes by age and by the
total size (never the file being written); its options change while it runs.

Server: the file and console levels are separate and read by the logging filters
at every line, so the admin panel's new Logs group applies without a restart; the
engine's level follows the lower of the two. This also fixes a bug: the file logger
was fixed at Information, so CHRONOS_LOG_LEVEL=Debug or Trace never reached the
files. New variables CHRONOS_LOG_CONSOLE_LEVEL, CHRONOS_LOG_RETENTION_DAYS,
CHRONOS_LOG_MAX_FILE_MB, CHRONOS_LOG_MAX_TOTAL_MB, CHRONOS_LOG_ROTATION,
CHRONOS_AUDIT_RETENTION_DAYS and CHRONOS_DIAGNOSTICS_LOG_MB lock their settings like
the others; the diagnostics zip keeps the configured share of each log.

Desktop: Settings > Advanced gains Log level, Keep logs, File size, Logs total,
Rotation and Diagnostics logs, applied at every save; Advanced's Reset section
restores them.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
(cherry picked from commit cc875784e4952ee0e4c807b9d9c18496d3d5a8c3)
2026-10-27 02:08:09 +01:00
85 changed files with 7227 additions and 95 deletions

No files matched your search

+10 -5
View File
@@ -176,17 +176,22 @@ svg.append('</svg>')
with write(os.path.join(here, "icons.svg")) as f:
f.write("\n".join(svg))
# The web admin's icons (its own names -> this set's), as inline SVG strings for app.js and the pages.
WEB = {"dashboard": "Library", "users": "Users", "archive": "Archive", "jobs": "Jobs", "settings": "Settings", "logs": "Logs",
"menu": "Menu", "power": "Power", "moon": "Moon", "refresh": "Refresh", "close": "Close", "plus": "Plus", "copy": "Copy",
"search": "Search"}
# The web admin's icons (its own names -> this set's), as inline SVG strings for app.js and the pages. The dashboard keeps
# the four tiles of mockup Admin.html, so the panel's Library (owner review 2, R6) is drawn as a photo.
WEB = {"dashboard": "Library", "library": "Image", "users": "Users", "archive": "Archive", "jobs": "Jobs", "settings": "Settings",
"logs": "Logs", "menu": "Menu", "power": "Power", "moon": "Moon", "refresh": "Refresh", "close": "Close", "plus": "Plus",
"copy": "Copy", "search": "Search", "grid": "ViewGrid", "list": "ViewList", "trash": "Delete", "upload": "Upload",
"download": "Download", "back": "Back", "previous": "ChevronLeft", "next": "ChevronRight", "star": "Star",
"starFilled": "StarFilled", "hero": "Hero", "image": "Image", "warning": "Warning"}
STROKE = 'fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"'
with write(os.path.join(here, "..", "..", "src", "Chronos.Server", "Admin", "web", "icons.js")) as f:
f.write("// Generated by branding/ui-icons/icons.py (same 16-px set as the desktop apps). Do not edit by hand.\n")
f.write("// Glyphs that point along the reading direction carry class=\"directional\" (mirrored in right-to-left pages, admin.css).\n")
f.write("export const icons = {\n")
for key, name in WEB.items():
stroke, fill = I[name]
paths = (f'<path d="{fill}" fill="currentColor"/>' if fill else "") + (f'<path d="{stroke}" {STROKE}/>' if stroke else "")
f.write(f' {key}: `<svg viewBox="0 0 16 16" width="16" height="16" aria-hidden="true">{paths}</svg>`,\n')
mirror = ' class="directional"' if name in DIRECTIONAL else ""
f.write(f' {key}: `<svg{mirror} viewBox="0 0 16 16" width="16" height="16" aria-hidden="true">{paths}</svg>`,\n')
f.write("};\n")
print(len(I), "icons,", len(WEB), "web icons")
+7 -6
View File
@@ -54,13 +54,13 @@ Dependencies point one way: `Core` ← `Core.Windows`, `Data`, `Protocol` ← `S
|---|---|
| `Sqlite`, `Postgres` | SQLite P/Invoke binding (winsqlite3 / libsqlite3), in-house PostgreSQL wire protocol v3 client with pool and LISTEN |
| `Migrations/{sqlite,postgres}/NNNN_name.sql` | Embedded, applied in one transaction at open (`MigrationRunner`) |
| `Repositories` | `ChronosDatabase` facade: archives, sequences, frames, tags, renders, jobs, cards, users, tokens, uploads, render nodes, settings, audit, schedules (`ScheduleRepository`: system rows seeded without overwriting edits and never deleted, the compare-and-set claim of a run); `DatabaseBackups` (`VACUUM INTO` copies of an SQLite index into `backups` next to it, every copy keeping as many as the backup schedules keep (`KeptAsync`), the newest copy that seeds the `index-backup` schedule (`Newest`, `SystemSchedule.LastDone`), restore staged for the next start and carried out before the index opens, so it also recovers one that no longer opens) |
| `Repositories` | `ChronosDatabase` facade: archives, sequences, frames, tags, renders, jobs, cards, users, tokens, uploads, render nodes, settings, audit, schedules (`ScheduleRepository`: system rows seeded without overwriting edits and never deleted, the compare-and-set claim of a run), tombstones of removed photos (`FrameRemovalRepository`, `frame_removals`, written from the sidecar's `removed` list); `DatabaseBackups` (`VACUUM INTO` copies of an SQLite index into `backups` next to it, every copy keeping as many as the backup schedules keep (`KeptAsync`), the newest copy that seeds the `index-backup` schedule (`Newest`, `SystemSchedule.LastDone`), restore staged for the next start and carried out before the index opens, so it also recovers one that no longer opens) |
| `Jobs` | `JobEngine` (one job at a time; reviews the priority queue and makes a lower running job yield, requeued with its checkpoint; no history purge, the housekeeping schedule's clean-up does it), `JobPriorityQueue` (a level per job kind, the claim order, settings round trip), `IJobHandler`, `IJobHandlerProvider`, `JobContext` (progress, checkpoints, follow-up jobs that never interrupt their parent), `JobThroughput`/`JobEta` (rate and bounded time left) |
| `Scheduling` | `Scheduler` (one per host: seeds the host's system schedules, claims due runs by compare-and-set, catch-up, clock changes, create/edit/reset/delete/run now as API v1 DTOs), `ScheduleRecurrence` (the in-house `every:`/`daily:`/`weekly:`/`monthly:` form, wall-clock times across DST), `ScheduleActions` (action names, parameters, availability, the archive jobs a run queues), `IScheduleHost` and `SystemSchedule` (what the server and the desktop supply), `ScheduleOutcome`, `ScheduleMapping` (model ↔ DTO) |
| `Housekeeping` | `BackupJobHandler`, `CleanupJobHandler`, `ICleanupStep` with the shared steps (`CleanupSteps`: job history, audit log, trash report that never deletes); hosts add their own steps through `ArchiveServiceOptions.CleanupSteps` |
| `Archiving` | `ArchiveService` (create/adopt/open, archive settings written to `archive.json` then the index), `ArchiveIndexer` (scan, rebuild), `ArchiveIngest` (uploads and imports), `ImportService`, `ArchiveVerifier`, `ArchiveImages` (thumbnail and proxy passes, several photos at once through `OrderedWork`, which hands results back in frame order), `FrameTiers` (decode tier, `PreviewOnly`/`Undecodable` flags and preview size of frames, written to sidecar and index by the light analysis, deep analysis, renders and image passes), `GprCompanions` (the JPEG of each GoPro GPR, found in the index when an import kept it in another sequence), `ArchiveMaintenance`, `MassRenamer`, `SequenceTrash` (delete into the archive's hidden trash with a dry run, restore; the folder moves back when the index step fails), job handlers |
| `Archiving` | `ArchiveService` (create/adopt/open, archive settings written to `archive.json` then the index), `ArchiveIndexer` (scan, rebuild), `ArchiveIngest` (uploads and imports), `ImportService`, `ArchiveVerifier`, `ArchiveImages` (thumbnail and proxy passes, several photos at once through `OrderedWork`, which hands results back in frame order), `FrameTiers` (decode tier, `PreviewOnly`/`Undecodable` flags and preview size of frames, written to sidecar and index by the light analysis, deep analysis, renders and image passes), `GprCompanions` (the JPEG of each GoPro GPR, found in the index when an import kept it in another sequence), `ArchiveMaintenance`, `MassRenamer`, `SequenceTrash` (delete into the archive's hidden trash with a dry run, restore; the folder moves back when the index step fails; lists sequence and photo entries; `SequenceTrash.Empty`: the emptying's dry run, fingerprint and erase), `FrameTrash` (photos of a sequence into `trash/photos` with a dry run, a journal that undoes an interrupted deletion, tombstones, positions parked and placed back, proxies renamed to follow their frames; restore re-hashes each file, into a new sequence through the ingest when theirs is gone), job handlers |
| `Processing` | `ProcessingService`, `SequenceAnalyser`, `DeepReports` (a saved deep report while it still describes the frames), `SequenceRender`, `ProjectStore`, `ProjectBundles` (a `.chronos` file for a sequence, and the sequence a file names), `RenderNodeClient`, job handlers |
| `Sync` | `SyncService` (sync table of one server: compare, link by content, settle conflicts, enqueue transfers), `SyncRules` (status, settings merge and differences, no I/O), `SyncPositions` (the settings' frame positions translated by photo to the frames of the copy they go to), `SyncLinkStore` (`sync_links`, `sync_state`), `SyncTransfers` and `SyncJobHandler` (resumable, hash-verified uploads and downloads as jobs; downloads commit through the archive ingest), `SyncAgent` (background comparison, server events, backoff, offline proxies), `ProxyCache` and `RemoteSequence` (server sequences opened with proxies), `ISyncRemote` (the server calls; `ChronosSyncRemote` over `ChronosClient`) |
| `Sync` | `SyncService` (sync table of one server: compare, link by content, settle conflicts, enqueue transfers), `SyncRules` (status, settings merge and differences, no I/O), `SyncTombstones` (photos either side removed are not offered back, a replaced photo counts as its replacement), `SyncPositions` (the settings' frame positions translated by photo to the frames of the copy they go to), `SyncLinkStore` (`sync_links`, `sync_state`), `SyncTransfers` and `SyncJobHandler` (resumable, hash-verified uploads and downloads as jobs; downloads commit through the archive ingest), `SyncAgent` (background comparison, server events, backoff, offline proxies), `ProxyCache` and `RemoteSequence` (server sequences opened with proxies), `ISyncRemote` (the server calls; `ChronosSyncRemote` over `ChronosClient`) |
### 2.3 Chronos.App areas
@@ -71,7 +71,7 @@ Dependencies point one way: `Core` ← `Core.Windows`, `Data`, `Protocol` ← `S
| `Library` | Filter, facets, pager, timeline, saved views, quick and mass actions, remote cards and thumbnails, thumbnail cache, list export |
| `Editor` | `EditorSession` (project, undo/redo, saving, merges), `ISequenceSource` (`LocalSequenceSource`, `RemoteSequenceSource`), the steps of the Edit path (`EditPath`: their order, each step's state, the step of each finding, the memory of the step shown; tabs Analysis, Frames, Exposure, Motion, Camera, Time, Stack, Export), `PreviewRenderer`, `ExportPlanner`, `ExportSync`, `SavedCopies`, `SequenceJobs`, `ProjectFiles` (save and open `.chronos` project files) |
| `Import` | `CardPool` (inserted cards, remembered cards, folders), camera profiles, plans and choices, destinations (archive, folder, server through `ServerImportSink`), card actions (verified delete, format, eject) |
| `Archive` | `CurrentArchive`, `ArchiveTree`, figures for the charts, maintenance reports, mass rename and move, delete and trash dialogs (`SequenceDeletion`, `DeletePlans`), `ArchiveFailures` |
| `Archive` | `CurrentArchive`, `ArchiveTree`, figures for the charts, maintenance reports, mass rename and move, delete and trash dialogs (`SequenceDeletion`, `DeletePlans`, `TrashEmptyPlans`: Empty… behind a dry run and a typed confirmation), `ArchiveFailures` |
| `Server` | `ServerSession`, `ConnectFlow` (trust on first use), `SyncHost` (sync engine, agent, metered hold, editor connections, Export Sync), sync table, `RemoteSequenceApi` |
| `Jobs`, `Settings`, `About` | Job list and buffering, `JobNotices` (which job endings raise a toast; `JobEndings` lets a batch speak once); the schedules of Jobs › Scheduled (`DesktopScheduleHost`: the desktop's `IScheduleHost` and its system schedules `archive-scan`, `index-backup`, `housekeeping`; `CacheTrimStep`, the host's clean-up step; `SchedulesViewModel`, `ScheduleRowViewModel`, `ScheduleEditorViewModel` and `ScheduleDialogs.xaml`, the in-window editor; `ScheduleText`); settings rows (`LogSettingsRows`: Advanced's log rows), encoder and format inventories, `ProcessingTuning` (Settings › Rendering and Analysis applied to each job: parallelism, memory budget, quality), `InterfacePriority`, language catalog, naming preview; `AboutViewModel` (owned by the shell, not a section: Settings › About, the update notice of Settings › Updates and the update check on start), update check and download |
| `Infrastructure` | `AppServices` (composition root), `AppSettings`, `AppLogging` (Settings › Advanced › Logs applied to the log files from their first line, a launch that only hands over included, and at every save), `AppEnvironment` (installed or portable), `AppClock` (today's date, frozen by `--capture`), `StartWithWindows` (this copy's sign-in entry), `UiLanguage`, `LiveRegion`, `RenderNodeHost`, `DiagnosticsBundle`, `ShellActions` (BRIEF §8.6), `SingleInstance` (one Chronos per data folder; a later launch hands its file over a named pipe, or waits for a closing one to exit and starts in its place), device monitor |
@@ -85,10 +85,10 @@ Dependencies point one way: `Core` ← `Core.Windows`, `Data`, `Protocol` ← `S
| `Ui/Controls` | `ChronosWindow` (chrome, language direction), `NavRail`, `JobBar`, `ToastHost`, `Field` (placeholder, icon, error), `Chip`, `AutoSlider`, `StatusGlyph`, `EmptyState`, `Icon`, `Bidi` (right-to-left rules), `Motion` (animations off for screenshots) |
| `Ui/Interop` | DWM calls of the window chrome; `TrayIcon` (`Shell_NotifyIconW`: the Uploader's tray, the client's Windows notifications) |
| `Ui/Visuals` | `DrawingElement` (hover readout, item keyboard and activation) and its charts (`BarChart`, `SeriesChart`, `StackedBar`, `HeatmapStrip`, `TimelineBands`), `Filmstrip`, `PreviewViewport`, `CurveEditor`, `SequenceCard`, `VirtualizingWrapPanel`, `SegmentedControl`, `SplitButton` |
| `Server/Api`, `Server/Events` | Endpoint groups (`XxxEndpoints.Map`; `ScheduleEndpoints`: `/api/v1/schedules`), API errors, the WebSocket `EventHub` |
| `Server/Api`, `Server/Events` | Endpoint groups (`XxxEndpoints.Map`; `ScheduleEndpoints`: `/api/v1/schedules`; `LibraryEndpoints`: the Library filters' facets, sequence thumbnail, photo delete, bulk delete/retag/jobs; `TrashEndpoints`: list, restore, empty), API errors, the WebSocket `EventHub` |
| `Server/Security` | Accounts, password hashing, tokens, session cookies, login guard, access rules, audit log |
| `Server/Storage`, `Server/Jobs` | Archive and processing modules, uploads (`UploadMaintenance`: recovery at start, and the sweep that is the `uploads` clean-up step), render store; `JobEngineHost`, `SchedulerHost` (the `Scheduler` on the engine, started after it; archive.json read every 10 minutes whatever the scan schedule does; every schedule change and run published as a `scheduleChanged` event) and `ServerScheduleHost` (time zone, archive refreshed from archive.json, system schedules), render node service, monitor and availability |
| `Server/Hosting`, `Server/Admin/web` | `ServerHost`, `ServerLogging` (console and file levels the logging filters read at every line, the file sink's limits, the engine's level; applied again when Settings › Logs is saved), certificates, discovery beacon, embedded static files, Windows service (start and stop failures in the Application event log); the admin panel (ES modules, one per page; `schedules.js` is the Jobs page's Scheduled tab) |
| `Server/Hosting`, `Server/Admin/web` | `ServerHost`, `ServerLogging` (console and file levels the logging filters read at every line, the file sink's limits, the engine's level; applied again when Settings › Logs is saved), certificates, discovery beacon, embedded static files (`EmbeddedStaticFiles`: `no-cache` and a content ETag, so an upgrade never mixes old and new modules), Windows service (start and stop failures in the Application event log); the admin panel (ES modules, one per page; `schedules.js` is the Jobs page's Scheduled tab; the Library's views in `pages/library/`: `sequence.js` a sequence and its photo viewer, `trash.js` the archive's trash, `shared.js` cards, selection and grid keyboard; `upload.js` the upload dialog the Library opens on demand, hashing in the module worker `hash-worker.js` with the in-house incremental SHA-256 of `sha256.js`, self-tested before its first use) |
### 2.5 Hosts
@@ -114,6 +114,7 @@ Dependencies point one way: `Core` ← `Core.Windows`, `Data`, `Protocol` ← `S
| `Duplicates`, `Orphans` | `Archiving/Jobs/ReportJobHandlers` (read-only reports into the job log, queued by schedules); the Archive screen still queries `ArchiveService` directly | yes | yes |
| `Backup` | `Housekeeping/BackupJobHandler` (via `ArchiveService.CreateJobHandlers`; an SQLite index file only) | yes | SQLite only |
| `Cleanup` | `Housekeeping/CleanupJobHandler` (shared steps, plus the host's from `ArchiveServiceOptions.CleanupSteps`) | yes | yes |
| `EmptyTrash` | `Archiving/Jobs/EmptyTrashJobHandler` (erases exactly a confirmed plan's trash entries; refuses a stale fingerprint) | yes | yes |
| `Adopt`, `Move` | none: done synchronously (`ArchiveService` actions) | — | — |
A job engine claims only kinds it has handlers for. Light analysis is queued by the engine (`JobContext` follow-up)
+324
View File
@@ -10,6 +10,7 @@
<data name="Admin.About.Uptime" xml:space="preserve"><value>Running for</value></data>
<data name="Admin.About.Version" xml:space="preserve"><value>Version</value></data>
<data name="Admin.Activity.ArchiveSettings" xml:space="preserve"><value>{0} changed the archive layout</value><comment>long</comment></data>
<data name="Admin.Activity.FramesDeleted" xml:space="preserve"><value>{0} deleted {1}</value><comment>long</comment></data>
<data name="Admin.Activity.JobCreated" xml:space="preserve"><value>{0} started {1}</value><comment>long</comment></data>
<data name="Admin.Activity.Login" xml:space="preserve"><value>{0} signed in · {1}</value><comment>long</comment></data>
<data name="Admin.Activity.LoginFailed" xml:space="preserve"><value>failed sign-in as {0}</value><comment>long</comment></data>
@@ -24,6 +25,8 @@
<data name="Admin.Activity.SequenceDeleted" xml:space="preserve"><value>{0} deleted {1}</value><comment>long</comment></data>
<data name="Admin.Activity.SequenceUpdated" xml:space="preserve"><value>{0} edited a sequence · {1}</value><comment>long</comment></data>
<data name="Admin.Activity.ServerSettings" xml:space="preserve"><value>{0} changed the server settings</value><comment>long</comment></data>
<data name="Admin.Activity.TrashEmptied" xml:space="preserve"><value>{0} emptied the trash · {1}</value><comment>long</comment></data>
<data name="Admin.Activity.TrashRestored" xml:space="preserve"><value>{0} restored {1} from the trash</value><comment>long</comment></data>
<data name="Admin.Activity.UserCreated" xml:space="preserve"><value>{0} created user {1}</value><comment>long</comment></data>
<data name="Admin.Activity.UserDeleted" xml:space="preserve"><value>{0} deleted user {1}</value><comment>long</comment></data>
<data name="Admin.Activity.UserUpdated" xml:space="preserve"><value>{0} changed a user · {1}</value><comment>long</comment></data>
@@ -52,6 +55,8 @@
<data name="Admin.Archive.Scan" xml:space="preserve"><value>Scan</value></data>
<data name="Admin.Archive.Scan.Tip" xml:space="preserve"><value>Look for new and changed sequences on disk</value></data>
<data name="Admin.Archive.Sequences" xml:space="preserve"><value>Sequences</value></data>
<data name="Admin.Archive.Trash" xml:space="preserve"><value>Trash</value></data>
<data name="Admin.Archive.Trash.Tip" xml:space="preserve"><value>Open the archive's trash: deleted sequences and photos, to restore or erase for good</value></data>
<data name="Admin.Archive.UnverifiedUnit.one" xml:space="preserve"><value>unverified</value></data>
<data name="Admin.Archive.UnverifiedUnit.other" xml:space="preserve"><value>unverified</value></data>
<data name="Admin.Archive.Verify" xml:space="preserve"><value>Verify</value></data>
@@ -70,9 +75,13 @@
<data name="Admin.Common.Save" xml:space="preserve"><value>Save</value></data>
<data name="Admin.Common.Save.Tip" xml:space="preserve"><value>Save the changes on the server</value></data>
<data name="Admin.Common.Saved" xml:space="preserve"><value>Saved.</value></data>
<data name="Admin.Common.TypeCount.Tip" xml:space="preserve"><value>Type the number shown: how many photos go</value></data>
<data name="Admin.Common.TypeCountFirst.Tip" xml:space="preserve"><value>Type the number above first</value></data>
<data name="Admin.Common.TypeFirst.Tip" xml:space="preserve"><value>Type the name above first</value></data>
<data name="Admin.Common.TypeToConfirm" xml:space="preserve"><value>Type {0} to confirm</value><comment>long</comment></data>
<data name="Admin.Common.TypeToConfirm.Tip" xml:space="preserve"><value>Type the name exactly as shown to confirm</value></data>
<data name="Admin.Common.TypeWord.Tip" xml:space="preserve"><value>Type the word exactly as shown; upper or lower case does not matter</value></data>
<data name="Admin.Common.TypeWordFirst.Tip" xml:space="preserve"><value>Type the word above first</value></data>
<data name="Admin.Dashboard.Activity" xml:space="preserve"><value>Recent activity</value></data>
<data name="Admin.Dashboard.AllLogs" xml:space="preserve"><value>All logs</value></data>
<data name="Admin.Dashboard.AllLogs.Tip" xml:space="preserve"><value>Open the audit log</value></data>
@@ -125,6 +134,7 @@
<data name="Admin.Job.Kind.Cleanup" xml:space="preserve"><value>Clean-up</value></data>
<data name="Admin.Job.Kind.DeepAnalyse" xml:space="preserve"><value>Deep analysis</value></data>
<data name="Admin.Job.Kind.Duplicates" xml:space="preserve"><value>Duplicates</value></data>
<data name="Admin.Job.Kind.EmptyTrash" xml:space="preserve"><value>Empty trash</value></data>
<data name="Admin.Job.Kind.Import" xml:space="preserve"><value>Import</value></data>
<data name="Admin.Job.Kind.LightAnalyse" xml:space="preserve"><value>Light analysis</value></data>
<data name="Admin.Job.Kind.Maintenance" xml:space="preserve"><value>Maintenance</value></data>
@@ -200,6 +210,131 @@
<data name="Admin.Jobs.Tab.Schedules.Tip" xml:space="preserve"><value>Jobs the server queues by itself on a schedule: see, create and change them</value></data>
<data name="Admin.Jobs.Target" xml:space="preserve"><value>Target</value></data>
<data name="Admin.Language.Tip" xml:space="preserve"><value>Language of this panel</value></data>
<data name="Admin.Library.AddTags" xml:space="preserve"><value>Add</value></data>
<data name="Admin.Library.AddTags.Tip" xml:space="preserve"><value>Tags to add, separated by commas</value></data>
<data name="Admin.Library.AnyCamera" xml:space="preserve"><value>All cameras</value></data>
<data name="Admin.Library.AnyStatus" xml:space="preserve"><value>Any status</value></data>
<data name="Admin.Library.AnyTag" xml:space="preserve"><value>All tags</value></data>
<data name="Admin.Library.AnyYear" xml:space="preserve"><value>All years</value></data>
<data name="Admin.Library.Apply" xml:space="preserve"><value>Apply</value></data>
<data name="Admin.Library.Apply.Tip" xml:space="preserve"><value>Change the tags of the selected sequences</value></data>
<data name="Admin.Library.BlockedItem" xml:space="preserve"><value>{0}: {1}</value><comment>long; {0} a sequence's title, {1} why it cannot move</comment></data>
<data name="Admin.Library.Camera.Tip" xml:space="preserve"><value>Show only the sequences of this camera model</value></data>
<data name="Admin.Library.ClearFilters" xml:space="preserve"><value>Clear filters</value></data>
<data name="Admin.Library.ClearFilters.Tip" xml:space="preserve"><value>Show every sequence again</value></data>
<data name="Admin.Library.ClearSelection.Tip" xml:space="preserve"><value>Deselect everything · Esc</value></data>
<data name="Admin.Library.Column.Camera" xml:space="preserve"><value>Camera</value></data>
<data name="Admin.Library.Column.Date" xml:space="preserve"><value>Date</value></data>
<data name="Admin.Library.Column.Photos" xml:space="preserve"><value>Photos</value></data>
<data name="Admin.Library.Column.Sequence" xml:space="preserve"><value>Sequence</value></data>
<data name="Admin.Library.Column.Size" xml:space="preserve"><value>Size</value></data>
<data name="Admin.Library.Count.one" xml:space="preserve"><value>{0} sequence</value></data>
<data name="Admin.Library.Count.other" xml:space="preserve"><value>{0} sequences</value></data>
<data name="Admin.Library.Csv.Bytes" xml:space="preserve"><value>Bytes</value></data>
<data name="Admin.Library.Csv.Camera" xml:space="preserve"><value>Camera</value></data>
<data name="Admin.Library.Csv.First" xml:space="preserve"><value>First photo</value></data>
<data name="Admin.Library.Csv.Last" xml:space="preserve"><value>Last photo</value></data>
<data name="Admin.Library.Csv.Photos" xml:space="preserve"><value>Photos</value></data>
<data name="Admin.Library.Csv.Tags" xml:space="preserve"><value>Tags</value></data>
<data name="Admin.Library.Csv.Title" xml:space="preserve"><value>Title</value></data>
<data name="Admin.Library.Delete" xml:space="preserve"><value>Delete…</value></data>
<data name="Admin.Library.Delete.Tip" xml:space="preserve"><value>Move the selected sequences into the archive's trash; a list shows what goes first</value></data>
<data name="Admin.Library.DeleteBlocked.one" xml:space="preserve"><value>{0} other sequence cannot move; the list says why.</value><comment>long</comment></data>
<data name="Admin.Library.DeleteBlocked.other" xml:space="preserve"><value>{0} other sequences cannot move; the list says why.</value><comment>long</comment></data>
<data name="Admin.Library.DeleteBody.one" xml:space="preserve"><value>{0} sequence, {1} ({2}), moves to the archive's trash; it can be restored until the trash is emptied.</value><comment>long</comment></data>
<data name="Admin.Library.DeleteBody.other" xml:space="preserve"><value>{0} sequences, {1} ({2}), move to the archive's trash; they can be restored until the trash is emptied.</value><comment>long</comment></data>
<data name="Admin.Library.DeleteConfirm" xml:space="preserve"><value>Move to trash</value></data>
<data name="Admin.Library.DeleteConfirm.Tip" xml:space="preserve"><value>Move them into the archive's trash; nothing is erased</value></data>
<data name="Admin.Library.DeleteTitle.one" xml:space="preserve"><value>Delete {0} sequence?</value><comment>long</comment></data>
<data name="Admin.Library.DeleteTitle.other" xml:space="preserve"><value>Delete {0} sequences?</value><comment>long</comment></data>
<data name="Admin.Library.Deleted.one" xml:space="preserve"><value>{0} sequence moved to the trash ({1})</value><comment>long</comment></data>
<data name="Admin.Library.Deleted.other" xml:space="preserve"><value>{0} sequences moved to the trash ({1})</value><comment>long</comment></data>
<data name="Admin.Library.Empty" xml:space="preserve"><value>No sequences yet</value></data>
<data name="Admin.Library.ExportCsv" xml:space="preserve"><value>Export CSV</value></data>
<data name="Admin.Library.ExportCsv.Tip" xml:space="preserve"><value>Save the selected sequences as a CSV file: title, camera, photos, size, dates and tags</value></data>
<data name="Admin.Library.Exported.one" xml:space="preserve"><value>{0} sequence exported</value><comment>long</comment></data>
<data name="Admin.Library.Exported.other" xml:space="preserve"><value>{0} sequences exported</value><comment>long</comment></data>
<data name="Admin.Library.Filter.Analysed" xml:space="preserve"><value>Analysed</value></data>
<data name="Admin.Library.Filter.Errors" xml:space="preserve"><value>With errors</value></data>
<data name="Admin.Library.Filter.NoProxies" xml:space="preserve"><value>Without proxies</value></data>
<data name="Admin.Library.Filter.NotAnalysed" xml:space="preserve"><value>Not analysed</value></data>
<data name="Admin.Library.Filter.NotRendered" xml:space="preserve"><value>Not rendered</value></data>
<data name="Admin.Library.Filter.NotVerified" xml:space="preserve"><value>Not verified</value></data>
<data name="Admin.Library.Filter.Proxies" xml:space="preserve"><value>With proxies</value></data>
<data name="Admin.Library.Filter.Rendered" xml:space="preserve"><value>Rendered</value></data>
<data name="Admin.Library.Filter.Verified" xml:space="preserve"><value>Verified</value></data>
<data name="Admin.Library.Filter.Warnings" xml:space="preserve"><value>With warnings</value></data>
<data name="Admin.Library.Job.Analyse" xml:space="preserve"><value>Analyse</value></data>
<data name="Admin.Library.Job.Analyse.Tip" xml:space="preserve"><value>Queue the light analysis of the selected sequences</value></data>
<data name="Admin.Library.Job.Proxies" xml:space="preserve"><value>Proxies</value></data>
<data name="Admin.Library.Job.Proxies.Tip" xml:space="preserve"><value>Queue building the proxies of the selected sequences</value></data>
<data name="Admin.Library.Job.Thumbnails" xml:space="preserve"><value>Thumbnails</value></data>
<data name="Admin.Library.Job.Thumbnails.Tip" xml:space="preserve"><value>Queue drawing the thumbnails of the selected sequences again</value></data>
<data name="Admin.Library.Job.Verify" xml:space="preserve"><value>Verify</value></data>
<data name="Admin.Library.Job.Verify.Tip" xml:space="preserve"><value>Queue a verify: every original of the selected sequences is read again and its SHA-256 compared</value></data>
<data name="Admin.Library.JobsQueued.one" xml:space="preserve"><value>{0} job queued.</value></data>
<data name="Admin.Library.JobsQueued.other" xml:space="preserve"><value>{0} jobs queued.</value></data>
<data name="Admin.Library.NoMatch" xml:space="preserve"><value>No sequences match the filters</value></data>
<data name="Admin.Library.NoTags" xml:space="preserve"><value>Type at least one tag to add or remove.</value><comment>long</comment></data>
<data name="Admin.Library.NothingQueued" xml:space="preserve"><value>Nothing queued.</value></data>
<data name="Admin.Library.NothingToDelete" xml:space="preserve"><value>None of the selected sequences can move to the trash.</value><comment>long</comment></data>
<data name="Admin.Library.Open.Tip" xml:space="preserve"><value>Enter or click opens the sequence; Space selects it, Shift+Space selects a range</value></data>
<data name="Admin.Library.Refresh.Tip" xml:space="preserve"><value>Read the list again</value></data>
<data name="Admin.Library.RemoveTags" xml:space="preserve"><value>Remove</value></data>
<data name="Admin.Library.RemoveTags.Tip" xml:space="preserve"><value>Tags to remove, separated by commas; upper or lower case does not matter</value></data>
<data name="Admin.Library.Retag" xml:space="preserve"><value>Tags…</value></data>
<data name="Admin.Library.Retag.Tip" xml:space="preserve"><value>Add tags to the selected sequences or remove tags from them</value></data>
<data name="Admin.Library.RetagTitle.one" xml:space="preserve"><value>Tags of {0} sequence</value><comment>long</comment></data>
<data name="Admin.Library.RetagTitle.other" xml:space="preserve"><value>Tags of {0} sequences</value><comment>long</comment></data>
<data name="Admin.Library.Retagged.one" xml:space="preserve"><value>Tags changed on {0} sequence</value><comment>long</comment></data>
<data name="Admin.Library.Retagged.other" xml:space="preserve"><value>Tags changed on {0} sequences</value><comment>long</comment></data>
<data name="Admin.Library.Search" xml:space="preserve"><value>Search title, camera, tag</value></data>
<data name="Admin.Library.Search.Tip" xml:space="preserve"><value>Show the sequences whose title, camera or a tag contains this text</value></data>
<data name="Admin.Library.Select.Tip" xml:space="preserve"><value>Select or deselect; with Shift, every sequence from the last one picked</value></data>
<data name="Admin.Library.SelectAll" xml:space="preserve"><value>Select all {0}</value></data>
<data name="Admin.Library.SelectAll.Tip" xml:space="preserve"><value>Select every sequence of these filters, also those not loaded yet</value></data>
<data name="Admin.Library.Selected.one" xml:space="preserve"><value>{0} selected</value></data>
<data name="Admin.Library.Selected.other" xml:space="preserve"><value>{0} selected</value></data>
<data name="Admin.Library.Selection" xml:space="preserve"><value>Selection</value></data>
<data name="Admin.Library.Sequences" xml:space="preserve"><value>Sequences</value></data>
<data name="Admin.Library.Shown" xml:space="preserve"><value>Showing {0} of {1}</value></data>
<data name="Admin.Library.Skipped.one" xml:space="preserve"><value>{0} skipped</value></data>
<data name="Admin.Library.Skipped.other" xml:space="preserve"><value>{0} skipped</value></data>
<data name="Admin.Library.Sort.FrameCount" xml:space="preserve"><value>Most photos</value></data>
<data name="Admin.Library.Sort.Newest" xml:space="preserve"><value>Newest first</value></data>
<data name="Admin.Library.Sort.Oldest" xml:space="preserve"><value>Oldest first</value></data>
<data name="Admin.Library.Sort.Size" xml:space="preserve"><value>Largest first</value></data>
<data name="Admin.Library.Sort.Tip" xml:space="preserve"><value>Order of the sequences</value></data>
<data name="Admin.Library.Sort.Title" xml:space="preserve"><value>Title</value></data>
<data name="Admin.Library.Status.Analysed" xml:space="preserve"><value>Analysed</value></data>
<data name="Admin.Library.Status.Analysed.Tip" xml:space="preserve"><value>The light analysis is done</value></data>
<data name="Admin.Library.Status.Errors" xml:space="preserve"><value>Errors</value></data>
<data name="Admin.Library.Status.Errors.Tip" xml:space="preserve"><value>Some photos are missing or damaged; a verify tells which</value></data>
<data name="Admin.Library.Status.NoProxies" xml:space="preserve"><value>No proxies</value></data>
<data name="Admin.Library.Status.NoProxies.Tip" xml:space="preserve"><value>No proxies yet: select it and choose Proxies</value></data>
<data name="Admin.Library.Status.NotAnalysed" xml:space="preserve"><value>Not analysed</value></data>
<data name="Admin.Library.Status.NotAnalysed.Tip" xml:space="preserve"><value>Not analysed yet: select it and choose Analyse</value></data>
<data name="Admin.Library.Status.Proxies" xml:space="preserve"><value>Proxies</value></data>
<data name="Admin.Library.Status.Proxies.Tip" xml:space="preserve"><value>Proxies are built for viewing and editing</value></data>
<data name="Admin.Library.Status.Renders.Tip" xml:space="preserve"><value>Videos rendered from this sequence, listed on its page</value></data>
<data name="Admin.Library.Status.Renders.one" xml:space="preserve"><value>{0} render</value></data>
<data name="Admin.Library.Status.Renders.other" xml:space="preserve"><value>{0} renders</value></data>
<data name="Admin.Library.Status.Tip" xml:space="preserve"><value>Show only the sequences in this state</value></data>
<data name="Admin.Library.Status.Verified" xml:space="preserve"><value>Verified</value></data>
<data name="Admin.Library.Status.Verified.Tip" xml:space="preserve"><value>Every original matched its SHA-256 at the last verify</value></data>
<data name="Admin.Library.Status.Warnings.Tip" xml:space="preserve"><value>The analysis found something to look at, such as flicker or gaps</value></data>
<data name="Admin.Library.Status.Warnings.one" xml:space="preserve"><value>{0} warning</value></data>
<data name="Admin.Library.Status.Warnings.other" xml:space="preserve"><value>{0} warnings</value></data>
<data name="Admin.Library.Tag.Tip" xml:space="preserve"><value>Show only the sequences with this tag</value></data>
<data name="Admin.Library.TagTooLong" xml:space="preserve"><value>A tag has at most 64 characters.</value><comment>long</comment></data>
<data name="Admin.Library.Trash" xml:space="preserve"><value>Trash</value></data>
<data name="Admin.Library.Trash.Tip" xml:space="preserve"><value>Deleted sequences and photos: restore them, or empty the trash</value></data>
<data name="Admin.Library.Upload" xml:space="preserve"><value>Upload</value></data>
<data name="Admin.Library.Upload.Tip" xml:space="preserve"><value>Upload photos from this computer into a new or an existing sequence</value></data>
<data name="Admin.Library.View" xml:space="preserve"><value>View</value></data>
<data name="Admin.Library.View.Grid.Tip" xml:space="preserve"><value>Show the sequences as cards</value></data>
<data name="Admin.Library.View.List.Tip" xml:space="preserve"><value>Show the sequences as a list</value></data>
<data name="Admin.Library.Year.Tip" xml:space="preserve"><value>Show only the sequences whose first photo was taken in this year</value></data>
<data name="Admin.Login.Failed" xml:space="preserve"><value>Wrong user name or password.</value><comment>long</comment></data>
<data name="Admin.Login.NotAdmin" xml:space="preserve"><value>Only administrators can use this panel.</value><comment>long</comment></data>
<data name="Admin.Login.Password" xml:space="preserve"><value>Password</value></data>
@@ -209,6 +344,7 @@
<data name="Admin.Login.User" xml:space="preserve"><value>User</value></data>
<data name="Admin.Login.User.Tip" xml:space="preserve"><value>Your user name on this server</value></data>
<data name="Admin.Logs.Action.ArchiveSettings" xml:space="preserve"><value>Archive layout</value></data>
<data name="Admin.Logs.Action.FramesDeleted" xml:space="preserve"><value>Photos deleted</value></data>
<data name="Admin.Logs.Action.JobCreated" xml:space="preserve"><value>Job started</value></data>
<data name="Admin.Logs.Action.Login" xml:space="preserve"><value>Sign-in</value></data>
<data name="Admin.Logs.Action.LoginFailed" xml:space="preserve"><value>Failed sign-in</value></data>
@@ -224,6 +360,8 @@
<data name="Admin.Logs.Action.SequenceUpdated" xml:space="preserve"><value>Sequence edited</value></data>
<data name="Admin.Logs.Action.ServerDiagnostics" xml:space="preserve"><value>Diagnostics exported</value></data>
<data name="Admin.Logs.Action.ServerSettings" xml:space="preserve"><value>Server settings</value></data>
<data name="Admin.Logs.Action.TrashEmptied" xml:space="preserve"><value>Trash emptied</value></data>
<data name="Admin.Logs.Action.TrashRestored" xml:space="preserve"><value>Restored from trash</value></data>
<data name="Admin.Logs.Action.UserCreated" xml:space="preserve"><value>User created</value></data>
<data name="Admin.Logs.Action.UserDeleted" xml:space="preserve"><value>User deleted</value></data>
<data name="Admin.Logs.Action.UserUpdated" xml:space="preserve"><value>User changed</value></data>
@@ -271,6 +409,8 @@
<data name="Admin.Nav.Expand.Tip" xml:space="preserve"><value>Show the menu names · Ctrl+B</value></data>
<data name="Admin.Nav.Jobs" xml:space="preserve"><value>Jobs</value></data>
<data name="Admin.Nav.Jobs.Tip" xml:space="preserve"><value>Queue, history and render nodes</value></data>
<data name="Admin.Nav.Library" xml:space="preserve"><value>Library</value></data>
<data name="Admin.Nav.Library.Tip" xml:space="preserve"><value>Sequences and photos: browse, view, delete, restore from the trash, mass operations</value></data>
<data name="Admin.Nav.Logs" xml:space="preserve"><value>Logs</value></data>
<data name="Admin.Nav.Logs.Tip" xml:space="preserve"><value>Recent log lines and downloads</value></data>
<data name="Admin.Nav.Settings" xml:space="preserve"><value>Settings</value></data>
@@ -432,6 +572,95 @@
<data name="Admin.Schedules.WeeklyAt" xml:space="preserve"><value>{0} at {1}</value></data>
<data name="Admin.Schedules.When" xml:space="preserve"><value>When</value></data>
<data name="Admin.Schedules.When.Tip" xml:space="preserve"><value>When it runs; times are in the server's time zone ({0})</value></data>
<data name="Admin.Sequence.AddPhotos" xml:space="preserve"><value>Add photos</value></data>
<data name="Admin.Sequence.AddPhotos.Tip" xml:space="preserve"><value>Upload photos from this computer into this sequence</value></data>
<data name="Admin.Sequence.AddTag" xml:space="preserve"><value>Add tag</value></data>
<data name="Admin.Sequence.AddTag.Tip" xml:space="preserve"><value>Type a tag and press Enter; commas separate several</value></data>
<data name="Admin.Sequence.Back" xml:space="preserve"><value>Library</value></data>
<data name="Admin.Sequence.Back.Tip" xml:space="preserve"><value>Back to the list, with its filters</value></data>
<data name="Admin.Sequence.ClearSelection" xml:space="preserve"><value>Deselect</value></data>
<data name="Admin.Sequence.ClearSelection.Tip" xml:space="preserve"><value>Deselect every photo · Esc</value></data>
<data name="Admin.Sequence.CloseViewer.Tip" xml:space="preserve"><value>Close the viewer · Esc</value></data>
<data name="Admin.Sequence.Cover.Tip" xml:space="preserve"><value>The sequence's cover</value></data>
<data name="Admin.Sequence.Delete" xml:space="preserve"><value>Delete…</value></data>
<data name="Admin.Sequence.Delete.Tip" xml:space="preserve"><value>Move the whole sequence into the archive's trash</value></data>
<data name="Admin.Sequence.DeleteBody.one" xml:space="preserve"><value>The sequence, its {0} photo ({1}) and its renders move to the archive's trash; restore it from there until the trash is emptied.</value><comment>long</comment></data>
<data name="Admin.Sequence.DeleteBody.other" xml:space="preserve"><value>The sequence, its {0} photos ({1}) and its renders move to the archive's trash; restore it from there until the trash is emptied.</value><comment>long</comment></data>
<data name="Admin.Sequence.DeleteConfirm.Tip" xml:space="preserve"><value>Move the sequence into the archive's trash; nothing is erased</value></data>
<data name="Admin.Sequence.DeletePhotos" xml:space="preserve"><value>Delete…</value></data>
<data name="Admin.Sequence.DeletePhotos.Tip" xml:space="preserve"><value>Move the selected photos into the archive's trash; the thumbnails, proxies and analysis follow</value></data>
<data name="Admin.Sequence.DeletePhotosBody.one" xml:space="preserve"><value>{0} photo ({1}) moves to the archive's trash; restore it from there until the trash is emptied.</value><comment>long</comment></data>
<data name="Admin.Sequence.DeletePhotosBody.other" xml:space="preserve"><value>{0} photos ({1}) move to the archive's trash; restore them from there until the trash is emptied.</value><comment>long</comment></data>
<data name="Admin.Sequence.DeletePhotosConfirm" xml:space="preserve"><value>Move to trash</value></data>
<data name="Admin.Sequence.DeletePhotosConfirm.Tip" xml:space="preserve"><value>Move the photos into the archive's trash; nothing is erased</value></data>
<data name="Admin.Sequence.DeletePhotosTitle.one" xml:space="preserve"><value>Delete {0} photo?</value><comment>long</comment></data>
<data name="Admin.Sequence.DeletePhotosTitle.other" xml:space="preserve"><value>Delete {0} photos?</value><comment>long</comment></data>
<data name="Admin.Sequence.DeleteTitle" xml:space="preserve"><value>Delete {0}?</value><comment>long</comment></data>
<data name="Admin.Sequence.Deleted" xml:space="preserve"><value>{0} moved to the trash.</value><comment>long</comment></data>
<data name="Admin.Sequence.Details" xml:space="preserve"><value>Sequence</value></data>
<data name="Admin.Sequence.Download" xml:space="preserve"><value>Download</value></data>
<data name="Admin.Sequence.Download.Tip" xml:space="preserve"><value>Save the original file of this photo, as it is in the archive</value></data>
<data name="Admin.Sequence.Fact.Aperture" xml:space="preserve"><value>Aperture</value></data>
<data name="Admin.Sequence.Fact.Camera" xml:space="preserve"><value>Camera</value></data>
<data name="Admin.Sequence.Fact.Captured" xml:space="preserve"><value>Taken</value></data>
<data name="Admin.Sequence.Fact.Dimensions" xml:space="preserve"><value>Resolution</value></data>
<data name="Admin.Sequence.Fact.Exposure" xml:space="preserve"><value>Exposure</value></data>
<data name="Admin.Sequence.Fact.Flags" xml:space="preserve"><value>Flags</value></data>
<data name="Admin.Sequence.Fact.Focal" xml:space="preserve"><value>Focal length</value></data>
<data name="Admin.Sequence.Fact.Folder" xml:space="preserve"><value>Folder</value></data>
<data name="Admin.Sequence.Fact.Format" xml:space="preserve"><value>Format</value></data>
<data name="Admin.Sequence.Fact.Interval" xml:space="preserve"><value>Interval</value></data>
<data name="Admin.Sequence.Fact.Iso" xml:space="preserve"><value>ISO</value></data>
<data name="Admin.Sequence.Fact.Lens" xml:space="preserve"><value>Lens</value></data>
<data name="Admin.Sequence.Fact.Photos" xml:space="preserve"><value>Photos</value></data>
<data name="Admin.Sequence.Fact.Sha256" xml:space="preserve"><value>SHA-256</value></data>
<data name="Admin.Sequence.Fact.Size" xml:space="preserve"><value>Size</value></data>
<data name="Admin.Sequence.Fact.Span" xml:space="preserve"><value>Span</value></data>
<data name="Admin.Sequence.Fact.Status" xml:space="preserve"><value>Status</value></data>
<data name="Admin.Sequence.Fact.Time" xml:space="preserve"><value>Taken</value></data>
<data name="Admin.Sequence.Fact.Updated" xml:space="preserve"><value>Changed</value></data>
<data name="Admin.Sequence.Flag.Corrupt" xml:space="preserve"><value>damaged</value></data>
<data name="Admin.Sequence.Flag.Duplicate" xml:space="preserve"><value>duplicate</value></data>
<data name="Admin.Sequence.Flag.Excluded" xml:space="preserve"><value>excluded</value></data>
<data name="Admin.Sequence.Flag.Missing" xml:space="preserve"><value>missing</value></data>
<data name="Admin.Sequence.Gone" xml:space="preserve"><value>This sequence is no longer in the library</value><comment>long</comment></data>
<data name="Admin.Sequence.MorePhotos.Tip" xml:space="preserve"><value>Show the next 500 photos</value></data>
<data name="Admin.Sequence.Next.Tip" xml:space="preserve"><value>Next photo · →</value></data>
<data name="Admin.Sequence.NoPhotos" xml:space="preserve"><value>No photos yet</value></data>
<data name="Admin.Sequence.NoRenders" xml:space="preserve"><value>No renders yet</value></data>
<data name="Admin.Sequence.Notes" xml:space="preserve"><value>Notes</value></data>
<data name="Admin.Sequence.Notes.Tip" xml:space="preserve"><value>Free notes on the sequence, saved when you leave the field</value></data>
<data name="Admin.Sequence.OnePhoto.Tip" xml:space="preserve"><value>Select exactly one photo first</value></data>
<data name="Admin.Sequence.Photo.Tip" xml:space="preserve"><value>{0} · Enter or click opens the viewer; Space selects, Shift+Space selects a range</value></data>
<data name="Admin.Sequence.Photos" xml:space="preserve"><value>Photos</value></data>
<data name="Admin.Sequence.PhotosDeleted.one" xml:space="preserve"><value>{0} photo moved to the trash</value><comment>long</comment></data>
<data name="Admin.Sequence.PhotosDeleted.other" xml:space="preserve"><value>{0} photos moved to the trash</value><comment>long</comment></data>
<data name="Admin.Sequence.Position" xml:space="preserve"><value>{0} / {1}</value><comment>invariant; a photo's number, then how many the sequence has</comment></data>
<data name="Admin.Sequence.Previous.Tip" xml:space="preserve"><value>Previous photo · ←</value></data>
<data name="Admin.Sequence.Rate.Tip" xml:space="preserve"><value>Rate it {0} out of 5</value></data>
<data name="Admin.Sequence.Rating" xml:space="preserve"><value>Rating</value></data>
<data name="Admin.Sequence.RemoveTag.Tip" xml:space="preserve"><value>Remove the tag {0}</value></data>
<data name="Admin.Sequence.Render.Created" xml:space="preserve"><value>Made</value></data>
<data name="Admin.Sequence.Render.Download" xml:space="preserve"><value>Download</value></data>
<data name="Admin.Sequence.Render.Download.Tip" xml:space="preserve"><value>Save this video</value></data>
<data name="Admin.Sequence.Render.Length" xml:space="preserve"><value>Length</value></data>
<data name="Admin.Sequence.Render.Preset" xml:space="preserve"><value>Preset</value></data>
<data name="Admin.Sequence.Render.Size" xml:space="preserve"><value>Size</value></data>
<data name="Admin.Sequence.Render.Video" xml:space="preserve"><value>Video</value></data>
<data name="Admin.Sequence.Renders" xml:space="preserve"><value>Renders</value></data>
<data name="Admin.Sequence.SelectAll" xml:space="preserve"><value>Select all</value></data>
<data name="Admin.Sequence.SelectAll.Tip" xml:space="preserve"><value>Select every photo shown · Ctrl+A</value></data>
<data name="Admin.Sequence.SelectPhoto.Tip" xml:space="preserve"><value>Select or deselect; with Shift, every photo from the last one picked</value></data>
<data name="Admin.Sequence.SetCover" xml:space="preserve"><value>Set cover</value></data>
<data name="Admin.Sequence.SetCover.Tip" xml:space="preserve"><value>Show this photo on the sequence's card in every Library</value></data>
<data name="Admin.Sequence.SomePhotos.Tip" xml:space="preserve"><value>Select one or more photos first</value></data>
<data name="Admin.Sequence.Stars.one" xml:space="preserve"><value>{0} star</value></data>
<data name="Admin.Sequence.Stars.other" xml:space="preserve"><value>{0} stars</value></data>
<data name="Admin.Sequence.Tags" xml:space="preserve"><value>Tags</value></data>
<data name="Admin.Sequence.Title" xml:space="preserve"><value>Title</value></data>
<data name="Admin.Sequence.Title.Tip" xml:space="preserve"><value>Title of the sequence; empty shows its date and camera · Enter saves, Esc reverts</value></data>
<data name="Admin.Sequence.TooManyTags" xml:space="preserve"><value>A sequence has at most 50 tags.</value><comment>long</comment></data>
<data name="Admin.Sequence.Unrate.Tip" xml:space="preserve"><value>Rated {0} out of 5; choose it again to clear the rating</value></data>
<data name="Admin.Settings.About" xml:space="preserve"><value>About</value></data>
<data name="Admin.Settings.AuditRetentionDays" xml:space="preserve"><value>Keep audit (days)</value></data>
<data name="Admin.Settings.AuditRetentionDays.Tip" xml:space="preserve"><value>Age limit of the Audit log clean-up schedule: older audit entries are deleted; 0: kept forever</value></data>
@@ -510,6 +739,101 @@
<data name="Admin.SignOut" xml:space="preserve"><value>Sign out</value></data>
<data name="Admin.SignOut.Tip" xml:space="preserve"><value>Sign out of the admin panel</value></data>
<data name="Admin.Theme.Tip" xml:space="preserve"><value>Switch between light and dark</value></data>
<data name="Admin.Trash.Back" xml:space="preserve"><value>Library</value></data>
<data name="Admin.Trash.Back.Tip" xml:space="preserve"><value>Back to the Library</value></data>
<data name="Admin.Trash.DeletedAt" xml:space="preserve"><value>Deleted</value></data>
<data name="Admin.Trash.DeletedBy" xml:space="preserve"><value>Deleted by</value></data>
<data name="Admin.Trash.Emptied" xml:space="preserve"><value>Trash emptied.</value><comment>long</comment></data>
<data name="Admin.Trash.Empty" xml:space="preserve"><value>Empty…</value></data>
<data name="Admin.Trash.Empty.Tip" xml:space="preserve"><value>Erase everything in the trash for good; a list shows what goes first</value></data>
<data name="Admin.Trash.EmptyBody.one" xml:space="preserve"><value>{0} file ({1}) is erased for good.</value><comment>long</comment></data>
<data name="Admin.Trash.EmptyBody.other" xml:space="preserve"><value>{0} files ({1}) are erased for good.</value><comment>long</comment></data>
<data name="Admin.Trash.EmptyConfirm" xml:space="preserve"><value>Empty trash</value></data>
<data name="Admin.Trash.EmptyConfirm.Tip" xml:space="preserve"><value>Erase every entry listed, for good</value></data>
<data name="Admin.Trash.EmptyFailed" xml:space="preserve"><value>The trash was not emptied; the job's log says why.</value><comment>long</comment></data>
<data name="Admin.Trash.EmptyFinal" xml:space="preserve"><value>This cannot be undone.</value><comment>long</comment></data>
<data name="Admin.Trash.EmptyQueued" xml:space="preserve"><value>Emptying the trash: job queued.</value><comment>long</comment></data>
<data name="Admin.Trash.EmptyTitle" xml:space="preserve"><value>Empty the trash?</value><comment>long</comment></data>
<data name="Admin.Trash.EmptyWord" xml:space="preserve"><value>empty</value><comment>the word typed to confirm emptying the trash, lower case</comment></data>
<data name="Admin.Trash.Emptying.Tip" xml:space="preserve"><value>The trash is being emptied</value></data>
<data name="Admin.Trash.EntryCount.one" xml:space="preserve"><value>{0} entry</value></data>
<data name="Admin.Trash.EntryCount.other" xml:space="preserve"><value>{0} entries</value></data>
<data name="Admin.Trash.IsEmpty" xml:space="preserve"><value>The trash is empty</value></data>
<data name="Admin.Trash.Kept.one" xml:space="preserve"><value>{0} file stays in the trash: it no longer matches its record.</value><comment>long</comment></data>
<data name="Admin.Trash.Kept.other" xml:space="preserve"><value>{0} files stay in the trash: they no longer match their record.</value><comment>long</comment></data>
<data name="Admin.Trash.Kind" xml:space="preserve"><value>Kind</value></data>
<data name="Admin.Trash.Kind.Photos" xml:space="preserve"><value>Photos</value></data>
<data name="Admin.Trash.Kind.Replaced" xml:space="preserve"><value>Replaced</value></data>
<data name="Admin.Trash.Kind.Sequence" xml:space="preserve"><value>Sequence</value></data>
<data name="Admin.Trash.NothingToEmpty.Tip" xml:space="preserve"><value>The trash is empty</value></data>
<data name="Admin.Trash.Photos" xml:space="preserve"><value>Photos</value></data>
<data name="Admin.Trash.PlanItem" xml:space="preserve"><value>{0} · {1} · {2}</value><comment>invariant; an entry's kind, title and size</comment></data>
<data name="Admin.Trash.Restore" xml:space="preserve"><value>Restore</value></data>
<data name="Admin.Trash.RestorePhotos.Tip" xml:space="preserve"><value>Put the photos back into their sequence (a new one if it is gone); each is checked against its SHA-256 first</value></data>
<data name="Admin.Trash.RestoreSequence.Tip" xml:space="preserve"><value>Put the sequence back into its folder and the library; its photos are checked against their SHA-256 first</value></data>
<data name="Admin.Trash.RestoredNew.one" xml:space="preserve"><value>{0} photo restored into a new sequence.</value><comment>long</comment></data>
<data name="Admin.Trash.RestoredNew.other" xml:space="preserve"><value>{0} photos restored into a new sequence.</value><comment>long</comment></data>
<data name="Admin.Trash.RestoredPhotos.one" xml:space="preserve"><value>{0} photo is back in {1}.</value><comment>long</comment></data>
<data name="Admin.Trash.RestoredPhotos.other" xml:space="preserve"><value>{0} photos are back in {1}.</value><comment>long</comment></data>
<data name="Admin.Trash.RestoredSequence" xml:space="preserve"><value>{0} is back in the library.</value><comment>long</comment></data>
<data name="Admin.Trash.Sequence" xml:space="preserve"><value>Sequence</value></data>
<data name="Admin.Trash.Size" xml:space="preserve"><value>Size</value></data>
<data name="Admin.Trash.Title" xml:space="preserve"><value>Trash</value></data>
<data name="Admin.Upload.Add" xml:space="preserve"><value>Add photos</value></data>
<data name="Admin.Upload.Add.Tip" xml:space="preserve"><value>Choose photos on this computer; you can also drop them on this dialog</value></data>
<data name="Admin.Upload.Bytes" xml:space="preserve"><value>{0} of {1}</value></data>
<data name="Admin.Upload.Cancel" xml:space="preserve"><value>Cancel</value></data>
<data name="Admin.Upload.Cancel.Tip" xml:space="preserve"><value>Stop now: the photos not finished yet are discarded on the server</value></data>
<data name="Admin.Upload.Close" xml:space="preserve"><value>Close</value></data>
<data name="Admin.Upload.Close.Tip" xml:space="preserve"><value>Close the upload dialog</value></data>
<data name="Admin.Upload.Count" xml:space="preserve"><value>Photos: {0} of {1}</value></data>
<data name="Admin.Upload.Drop" xml:space="preserve"><value>Drop photos here</value></data>
<data name="Admin.Upload.Existing" xml:space="preserve"><value>Existing sequence</value></data>
<data name="Admin.Upload.Existing.Tip" xml:space="preserve"><value>Add the photos to a sequence already on the server</value></data>
<data name="Admin.Upload.Failed" xml:space="preserve"><value>Failed: {0}</value></data>
<data name="Admin.Upload.HashFailed" xml:space="preserve"><value>Photos cannot be hashed in this browser, so nothing was uploaded.</value><comment>long</comment></data>
<data name="Admin.Upload.New" xml:space="preserve"><value>New sequence</value></data>
<data name="Admin.Upload.New.Tip" xml:space="preserve"><value>Create a sequence on the server for these photos</value></data>
<data name="Admin.Upload.NewTitle" xml:space="preserve"><value>Title</value></data>
<data name="Admin.Upload.NewTitle.Tip" xml:space="preserve"><value>Name of the new sequence; left empty, it is named after the date and camera of its photos</value></data>
<data name="Admin.Upload.NoMatch" xml:space="preserve"><value>No sequence found</value></data>
<data name="Admin.Upload.PhotoCount.one" xml:space="preserve"><value>{0} photo</value></data>
<data name="Admin.Upload.PhotoCount.other" xml:space="preserve"><value>{0} photos</value></data>
<data name="Admin.Upload.Photos" xml:space="preserve"><value>Photos</value></data>
<data name="Admin.Upload.PickFirst" xml:space="preserve"><value>Choose a sequence first.</value></data>
<data name="Admin.Upload.ReadFailed" xml:space="preserve"><value>The file could not be read.</value></data>
<data name="Admin.Upload.Remove" xml:space="preserve"><value>Remove {0}</value></data>
<data name="Admin.Upload.Remove.Tip" xml:space="preserve"><value>Take this photo off the list</value></data>
<data name="Admin.Upload.Search" xml:space="preserve"><value>Search sequences</value></data>
<data name="Admin.Upload.Search.Tip" xml:space="preserve"><value>Find a sequence by title, camera or tag</value></data>
<data name="Admin.Upload.SelfTestFailed" xml:space="preserve"><value>This browser computed a test SHA-256 wrongly, so nothing is uploaded from it.</value><comment>long</comment></data>
<data name="Admin.Upload.Sequences" xml:space="preserve"><value>Sequences</value></data>
<data name="Admin.Upload.Sequences.Tip" xml:space="preserve"><value>The sequence the photos go into</value></data>
<data name="Admin.Upload.Skipped.Folders" xml:space="preserve"><value>Folders skipped: {0}</value></data>
<data name="Admin.Upload.Skipped.Folders.Tip" xml:space="preserve"><value>Folders are imported with the desktop app; here only photos are uploaded</value></data>
<data name="Admin.Upload.Skipped.Formats" xml:space="preserve"><value>Not photos: {0}</value></data>
<data name="Admin.Upload.Skipped.Formats.Tip" xml:space="preserve"><value>Files in a format the server does not read as photos were left out</value></data>
<data name="Admin.Upload.Skipped.Size" xml:space="preserve"><value>Too large: {0}</value></data>
<data name="Admin.Upload.Skipped.Size.Tip" xml:space="preserve"><value>Files larger than the server's upload limit ({0}) were left out</value></data>
<data name="Admin.Upload.Start" xml:space="preserve"><value>Upload</value></data>
<data name="Admin.Upload.Start.Tip" xml:space="preserve"><value>Send the photos not on the server yet; the server checks each one against its SHA-256</value></data>
<data name="Admin.Upload.State.Cancelled" xml:space="preserve"><value>Cancelled</value></data>
<data name="Admin.Upload.State.Deleted" xml:space="preserve"><value>Deleted before</value></data>
<data name="Admin.Upload.State.Deleted.Tip" xml:space="preserve"><value>Deleted from this sequence earlier: restore it from the trash to bring it back</value></data>
<data name="Admin.Upload.State.Done" xml:space="preserve"><value>Uploaded</value></data>
<data name="Admin.Upload.State.Done.Tip" xml:space="preserve"><value>On the server and verified against its SHA-256</value></data>
<data name="Admin.Upload.State.Exists" xml:space="preserve"><value>Already there</value></data>
<data name="Admin.Upload.State.Exists.Tip" xml:space="preserve"><value>The server already has this photo</value></data>
<data name="Admin.Upload.State.Failed" xml:space="preserve"><value>Failed</value></data>
<data name="Admin.Upload.State.Hashing" xml:space="preserve"><value>Hashing {0}</value></data>
<data name="Admin.Upload.State.NotSent" xml:space="preserve"><value>Not sent</value></data>
<data name="Admin.Upload.State.NotSent.Tip" xml:space="preserve"><value>Not sent: the upload stopped before this photo</value></data>
<data name="Admin.Upload.State.Starting" xml:space="preserve"><value>Starting</value></data>
<data name="Admin.Upload.State.Uploading" xml:space="preserve"><value>Uploading {0}</value></data>
<data name="Admin.Upload.State.Verifying" xml:space="preserve"><value>Verifying</value></data>
<data name="Admin.Upload.State.Waiting" xml:space="preserve"><value>Waiting</value></data>
<data name="Admin.Upload.Target" xml:space="preserve"><value>Sequence</value></data>
<data name="Admin.Upload.Title" xml:space="preserve"><value>Upload photos</value></data>
<data name="Admin.Users.Accounts.one" xml:space="preserve"><value>{0} account</value></data>
<data name="Admin.Users.Accounts.other" xml:space="preserve"><value>{0} accounts</value></data>
<data name="Admin.Users.Active" xml:space="preserve"><value>Active</value></data>
+20 -1
View File
@@ -89,6 +89,10 @@
<data name="Archive.Error.SourceChanged" xml:space="preserve"><value>{0} changed after the plan was made.</value><comment>long: error sentence</comment></data>
<data name="Archive.Error.SourceGone" xml:space="preserve"><value>The card or folder {0} is no longer available.</value><comment>long: error sentence</comment></data>
<data name="Archive.Error.StalePlan" xml:space="preserve"><value>The archive changed after this plan was made.</value><comment>long: error sentence</comment></data>
<data name="Archive.Error.TrashChanged" xml:space="preserve"><value>The trash changed after it was checked; nothing was erased.</value><comment>long: error sentence</comment></data>
<data name="Archive.Error.TrashKept.one" xml:space="preserve"><value>{0:N0} trash entry was kept: it changed, or a replacement no longer matches.</value><comment>long: error sentence of an emptying job</comment></data>
<data name="Archive.Error.TrashKept.other" xml:space="preserve"><value>{0:N0} trash entries were kept: they changed, or a replacement no longer matches.</value><comment>long: error sentence of an emptying job</comment></data>
<data name="Archive.Error.TrashMismatch" xml:space="preserve"><value>No file of this trash entry matches its record any more; it stays in the trash.</value><comment>long: error sentence</comment></data>
<data name="Archive.Failed.Access" xml:space="preserve"><value>Chronos was denied access to the archive.</value><comment>long</comment></data>
<data name="Archive.Failed.Files" xml:space="preserve"><value>A file of the archive could not be read or written.</value><comment>long</comment></data>
<data name="Archive.Failed.Gone" xml:space="preserve"><value>The sequence is no longer in the index.</value><comment>long</comment></data>
@@ -152,7 +156,9 @@
<data name="Archive.Log.SequenceMissing" xml:space="preserve"><value>Sequence not found: {0}</value><comment>long: job log line</comment></data>
<data name="Archive.Log.StepFailed" xml:space="preserve"><value>Clean-up step {0} failed: {1}</value><comment>long: job log line; {0} step name (job-history, audit…); {1} error message</comment></data>
<data name="Archive.Log.StepUnknown" xml:space="preserve"><value>Clean-up step unknown here: {0}</value><comment>long: job log line; {0} step name</comment></data>
<data name="Archive.Log.TrashEmptied" xml:space="preserve"><value>Entries erased: {0}, size: {1}</value><comment>long: job log line; {0} count; {1} size</comment></data>
<data name="Archive.Log.TrashEntry" xml:space="preserve"><value>In the trash since {0}: {1} ({2})</value><comment>long: job log line; {0} date; {1} sequence title; {2} size</comment></data>
<data name="Archive.Log.TrashKept" xml:space="preserve"><value>Kept in the trash: {0}</value><comment>long: job log line; {0} sequence title</comment></data>
<data name="Archive.Log.TrashOffline" xml:space="preserve"><value>Trash not checked: the archive cannot be reached</value><comment>long: job log line</comment></data>
<data name="Archive.Log.TrashReport" xml:space="preserve"><value>Old trash entries: {0}, size: {1}; nothing was deleted</value><comment>long: job log line; entries older than the clean-up's age limit</comment></data>
<data name="Archive.Log.VerifyDone" xml:space="preserve"><value>Photos checked: {0}, intact: {1}, hashed: {2}, with problems: {3}</value><comment>long: job log line</comment></data>
@@ -248,11 +254,24 @@
<data name="Archive.Toolbar.Rebuild" xml:space="preserve"><value>Rebuild index…</value></data>
<data name="Archive.Toolbar.Scan" xml:space="preserve"><value>Scan</value></data>
<data name="Archive.Toolbar.Verify" xml:space="preserve"><value>Verify</value></data>
<data name="Archive.Trash.Checking" xml:space="preserve"><value>Checking the trash…</value></data>
<data name="Archive.Trash.Deleted" xml:space="preserve"><value>Deleted {0}</value><comment>long</comment></data>
<data name="Archive.Trash.Empty" xml:space="preserve"><value>The trash is empty</value><comment>long</comment></data>
<data name="Archive.Trash.EmptyAction" xml:space="preserve"><value>Empty…</value></data>
<data name="Archive.Trash.EmptyHeading.one" xml:space="preserve"><value>Erase {0:N0} trash entry for good?</value><comment>long</comment></data>
<data name="Archive.Trash.EmptyHeading.other" xml:space="preserve"><value>Erase {0:N0} trash entries for good?</value><comment>long</comment></data>
<data name="Archive.Trash.EmptyMessage" xml:space="preserve"><value>{0} and {1} ({2}) are erased from the archive; this cannot be undone.</value><comment>long</comment></data>
<data name="Archive.Trash.Entries.one" xml:space="preserve"><value>{0:N0} entry</value></data>
<data name="Archive.Trash.Entries.other" xml:space="preserve"><value>{0:N0} entries</value></data>
<data name="Archive.Trash.Erase" xml:space="preserve"><value>Erase for good</value></data>
<data name="Archive.Trash.Failed" xml:space="preserve"><value>The sequence could not come back from the trash</value><comment>long</comment></data>
<data name="Archive.Trash.Heading" xml:space="preserve"><value>Trash · {0}</value><comment>long</comment></data>
<data name="Archive.Trash.List" xml:space="preserve"><value>Deleted sequences</value></data>
<data name="Archive.Trash.KeptFiles.one" xml:space="preserve"><value>{0:N0} file stayed in the trash: it no longer matches its record.</value><comment>long</comment></data>
<data name="Archive.Trash.KeptFiles.other" xml:space="preserve"><value>{0:N0} files stayed in the trash: they no longer match their record.</value><comment>long</comment></data>
<data name="Archive.Trash.Kind.Photos" xml:space="preserve"><value>Photos</value></data>
<data name="Archive.Trash.Kind.Replaced" xml:space="preserve"><value>Replaced originals</value></data>
<data name="Archive.Trash.Kind.Sequence" xml:space="preserve"><value>Sequence</value></data>
<data name="Archive.Trash.List" xml:space="preserve"><value>Trash entries</value></data>
<data name="Archive.Trash.Reading" xml:space="preserve"><value>Reading the trash…</value></data>
<data name="Archive.Trash.Restore" xml:space="preserve"><value>Restore</value></data>
<data name="Archive.Trash.Restored.one" xml:space="preserve"><value>{0:N0} sequence restored</value><comment>long</comment></data>
+1
View File
@@ -72,6 +72,7 @@
<data name="Jobs.Kind.DeepAnalyse" xml:space="preserve"><value>Deep analysis</value></data>
<data name="Jobs.Kind.Download" xml:space="preserve"><value>Download</value></data>
<data name="Jobs.Kind.Duplicates" xml:space="preserve"><value>Duplicates</value></data>
<data name="Jobs.Kind.EmptyTrash" xml:space="preserve"><value>Empty trash</value></data>
<data name="Jobs.Kind.Import" xml:space="preserve"><value>Import</value></data>
<data name="Jobs.Kind.LightAnalyse" xml:space="preserve"><value>Light analysis</value></data>
<data name="Jobs.Kind.Maintenance" xml:space="preserve"><value>Maintenance</value></data>
+4
View File
@@ -87,12 +87,15 @@
<data name="Server.Error.ScheduleSystem" xml:space="preserve"><value>A system schedule cannot be deleted; turn it off instead.</value><comment>long</comment></data>
<data name="Server.Error.Self" xml:space="preserve"><value>You cannot do this to your own account.</value><comment>long</comment></data>
<data name="Server.Error.SequenceBusy" xml:space="preserve"><value>A job is working on this sequence or its archive; try again when it is free.</value><comment>long</comment></data>
<data name="Server.Error.SequenceInLibrary" xml:space="preserve"><value>That sequence is in the library already.</value><comment>long</comment></data>
<data name="Server.Error.SessionExpired" xml:space="preserve"><value>The session expired; sign in again.</value><comment>long</comment></data>
<data name="Server.Error.SettingLocked" xml:space="preserve"><value>An environment variable sets this; change it there.</value><comment>long</comment></data>
<data name="Server.Error.SettingsConflict" xml:space="preserve"><value>The sequence changed on the server; reload it and apply your edit again.</value><comment>long</comment></data>
<data name="Server.Error.SidecarMismatch" xml:space="preserve"><value>Its folder holds another sequence; scan the archive first.</value><comment>long</comment></data>
<data name="Server.Error.TooLarge" xml:space="preserve"><value>The request is larger than the server accepts.</value><comment>long</comment></data>
<data name="Server.Error.TooManyUploads" xml:space="preserve"><value>Too many uploads at once; retry shortly.</value><comment>long</comment></data>
<data name="Server.Error.TrashChanged" xml:space="preserve"><value>The trash changed after it was checked; check it again before emptying it.</value><comment>long</comment></data>
<data name="Server.Error.TrashMismatch" xml:space="preserve"><value>No file of this trash entry matches its record any more; it stays in the trash.</value><comment>long</comment></data>
<data name="Server.Error.Unauthorized" xml:space="preserve"><value>Sign in to continue.</value><comment>long</comment></data>
<data name="Server.Error.Unreachable" xml:space="preserve"><value>The server does not answer; check the address and the network.</value><comment>long</comment></data>
<data name="Server.Error.UnsupportedMediaType" xml:space="preserve"><value>Send the body as JSON.</value><comment>long</comment></data>
@@ -101,6 +104,7 @@
<data name="Server.Error.UsernameTaken" xml:space="preserve"><value>That user name is taken.</value><comment>long</comment></data>
<data name="Server.Error.WeakPassword" xml:space="preserve"><value>Use at least {0} characters.</value><comment>long</comment></data>
<data name="Server.Error.WebsocketRequired" xml:space="preserve"><value>Connect with a WebSocket.</value><comment>long</comment></data>
<data name="Server.Error.WouldEmpty" xml:space="preserve"><value>Every photo of the sequence would go; delete the sequence instead.</value><comment>long</comment></data>
<data name="Server.Error.WrongPassword" xml:space="preserve"><value>The current password is wrong.</value><comment>long</comment></data>
<data name="Server.Error.WrongUploadKind" xml:space="preserve"><value>This upload belongs to a render job.</value><comment>long</comment></data>
<data name="Server.Found" xml:space="preserve"><value>Servers found</value></data>
+6 -2
View File
@@ -91,8 +91,12 @@
<data name="Tooltips.Archive.TagsAdd" xml:space="preserve"><value>Tags to add, separated by commas</value></data>
<data name="Tooltips.Archive.TagsRemove" xml:space="preserve"><value>Tags to remove, separated by commas</value></data>
<data name="Tooltips.Archive.TitleTemplate" xml:space="preserve"><value>Title template; the title token is the current title · checked as you type</value></data>
<data name="Tooltips.Archive.Trash" xml:space="preserve"><value>The sequences deleted from this archive, each one restorable</value></data>
<data name="Tooltips.Archive.TrashRestore" xml:space="preserve"><value>Move this sequence back into its folder and the library, with its settings and renders</value></data>
<data name="Tooltips.Archive.Trash" xml:space="preserve"><value>The sequences and photos deleted from this archive, each one restorable</value></data>
<data name="Tooltips.Archive.TrashEmpty" xml:space="preserve"><value>Erase the entries of this trash for good, after a check of what they hold and a typed confirmation</value></data>
<data name="Tooltips.Archive.TrashEmptyPlan" xml:space="preserve"><value>What is erased from the archive for good</value></data>
<data name="Tooltips.Archive.TrashErase.one" xml:space="preserve"><value>Erase {0:N0} entry for good; type the number above first</value></data>
<data name="Tooltips.Archive.TrashErase.other" xml:space="preserve"><value>Erase {0:N0} entries for good; type the number above first</value></data>
<data name="Tooltips.Archive.TrashRestore" xml:space="preserve"><value>Move this entry back: a sequence into its folder and the library, photos into their sequence after a hash check</value></data>
<data name="Tooltips.Archive.Verify" xml:space="preserve"><value>Re-hash every original and report bit rot · reads the whole archive</value></data>
<data name="Tooltips.Archive.YearRow" xml:space="preserve"><value>{0} · Right arrow opens the year, Left arrow closes it</value></data>
<data name="Tooltips.Archive.YearRowRtl" xml:space="preserve"><value>{0} · Left arrow opens the year, Right arrow closes it</value></data>
+322
View File
@@ -10,6 +10,7 @@
<data name="Admin.About.Uptime" xml:space="preserve"><value>In esecuzione da</value></data>
<data name="Admin.About.Version" xml:space="preserve"><value>Versione</value></data>
<data name="Admin.Activity.ArchiveSettings" xml:space="preserve"><value>{0} ha modificato l'organizzazione dell'archivio</value></data>
<data name="Admin.Activity.FramesDeleted" xml:space="preserve"><value>{0} ha eliminato {1}</value><comment>long</comment></data>
<data name="Admin.Activity.JobCreated" xml:space="preserve"><value>{0} ha avviato {1}</value></data>
<data name="Admin.Activity.Login" xml:space="preserve"><value>{0} ha effettuato l'accesso · {1}</value></data>
<data name="Admin.Activity.LoginFailed" xml:space="preserve"><value>accesso fallito come {0}</value></data>
@@ -24,6 +25,8 @@
<data name="Admin.Activity.SequenceDeleted" xml:space="preserve"><value>{0} ha eliminato {1}</value></data>
<data name="Admin.Activity.SequenceUpdated" xml:space="preserve"><value>{0} ha modificato una sequenza · {1}</value></data>
<data name="Admin.Activity.ServerSettings" xml:space="preserve"><value>{0} ha modificato le impostazioni del server</value></data>
<data name="Admin.Activity.TrashEmptied" xml:space="preserve"><value>{0} ha svuotato il cestino · {1}</value><comment>long</comment></data>
<data name="Admin.Activity.TrashRestored" xml:space="preserve"><value>{0} ha ripristinato {1} dal cestino</value><comment>long</comment></data>
<data name="Admin.Activity.UserCreated" xml:space="preserve"><value>{0} ha creato l'utente {1}</value></data>
<data name="Admin.Activity.UserDeleted" xml:space="preserve"><value>{0} ha eliminato l'utente {1}</value></data>
<data name="Admin.Activity.UserUpdated" xml:space="preserve"><value>{0} ha modificato un utente · {1}</value></data>
@@ -52,6 +55,8 @@
<data name="Admin.Archive.Scan" xml:space="preserve"><value>Scansiona</value></data>
<data name="Admin.Archive.Scan.Tip" xml:space="preserve"><value>Cerca sequenze nuove e modificate sul disco</value></data>
<data name="Admin.Archive.Sequences" xml:space="preserve"><value>Sequenze</value></data>
<data name="Admin.Archive.Trash" xml:space="preserve"><value>Cestino</value></data>
<data name="Admin.Archive.Trash.Tip" xml:space="preserve"><value>Apri il cestino dell'archivio: sequenze e foto eliminate, da ripristinare o cancellare per sempre</value></data>
<data name="Admin.Archive.UnverifiedUnit.one" xml:space="preserve"><value>non verificata</value></data>
<data name="Admin.Archive.UnverifiedUnit.other" xml:space="preserve"><value>non verificate</value></data>
<data name="Admin.Archive.Verify" xml:space="preserve"><value>Verifica</value></data>
@@ -70,9 +75,13 @@
<data name="Admin.Common.Save" xml:space="preserve"><value>Salva</value></data>
<data name="Admin.Common.Save.Tip" xml:space="preserve"><value>Salva le modifiche sul server</value></data>
<data name="Admin.Common.Saved" xml:space="preserve"><value>Salvato.</value></data>
<data name="Admin.Common.TypeCount.Tip" xml:space="preserve"><value>Digita il numero mostrato: quante foto vengono spostate</value></data>
<data name="Admin.Common.TypeCountFirst.Tip" xml:space="preserve"><value>Prima digita il numero qui sopra</value></data>
<data name="Admin.Common.TypeFirst.Tip" xml:space="preserve"><value>Prima digita il nome qui sopra</value></data>
<data name="Admin.Common.TypeToConfirm" xml:space="preserve"><value>Digita {0} per confermare</value></data>
<data name="Admin.Common.TypeToConfirm.Tip" xml:space="preserve"><value>Digita il nome esattamente come mostrato per confermare</value></data>
<data name="Admin.Common.TypeWord.Tip" xml:space="preserve"><value>Digita la parola come mostrata; maiuscole e minuscole non contano</value></data>
<data name="Admin.Common.TypeWordFirst.Tip" xml:space="preserve"><value>Prima digita la parola qui sopra</value></data>
<data name="Admin.Dashboard.Activity" xml:space="preserve"><value>Attività recenti</value></data>
<data name="Admin.Dashboard.AllLogs" xml:space="preserve"><value>Tutti i log</value></data>
<data name="Admin.Dashboard.AllLogs.Tip" xml:space="preserve"><value>Apri il registro di controllo</value></data>
@@ -125,6 +134,7 @@
<data name="Admin.Job.Kind.Cleanup" xml:space="preserve"><value>Pulizia</value></data>
<data name="Admin.Job.Kind.DeepAnalyse" xml:space="preserve"><value>Analisi completa</value></data>
<data name="Admin.Job.Kind.Duplicates" xml:space="preserve"><value>Duplicati</value></data>
<data name="Admin.Job.Kind.EmptyTrash" xml:space="preserve"><value>Svuota cestino</value></data>
<data name="Admin.Job.Kind.Import" xml:space="preserve"><value>Importazione</value></data>
<data name="Admin.Job.Kind.LightAnalyse" xml:space="preserve"><value>Analisi rapida</value></data>
<data name="Admin.Job.Kind.Maintenance" xml:space="preserve"><value>Manutenzione</value></data>
@@ -200,6 +210,131 @@
<data name="Admin.Jobs.Tab.Schedules.Tip" xml:space="preserve"><value>Job che il server mette in coda da solo secondo una pianificazione: visualizzali, creali e modificali</value></data>
<data name="Admin.Jobs.Target" xml:space="preserve"><value>Oggetto</value></data>
<data name="Admin.Language.Tip" xml:space="preserve"><value>Lingua di questo pannello</value></data>
<data name="Admin.Library.AddTags" xml:space="preserve"><value>Aggiungi</value></data>
<data name="Admin.Library.AddTags.Tip" xml:space="preserve"><value>Tag da aggiungere, separati da virgole</value></data>
<data name="Admin.Library.AnyCamera" xml:space="preserve"><value>Tutte le fotocamere</value></data>
<data name="Admin.Library.AnyStatus" xml:space="preserve"><value>Qualsiasi stato</value></data>
<data name="Admin.Library.AnyTag" xml:space="preserve"><value>Tutti i tag</value></data>
<data name="Admin.Library.AnyYear" xml:space="preserve"><value>Tutti gli anni</value></data>
<data name="Admin.Library.Apply" xml:space="preserve"><value>Applica</value></data>
<data name="Admin.Library.Apply.Tip" xml:space="preserve"><value>Cambia i tag delle sequenze selezionate</value></data>
<data name="Admin.Library.BlockedItem" xml:space="preserve"><value>{0}: {1}</value><comment>long</comment></data>
<data name="Admin.Library.Camera.Tip" xml:space="preserve"><value>Mostra solo le sequenze di questo modello di fotocamera</value></data>
<data name="Admin.Library.ClearFilters" xml:space="preserve"><value>Azzera filtri</value></data>
<data name="Admin.Library.ClearFilters.Tip" xml:space="preserve"><value>Mostra di nuovo tutte le sequenze</value></data>
<data name="Admin.Library.ClearSelection.Tip" xml:space="preserve"><value>Deseleziona tutto · Esc</value></data>
<data name="Admin.Library.Column.Camera" xml:space="preserve"><value>Fotocamera</value></data>
<data name="Admin.Library.Column.Date" xml:space="preserve"><value>Data</value></data>
<data name="Admin.Library.Column.Photos" xml:space="preserve"><value>Foto</value></data>
<data name="Admin.Library.Column.Sequence" xml:space="preserve"><value>Sequenza</value></data>
<data name="Admin.Library.Column.Size" xml:space="preserve"><value>Dimensione</value></data>
<data name="Admin.Library.Count.one" xml:space="preserve"><value>{0} sequenza</value></data>
<data name="Admin.Library.Count.other" xml:space="preserve"><value>{0} sequenze</value></data>
<data name="Admin.Library.Csv.Bytes" xml:space="preserve"><value>Byte</value></data>
<data name="Admin.Library.Csv.Camera" xml:space="preserve"><value>Fotocamera</value></data>
<data name="Admin.Library.Csv.First" xml:space="preserve"><value>Prima foto</value></data>
<data name="Admin.Library.Csv.Last" xml:space="preserve"><value>Ultima foto</value></data>
<data name="Admin.Library.Csv.Photos" xml:space="preserve"><value>Foto</value></data>
<data name="Admin.Library.Csv.Tags" xml:space="preserve"><value>Tag</value></data>
<data name="Admin.Library.Csv.Title" xml:space="preserve"><value>Titolo</value></data>
<data name="Admin.Library.Delete" xml:space="preserve"><value>Elimina…</value></data>
<data name="Admin.Library.Delete.Tip" xml:space="preserve"><value>Sposta le sequenze selezionate nel cestino dell'archivio; prima un elenco mostra cosa viene spostato</value></data>
<data name="Admin.Library.DeleteBlocked.one" xml:space="preserve"><value>{0} altra sequenza non può essere spostata; l'elenco dice perché.</value><comment>long</comment></data>
<data name="Admin.Library.DeleteBlocked.other" xml:space="preserve"><value>Altre {0} sequenze non possono essere spostate; l'elenco dice perché.</value><comment>long</comment></data>
<data name="Admin.Library.DeleteBody.one" xml:space="preserve"><value>{0} sequenza, {1} ({2}), va nel cestino dell'archivio; si può ripristinare finché il cestino non viene svuotato.</value><comment>long</comment></data>
<data name="Admin.Library.DeleteBody.other" xml:space="preserve"><value>{0} sequenze, {1} ({2}), vanno nel cestino dell'archivio; si possono ripristinare finché il cestino non viene svuotato.</value><comment>long</comment></data>
<data name="Admin.Library.DeleteConfirm" xml:space="preserve"><value>Sposta nel cestino</value></data>
<data name="Admin.Library.DeleteConfirm.Tip" xml:space="preserve"><value>Spostale nel cestino dell'archivio; nulla viene cancellato</value></data>
<data name="Admin.Library.DeleteTitle.one" xml:space="preserve"><value>Eliminare {0} sequenza?</value><comment>long</comment></data>
<data name="Admin.Library.DeleteTitle.other" xml:space="preserve"><value>Eliminare {0} sequenze?</value><comment>long</comment></data>
<data name="Admin.Library.Deleted.one" xml:space="preserve"><value>{0} sequenza spostata nel cestino ({1})</value><comment>long</comment></data>
<data name="Admin.Library.Deleted.other" xml:space="preserve"><value>{0} sequenze spostate nel cestino ({1})</value><comment>long</comment></data>
<data name="Admin.Library.Empty" xml:space="preserve"><value>Ancora nessuna sequenza</value></data>
<data name="Admin.Library.ExportCsv" xml:space="preserve"><value>Esporta CSV</value></data>
<data name="Admin.Library.ExportCsv.Tip" xml:space="preserve"><value>Salva le sequenze selezionate in un file CSV: titolo, fotocamera, foto, dimensione, date e tag</value></data>
<data name="Admin.Library.Exported.one" xml:space="preserve"><value>{0} sequenza esportata</value><comment>long</comment></data>
<data name="Admin.Library.Exported.other" xml:space="preserve"><value>{0} sequenze esportate</value><comment>long</comment></data>
<data name="Admin.Library.Filter.Analysed" xml:space="preserve"><value>Analizzate</value></data>
<data name="Admin.Library.Filter.Errors" xml:space="preserve"><value>Con errori</value></data>
<data name="Admin.Library.Filter.NoProxies" xml:space="preserve"><value>Senza proxy</value></data>
<data name="Admin.Library.Filter.NotAnalysed" xml:space="preserve"><value>Non analizzate</value></data>
<data name="Admin.Library.Filter.NotRendered" xml:space="preserve"><value>Non renderizzate</value></data>
<data name="Admin.Library.Filter.NotVerified" xml:space="preserve"><value>Non verificate</value></data>
<data name="Admin.Library.Filter.Proxies" xml:space="preserve"><value>Con proxy</value></data>
<data name="Admin.Library.Filter.Rendered" xml:space="preserve"><value>Renderizzate</value></data>
<data name="Admin.Library.Filter.Verified" xml:space="preserve"><value>Verificate</value></data>
<data name="Admin.Library.Filter.Warnings" xml:space="preserve"><value>Con avvisi</value></data>
<data name="Admin.Library.Job.Analyse" xml:space="preserve"><value>Analizza</value></data>
<data name="Admin.Library.Job.Analyse.Tip" xml:space="preserve"><value>Metti in coda l'analisi leggera delle sequenze selezionate</value></data>
<data name="Admin.Library.Job.Proxies" xml:space="preserve"><value>Proxy</value></data>
<data name="Admin.Library.Job.Proxies.Tip" xml:space="preserve"><value>Metti in coda la creazione dei proxy delle sequenze selezionate</value></data>
<data name="Admin.Library.Job.Thumbnails" xml:space="preserve"><value>Miniature</value></data>
<data name="Admin.Library.Job.Thumbnails.Tip" xml:space="preserve"><value>Metti in coda il ridisegno delle miniature delle sequenze selezionate</value></data>
<data name="Admin.Library.Job.Verify" xml:space="preserve"><value>Verifica</value></data>
<data name="Admin.Library.Job.Verify.Tip" xml:space="preserve"><value>Metti in coda una verifica: ogni originale delle sequenze selezionate viene riletto e il suo SHA-256 confrontato</value></data>
<data name="Admin.Library.JobsQueued.one" xml:space="preserve"><value>{0} job in coda.</value></data>
<data name="Admin.Library.JobsQueued.other" xml:space="preserve"><value>{0} job in coda.</value></data>
<data name="Admin.Library.NoMatch" xml:space="preserve"><value>Nessuna sequenza corrisponde ai filtri</value></data>
<data name="Admin.Library.NoTags" xml:space="preserve"><value>Digita almeno un tag da aggiungere o togliere.</value><comment>long</comment></data>
<data name="Admin.Library.NothingQueued" xml:space="preserve"><value>Nulla in coda.</value></data>
<data name="Admin.Library.NothingToDelete" xml:space="preserve"><value>Nessuna delle sequenze selezionate può andare nel cestino.</value><comment>long</comment></data>
<data name="Admin.Library.Open.Tip" xml:space="preserve"><value>Invio o clic apre la sequenza; Spazio la seleziona, Maiusc+Spazio seleziona un intervallo</value></data>
<data name="Admin.Library.Refresh.Tip" xml:space="preserve"><value>Rileggi l'elenco</value></data>
<data name="Admin.Library.RemoveTags" xml:space="preserve"><value>Togli</value></data>
<data name="Admin.Library.RemoveTags.Tip" xml:space="preserve"><value>Tag da togliere, separati da virgole; maiuscole e minuscole non contano</value></data>
<data name="Admin.Library.Retag" xml:space="preserve"><value>Tag…</value></data>
<data name="Admin.Library.Retag.Tip" xml:space="preserve"><value>Aggiungi tag alle sequenze selezionate o toglili</value></data>
<data name="Admin.Library.RetagTitle.one" xml:space="preserve"><value>Tag di {0} sequenza</value><comment>long</comment></data>
<data name="Admin.Library.RetagTitle.other" xml:space="preserve"><value>Tag di {0} sequenze</value><comment>long</comment></data>
<data name="Admin.Library.Retagged.one" xml:space="preserve"><value>Tag cambiati su {0} sequenza</value><comment>long</comment></data>
<data name="Admin.Library.Retagged.other" xml:space="preserve"><value>Tag cambiati su {0} sequenze</value><comment>long</comment></data>
<data name="Admin.Library.Search" xml:space="preserve"><value>Cerca titolo, fotocamera, tag</value></data>
<data name="Admin.Library.Search.Tip" xml:space="preserve"><value>Mostra le sequenze il cui titolo, fotocamera o un tag contiene questo testo</value></data>
<data name="Admin.Library.Select.Tip" xml:space="preserve"><value>Seleziona o deseleziona; con Maiusc, tutte le sequenze dall'ultima scelta</value></data>
<data name="Admin.Library.SelectAll" xml:space="preserve"><value>Seleziona tutte ({0})</value></data>
<data name="Admin.Library.SelectAll.Tip" xml:space="preserve"><value>Seleziona tutte le sequenze di questi filtri, anche quelle non ancora caricate</value></data>
<data name="Admin.Library.Selected.one" xml:space="preserve"><value>{0} selezionata</value></data>
<data name="Admin.Library.Selected.other" xml:space="preserve"><value>{0} selezionate</value></data>
<data name="Admin.Library.Selection" xml:space="preserve"><value>Selezione</value></data>
<data name="Admin.Library.Sequences" xml:space="preserve"><value>Sequenze</value></data>
<data name="Admin.Library.Shown" xml:space="preserve"><value>Mostrate {0} di {1}</value></data>
<data name="Admin.Library.Skipped.one" xml:space="preserve"><value>{0} saltata</value></data>
<data name="Admin.Library.Skipped.other" xml:space="preserve"><value>{0} saltate</value></data>
<data name="Admin.Library.Sort.FrameCount" xml:space="preserve"><value>Più foto</value></data>
<data name="Admin.Library.Sort.Newest" xml:space="preserve"><value>Più recenti</value></data>
<data name="Admin.Library.Sort.Oldest" xml:space="preserve"><value>Meno recenti</value></data>
<data name="Admin.Library.Sort.Size" xml:space="preserve"><value>Più grandi</value></data>
<data name="Admin.Library.Sort.Tip" xml:space="preserve"><value>Ordine delle sequenze</value></data>
<data name="Admin.Library.Sort.Title" xml:space="preserve"><value>Titolo</value></data>
<data name="Admin.Library.Status.Analysed" xml:space="preserve"><value>Analizzata</value></data>
<data name="Admin.Library.Status.Analysed.Tip" xml:space="preserve"><value>L'analisi leggera è fatta</value></data>
<data name="Admin.Library.Status.Errors" xml:space="preserve"><value>Errori</value></data>
<data name="Admin.Library.Status.Errors.Tip" xml:space="preserve"><value>Alcune foto mancano o sono danneggiate; una verifica dice quali</value></data>
<data name="Admin.Library.Status.NoProxies" xml:space="preserve"><value>Senza proxy</value></data>
<data name="Admin.Library.Status.NoProxies.Tip" xml:space="preserve"><value>Ancora nessun proxy: selezionala e scegli Proxy</value></data>
<data name="Admin.Library.Status.NotAnalysed" xml:space="preserve"><value>Non analizzata</value></data>
<data name="Admin.Library.Status.NotAnalysed.Tip" xml:space="preserve"><value>Non ancora analizzata: selezionala e scegli Analizza</value></data>
<data name="Admin.Library.Status.Proxies" xml:space="preserve"><value>Proxy</value></data>
<data name="Admin.Library.Status.Proxies.Tip" xml:space="preserve"><value>I proxy per la visione e il montaggio sono pronti</value></data>
<data name="Admin.Library.Status.Renders.Tip" xml:space="preserve"><value>Video renderizzati da questa sequenza, elencati nella sua pagina</value></data>
<data name="Admin.Library.Status.Renders.one" xml:space="preserve"><value>{0} render</value></data>
<data name="Admin.Library.Status.Renders.other" xml:space="preserve"><value>{0} render</value></data>
<data name="Admin.Library.Status.Tip" xml:space="preserve"><value>Mostra solo le sequenze in questo stato</value></data>
<data name="Admin.Library.Status.Verified" xml:space="preserve"><value>Verificata</value></data>
<data name="Admin.Library.Status.Verified.Tip" xml:space="preserve"><value>Ogni originale corrispondeva al suo SHA-256 all'ultima verifica</value></data>
<data name="Admin.Library.Status.Warnings.Tip" xml:space="preserve"><value>L'analisi ha trovato qualcosa da controllare, come sfarfallio o pause</value></data>
<data name="Admin.Library.Status.Warnings.one" xml:space="preserve"><value>{0} avviso</value></data>
<data name="Admin.Library.Status.Warnings.other" xml:space="preserve"><value>{0} avvisi</value></data>
<data name="Admin.Library.Tag.Tip" xml:space="preserve"><value>Mostra solo le sequenze con questo tag</value></data>
<data name="Admin.Library.TagTooLong" xml:space="preserve"><value>Un tag ha al massimo 64 caratteri.</value><comment>long</comment></data>
<data name="Admin.Library.Trash" xml:space="preserve"><value>Cestino</value></data>
<data name="Admin.Library.Trash.Tip" xml:space="preserve"><value>Sequenze e foto eliminate: ripristinale o svuota il cestino</value></data>
<data name="Admin.Library.Upload" xml:space="preserve"><value>Carica</value></data>
<data name="Admin.Library.Upload.Tip" xml:space="preserve"><value>Carica foto da questo computer in una sequenza nuova o esistente</value></data>
<data name="Admin.Library.View" xml:space="preserve"><value>Vista</value></data>
<data name="Admin.Library.View.Grid.Tip" xml:space="preserve"><value>Mostra le sequenze come schede</value></data>
<data name="Admin.Library.View.List.Tip" xml:space="preserve"><value>Mostra le sequenze come elenco</value></data>
<data name="Admin.Library.Year.Tip" xml:space="preserve"><value>Mostra solo le sequenze la cui prima foto è stata scattata in quest'anno</value></data>
<data name="Admin.Login.Failed" xml:space="preserve"><value>Nome utente o password errati.</value></data>
<data name="Admin.Login.NotAdmin" xml:space="preserve"><value>Solo gli amministratori possono usare questo pannello.</value></data>
<data name="Admin.Login.Password" xml:space="preserve"><value>Password</value></data>
@@ -209,6 +344,7 @@
<data name="Admin.Login.User" xml:space="preserve"><value>Utente</value></data>
<data name="Admin.Login.User.Tip" xml:space="preserve"><value>Il tuo nome utente su questo server</value></data>
<data name="Admin.Logs.Action.ArchiveSettings" xml:space="preserve"><value>Organizzazione archivio</value></data>
<data name="Admin.Logs.Action.FramesDeleted" xml:space="preserve"><value>Foto eliminate</value></data>
<data name="Admin.Logs.Action.JobCreated" xml:space="preserve"><value>Job avviato</value></data>
<data name="Admin.Logs.Action.Login" xml:space="preserve"><value>Accesso</value></data>
<data name="Admin.Logs.Action.LoginFailed" xml:space="preserve"><value>Accesso fallito</value></data>
@@ -224,6 +360,8 @@
<data name="Admin.Logs.Action.SequenceUpdated" xml:space="preserve"><value>Sequenza modificata</value></data>
<data name="Admin.Logs.Action.ServerDiagnostics" xml:space="preserve"><value>Diagnostica esportata</value></data>
<data name="Admin.Logs.Action.ServerSettings" xml:space="preserve"><value>Impostazioni server</value></data>
<data name="Admin.Logs.Action.TrashEmptied" xml:space="preserve"><value>Cestino svuotato</value></data>
<data name="Admin.Logs.Action.TrashRestored" xml:space="preserve"><value>Ripristino dal cestino</value></data>
<data name="Admin.Logs.Action.UserCreated" xml:space="preserve"><value>Utente creato</value></data>
<data name="Admin.Logs.Action.UserDeleted" xml:space="preserve"><value>Utente eliminato</value></data>
<data name="Admin.Logs.Action.UserUpdated" xml:space="preserve"><value>Utente modificato</value></data>
@@ -270,6 +408,8 @@
<data name="Admin.Nav.Expand.Tip" xml:space="preserve"><value>Mostra i nomi del menu · Ctrl+B</value></data>
<data name="Admin.Nav.Jobs" xml:space="preserve"><value>Attività</value></data>
<data name="Admin.Nav.Jobs.Tip" xml:space="preserve"><value>Coda, cronologia e nodi di rendering</value></data>
<data name="Admin.Nav.Library" xml:space="preserve"><value>Libreria</value></data>
<data name="Admin.Nav.Library.Tip" xml:space="preserve"><value>Sequenze e foto: sfoglia, guarda, elimina, ripristina dal cestino, operazioni di massa</value></data>
<data name="Admin.Nav.Logs" xml:space="preserve"><value>Log</value></data>
<data name="Admin.Nav.Logs.Tip" xml:space="preserve"><value>Ultime righe di log e download</value></data>
<data name="Admin.Nav.Settings" xml:space="preserve"><value>Impostazioni</value></data>
@@ -431,6 +571,94 @@
<data name="Admin.Schedules.WeeklyAt" xml:space="preserve"><value>{0} alle {1}</value></data>
<data name="Admin.Schedules.When" xml:space="preserve"><value>Quando</value></data>
<data name="Admin.Schedules.When.Tip" xml:space="preserve"><value>Quando parte; gli orari sono nel fuso orario del server ({0})</value></data>
<data name="Admin.Sequence.AddPhotos" xml:space="preserve"><value>Aggiungi foto</value></data>
<data name="Admin.Sequence.AddPhotos.Tip" xml:space="preserve"><value>Carica foto da questo computer in questa sequenza</value></data>
<data name="Admin.Sequence.AddTag" xml:space="preserve"><value>Aggiungi tag</value></data>
<data name="Admin.Sequence.AddTag.Tip" xml:space="preserve"><value>Digita un tag e premi Invio; le virgole ne separano più di uno</value></data>
<data name="Admin.Sequence.Back" xml:space="preserve"><value>Libreria</value></data>
<data name="Admin.Sequence.Back.Tip" xml:space="preserve"><value>Torna all'elenco, con i suoi filtri</value></data>
<data name="Admin.Sequence.ClearSelection" xml:space="preserve"><value>Deseleziona</value></data>
<data name="Admin.Sequence.ClearSelection.Tip" xml:space="preserve"><value>Deseleziona tutte le foto · Esc</value></data>
<data name="Admin.Sequence.CloseViewer.Tip" xml:space="preserve"><value>Chiudi il visualizzatore · Esc</value></data>
<data name="Admin.Sequence.Cover.Tip" xml:space="preserve"><value>La copertina della sequenza</value></data>
<data name="Admin.Sequence.Delete" xml:space="preserve"><value>Elimina…</value></data>
<data name="Admin.Sequence.Delete.Tip" xml:space="preserve"><value>Sposta l'intera sequenza nel cestino dell'archivio</value></data>
<data name="Admin.Sequence.DeleteBody.one" xml:space="preserve"><value>La sequenza, la sua {0} foto ({1}) e i suoi render vanno nel cestino dell'archivio; ripristinala da lì finché il cestino non viene svuotato.</value><comment>long</comment></data>
<data name="Admin.Sequence.DeleteBody.other" xml:space="preserve"><value>La sequenza, le sue {0} foto ({1}) e i suoi render vanno nel cestino dell'archivio; ripristinala da lì finché il cestino non viene svuotato.</value><comment>long</comment></data>
<data name="Admin.Sequence.DeleteConfirm.Tip" xml:space="preserve"><value>Sposta la sequenza nel cestino dell'archivio; nulla viene cancellato</value></data>
<data name="Admin.Sequence.DeletePhotos" xml:space="preserve"><value>Elimina…</value></data>
<data name="Admin.Sequence.DeletePhotos.Tip" xml:space="preserve"><value>Sposta le foto selezionate nel cestino dell'archivio; miniature, proxy e analisi si aggiornano</value></data>
<data name="Admin.Sequence.DeletePhotosBody.one" xml:space="preserve"><value>{0} foto ({1}) va nel cestino dell'archivio; ripristinala da lì finché il cestino non viene svuotato.</value><comment>long</comment></data>
<data name="Admin.Sequence.DeletePhotosBody.other" xml:space="preserve"><value>{0} foto ({1}) vanno nel cestino dell'archivio; ripristinale da lì finché il cestino non viene svuotato.</value><comment>long</comment></data>
<data name="Admin.Sequence.DeletePhotosConfirm" xml:space="preserve"><value>Sposta nel cestino</value></data>
<data name="Admin.Sequence.DeletePhotosConfirm.Tip" xml:space="preserve"><value>Sposta le foto nel cestino dell'archivio; nulla viene cancellato</value></data>
<data name="Admin.Sequence.DeletePhotosTitle.one" xml:space="preserve"><value>Eliminare {0} foto?</value><comment>long</comment></data>
<data name="Admin.Sequence.DeletePhotosTitle.other" xml:space="preserve"><value>Eliminare {0} foto?</value><comment>long</comment></data>
<data name="Admin.Sequence.DeleteTitle" xml:space="preserve"><value>Eliminare {0}?</value><comment>long</comment></data>
<data name="Admin.Sequence.Deleted" xml:space="preserve"><value>{0} spostata nel cestino.</value><comment>long</comment></data>
<data name="Admin.Sequence.Details" xml:space="preserve"><value>Sequenza</value></data>
<data name="Admin.Sequence.Download" xml:space="preserve"><value>Scarica</value></data>
<data name="Admin.Sequence.Download.Tip" xml:space="preserve"><value>Salva il file originale di questa foto, com'è nell'archivio</value></data>
<data name="Admin.Sequence.Fact.Aperture" xml:space="preserve"><value>Diaframma</value></data>
<data name="Admin.Sequence.Fact.Camera" xml:space="preserve"><value>Fotocamera</value></data>
<data name="Admin.Sequence.Fact.Captured" xml:space="preserve"><value>Scattata</value></data>
<data name="Admin.Sequence.Fact.Dimensions" xml:space="preserve"><value>Risoluzione</value></data>
<data name="Admin.Sequence.Fact.Exposure" xml:space="preserve"><value>Esposizione</value></data>
<data name="Admin.Sequence.Fact.Flags" xml:space="preserve"><value>Segnalazioni</value></data>
<data name="Admin.Sequence.Fact.Focal" xml:space="preserve"><value>Focale</value></data>
<data name="Admin.Sequence.Fact.Folder" xml:space="preserve"><value>Cartella</value></data>
<data name="Admin.Sequence.Fact.Format" xml:space="preserve"><value>Formato</value></data>
<data name="Admin.Sequence.Fact.Interval" xml:space="preserve"><value>Intervallo</value></data>
<data name="Admin.Sequence.Fact.Iso" xml:space="preserve"><value>ISO</value></data>
<data name="Admin.Sequence.Fact.Lens" xml:space="preserve"><value>Obiettivo</value></data>
<data name="Admin.Sequence.Fact.Photos" xml:space="preserve"><value>Foto</value></data>
<data name="Admin.Sequence.Fact.Sha256" xml:space="preserve"><value>SHA-256</value></data>
<data name="Admin.Sequence.Fact.Size" xml:space="preserve"><value>Dimensione</value></data>
<data name="Admin.Sequence.Fact.Span" xml:space="preserve"><value>Durata</value></data>
<data name="Admin.Sequence.Fact.Status" xml:space="preserve"><value>Stato</value></data>
<data name="Admin.Sequence.Fact.Time" xml:space="preserve"><value>Scattata</value></data>
<data name="Admin.Sequence.Fact.Updated" xml:space="preserve"><value>Modificata</value></data>
<data name="Admin.Sequence.Flag.Corrupt" xml:space="preserve"><value>danneggiata</value></data>
<data name="Admin.Sequence.Flag.Duplicate" xml:space="preserve"><value>duplicata</value></data>
<data name="Admin.Sequence.Flag.Excluded" xml:space="preserve"><value>esclusa</value></data>
<data name="Admin.Sequence.Flag.Missing" xml:space="preserve"><value>mancante</value></data>
<data name="Admin.Sequence.Gone" xml:space="preserve"><value>Questa sequenza non è più nella libreria</value><comment>long</comment></data>
<data name="Admin.Sequence.MorePhotos.Tip" xml:space="preserve"><value>Mostra le 500 foto successive</value></data>
<data name="Admin.Sequence.Next.Tip" xml:space="preserve"><value>Foto successiva · →</value></data>
<data name="Admin.Sequence.NoPhotos" xml:space="preserve"><value>Ancora nessuna foto</value></data>
<data name="Admin.Sequence.NoRenders" xml:space="preserve"><value>Ancora nessun render</value></data>
<data name="Admin.Sequence.Notes" xml:space="preserve"><value>Note</value></data>
<data name="Admin.Sequence.Notes.Tip" xml:space="preserve"><value>Note libere sulla sequenza, salvate quando lasci il campo</value></data>
<data name="Admin.Sequence.OnePhoto.Tip" xml:space="preserve"><value>Prima seleziona una sola foto</value></data>
<data name="Admin.Sequence.Photo.Tip" xml:space="preserve"><value>{0} · Invio o clic apre il visualizzatore; Spazio seleziona, Maiusc+Spazio seleziona un intervallo</value></data>
<data name="Admin.Sequence.Photos" xml:space="preserve"><value>Foto</value></data>
<data name="Admin.Sequence.PhotosDeleted.one" xml:space="preserve"><value>{0} foto spostata nel cestino</value><comment>long</comment></data>
<data name="Admin.Sequence.PhotosDeleted.other" xml:space="preserve"><value>{0} foto spostate nel cestino</value><comment>long</comment></data>
<data name="Admin.Sequence.Previous.Tip" xml:space="preserve"><value>Foto precedente · ←</value></data>
<data name="Admin.Sequence.Rate.Tip" xml:space="preserve"><value>Dai voto {0} su 5</value></data>
<data name="Admin.Sequence.Rating" xml:space="preserve"><value>Voto</value></data>
<data name="Admin.Sequence.RemoveTag.Tip" xml:space="preserve"><value>Togli il tag {0}</value></data>
<data name="Admin.Sequence.Render.Created" xml:space="preserve"><value>Creato</value></data>
<data name="Admin.Sequence.Render.Download" xml:space="preserve"><value>Scarica</value></data>
<data name="Admin.Sequence.Render.Download.Tip" xml:space="preserve"><value>Salva questo video</value></data>
<data name="Admin.Sequence.Render.Length" xml:space="preserve"><value>Durata</value></data>
<data name="Admin.Sequence.Render.Preset" xml:space="preserve"><value>Preset</value></data>
<data name="Admin.Sequence.Render.Size" xml:space="preserve"><value>Dimensione</value></data>
<data name="Admin.Sequence.Render.Video" xml:space="preserve"><value>Video</value></data>
<data name="Admin.Sequence.Renders" xml:space="preserve"><value>Render</value></data>
<data name="Admin.Sequence.SelectAll" xml:space="preserve"><value>Seleziona tutte</value></data>
<data name="Admin.Sequence.SelectAll.Tip" xml:space="preserve"><value>Seleziona tutte le foto mostrate · Ctrl+A</value></data>
<data name="Admin.Sequence.SelectPhoto.Tip" xml:space="preserve"><value>Seleziona o deseleziona; con Maiusc, tutte le foto dall'ultima scelta</value></data>
<data name="Admin.Sequence.SetCover" xml:space="preserve"><value>Imposta copertina</value></data>
<data name="Admin.Sequence.SetCover.Tip" xml:space="preserve"><value>Mostra questa foto sulla scheda della sequenza in ogni Libreria</value></data>
<data name="Admin.Sequence.SomePhotos.Tip" xml:space="preserve"><value>Prima seleziona una o più foto</value></data>
<data name="Admin.Sequence.Stars.one" xml:space="preserve"><value>{0} stella</value></data>
<data name="Admin.Sequence.Stars.other" xml:space="preserve"><value>{0} stelle</value></data>
<data name="Admin.Sequence.Tags" xml:space="preserve"><value>Tag</value></data>
<data name="Admin.Sequence.Title" xml:space="preserve"><value>Titolo</value></data>
<data name="Admin.Sequence.Title.Tip" xml:space="preserve"><value>Titolo della sequenza; vuoto mostra data e fotocamera · Invio salva, Esc annulla</value></data>
<data name="Admin.Sequence.TooManyTags" xml:space="preserve"><value>Una sequenza ha al massimo 50 tag.</value><comment>long</comment></data>
<data name="Admin.Sequence.Unrate.Tip" xml:space="preserve"><value>Voto {0} su 5; sceglilo di nuovo per togliere il voto</value></data>
<data name="Admin.Settings.About" xml:space="preserve"><value>Informazioni</value></data>
<data name="Admin.Settings.AuditRetentionDays" xml:space="preserve"><value>Conserva controllo (giorni)</value></data>
<data name="Admin.Settings.AuditRetentionDays.Tip" xml:space="preserve"><value>Limite di età della pianificazione Pulizia registro controllo: le voci più vecchie vengono eliminate; 0: conservate per sempre</value></data>
@@ -509,6 +737,100 @@
<data name="Admin.SignOut" xml:space="preserve"><value>Esci</value></data>
<data name="Admin.SignOut.Tip" xml:space="preserve"><value>Esci dal pannello di amministrazione</value></data>
<data name="Admin.Theme.Tip" xml:space="preserve"><value>Alterna tema chiaro e scuro</value></data>
<data name="Admin.Trash.Back" xml:space="preserve"><value>Libreria</value></data>
<data name="Admin.Trash.Back.Tip" xml:space="preserve"><value>Torna alla Libreria</value></data>
<data name="Admin.Trash.DeletedAt" xml:space="preserve"><value>Eliminato</value></data>
<data name="Admin.Trash.DeletedBy" xml:space="preserve"><value>Eliminato da</value></data>
<data name="Admin.Trash.Emptied" xml:space="preserve"><value>Cestino svuotato.</value><comment>long</comment></data>
<data name="Admin.Trash.Empty" xml:space="preserve"><value>Svuota…</value></data>
<data name="Admin.Trash.Empty.Tip" xml:space="preserve"><value>Cancella per sempre tutto il contenuto del cestino; prima un elenco mostra cosa viene cancellato</value></data>
<data name="Admin.Trash.EmptyBody.one" xml:space="preserve"><value>{0} file ({1}) viene cancellato per sempre.</value><comment>long</comment></data>
<data name="Admin.Trash.EmptyBody.other" xml:space="preserve"><value>{0} file ({1}) vengono cancellati per sempre.</value><comment>long</comment></data>
<data name="Admin.Trash.EmptyConfirm" xml:space="preserve"><value>Svuota cestino</value></data>
<data name="Admin.Trash.EmptyConfirm.Tip" xml:space="preserve"><value>Cancella per sempre ogni voce dell'elenco</value></data>
<data name="Admin.Trash.EmptyFailed" xml:space="preserve"><value>Il cestino non è stato svuotato; il log del job dice perché.</value><comment>long</comment></data>
<data name="Admin.Trash.EmptyFinal" xml:space="preserve"><value>Non si può annullare.</value><comment>long</comment></data>
<data name="Admin.Trash.EmptyQueued" xml:space="preserve"><value>Svuotamento del cestino: job in coda.</value><comment>long</comment></data>
<data name="Admin.Trash.EmptyTitle" xml:space="preserve"><value>Svuotare il cestino?</value><comment>long</comment></data>
<data name="Admin.Trash.EmptyWord" xml:space="preserve"><value>svuota</value></data>
<data name="Admin.Trash.Emptying.Tip" xml:space="preserve"><value>Il cestino si sta svuotando</value></data>
<data name="Admin.Trash.EntryCount.one" xml:space="preserve"><value>{0} voce</value></data>
<data name="Admin.Trash.EntryCount.other" xml:space="preserve"><value>{0} voci</value></data>
<data name="Admin.Trash.IsEmpty" xml:space="preserve"><value>Il cestino è vuoto</value></data>
<data name="Admin.Trash.Kept.one" xml:space="preserve"><value>{0} file resta nel cestino: non corrisponde più al suo record.</value><comment>long</comment></data>
<data name="Admin.Trash.Kept.other" xml:space="preserve"><value>{0} file restano nel cestino: non corrispondono più al loro record.</value><comment>long</comment></data>
<data name="Admin.Trash.Kind" xml:space="preserve"><value>Tipo</value></data>
<data name="Admin.Trash.Kind.Photos" xml:space="preserve"><value>Foto</value></data>
<data name="Admin.Trash.Kind.Replaced" xml:space="preserve"><value>Sostituite</value></data>
<data name="Admin.Trash.Kind.Sequence" xml:space="preserve"><value>Sequenza</value></data>
<data name="Admin.Trash.NothingToEmpty.Tip" xml:space="preserve"><value>Il cestino è vuoto</value></data>
<data name="Admin.Trash.Photos" xml:space="preserve"><value>Foto</value></data>
<data name="Admin.Trash.Restore" xml:space="preserve"><value>Ripristina</value></data>
<data name="Admin.Trash.RestorePhotos.Tip" xml:space="preserve"><value>Rimetti le foto nella loro sequenza (una nuova se non c'è più); prima ognuna viene controllata con il suo SHA-256</value></data>
<data name="Admin.Trash.RestoreSequence.Tip" xml:space="preserve"><value>Rimetti la sequenza nella sua cartella e nella libreria; prima le sue foto vengono controllate con il loro SHA-256</value></data>
<data name="Admin.Trash.RestoredNew.one" xml:space="preserve"><value>{0} foto ripristinata in una nuova sequenza.</value><comment>long</comment></data>
<data name="Admin.Trash.RestoredNew.other" xml:space="preserve"><value>{0} foto ripristinate in una nuova sequenza.</value><comment>long</comment></data>
<data name="Admin.Trash.RestoredPhotos.one" xml:space="preserve"><value>{0} foto è di nuovo in {1}.</value><comment>long</comment></data>
<data name="Admin.Trash.RestoredPhotos.other" xml:space="preserve"><value>{0} foto sono di nuovo in {1}.</value><comment>long</comment></data>
<data name="Admin.Trash.RestoredSequence" xml:space="preserve"><value>{0} è di nuovo nella libreria.</value><comment>long</comment></data>
<data name="Admin.Trash.Sequence" xml:space="preserve"><value>Sequenza</value></data>
<data name="Admin.Trash.Size" xml:space="preserve"><value>Dimensione</value></data>
<data name="Admin.Trash.Title" xml:space="preserve"><value>Cestino</value></data>
<data name="Admin.Upload.Add" xml:space="preserve"><value>Aggiungi foto</value></data>
<data name="Admin.Upload.Add.Tip" xml:space="preserve"><value>Scegli le foto su questo computer; puoi anche trascinarle in questa finestra</value></data>
<data name="Admin.Upload.Bytes" xml:space="preserve"><value>{0} di {1}</value></data>
<data name="Admin.Upload.Cancel" xml:space="preserve"><value>Annulla</value></data>
<data name="Admin.Upload.Cancel.Tip" xml:space="preserve"><value>Ferma ora: le foto non ancora finite vengono scartate sul server</value></data>
<data name="Admin.Upload.Close" xml:space="preserve"><value>Chiudi</value></data>
<data name="Admin.Upload.Close.Tip" xml:space="preserve"><value>Chiudi la finestra di caricamento</value></data>
<data name="Admin.Upload.Count" xml:space="preserve"><value>Foto: {0} di {1}</value></data>
<data name="Admin.Upload.Drop" xml:space="preserve"><value>Trascina qui le foto</value></data>
<data name="Admin.Upload.Existing" xml:space="preserve"><value>Sequenza esistente</value></data>
<data name="Admin.Upload.Existing.Tip" xml:space="preserve"><value>Aggiungi le foto a una sequenza già presente sul server</value></data>
<data name="Admin.Upload.Failed" xml:space="preserve"><value>Non riuscite: {0}</value></data>
<data name="Admin.Upload.HashFailed" xml:space="preserve"><value>In questo browser non si può calcolare l'hash delle foto, quindi non è stato caricato nulla.</value></data>
<data name="Admin.Upload.New" xml:space="preserve"><value>Nuova sequenza</value></data>
<data name="Admin.Upload.New.Tip" xml:space="preserve"><value>Crea sul server una sequenza per queste foto</value></data>
<data name="Admin.Upload.NewTitle" xml:space="preserve"><value>Titolo</value></data>
<data name="Admin.Upload.NewTitle.Tip" xml:space="preserve"><value>Nome della nuova sequenza; se resta vuoto, prende data e fotocamera delle sue foto</value></data>
<data name="Admin.Upload.NoMatch" xml:space="preserve"><value>Nessuna sequenza trovata</value></data>
<data name="Admin.Upload.PhotoCount.one" xml:space="preserve"><value>{0} foto</value></data>
<data name="Admin.Upload.PhotoCount.other" xml:space="preserve"><value>{0} foto</value></data>
<data name="Admin.Upload.Photos" xml:space="preserve"><value>Foto</value></data>
<data name="Admin.Upload.PickFirst" xml:space="preserve"><value>Scegli prima una sequenza.</value></data>
<data name="Admin.Upload.ReadFailed" xml:space="preserve"><value>Impossibile leggere il file.</value></data>
<data name="Admin.Upload.Remove" xml:space="preserve"><value>Togli {0}</value></data>
<data name="Admin.Upload.Remove.Tip" xml:space="preserve"><value>Togli questa foto dall'elenco</value></data>
<data name="Admin.Upload.Search" xml:space="preserve"><value>Cerca sequenze</value></data>
<data name="Admin.Upload.Search.Tip" xml:space="preserve"><value>Trova una sequenza per titolo, fotocamera o tag</value></data>
<data name="Admin.Upload.SelfTestFailed" xml:space="preserve"><value>Questo browser ha calcolato male uno SHA-256 di prova, quindi non carica nulla.</value></data>
<data name="Admin.Upload.Sequences" xml:space="preserve"><value>Sequenze</value></data>
<data name="Admin.Upload.Sequences.Tip" xml:space="preserve"><value>La sequenza in cui vanno le foto</value></data>
<data name="Admin.Upload.Skipped.Folders" xml:space="preserve"><value>Cartelle saltate: {0}</value></data>
<data name="Admin.Upload.Skipped.Folders.Tip" xml:space="preserve"><value>Le cartelle si importano con l'app desktop; qui si caricano solo foto</value></data>
<data name="Admin.Upload.Skipped.Formats" xml:space="preserve"><value>Non foto: {0}</value></data>
<data name="Admin.Upload.Skipped.Formats.Tip" xml:space="preserve"><value>Esclusi i file in un formato che il server non legge come foto</value></data>
<data name="Admin.Upload.Skipped.Size" xml:space="preserve"><value>Troppo grandi: {0}</value></data>
<data name="Admin.Upload.Skipped.Size.Tip" xml:space="preserve"><value>Esclusi i file oltre il limite di caricamento del server ({0})</value></data>
<data name="Admin.Upload.Start" xml:space="preserve"><value>Carica</value></data>
<data name="Admin.Upload.Start.Tip" xml:space="preserve"><value>Invia le foto non ancora sul server; il server controlla ognuna con il suo SHA-256</value></data>
<data name="Admin.Upload.State.Cancelled" xml:space="preserve"><value>Annullata</value></data>
<data name="Admin.Upload.State.Deleted" xml:space="preserve"><value>Eliminata prima</value></data>
<data name="Admin.Upload.State.Deleted.Tip" xml:space="preserve"><value>Eliminata in precedenza da questa sequenza: ripristinala dal cestino per riaverla</value></data>
<data name="Admin.Upload.State.Done" xml:space="preserve"><value>Caricata</value></data>
<data name="Admin.Upload.State.Done.Tip" xml:space="preserve"><value>Sul server e verificata con il suo SHA-256</value></data>
<data name="Admin.Upload.State.Exists" xml:space="preserve"><value>Già presente</value></data>
<data name="Admin.Upload.State.Exists.Tip" xml:space="preserve"><value>Il server ha già questa foto</value></data>
<data name="Admin.Upload.State.Failed" xml:space="preserve"><value>Non riuscita</value></data>
<data name="Admin.Upload.State.Hashing" xml:space="preserve"><value>Calcolo hash {0}</value></data>
<data name="Admin.Upload.State.NotSent" xml:space="preserve"><value>Non inviata</value></data>
<data name="Admin.Upload.State.NotSent.Tip" xml:space="preserve"><value>Non inviata: il caricamento si è fermato prima di questa foto</value></data>
<data name="Admin.Upload.State.Starting" xml:space="preserve"><value>Avvio</value></data>
<data name="Admin.Upload.State.Uploading" xml:space="preserve"><value>Invio {0}</value></data>
<data name="Admin.Upload.State.Verifying" xml:space="preserve"><value>Verifica</value></data>
<data name="Admin.Upload.State.Waiting" xml:space="preserve"><value>In attesa</value></data>
<data name="Admin.Upload.Target" xml:space="preserve"><value>Sequenza</value></data>
<data name="Admin.Upload.Title" xml:space="preserve"><value>Carica foto</value></data>
<data name="Admin.Users.Accounts.one" xml:space="preserve"><value>{0} account</value></data>
<data name="Admin.Users.Accounts.other" xml:space="preserve"><value>{0} account</value></data>
<data name="Admin.Users.Active" xml:space="preserve"><value>Attivo</value></data>
+20 -1
View File
@@ -84,6 +84,10 @@
<data name="Archive.Error.SourceChanged" xml:space="preserve"><value>{0} è cambiato dopo la creazione del piano.</value></data>
<data name="Archive.Error.SourceGone" xml:space="preserve"><value>La scheda o cartella {0} non è più disponibile.</value></data>
<data name="Archive.Error.StalePlan" xml:space="preserve"><value>L'archivio è cambiato dopo la creazione del piano.</value></data>
<data name="Archive.Error.TrashChanged" xml:space="preserve"><value>Il cestino è cambiato dopo il controllo; non è stato cancellato nulla.</value></data>
<data name="Archive.Error.TrashKept.one" xml:space="preserve"><value>{0:N0} elemento del cestino è stato mantenuto: è cambiato, o una sostituzione non corrisponde più.</value></data>
<data name="Archive.Error.TrashKept.other" xml:space="preserve"><value>{0:N0} elementi del cestino sono stati mantenuti: sono cambiati, o una sostituzione non corrisponde più.</value></data>
<data name="Archive.Error.TrashMismatch" xml:space="preserve"><value>Nessun file di questo elemento del cestino corrisponde più al suo registro; resta nel cestino.</value></data>
<data name="Archive.Failed.Access" xml:space="preserve"><value>Chronos non ha accesso all'archivio.</value></data>
<data name="Archive.Failed.Files" xml:space="preserve"><value>Non è stato possibile leggere o scrivere un file dell'archivio.</value></data>
<data name="Archive.Failed.Gone" xml:space="preserve"><value>La sequenza non è più nell'indice.</value></data>
@@ -147,7 +151,9 @@
<data name="Archive.Log.SequenceMissing" xml:space="preserve"><value>Sequenza non trovata: {0}</value></data>
<data name="Archive.Log.StepFailed" xml:space="preserve"><value>Passo di pulizia {0} non riuscito: {1}</value></data>
<data name="Archive.Log.StepUnknown" xml:space="preserve"><value>Passo di pulizia sconosciuto qui: {0}</value></data>
<data name="Archive.Log.TrashEmptied" xml:space="preserve"><value>Elementi cancellati: {0}, dimensione: {1}</value></data>
<data name="Archive.Log.TrashEntry" xml:space="preserve"><value>Nel cestino dal {0}: {1} ({2})</value></data>
<data name="Archive.Log.TrashKept" xml:space="preserve"><value>Mantenuto nel cestino: {0}</value></data>
<data name="Archive.Log.TrashOffline" xml:space="preserve"><value>Cestino non controllato: l'archivio non è raggiungibile</value></data>
<data name="Archive.Log.TrashReport" xml:space="preserve"><value>Voci vecchie nel cestino: {0}, dimensione: {1}; nulla è stato eliminato</value></data>
<data name="Archive.Log.VerifyDone" xml:space="preserve"><value>Foto controllate: {0}, integre: {1}, con impronta nuova: {2}, con problemi: {3}</value></data>
@@ -241,11 +247,24 @@
<data name="Archive.Toolbar.Rebuild" xml:space="preserve"><value>Ricostruisci indice…</value></data>
<data name="Archive.Toolbar.Scan" xml:space="preserve"><value>Scansiona</value></data>
<data name="Archive.Toolbar.Verify" xml:space="preserve"><value>Verifica</value></data>
<data name="Archive.Trash.Checking" xml:space="preserve"><value>Controllo del cestino…</value></data>
<data name="Archive.Trash.Deleted" xml:space="preserve"><value>Eliminata il {0}</value></data>
<data name="Archive.Trash.Empty" xml:space="preserve"><value>Il cestino è vuoto</value></data>
<data name="Archive.Trash.EmptyAction" xml:space="preserve"><value>Svuota…</value></data>
<data name="Archive.Trash.EmptyHeading.one" xml:space="preserve"><value>Cancellare per sempre {0:N0} elemento del cestino?</value></data>
<data name="Archive.Trash.EmptyHeading.other" xml:space="preserve"><value>Cancellare per sempre {0:N0} elementi del cestino?</value></data>
<data name="Archive.Trash.EmptyMessage" xml:space="preserve"><value>{0} e {1} ({2}) vengono cancellati dall'archivio; non si può annullare.</value></data>
<data name="Archive.Trash.Entries.one" xml:space="preserve"><value>{0:N0} elemento</value></data>
<data name="Archive.Trash.Entries.other" xml:space="preserve"><value>{0:N0} elementi</value></data>
<data name="Archive.Trash.Erase" xml:space="preserve"><value>Cancella per sempre</value></data>
<data name="Archive.Trash.Failed" xml:space="preserve"><value>Impossibile ripristinare la sequenza dal cestino</value></data>
<data name="Archive.Trash.Heading" xml:space="preserve"><value>Cestino · {0}</value></data>
<data name="Archive.Trash.List" xml:space="preserve"><value>Sequenze eliminate</value></data>
<data name="Archive.Trash.KeptFiles.one" xml:space="preserve"><value>{0:N0} file è rimasto nel cestino: non corrisponde più al suo registro.</value></data>
<data name="Archive.Trash.KeptFiles.other" xml:space="preserve"><value>{0:N0} file sono rimasti nel cestino: non corrispondono più al loro registro.</value></data>
<data name="Archive.Trash.Kind.Photos" xml:space="preserve"><value>Foto</value></data>
<data name="Archive.Trash.Kind.Replaced" xml:space="preserve"><value>Originali sostituiti</value></data>
<data name="Archive.Trash.Kind.Sequence" xml:space="preserve"><value>Sequenza</value></data>
<data name="Archive.Trash.List" xml:space="preserve"><value>Elementi del cestino</value></data>
<data name="Archive.Trash.Reading" xml:space="preserve"><value>Lettura del cestino…</value></data>
<data name="Archive.Trash.Restore" xml:space="preserve"><value>Ripristina</value></data>
<data name="Archive.Trash.Restored.one" xml:space="preserve"><value>{0:N0} sequenza ripristinata</value></data>
+1
View File
@@ -72,6 +72,7 @@
<data name="Jobs.Kind.DeepAnalyse" xml:space="preserve"><value>Analisi approfondita</value></data>
<data name="Jobs.Kind.Download" xml:space="preserve"><value>Scaricamento</value></data>
<data name="Jobs.Kind.Duplicates" xml:space="preserve"><value>Duplicati</value></data>
<data name="Jobs.Kind.EmptyTrash" xml:space="preserve"><value>Svuota cestino</value></data>
<data name="Jobs.Kind.Import" xml:space="preserve"><value>Importazione</value></data>
<data name="Jobs.Kind.LightAnalyse" xml:space="preserve"><value>Analisi rapida</value></data>
<data name="Jobs.Kind.Maintenance" xml:space="preserve"><value>Manutenzione</value></data>
+4
View File
@@ -85,12 +85,15 @@
<data name="Server.Error.ScheduleSystem" xml:space="preserve"><value>Una pianificazione di sistema non si può eliminare; disattivala.</value><comment>long</comment></data>
<data name="Server.Error.Self" xml:space="preserve"><value>Non puoi farlo sul tuo account.</value></data>
<data name="Server.Error.SequenceBusy" xml:space="preserve"><value>Un'attività sta lavorando su questa sequenza o sul suo archivio; riprova quando è libera.</value></data>
<data name="Server.Error.SequenceInLibrary" xml:space="preserve"><value>Quella sequenza è già nella libreria.</value></data>
<data name="Server.Error.SessionExpired" xml:space="preserve"><value>La sessione è scaduta; accedi di nuovo.</value></data>
<data name="Server.Error.SettingLocked" xml:space="preserve"><value>È impostato da una variabile d'ambiente; modificala lì.</value></data>
<data name="Server.Error.SettingsConflict" xml:space="preserve"><value>La sequenza è cambiata sul server; ricaricala e riapplica la modifica.</value></data>
<data name="Server.Error.SidecarMismatch" xml:space="preserve"><value>La sua cartella contiene un'altra sequenza; prima esegui una scansione dell'archivio.</value></data>
<data name="Server.Error.TooLarge" xml:space="preserve"><value>La richiesta supera la dimensione accettata dal server.</value></data>
<data name="Server.Error.TooManyUploads" xml:space="preserve"><value>Troppi caricamenti insieme; riprova tra poco.</value></data>
<data name="Server.Error.TrashChanged" xml:space="preserve"><value>Il cestino è cambiato dopo il controllo; ricontrollalo prima di svuotarlo.</value></data>
<data name="Server.Error.TrashMismatch" xml:space="preserve"><value>Nessun file di questo elemento del cestino corrisponde più al suo registro; resta nel cestino.</value></data>
<data name="Server.Error.Unauthorized" xml:space="preserve"><value>Accedi per continuare.</value></data>
<data name="Server.Error.Unreachable" xml:space="preserve"><value>Il server non risponde; controlla l'indirizzo e la rete.</value></data>
<data name="Server.Error.UnsupportedMediaType" xml:space="preserve"><value>Invia il corpo come JSON.</value></data>
@@ -99,6 +102,7 @@
<data name="Server.Error.UsernameTaken" xml:space="preserve"><value>Questo nome utente è già in uso.</value></data>
<data name="Server.Error.WeakPassword" xml:space="preserve"><value>Usa almeno {0} caratteri.</value></data>
<data name="Server.Error.WebsocketRequired" xml:space="preserve"><value>Connettiti con un WebSocket.</value></data>
<data name="Server.Error.WouldEmpty" xml:space="preserve"><value>Se ne andrebbero tutte le foto della sequenza; elimina invece la sequenza.</value></data>
<data name="Server.Error.WrongPassword" xml:space="preserve"><value>La password attuale è errata.</value></data>
<data name="Server.Error.WrongUploadKind" xml:space="preserve"><value>Questo caricamento appartiene a un job di rendering.</value></data>
<data name="Server.Found" xml:space="preserve"><value>Server trovati</value></data>
+6 -2
View File
@@ -91,8 +91,12 @@
<data name="Tooltips.Archive.TagsAdd" xml:space="preserve"><value>Tag da aggiungere, separati da virgole</value></data>
<data name="Tooltips.Archive.TagsRemove" xml:space="preserve"><value>Tag da rimuovere, separati da virgole</value></data>
<data name="Tooltips.Archive.TitleTemplate" xml:space="preserve"><value>Modello del titolo; il segnaposto title è il titolo attuale · controllato mentre scrivi</value></data>
<data name="Tooltips.Archive.Trash" xml:space="preserve"><value>Le sequenze eliminate da questo archivio, ognuna ripristinabile</value></data>
<data name="Tooltips.Archive.TrashRestore" xml:space="preserve"><value>Riporta questa sequenza nella sua cartella e nella libreria, con impostazioni e render</value></data>
<data name="Tooltips.Archive.Trash" xml:space="preserve"><value>Le sequenze e le foto eliminate da questo archivio, ognuna ripristinabile</value></data>
<data name="Tooltips.Archive.TrashEmpty" xml:space="preserve"><value>Cancella per sempre gli elementi di questo cestino, dopo un controllo di cosa contengono e una conferma digitata</value></data>
<data name="Tooltips.Archive.TrashEmptyPlan" xml:space="preserve"><value>Cosa viene cancellato per sempre dall'archivio</value></data>
<data name="Tooltips.Archive.TrashErase.one" xml:space="preserve"><value>Cancella per sempre {0:N0} elemento; prima digita il numero qui sopra</value></data>
<data name="Tooltips.Archive.TrashErase.other" xml:space="preserve"><value>Cancella per sempre {0:N0} elementi; prima digita il numero qui sopra</value></data>
<data name="Tooltips.Archive.TrashRestore" xml:space="preserve"><value>Riporta indietro questo elemento: una sequenza nella sua cartella e nella libreria, le foto nella loro sequenza dopo un controllo dell'hash</value></data>
<data name="Tooltips.Archive.Verify" xml:space="preserve"><value>Ricalcola l'hash di ogni originale e segnala i danni · legge tutto l'archivio</value></data>
<data name="Tooltips.Archive.YearRow" xml:space="preserve"><value>{0} · Freccia destra apre l'anno, freccia sinistra lo chiude</value></data>
<data name="Tooltips.Archive.YearRowRtl" xml:space="preserve"><value>{0} · Freccia sinistra apre l'anno, freccia destra lo chiude</value></data>
@@ -242,6 +242,9 @@
<DockPanel Grid.Row="3" Margin="0,16,0,0">
<Button DockPanel.Dock="Right" Content="{l:Loc Archive.Dialog.Close}" Command="{Binding CloseCommand}" ToolTip="{Binding CloseToolTip}" IsCancel="True"
IsDefault="True" MinWidth="96" />
<!-- Erasing for good: a dry run and a typed confirmation first, never the default button. -->
<Button DockPanel.Dock="Right" Content="{l:Loc Archive.Trash.EmptyAction}" Command="{Binding EmptyCommand}" ToolTip="{Binding EmptyToolTip}"
ToolTipService.ShowOnDisabled="True" MinWidth="96" Margin="0,0,8,0" />
<Grid Margin="0,0,12,0">
<TextBlock Style="{StaticResource Text.Live}" Text="{Binding BusyText}" infra:LiveRegion.Text="{Binding BusyText}" />
<ui:StatusGlyph Style="{StaticResource Status.DialogError}" />
+8 -3
View File
@@ -32,14 +32,19 @@ public static class SampleReports
? new OrphanReport([], [], [])
: new OrphanReport([new SequenceOrphans(sequences[2].Folder, ["IMG_0412.CR2", "IMG_0413.CR2"], [])], [sequences[3]], ["2024/2024-12-31 Unsorted"]);
/// <summary>The trash dialog's rows: the first two sample sequences, deleted an hour and a day ago (nothing moves on disk).</summary>
/// <summary>
/// The trash dialog's rows: the first sample sequence, deleted an hour ago, and 24 photos of the second, deleted a day ago
/// (nothing moves on disk).
/// </summary>
public static IReadOnlyList<TrashEntry> Trash(Guid archiveId, IReadOnlyList<SequenceLocation> sequences)
{
var now = SampleData.Now;
return
[
.. sequences.Take(2).Select((s, i) => new TrashEntry(archiveId, s.Id.ToString("N"), s.Id, s.Title ?? s.Folder, s.Folder, 1_200 * (i + 1), 1_206 * (i + 1),
31_457_280L * 1_200 * (i + 1), now.AddHours(-1 - (23 * i)), "alberto")),
.. sequences.Take(1).Select(s => new TrashEntry(archiveId, s.Id.ToString("N"), s.Id, s.Title ?? s.Folder, s.Folder, 1_200, 1_206,
31_457_280L * 1_200, now.AddHours(-1), "alberto")),
.. sequences.Skip(1).Take(1).Select(s => new TrashEntry(archiveId, FrameTrash.EntryPrefix + s.Id.ToString("N") + "-20260927180400", s.Id,
s.Title ?? s.Folder, s.Folder, 24, 24, 31_457_280L * 24, now.AddHours(-24), "alberto", TrashKind.Photos)),
];
}
+119 -12
View File
@@ -1,3 +1,4 @@
using System.Globalization;
using System.IO;
using System.Windows.Input;
using Chronos.App.Infrastructure;
@@ -6,18 +7,24 @@ using Chronos.Core.Diagnostics;
using Chronos.Core.Localization;
using Chronos.Data;
using Chronos.Data.Archiving;
using Chronos.Data.Archiving.Jobs;
using Chronos.Data.Jobs;
using Chronos.Ui.Mvvm;
namespace Chronos.App.Archiving;
/// <summary>One deleted sequence in the trash: what it was, when it went, and Restore.</summary>
/// <summary>One entry of the trash: a deleted sequence or photos deleted from one, when it went, and Restore.</summary>
public sealed class TrashRowViewModel(TrashEntry entry, ICommand restore)
{
public TrashEntry Entry { get; } = entry;
public string Title => Entry.Title;
/// <summary>"3,600 photos · 96.2 GB · 2026/2026-09-28 Canon EOS R5" (the folder left to right in every language).</summary>
public string Detail => string.Join(Loc.Separator, Loc.Plural("Shell.Status.Photos", Entry.Frames), Formatting.Bytes(Entry.Bytes), Formatting.LeftToRight(Entry.Folder));
/// <summary>"Photos", "Sequence": what the entry holds.</summary>
public string KindText => TrashEmptyPlans.KindText(Entry.Kind);
/// <summary>"Photos · 12 photos · 340 MB · 2026/2026-09-28 Canon EOS R5" (the folder left to right in every language).</summary>
public string Detail => string.Join(Loc.Separator, KindText, Loc.Plural("Shell.Status.Photos", Entry.Frames), Formatting.Bytes(Entry.Bytes),
Formatting.LeftToRight(Entry.Folder));
/// <summary>"Deleted 02/10/2026 18:04".</summary>
public string DeletedText => Loc.L("Archive.Trash.Deleted", Formatting.Date(Entry.DeletedAt) + " " + Formatting.TimeOfDay(Entry.DeletedAt));
@@ -25,23 +32,71 @@ public sealed class TrashRowViewModel(TrashEntry entry, ICommand restore)
public ICommand RestoreCommand { get; } = restore;
}
/// <summary>The words of an emptying of the trash (<see cref="TrashEmptyPlan"/>): the destructive, typed confirmation.</summary>
public static class TrashEmptyPlans
{
/// <summary>"Photos", "Sequence", "Replaced".</summary>
public static string KindText(TrashKind kind) => Loc.L("Archive.Trash.Kind." + kind);
/// <summary>The confirmation of erasing the planned entries for good; null when the plan holds none.</summary>
public static ConfirmRequest? Request(TrashEmptyPlan plan)
{
ArgumentNullException.ThrowIfNull(plan);
if (plan.Entries.Count == 0) return null;
var count = plan.Entries.Count.ToString(CultureInfo.InvariantCulture);
var lines = plan.Entries.Take(DeletePlans.ListedLines).Select(e => Loc.L("Archive.Delete.Line", e.Title,
KindText(e.Kind) + Loc.Separator + Loc.Plural("Shell.Status.Photos", e.Frames), Formatting.Bytes(e.Bytes))).ToList();
if (plan.Entries.Count > DeletePlans.ListedLines) lines.Add(Loc.Plural("Archive.Delete.More", plan.Entries.Count - DeletePlans.ListedLines));
return new ConfirmRequest
{
Heading = Loc.Plural("Archive.Trash.EmptyHeading", plan.Entries.Count),
Message = Loc.L("Archive.Trash.EmptyMessage", Loc.Plural("Shell.Status.Photos", plan.Photos), Loc.Plural("Archive.Delete.Files", plan.Files),
Formatting.Bytes(plan.Bytes)),
Detail = string.Join(Environment.NewLine, lines),
IsDetailMonospaced = false,
DetailToolTip = Loc.L("Tooltips.Archive.TrashEmptyPlan"),
SafeText = Loc.L("Archive.Delete.Keep"),
SafeToolTip = Loc.L("Tooltips.Archive.DeleteKeep"),
ActionText = Loc.L("Archive.Trash.Erase"),
ActionToolTip = Loc.Plural("Tooltips.Archive.TrashErase", plan.Entries.Count),
IsDestructive = true,
TypedConfirmation = count,
TypedPrompt = Loc.L("Archive.Delete.Type", count),
};
}
}
/// <summary>
/// The archive's trash (BRIEF §0.2 rule 8): every sequence deleted from the Library or the Archive manager, newest
/// first, each restorable into its folder (or a free one next to it) with its ids, settings and renders.
/// The archive's trash (BRIEF §0.2 rule 8, §12.5): every sequence deleted from the Library or the Archive manager and the
/// photos deleted from sequences (owner review 2, R6), newest first, each restorable — a sequence into its folder (or a
/// free one next to it) with its ids, settings and renders, photos into their sequence after their files are re-hashed.
/// Empty… erases the entries for good: a dry run, a typed confirmation, then the <c>EmptyTrash</c> job, which refuses when
/// the trash changed since.
/// </summary>
public sealed class TrashDialogViewModel : ArchiveDialogViewModel
{
private readonly ArchiveService _archives;
private readonly Core.Model.Archive _archive;
private readonly Func<Task> _restored;
private readonly Func<ConfirmRequest, bool>? _confirm;
private readonly Func<ArchiveJobRequest, Task>? _enqueue;
private readonly JobEngine? _followUps;
private IReadOnlyList<TrashRowViewModel> _rows = [];
public TrashDialogViewModel(ArchiveService archives, Core.Model.Archive archive, Func<Task> restored, Action<ArchiveDialogViewModel> close)
/// <param name="confirm">Asks the typed confirmation of an emptying (null: the trash cannot be emptied here).</param>
/// <param name="enqueue">Queues the emptying job and says so (null: the trash cannot be emptied here).</param>
/// <param name="followUps">The engine that takes the analyses and images restored photos need again.</param>
public TrashDialogViewModel(ArchiveService archives, Core.Model.Archive archive, Func<Task> restored, Action<ArchiveDialogViewModel> close,
Func<ConfirmRequest, bool>? confirm = null, Func<ArchiveJobRequest, Task>? enqueue = null, JobEngine? followUps = null)
: base(close)
{
_archives = archives;
_archive = archive;
_restored = restored;
_confirm = confirm;
_enqueue = enqueue;
_followUps = followUps;
EmptyCommand = new AsyncRelayCommand(EmptyAsync, () => CanEmpty);
}
public string Heading => Loc.L("Archive.Trash.Heading", _archive.Name);
@@ -55,6 +110,8 @@ public sealed class TrashDialogViewModel : ArchiveDialogViewModel
OnPropertyChanged(nameof(IsEmpty));
OnPropertyChanged(nameof(HasRows));
OnPropertyChanged(nameof(SummaryText));
OnPropertyChanged(nameof(EmptyToolTip));
CommandManager.InvalidateRequerySuggested();
}
}
@@ -63,9 +120,17 @@ public sealed class TrashDialogViewModel : ArchiveDialogViewModel
/// <summary>The list shows; an empty trash is its summary sentence alone.</summary>
public bool HasRows => _rows.Count > 0;
/// <summary>"3 sequences · 182 GB", or "The trash is empty".</summary>
/// <summary>"3 entries · 182 GB", or "The trash is empty".</summary>
public string SummaryText => _rows.Count == 0 ? Loc.L("Archive.Trash.Empty")
: Loc.Plural("Shell.Status.Sequences", _rows.Count) + Loc.Separator + Formatting.Bytes(_rows.Sum(r => r.Entry.Bytes));
: Loc.Plural("Archive.Trash.Entries", _rows.Count) + Loc.Separator + Formatting.Bytes(_rows.Sum(r => r.Entry.Bytes));
/// <summary>Empty…: the dry run, the typed confirmation, then the job.</summary>
public ICommand EmptyCommand { get; }
/// <summary>Emptying is offered here, and there is something to erase.</summary>
public bool CanEmpty => !IsBusy && HasRows && _confirm is not null && _enqueue is not null;
public string EmptyToolTip => HasRows ? Loc.L("Tooltips.Archive.TrashEmpty") : Loc.L("Archive.Trash.Empty");
/// <summary>Reads the trash of the archive (off the UI thread).</summary>
public async Task LoadAsync()
@@ -75,7 +140,7 @@ public sealed class TrashDialogViewModel : ArchiveDialogViewModel
try
{
var entries = await Task.Run(() => _archives.ListTrashAsync(_archive.Id));
Rows = [.. entries.Select(e => new TrashRowViewModel(e, new AsyncRelayCommand(() => RestoreAsync(e), () => !IsBusy)))];
Rows = [.. entries.Select(Row)];
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or DatabaseException or ArgumentException)
{
@@ -92,6 +157,8 @@ public sealed class TrashDialogViewModel : ArchiveDialogViewModel
public void Show(IReadOnlyList<TrashEntry> entries) =>
Rows = [.. entries.Select(e => new TrashRowViewModel(e, new AsyncRelayCommand(() => Task.CompletedTask)))];
private TrashRowViewModel Row(TrashEntry entry) => new(entry, new AsyncRelayCommand(() => RestoreAsync(entry), () => !IsBusy));
private async Task RestoreAsync(TrashEntry entry)
{
ClearError();
@@ -99,10 +166,19 @@ public sealed class TrashDialogViewModel : ArchiveDialogViewModel
BusyText = Loc.L("Archive.Trash.Restoring", entry.Title);
try
{
await Task.Run(() => _archives.RestoreAsync(entry.ArchiveId, entry.Name));
Log.Info("archive", $"{entry.Title} restored from the trash");
Rows = [.. _rows.Where(r => r.Entry != entry)];
var result = await Task.Run(() => _archives.RestoreEntryAsync(entry.ArchiveId, entry.Name, _followUps));
Log.Info("archive", $"{entry.Title} restored from the trash ({entry.Kind}, {result.Photos} photo(s), {result.Kept.Count} kept)");
BusyText = null;
if (result.Kept.Count > 0)
{
// Files that no longer match their record stay in the trash: the entry stays, with what is left.
await LoadAsync();
ShowError(new InvalidDataException(Loc.Plural("Archive.Trash.KeptFiles", result.Kept.Count)));
}
else
{
Rows = [.. _rows.Where(r => r.Entry != entry)];
}
await _restored();
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or InvalidDataException or SequenceInLibraryException or NewerFormatException
@@ -117,4 +193,35 @@ public sealed class TrashDialogViewModel : ArchiveDialogViewModel
BusyText = null;
}
}
/// <summary>
/// Empty…: measures every entry (the dry run), asks to type how many entries go, and queues the job that erases exactly
/// those; the dialog closes, and the job says how it ended.
/// </summary>
private async Task EmptyAsync()
{
if (_confirm is null || _enqueue is null) return;
ClearError();
IsBusy = true;
BusyText = Loc.L("Archive.Trash.Checking");
TrashEmptyPlan plan;
try
{
plan = await Task.Run(() => _archives.PlanEmptyTrashAsync(_archive.Id));
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or DatabaseException or ArgumentException)
{
Log.Warning("archive", "The dry run of emptying the trash failed", ex);
ShowError(ex);
return;
}
finally
{
IsBusy = false;
BusyText = null;
}
if (TrashEmptyPlans.Request(plan) is not { } request || !_confirm(request)) return;
await _enqueue(ArchiveJobs.EmptyTrash(_archive, plan));
Close();
}
}
+1 -1
View File
@@ -40,7 +40,7 @@ public static class JobNotices
private static bool Announces(JobKind kind) =>
kind is JobKind.Render or JobKind.DeepAnalyse or JobKind.Verify or JobKind.Rebuild or JobKind.Maintenance or JobKind.UploadCommit
or JobKind.Move or JobKind.Adopt;
or JobKind.Move or JobKind.Adopt or JobKind.EmptyTrash;
/// <summary>
/// Work that keeps the index and its previews current: the next run repeats it, the Archive screen shows what is missing.
+6 -1
View File
@@ -782,11 +782,16 @@ public sealed class ArchiveViewModel : SectionViewModel
public async Task OpenTrashAsync()
{
if (Services.Archives is not { } archives || _archive is not { } archive) return;
var engine = Services.Engine;
var dialog = new TrashDialogViewModel(archives, archive, async () =>
{
await LoadAsync();
await Shell.Library.RefreshAsync();
}, CloseDialog);
}, CloseDialog, Services.Dialogs.Confirm, engine is null ? null : async request =>
{
await engine.EnqueueAsync(request);
Queued(request.Kind, archive.Name);
}, engine);
OpenDialog(dialog);
await dialog.LoadAsync();
}
@@ -1130,7 +1130,7 @@ public sealed class SettingsViewModel : SectionViewModel
[
JobKind.Render, JobKind.Import, JobKind.Download, JobKind.UploadCommit, JobKind.Scan, JobKind.Rebuild, JobKind.Verify, JobKind.LightAnalyse,
JobKind.DeepAnalyse, JobKind.Thumbs, JobKind.Proxies, JobKind.Maintenance, JobKind.Duplicates, JobKind.Orphans, JobKind.Adopt, JobKind.Move,
JobKind.Backup, JobKind.Cleanup,
JobKind.Backup, JobKind.Cleanup, JobKind.EmptyTrash,
];
/// <summary>Stores <paramref name="level"/> for <paramref name="kind"/>, keeping only the levels that differ from the defaults.</summary>
@@ -14,6 +14,7 @@ namespace Chronos.Core.Archiving;
[JsonSerializable(typeof(SequenceManifest))]
[JsonSerializable(typeof(LeaseRecord))]
[JsonSerializable(typeof(IngestJournal))]
[JsonSerializable(typeof(FrameRemovalJournal))]
[JsonSerializable(typeof(RenameJournal))]
internal sealed partial class ArchiveJson : JsonSerializerContext;
@@ -30,6 +30,9 @@ public static class ArchiveLayout
/// <summary>Moves of an ingest batch that were started but not yet recorded in <see cref="SequenceManifestFile"/>.</summary>
public const string IngestJournalFile = "ingest.pending.json";
/// <summary>Moves of a photo deletion into the trash that were started but not yet recorded in <see cref="SequenceManifestFile"/>.</summary>
public const string RemovalJournalFile = "remove.pending.json";
/// <summary>Folder names inside a sequence folder that never hold a sequence of their own.</summary>
public static bool IsReservedFolder(string name) =>
name.Equals(MetaFolder, StringComparison.OrdinalIgnoreCase)
@@ -74,11 +77,15 @@ public sealed class SequencePaths
internal SequencePaths(ArchivePaths archive, string relativeFolder)
{
ArgumentNullException.ThrowIfNull(relativeFolder);
Archive = archive;
RelativeFolder = relativeFolder.Replace('\\', '/').Trim('/');
Folder = archive.FromRelative(RelativeFolder);
MetaDirectory = Path.Combine(Folder, ArchiveLayout.MetaFolder);
}
/// <summary>The archive the sequence belongs to.</summary>
public ArchivePaths Archive { get; }
/// <summary>Folder relative to the archive root, forward slashes; empty when the root itself holds the photos (adopted folder).</summary>
public string RelativeFolder { get; }
@@ -92,6 +99,7 @@ public sealed class SequencePaths
public string ProjectPath => Path.Combine(MetaDirectory, ArchiveLayout.ProjectFile);
public string ThumbsPackPath => Path.Combine(MetaDirectory, ArchiveLayout.ThumbsPackFile);
public string IngestJournalPath => Path.Combine(MetaDirectory, ArchiveLayout.IngestJournalFile);
public string RemovalJournalPath => Path.Combine(MetaDirectory, ArchiveLayout.RemovalJournalFile);
public string Proxy(int index) => Path.Combine(Proxies, ArchiveLayout.ProxyFileName(index));
@@ -0,0 +1,94 @@
using System.Text.Json;
using Chronos.Core.Diagnostics;
using Chronos.Core.IO;
namespace Chronos.Core.Archiving;
/// <summary>One file of a photo deletion: where it was in the sequence folder and where it went in the archive's trash.</summary>
/// <param name="From">Path relative to the sequence folder (forward slashes).</param>
/// <param name="To">Path relative to the archive root (forward slashes), inside the trash entry.</param>
public sealed record FrameRemovalMove(string From, string To);
/// <summary>
/// Write-ahead record of a photo deletion (<c>.chronos/remove.pending.json</c>, owner review 2, R6): the trash entry the
/// photos move into, the frames leaving the sidecar and every file move. Written before the first move and removed once
/// <c>sequence.json</c> no longer lists the frames, so a crash in between is undone by <see cref="Recover"/>: the files go
/// back to their places, the entry's record and folder go, and the sequence is as it was.
/// </summary>
/// <param name="Record">The entry's record, relative to the archive root.</param>
/// <param name="Folder">The entry's folder, relative to the archive root.</param>
public sealed record FrameRemovalJournal(string Record, string Folder, IReadOnlyList<Guid> Frames, IReadOnlyList<FrameRemovalMove> Moves)
{
public static void Write(SequencePaths sequence, FrameRemovalJournal journal)
{
ArgumentNullException.ThrowIfNull(sequence);
Directory.CreateDirectory(sequence.MetaDirectory);
AtomicFile.WriteAllBytes(sequence.RemovalJournalPath, JsonSerializer.SerializeToUtf8Bytes(journal, ArchiveJson.Default.FrameRemovalJournal));
}
public static void Delete(SequencePaths sequence)
{
ArgumentNullException.ThrowIfNull(sequence);
if (File.Exists(sequence.RemovalJournalPath)) File.Delete(sequence.RemovalJournalPath);
}
/// <summary>
/// Undoes a deletion a crash interrupted before its sidecar was written: while <paramref name="manifest"/> still lists a
/// frame of the journal, each file that reached the trash moves back (one whose place is taken again stays in the trash,
/// logged, and so does the entry then), and the entry's record and its emptied folder go. A deletion whose sidecar was
/// written is complete: only the journal goes. Returns whether a deletion was undone. The caller holds the lease.
/// </summary>
public static bool Recover(SequencePaths sequence, SequenceManifest manifest)
{
ArgumentNullException.ThrowIfNull(sequence);
ArgumentNullException.ThrowIfNull(manifest);
if (!File.Exists(sequence.RemovalJournalPath)) return false;
FrameRemovalJournal? journal;
try
{
journal = JsonSerializer.Deserialize(AtomicFile.ReadAllBytes(sequence.RemovalJournalPath), ArchiveJson.Default.FrameRemovalJournal);
}
catch (JsonException)
{
journal = null; // torn while being written: nothing was moved yet
}
var undone = false;
if (journal is not null && manifest.Frames.Any(f => journal.Frames.Contains(f.Id)))
{
var archive = sequence.Archive;
var kept = 0;
foreach (var move in journal.Moves)
{
var trashed = archive.FromRelative(move.To);
var place = sequence.File(move.From);
if (!File.Exists(trashed)) continue;
if (File.Exists(place))
{
kept++;
Log.Warning("archive", $"{sequence.ArchiveRelative(move.From)} is there again; its deleted copy stays in {move.To}");
continue;
}
Directory.CreateDirectory(Path.GetDirectoryName(place)!);
File.Move(trashed, place, overwrite: false);
}
if (kept == 0)
{
var record = archive.FromRelative(journal.Record);
if (File.Exists(record)) File.Delete(record);
RemoveEmpty(archive.FromRelative(journal.Folder));
}
Log.Warning("archive", $"An interrupted photo deletion in {sequence.RelativeFolder} was undone");
undone = true;
}
Delete(sequence);
return undone;
}
/// <summary>Removes <paramref name="folder"/> and its subfolders when they hold no file.</summary>
public static void RemoveEmpty(string folder)
{
if (!Directory.Exists(folder)) return;
foreach (var child in Directory.EnumerateDirectories(folder)) RemoveEmpty(child);
if (!Directory.EnumerateFileSystemEntries(folder).Any()) Directory.Delete(folder);
}
}
@@ -42,6 +42,13 @@ public sealed record SequenceManifest
/// <summary>Session keys of automatic grouping (uploads, card imports) that resolve to this sequence.</summary>
public IReadOnlyList<string> SessionKeys { get; init; } = [];
/// <summary>
/// Tombstones of the photos removed from the sequence (owner review 2, R6), by SHA-256; null when there are none, so a
/// sidecar without removals is written as before. A build that does not know the field keeps it in its
/// <see cref="Extra"/> and writes it back unchanged.
/// </summary>
public IReadOnlyList<RemovedPhoto>? Removed { get; init; }
[JsonExtensionData]
public Dictionary<string, JsonElement>? Extra { get; set; }
}
@@ -127,6 +134,53 @@ public sealed record SidecarFrame
/// <summary><see cref="FrameFlags"/> bits, stored as a number so bits of newer builds survive.</summary>
public FrameFlags Flags { get; init; }
/// <summary>
/// The file this frame was converted from (reserved for the conversion of owner review 2, R7); null for an original.
/// Read and written only: nothing acts on it yet.
/// </summary>
public FrameSource? Source { get; init; }
[JsonExtensionData]
public Dictionary<string, JsonElement>? Extra { get; set; }
}
/// <summary>
/// The tombstone of a photo removed from a sequence (owner review 2, R6): sync never offers that content back to the
/// sequence, and an upload of it is answered as already there. <see cref="Replacement"/> names the converted file that took
/// its place (<see cref="RemovalReason.Replaced"/>), which sync then counts as the same photo.
/// </summary>
public sealed record RemovedPhoto
{
/// <summary>Lower-case hex SHA-256 of the removed photo.</summary>
public required string Sha256 { get; init; }
/// <summary>Lower-case hex SHA-256 of the file that replaced it; null for a photo deleted outright.</summary>
public string? Replacement { get; init; }
[JsonConverter(typeof(TolerantEnumConverter<RemovalReason>))]
public RemovalReason Reason { get; init; }
/// <summary>When it was removed (UTC).</summary>
public DateTimeOffset At { get; init; }
[JsonExtensionData]
public Dictionary<string, JsonElement>? Extra { get; set; }
}
/// <summary>The original a converted frame was made from (reserved for owner review 2, R7): its content, format, file and size.</summary>
public sealed record FrameSource
{
/// <summary>Lower-case hex SHA-256 of the source file.</summary>
public string? Sha256 { get; init; }
[JsonConverter(typeof(TolerantEnumConverter<ImageFileFormat>))]
public ImageFileFormat Format { get; init; }
/// <summary>The source's path relative to the sequence folder (forward slashes) when it was converted.</summary>
public string? File { get; init; }
public long Size { get; init; }
[JsonExtensionData]
public Dictionary<string, JsonElement>? Extra { get; set; }
}
+7
View File
@@ -17,6 +17,13 @@ public sealed record Archive
public int ProxyLongEdge { get; init; } = 1920;
}
/// <summary>
/// The tombstone of a photo removed from a sequence (owner review 2, R6): its SHA-256, the replacement's when it was
/// replaced by a converted file, why and when. Kept in the sidecar (<c>removed</c>) and the index (<c>frame_removals</c>), so
/// sync never offers the photo back and an upload of that content into the sequence is answered as already there.
/// </summary>
public sealed record FrameRemoval(Guid SequenceId, string Sha256, string? ReplacementSha256, RemovalReason Reason, DateTimeOffset RemovedAt);
/// <summary>One shoot: a folder of frames that becomes one project (BRIEF §5).</summary>
public sealed record Sequence
{
+16
View File
@@ -87,6 +87,22 @@ public enum JobKind
/// <summary>Housekeeping steps: job history, audit log, trash report and the host's own (owner review 2, R10); stored as 17.</summary>
Cleanup = 17,
/// <summary>
/// Erases exactly the trash entries of a confirmed plan, refused when the trash changed since (owner review 2, R6); stored
/// as 18.
/// </summary>
EmptyTrash = 18,
}
/// <summary>Why a photo left a sequence (its tombstone, owner review 2, R6); stored as a number.</summary>
public enum RemovalReason
{
/// <summary>Deleted by a user into the archive's trash.</summary>
Deleted = 0,
/// <summary>Replaced by a converted file (a later phase): the tombstone names the replacement's SHA-256.</summary>
Replaced = 1,
}
public enum JobState
@@ -152,8 +152,11 @@ public sealed class ArchiveIndexer
if (positions is not null) existing = positions.ApplyTo(existing);
}
var row = SequenceMapping.ToSequence(manifest, archive.Id, sequence, existing);
// A hero frame the sidecar no longer lists (a photo deleted) names nothing: the project's hero waits for its photo.
if (row.HeroFrameId is { } hero && !manifest.Frames.Any(f => f.Id == hero)) row = row with { HeroFrameId = null };
await tx.Sequences.UpsertAsync(row with { Status = row.Status & ~clear }, cancellationToken).ConfigureAwait(false);
await tx.Frames.SyncSequenceAsync(manifest.Id, SequenceMapping.ToFrames(manifest, sequence), cancellationToken).ConfigureAwait(false);
await tx.FrameRemovals.SyncSequenceAsync(manifest.Id, SequenceMapping.ToRemovals(manifest), cancellationToken).ConfigureAwait(false);
foreach (var key in manifest.SessionKeys)
await tx.Sequences.MapSessionKeyAsync(archive.Id, key, manifest.Id, cancellationToken).ConfigureAwait(false);
await tx.CommitAsync(cancellationToken).ConfigureAwait(false);
+21 -1
View File
@@ -358,13 +358,17 @@ public sealed class ArchiveIngest : IArchiveIngest
updated = SequenceFrames.Update(updated, repaired.ToDictionary(id => id,
_ => (Func<SidecarFrame, SidecarFrame>)(f => f with { Flags = f.Flags & ~(FrameFlags.Missing | FrameFlags.Corrupt) })));
}
// A photo deleted from the sequence and filed into it again (a card imported again, a sync download) is back: its
// tombstone goes, so sync offers it like any other.
var back = Readded(updated, moved);
if (back) updated = updated with { Removed = Remaining(updated.Removed!, moved) };
if (moved.Count > 0 || repaired.Count > 0) ManifestStore.WriteSequence(sequence.ManifestPath, updated);
IngestJournal.Delete(sequence);
var byId = updated.Frames.ToDictionary(f => f.Id);
if (moved.Count > 0 || repaired.Count > 0)
{
await IndexAsync(archive, sequence, updated, inStep, photosChanged, before, moved.ConvertAll(m => byId[m.Id]), repaired.Count > 0,
await IndexAsync(archive, sequence, updated, inStep, photosChanged, before, moved.ConvertAll(m => byId[m.Id]), repaired.Count > 0 || back,
cancellationToken).ConfigureAwait(false);
}
foreach (var (p, frame) in accepted.Where(a => byId.ContainsKey(a.Frame.Id)))
@@ -382,6 +386,22 @@ public sealed class ArchiveIngest : IArchiveIngest
}
}
/// <summary>Whether a frame filed by the batch holds content the sequence's tombstones name.</summary>
private static bool Readded(SequenceManifest manifest, List<SidecarFrame> moved)
{
if (manifest.Removed is not { Count: > 0 } removed || moved.Count == 0) return false;
var tombstoned = removed.Select(r => r.Sha256).ToHashSet(StringComparer.OrdinalIgnoreCase);
return moved.Any(f => f.Sha256 is { } sha && tombstoned.Contains(sha));
}
/// <summary>The tombstones without those of the content filed again; null when none is left.</summary>
private static IReadOnlyList<RemovedPhoto>? Remaining(IReadOnlyList<RemovedPhoto> removed, List<SidecarFrame> moved)
{
var filed = moved.Where(f => f.Sha256 is not null).Select(f => f.Sha256!).ToHashSet(StringComparer.OrdinalIgnoreCase);
var left = removed.Where(r => !filed.Contains(r.Sha256)).ToList();
return left.Count == 0 ? null : left;
}
/// <summary>Final file names, in capture order: the plan's name or the template with <c>{n}</c> = index + 1, made unique.</summary>
private static Dictionary<Guid, SidecarFrame> Name(Archive archive, SequencePaths sequence, SequenceManifest manifest,
List<(Pending Pending, SidecarFrame Frame)> accepted)
+50 -4
View File
@@ -40,6 +40,7 @@ public sealed class ArchiveService : IJobHandlerProvider
Images = new ArchiveImages(db, _writer, Indexer);
Imports = new ImportService(db, Ingest);
Trash = new SequenceTrash(db, _writer, Indexer);
FrameTrash = new FrameTrash(db, _writer, Indexer, Ingest, Trash);
var shared = Housekeeping.CleanupSteps.Shared(Trash);
CleanupSteps = [.. shared, .. _writer.Options.CleanupSteps.Where(s => !shared.Any(o => o.Name == s.Name))];
}
@@ -55,9 +56,12 @@ public sealed class ArchiveService : IJobHandlerProvider
public ArchiveImages Images { get; }
public ImportService Imports { get; }
/// <summary>Deletes sequences into the archive's trash and restores them.</summary>
/// <summary>Deletes sequences into the archive's trash and restores them; lists and empties the trash.</summary>
public SequenceTrash Trash { get; }
/// <summary>Deletes photos of a sequence into the archive's trash and restores them (owner review 2, R6).</summary>
public FrameTrash FrameTrash { get; }
/// <summary>
/// The steps this host's <see cref="JobKind.Cleanup"/> jobs can run: the shared ones (<see cref="Housekeeping.CleanupSteps.Shared"/>),
/// then the host's (<see cref="ArchiveServiceOptions.CleanupSteps"/>). A schedule host lists their names.
@@ -69,7 +73,8 @@ public sealed class ArchiveService : IJobHandlerProvider
/// <summary>
/// Handlers for scan, rebuild, verify, import, thumbs, proxies and maintenance jobs, the read-only duplicates and orphans
/// reports, index backups and clean-ups (owner review 2, R10); register them on the <see cref="JobEngine"/>.
/// reports, index backups and clean-ups (owner review 2, R10) and the emptying of the trash (R6); register them on the
/// <see cref="JobEngine"/>.
/// </summary>
public IReadOnlyList<IJobHandler> CreateJobHandlers() =>
[
@@ -84,6 +89,7 @@ public sealed class ArchiveService : IJobHandlerProvider
new OrphansJobHandler(_db, Maintenance),
new Housekeeping.BackupJobHandler(_db, _writer.Options.BackupDirectory),
new Housekeeping.CleanupJobHandler(_db, CleanupSteps, TimeProvider.System),
new EmptyTrashJobHandler(_db, Trash),
];
/// <summary>Makes <paramref name="root"/> a new, empty archive and indexes it.</summary>
@@ -362,9 +368,30 @@ public sealed class ArchiveService : IJobHandlerProvider
public async Task<IReadOnlyList<TrashEntry>> ListTrashAsync(Guid archiveId, CancellationToken cancellationToken = default) =>
await Trash.ListAsync(await LoadArchiveAsync(archiveId, cancellationToken).ConfigureAwait(false), cancellationToken).ConfigureAwait(false);
/// <summary>Moves a sequence back from the trash and indexes it again.</summary>
/// <summary>Moves a sequence back from the trash and indexes it again (an entry of deleted photos: see <see cref="RestoreEntryAsync"/>).</summary>
public async Task<Sequence> RestoreAsync(Guid archiveId, string entryName, CancellationToken cancellationToken = default) =>
await Trash.RestoreAsync(await LoadArchiveAsync(archiveId, cancellationToken).ConfigureAwait(false), entryName, cancellationToken).ConfigureAwait(false);
(await RestoreEntryAsync(archiveId, entryName, null, cancellationToken).ConfigureAwait(false)).Sequence;
/// <summary>
/// Brings a trash entry back: a sequence into its folder (<see cref="SequenceTrash.RestoreAsync"/>), or photos into
/// their sequence (<see cref="Archiving.FrameTrash.RestoreAsync"/>, which queues on <paramref name="followUps"/> what the
/// frames need again).
/// </summary>
/// <exception cref="DirectoryNotFoundException">The entry is not in the trash.</exception>
/// <exception cref="SequenceInLibraryException">A sequence entry whose sequence is in the index already.</exception>
public async Task<TrashRestoreResult> RestoreEntryAsync(Guid archiveId, string entryName, JobEngine? followUps = null,
CancellationToken cancellationToken = default)
{
var archive = await LoadArchiveAsync(archiveId, cancellationToken).ConfigureAwait(false);
if (!Archiving.FrameTrash.IsPhotoEntry(entryName))
return new TrashRestoreResult(TrashKind.Sequence, await Trash.RestoreAsync(archive, entryName, cancellationToken).ConfigureAwait(false), 0, [], false);
var photos = await FrameTrash.RestoreAsync(archive, entryName, followUps, cancellationToken).ConfigureAwait(false);
return new TrashRestoreResult(TrashKind.Photos, photos.Sequence, photos.Restored, photos.Kept, photos.NewSequence);
}
/// <summary>The dry run of emptying an archive's trash: <paramref name="names"/> of the entries (null: all), measured, with the plan's fingerprint.</summary>
public async Task<TrashEmptyPlan> PlanEmptyTrashAsync(Guid archiveId, IReadOnlyList<string>? names = null, CancellationToken cancellationToken = default) =>
await Trash.PlanEmptyAsync(await LoadArchiveAsync(archiveId, cancellationToken).ConfigureAwait(false), names, cancellationToken).ConfigureAwait(false);
/// <summary>Plans a card or folder import into an archive (nothing is copied).</summary>
public async Task<ImportPlan> PlanImportAsync(Guid archiveId, string sourceRoot, ImportOptions options, Guid? cardId = null, IProgress<int>? progress = null,
@@ -440,6 +467,12 @@ public sealed class ArchiveService : IJobHandlerProvider
private static ArgumentException Unknown(Guid sequenceId) => new($"Unknown sequence {sequenceId}.", nameof(sequenceId));
}
/// <summary>
/// What a restore from the trash did: the kind of entry, the sequence restored (or the one the photos went back into),
/// and for photos how many came back, the files kept in the trash and whether they went into a new sequence.
/// </summary>
public sealed record TrashRestoreResult(TrashKind Kind, Sequence Sequence, int Photos, IReadOnlyList<string> Kept, bool NewSequence);
/// <summary>The fields of a sequence the user describes it with (sidecar and index).</summary>
public sealed record SequenceInfo(string? Title, IReadOnlyList<string> Tags, int Rating, string? Notes);
@@ -518,6 +551,19 @@ public static class ArchiveJobs
new(JobKind.Cleanup, archive is null ? [] : [archive.Id], archive?.Name,
Json(new CleanupParameters(steps, olderThanDays), ArchiveJobJson.Default.CleanupParameters), JobPriority.Normal);
/// <summary>
/// <see cref="JobKind.EmptyTrash"/>: erases exactly the entries of a confirmed <paramref name="plan"/>, refused when the
/// trash no longer matches its fingerprint (owner review 2, R6).
/// </summary>
public static ArchiveJobRequest EmptyTrash(Archive archive, TrashEmptyPlan plan)
{
ArgumentNullException.ThrowIfNull(archive);
ArgumentNullException.ThrowIfNull(plan);
var items = plan.Entries.OrderBy(e => e.Name, StringComparer.Ordinal).Select(e => new EmptyTrashItem(e.Name, SequenceTrash.EntryFingerprint(e))).ToList();
return new(JobKind.EmptyTrash, [archive.Id], archive.Name, Json(new EmptyTrashParameters(items, plan.Fingerprint), ArchiveJobJson.Default.EmptyTrashParameters),
JobPriority.User);
}
public static Task<Job> EnqueueAsync(this JobEngine engine, ArchiveJobRequest request, Guid? createdBy = null, CancellationToken cancellationToken = default) =>
engine.EnqueueAsync(request.Kind, request.Targets, request.Label, request.ParametersJson, request.Priority, createdBy, cancellationToken);
+686
View File
@@ -0,0 +1,686 @@
using System.Globalization;
using System.Text.Json;
using Chronos.Core.Archiving;
using Chronos.Core.Diagnostics;
using Chronos.Core.IO;
using Chronos.Core.Metadata;
using Chronos.Core.Model;
using Chronos.Data.Archiving.Jobs;
using Chronos.Data.Jobs;
using ProcessingJobs = Chronos.Data.Processing.ProcessingJobs;
using ProcessingFrames = Chronos.Data.Processing.SequenceFrames;
using SequenceFrames = Chronos.Core.Archiving.SequenceFrames;
namespace Chronos.Data.Archiving;
/// <summary>Why photos cannot leave their sequence; nothing is touched.</summary>
public enum FrameDeleteBlock
{
/// <summary>The archive is offline or read-only.</summary>
Offline,
/// <summary>A running or paused job works on the sequence or its whole archive (<see cref="SequenceTrash"/>'s rule).</summary>
Busy,
/// <summary>The sequence's frames changed since the caller read them (another version, or a frame named is gone).</summary>
FramesChanged,
/// <summary>Every frame of the sequence would go: delete the sequence instead, which keeps its settings and renders.</summary>
WouldEmpty,
}
/// <summary>The dry run of deleting photos of one sequence into the archive's trash (owner review 2, R6).</summary>
/// <param name="Frames">The frames that go, in index order.</param>
/// <param name="Bytes">Their originals' size.</param>
/// <param name="Blocked">Why they cannot go; empty when they can.</param>
public sealed record FrameDeletePlan(Sequence Sequence, IReadOnlyList<Frame> Frames, long Bytes, IReadOnlyList<FrameDeleteBlock> Blocked)
{
public bool CanDelete => Blocked.Count == 0 && Frames.Count > 0;
}
/// <summary>What a photo deletion did: the trash entry made and the sequence as it is now.</summary>
public sealed record FrameDeleteResult(TrashEntry Entry, Sequence Sequence);
/// <summary>
/// What a restore of photos did: the sequence they went back into (a new one when theirs is gone), how many came back, and
/// the files kept in the trash because they no longer match their record (or their photo is in the sequence again).
/// </summary>
public sealed record PhotoRestoreResult(Sequence Sequence, int Restored, IReadOnlyList<string> Kept, bool NewSequence);
/// <summary>
/// Deleting photos of a sequence without erasing anything (owner review 2, R6; BRIEF §0.2 rule 8): <see cref="PlanDeleteAsync"/>
/// is the dry run; <see cref="DeleteAsync"/> moves each original (and its XMP companion) under the sequence's lease into
/// <c>.chronos/trash/photos/&lt;sequence&gt;-&lt;time&gt;/originals</c> next to a record of the frames, writes the sidecar
/// without them (frames version + 1) and with their tombstones, and indexes it: what covered the frames is cleared and
/// queued again, and the project's positions follow their photos (those on the photos that went wait as pending frames).
/// A journal undoes a deletion a crash interrupted. <see cref="RestoreAsync"/> re-hashes each file against its record and
/// moves the matching ones back with the same frame records, dropping their tombstones; into a new sequence through the
/// archive ingest when theirs is gone.
/// </summary>
public sealed class FrameTrash
{
/// <summary>Folder of the photo entries inside the trash.</summary>
public const string FolderName = "photos";
/// <summary>What <see cref="TrashEntry.Name"/> of a photo entry starts with (the folder name follows).</summary>
public const string EntryPrefix = "photos-";
private const string RecordExtension = ".json";
/// <summary>Statuses the frames removed or put back no longer let stand: the passes make them again.</summary>
private const SequenceStatus Uncovered = SequenceStatus.AnalyzedLight | SequenceStatus.AnalyzedDeep | SequenceStatus.ThumbsBuilt | SequenceStatus.ProxiesBuilt;
private readonly ChronosDatabase _db;
private readonly SequenceWriter _writer;
private readonly ArchiveIndexer _indexer;
private readonly ArchiveIngest _ingest;
private readonly SequenceTrash _trash;
internal FrameTrash(ChronosDatabase db, SequenceWriter writer, ArchiveIndexer indexer, ArchiveIngest ingest, SequenceTrash trash)
{
_db = db;
_writer = writer;
_indexer = indexer;
_ingest = ingest;
_trash = trash;
}
/// <summary>The folder of the photo entries of an archive's trash.</summary>
public static string Directory(ArchivePaths archive) => Path.Combine(SequenceTrash.TrashDirectory(archive), FolderName);
/// <summary>Whether <paramref name="name"/> names a photo entry (<see cref="EntryPrefix"/>).</summary>
public static bool IsPhotoEntry(string name) => name.StartsWith(EntryPrefix, StringComparison.Ordinal);
/// <summary>
/// The dry run: the frames of <paramref name="frameIds"/> that go and their size, or why they cannot go. With
/// <paramref name="expectedFramesVersion"/>, frames that changed since the caller read that version block the plan.
/// </summary>
/// <exception cref="ArgumentException">The sequence is not in the index, or no frame is named.</exception>
public async Task<FrameDeletePlan> PlanDeleteAsync(Guid sequenceId, IReadOnlyList<Guid> frameIds, int? expectedFramesVersion = null,
CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(frameIds);
if (frameIds.Count == 0) throw new ArgumentException("No frame is named.", nameof(frameIds));
var sequence = await _db.Sequences.GetAsync(sequenceId, cancellationToken).ConfigureAwait(false)
?? throw new ArgumentException($"Unknown sequence {sequenceId}.", nameof(sequenceId));
var archive = await _db.Archives.GetAsync(sequence.ArchiveId, cancellationToken).ConfigureAwait(false)
?? throw new ArgumentException($"Unknown archive {sequence.ArchiveId}.", nameof(sequenceId));
var all = await ProcessingFrames.ListAsync(_db, sequenceId, cancellationToken).ConfigureAwait(false);
var wanted = frameIds.ToHashSet();
var frames = all.Where(f => wanted.Contains(f.Id)).ToList();
var blocked = new List<FrameDeleteBlock>();
if (ArchiveVolume.Probe(new ArchivePaths(archive.RootPath)) != ArchiveAvailability.Online) blocked.Add(FrameDeleteBlock.Offline);
var busy = await _trash.BusyAsync(cancellationToken).ConfigureAwait(false);
if (busy.Contains(sequence.Id) || busy.Contains(sequence.ArchiveId)) blocked.Add(FrameDeleteBlock.Busy);
if (frames.Count != wanted.Count || (expectedFramesVersion is { } expected && expected != sequence.FramesVersion)) blocked.Add(FrameDeleteBlock.FramesChanged);
if (frames.Count > 0 && frames.Count == all.Count) blocked.Add(FrameDeleteBlock.WouldEmpty);
return new FrameDeletePlan(sequence, frames, frames.Sum(f => f.Size), blocked);
}
/// <summary>
/// Moves exactly the planned photos into the trash and takes them out of the sequence, then queues on
/// <paramref name="followUps"/> (null: nothing) what the frames need again: the light analysis, a background deep analysis
/// when the sequence had one, and the thumbnails and proxies the host keeps (always on a server; on a desktop those it
/// had). A kind the engine does not run, or one already queued for the sequence, is left out.
/// </summary>
/// <param name="deletedBy">Who asked (user name or client), kept in the trash record.</param>
/// <exception cref="StaleDeletePlanException">The plan is blocked, or the sequence changed since it was made; nothing moved.</exception>
/// <exception cref="ArchiveOfflineException">The archive went offline; nothing moved.</exception>
/// <exception cref="IOException">A file is open elsewhere; nothing moved.</exception>
public async Task<FrameDeleteResult> DeleteAsync(FrameDeletePlan plan, string? deletedBy = null, JobEngine? followUps = null,
CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(plan);
var id = plan.Sequence.Id;
if (!plan.CanDelete) throw new StaleDeletePlanException(id);
var revised = await PlanDeleteAsync(id, [.. plan.Frames.Select(f => f.Id)], plan.Sequence.FramesVersion, cancellationToken).ConfigureAwait(false);
var archive = await ArchiveOfAsync(revised.Sequence, cancellationToken).ConfigureAwait(false);
var paths = new ArchivePaths(archive.RootPath);
// Offline since the plan: said as such (ArchiveOfflineException), not as a stale plan.
ArchiveVolume.EnsureWritable(paths);
if (!revised.CanDelete || revised.Sequence.Folder != plan.Sequence.Folder) throw new StaleDeletePlanException(id);
var folder = paths.Sequence(revised.Sequence.Folder);
var had = revised.Sequence.Status;
TrashEntry entry;
SequenceManifest updated;
await using (await _writer.LockAsync(paths, id, cancellationToken).ConfigureAwait(false))
{
var manifest = SequenceWriter.ReadLocked(folder, id);
var plannedPaths = plan.Frames.ToDictionary(f => f.Id, f => f.RelativePath);
var planned = plannedPaths.Keys.ToHashSet();
var removed = manifest.Frames.Where(f => planned.Contains(f.Id)).ToList();
if (manifest.Versions.Frames != plan.Sequence.FramesVersion || removed.Count != planned.Count
|| removed.Any(f => plannedPaths[f.Id] != folder.ArchiveRelative(f.File)))
throw new StaleDeletePlanException(id);
var kept = manifest.Frames.Where(f => !planned.Contains(f.Id)).ToList();
if (kept.Count == 0) throw new StaleDeletePlanException(id);
var inStep = await _indexer.InStepAsync(archive, folder, manifest, cancellationToken).ConfigureAwait(false);
var photosChanged = !inStep && await _indexer.PhotosChangedAsync(archive, folder, cancellationToken).ConfigureAwait(false);
var trash = Directory(paths);
System.IO.Directory.CreateDirectory(trash);
var name = EntryName(trash, id);
var entryFolder = Path.Combine(trash, name);
var recordPath = entryFolder + RecordExtension;
var photos = await TrashedAsync(folder, removed, kept, cancellationToken).ConfigureAwait(false);
var now = DateTimeOffset.UtcNow;
var record = new PhotoTrashRecord(TrashKind.Photos, id, revised.Sequence.DisplayTitle, revised.Sequence.Folder, photos,
photos.Sum(p => p.Files.Sum(f => f.Size)), now, deletedBy);
var moves = photos.SelectMany(p => p.Files).Select(f => new FrameRemovalMove(f.From, paths.ToRelative(Path.Combine(entryFolder, f.Path)))).ToList();
cancellationToken.ThrowIfCancellationRequested();
// The journal first: a crash from here until the sidecar is written puts every file back (ReadLocked).
FrameRemovalJournal.Write(folder, new FrameRemovalJournal(paths.ToRelative(recordPath), paths.ToRelative(entryFolder), [.. planned], moves));
AtomicFile.WriteAllText(recordPath, JsonSerializer.Serialize(record, TrashJson.Default.PhotoTrashRecord));
System.IO.Directory.CreateDirectory(entryFolder);
var done = new List<FrameRemovalMove>();
try
{
foreach (var move in moves)
{
var target = paths.FromRelative(move.To);
System.IO.Directory.CreateDirectory(Path.GetDirectoryName(target)!);
File.Move(folder.File(move.From), target, overwrite: false);
done.Add(move);
}
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
// A file is open elsewhere: the ones that moved go back, and nothing changed.
Undo(paths, folder, done, recordPath, entryFolder);
throw;
}
updated = SequenceFrames.WithFrames(manifest, kept) with
{
Status = manifest.Status & ~Uncovered,
Removed = WithTombstones(manifest.Removed, removed, kept, now),
};
ManifestStore.WriteSequence(folder.ManifestPath, updated);
FrameRemovalJournal.Delete(folder);
Log.Info("archive", $"{revised.Sequence.DisplayTitle}: {removed.Count} photo(s) moved to the trash ({name}, {record.Bytes} bytes)");
// The files have moved: the index follows to the end, whatever the caller cancels meanwhile.
await _indexer.SyncAsync(archive, folder, updated, null, Uncovered, photosChanged, CancellationToken.None).ConfigureAwait(false);
ShiftProxies(folder, manifest.Frames, updated.Frames, removed);
entry = Entry(archive.Id, name, record);
}
var sequence = await _db.Sequences.GetAsync(id, CancellationToken.None).ConfigureAwait(false) ?? revised.Sequence;
await QueueAsync(followUps, archive, sequence, had, CancellationToken.None).ConfigureAwait(false);
return new FrameDeleteResult(entry, sequence);
}
/// <summary>
/// Brings the photos of a trash entry back. Each file is re-hashed against its record: a file that no longer matches
/// (or is missing) stays in the trash with its photo, which is reported, as is a photo whose content the sequence holds
/// again. The others move back to their places (a name taken since gets <c>_2</c>, <c>_3</c>…) with the same frame
/// records, inserted by capture time, and their tombstones go. When the sequence is gone (deleted, or never indexed in
/// this archive), they go into a new sequence through the archive ingest, titled and placed as theirs was. The entry
/// goes once nothing is left in it.
/// </summary>
/// <param name="name">The entry's <see cref="TrashEntry.Name"/> (<c>photos-…</c>).</param>
/// <exception cref="DirectoryNotFoundException">The entry is not in the trash.</exception>
public async Task<PhotoRestoreResult> RestoreAsync(Archive archive, string name, JobEngine? followUps = null, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(archive);
ArgumentException.ThrowIfNullOrWhiteSpace(name);
var paths = new ArchivePaths(archive.RootPath);
ArchiveVolume.EnsureWritable(paths);
var folderName = DiskName(name);
var entryFolder = Path.Combine(Directory(paths), folderName);
var recordPath = entryFolder + RecordExtension;
using (await LeaseFile.AcquireAsync(paths.LocksDirectory, SequenceTrash.EntryLease(name), _writer.Options.Owner, _writer.Options.LeaseWait,
_writer.Options.LeaseDuration, cancellationToken).ConfigureAwait(false))
{
if (!System.IO.Directory.Exists(entryFolder) || ReadRecord(recordPath) is not { } record)
throw new DirectoryNotFoundException($"{name} is not in the trash of {archive.Name}.");
var (intact, kept) = await CheckAsync(entryFolder, record, cancellationToken).ConfigureAwait(false);
// Nothing that matches its record: the entry stays as it is.
if (intact.Count == 0) throw new InvalidDataException(Core.Localization.Loc.L("Archive.Error.TrashMismatch"));
var sequence = await _db.Sequences.GetAsync(record.SequenceId, cancellationToken).ConfigureAwait(false);
var had = sequence?.Status ?? SequenceStatus.None;
PhotoRestoreResult result;
List<TrashedPhoto> left;
if (sequence is not null && sequence.ArchiveId == archive.Id)
(result, left) = await IntoSequenceAsync(archive, paths, sequence, entryFolder, intact, cancellationToken).ConfigureAwait(false);
else
(result, left) = await IntoNewSequenceAsync(archive, paths, record, entryFolder, intact, cancellationToken).ConfigureAwait(false);
var stays = kept.Concat(left).ToList();
FrameRemovalJournal.RemoveEmpty(entryFolder);
// Only an entry left without a file goes; anything still in its folder keeps it listed, never erased by a restore.
if (stays.Count == 0 && !System.IO.Directory.Exists(entryFolder))
{
File.Delete(recordPath);
}
else
{
AtomicFile.WriteAllText(recordPath, JsonSerializer.Serialize(record with
{
Photos = stays,
Bytes = stays.Sum(p => p.Files.Sum(f => f.Size)),
}, TrashJson.Default.PhotoTrashRecord));
}
Log.Info("archive", $"{record.SequenceTitle}: {result.Restored} photo(s) restored from the trash, {stays.Count} kept there");
var all = result with { Kept = [.. stays.Select(p => p.Frame.Original ?? Path.GetFileName(p.Frame.File))] };
if (result.Restored > 0) await QueueAsync(followUps, archive, all.Sequence, had, CancellationToken.None).ConfigureAwait(false);
return all;
}
}
/// <summary>The photo entries of an archive's trash (records whose folder is gone are left out).</summary>
internal static IReadOnlyList<TrashEntry> List(Archive archive, CancellationToken cancellationToken)
{
var folder = Directory(new ArchivePaths(archive.RootPath));
if (!System.IO.Directory.Exists(folder)) return [];
var entries = new List<TrashEntry>();
foreach (var path in System.IO.Directory.EnumerateFiles(folder, "*" + RecordExtension))
{
cancellationToken.ThrowIfCancellationRequested();
var name = Path.GetFileNameWithoutExtension(path);
if (!System.IO.Directory.Exists(Path.Combine(folder, name)) || ReadRecord(path) is not { } record) continue;
entries.Add(Entry(archive.Id, name, record));
}
return entries;
}
/// <summary>The record of a photo entry; null when it is not one or cannot be read.</summary>
internal static PhotoTrashRecord? ReadEntry(ArchivePaths paths, string name) =>
IsPhotoEntry(name) ? ReadRecord(Path.Combine(Directory(paths), DiskName(name)) + RecordExtension) : null;
/// <summary>The entry's folder and record on disk.</summary>
internal static (string Folder, string Record) Location(ArchivePaths paths, string name)
{
var folder = Path.Combine(Directory(paths), DiskName(name));
return (folder, folder + RecordExtension);
}
/// <summary>The folder name of an entry: its name without <see cref="EntryPrefix"/>, never a path.</summary>
private static string DiskName(string name) => Path.GetFileName(IsPhotoEntry(name) ? name[EntryPrefix.Length..] : name);
private async Task<Archive> ArchiveOfAsync(Sequence sequence, CancellationToken cancellationToken) =>
await _db.Archives.GetAsync(sequence.ArchiveId, cancellationToken).ConfigureAwait(false) ?? throw new StaleDeletePlanException(sequence.Id);
/// <summary>
/// The files of each frame that goes: its original (with the hash it was archived with, or one computed now for a frame
/// never hashed) under the entry's <c>originals/</c>, and an XMP companion (<c>IMG_0001.xmp</c>, <c>IMG_0001.CR2.xmp</c>)
/// no frame that stays shares. A frame whose original is missing goes without a file.
/// </summary>
private static async Task<List<TrashedPhoto>> TrashedAsync(SequencePaths folder, List<SidecarFrame> removed, List<SidecarFrame> kept,
CancellationToken cancellationToken)
{
var used = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
var claimed = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
var keptStems = kept.Select(f => Stem(f.File)).ToHashSet(StringComparer.OrdinalIgnoreCase);
var photos = new List<TrashedPhoto>(removed.Count);
foreach (var frame in removed)
{
cancellationToken.ThrowIfCancellationRequested();
var files = new List<TrashedFile>();
var original = new FileInfo(folder.File(frame.File));
var sha = frame.Sha256;
if (original.Exists)
{
sha ??= await ContentHash.Sha256Async(original.FullName, null, cancellationToken).ConfigureAwait(false);
files.Add(new TrashedFile(frame.File, Unique(used, "originals/" + Inside(frame.File)), original.Length, sha));
if (!keptStems.Contains(Stem(frame.File)))
{
foreach (var companion in Companions(folder, frame.File).Where(claimed.Add))
{
var path = folder.File(companion);
files.Add(new TrashedFile(companion, Unique(used, "originals/" + Inside(companion)), new FileInfo(path).Length,
await ContentHash.Sha256Async(path, null, cancellationToken).ConfigureAwait(false)));
}
}
}
photos.Add(new TrashedPhoto(frame with { Sha256 = sha }, files, null));
}
return photos;
}
/// <summary>The XMP files beside a photo that name it (<c>stem.xmp</c> or <c>file.xmp</c>), relative to the sequence folder.</summary>
private static IEnumerable<string> Companions(SequencePaths folder, string file)
{
var directory = Path.GetDirectoryName(folder.File(file))!;
if (!System.IO.Directory.Exists(directory)) yield break;
var prefix = file.Contains('/') ? file[..(file.LastIndexOf('/') + 1)] : string.Empty;
var name = Path.GetFileName(file);
var stem = Path.GetFileNameWithoutExtension(name);
foreach (var candidate in System.IO.Directory.EnumerateFiles(directory, "*.xmp"))
{
var candidateName = Path.GetFileName(candidate);
if (!Path.GetExtension(candidateName).Equals(".xmp", StringComparison.OrdinalIgnoreCase)) continue;
var named = Path.GetFileNameWithoutExtension(candidateName);
if (named.Equals(stem, StringComparison.OrdinalIgnoreCase) || named.Equals(name, StringComparison.OrdinalIgnoreCase)) yield return prefix + candidateName;
}
}
/// <summary>A photo's stem with its folder (<c>originals/IMG_0001</c>): its companions share it.</summary>
private static string Stem(string file)
{
var slash = file.LastIndexOf('/');
var name = file[(slash + 1)..];
var dot = name.IndexOf('.', StringComparison.Ordinal);
return file[..(slash + 1)] + (dot > 0 ? name[..dot] : name);
}
/// <summary>A sequence-relative path without its leading <c>originals/</c>.</summary>
private static string Inside(string file) =>
file.StartsWith(ArchiveLayout.OriginalsFolder + "/", StringComparison.OrdinalIgnoreCase) ? file[(ArchiveLayout.OriginalsFolder.Length + 1)..] : file;
/// <summary><paramref name="path"/>, or with <c>_2</c>, <c>_3</c>… before its extension when another file of the entry has it.</summary>
private static string Unique(HashSet<string> used, string path)
{
var candidate = path;
for (var n = 2; !used.Add(candidate); n++)
candidate = string.Create(CultureInfo.InvariantCulture, $"{Path.ChangeExtension(path, null)}_{n}{Path.GetExtension(path)}");
return candidate;
}
/// <summary>
/// The tombstones after a deletion: those of before, and one per SHA-256 of the photos that went that no frame staying
/// holds (a duplicate that stays keeps the content in the sequence). A photo without a hash leaves none.
/// </summary>
private static List<RemovedPhoto>? WithTombstones(IReadOnlyList<RemovedPhoto>? before, List<SidecarFrame> removed, List<SidecarFrame> kept,
DateTimeOffset at)
{
var held = kept.Where(f => f.Sha256 is not null).Select(f => f.Sha256!).ToHashSet(StringComparer.OrdinalIgnoreCase);
var tombstones = new Dictionary<string, RemovedPhoto>(StringComparer.OrdinalIgnoreCase);
foreach (var tombstone in before ?? []) tombstones[tombstone.Sha256] = tombstone;
foreach (var sha in removed.Select(f => f.Sha256).OfType<string>())
{
if (!held.Contains(sha)) tombstones[sha] = new RemovedPhoto { Sha256 = sha.ToLowerInvariant(), Reason = RemovalReason.Deleted, At = at };
}
return tombstones.Count == 0 ? null : [.. tombstones.Values];
}
/// <summary>Puts back the files of a deletion that failed half-way, and removes its record, folder and journal.</summary>
private static void Undo(ArchivePaths paths, SequencePaths folder, List<FrameRemovalMove> done, string recordPath, string entryFolder)
{
foreach (var move in done)
{
try
{
File.Move(paths.FromRelative(move.To), folder.File(move.From), overwrite: false);
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
Log.Error("archive", $"{move.To} could not move back to {folder.ArchiveRelative(move.From)}; the journal puts it back later", ex);
return;
}
}
File.Delete(recordPath);
FrameRemovalJournal.RemoveEmpty(entryFolder);
FrameRemovalJournal.Delete(folder);
}
/// <summary>
/// Renames the proxies of the frames whose index changed (BRIEF §8.5: proxies are named by frame index) so they stay
/// theirs, and deletes those of the frames removed: the passes queued afterwards reuse them instead of making the
/// sequence's proxies again. Proxies are regenerable and carry their frame's capture time, so one left in the wrong
/// place (a failure here, logged) is made again.
/// </summary>
internal static void ShiftProxies(SequencePaths folder, IReadOnlyList<SidecarFrame> before, IReadOnlyList<SidecarFrame> after,
IReadOnlyList<SidecarFrame> removed)
{
if (!System.IO.Directory.Exists(folder.Proxies)) return;
try
{
foreach (var frame in removed)
{
var stale = folder.Proxy(frame.I);
if (File.Exists(stale)) File.Delete(stale);
}
var now = after.ToDictionary(f => f.Id, f => f.I);
var moves = before.Where(f => now.TryGetValue(f.Id, out var to) && to != f.I).Select(f => (From: f.I, To: now[f.Id])).ToList();
if (moves.Count == 0) return;
// Downwards from the lowest when frames left, upwards from the highest when frames came: each target is free by then.
var ordered = moves[0].To < moves[0].From ? moves.OrderBy(m => m.From) : moves.OrderByDescending(m => m.From);
foreach (var (from, to) in ordered)
{
var source = folder.Proxy(from);
var target = folder.Proxy(to);
if (File.Exists(source)) File.Move(source, target, overwrite: true);
else if (File.Exists(target)) File.Delete(target);
}
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
Log.Warning("archive", $"Proxies of {folder.RelativeFolder} did not follow their frames; the proxy pass makes them again", ex);
}
}
/// <summary>Queues what the frames need again (see <see cref="DeleteAsync"/>), as an orphans fix does.</summary>
private async Task QueueAsync(JobEngine? followUps, Archive archive, Sequence sequence, SequenceStatus had, CancellationToken cancellationToken)
{
if (followUps is null) return;
var label = sequence.DisplayTitle;
List<ArchiveJobRequest> requests = [ProcessingJobs.LightAnalysis([sequence.Id], label)];
if ((had & SequenceStatus.AnalyzedDeep) != 0) requests.Add(ProcessingJobs.DeepAnalysis([sequence.Id], label) with { Priority = JobPriority.Background });
var images = _writer.Options.ImagesAfterScan;
if (images || (had & SequenceStatus.ThumbsBuilt) != 0) requests.Add(ArchiveJobs.Thumbnails([sequence.Id], label));
if ((images || (had & SequenceStatus.ProxiesBuilt) != 0) && archive.ProxyLongEdge != ProxyPolicy.Disabled)
requests.Add(ArchiveJobs.Proxies([sequence.Id], label));
foreach (var request in requests)
{
if (!followUps.Runs(request.Kind) || await _db.Jobs.IsQueuedAsync(request.Kind, sequence.Id, cancellationToken).ConfigureAwait(false)) continue;
await followUps.EnqueueAsync(request, cancellationToken: cancellationToken).ConfigureAwait(false);
}
}
/// <summary>Each photo whose files all match their record (size and SHA-256), and those that stay in the trash.</summary>
private static async Task<(List<TrashedPhoto> Intact, List<TrashedPhoto> Kept)> CheckAsync(string entryFolder, PhotoTrashRecord record,
CancellationToken cancellationToken)
{
var intact = new List<TrashedPhoto>();
var kept = new List<TrashedPhoto>();
foreach (var photo in record.Photos)
{
var ok = photo.Files.Count > 0;
foreach (var file in photo.Files)
{
var path = Path.Combine(entryFolder, file.Path);
var info = new FileInfo(path);
if (!info.Exists || info.Length != file.Size
|| (file.Sha256 is { } sha && !string.Equals(sha, await ContentHash.Sha256Async(path, null, cancellationToken).ConfigureAwait(false),
StringComparison.OrdinalIgnoreCase)))
{
Log.Warning("archive", $"{file.Path} of trash entry {Path.GetFileName(entryFolder)} does not match its record; it stays in the trash");
ok = false;
break;
}
}
(ok ? intact : kept).Add(photo);
}
return (intact, kept);
}
/// <summary>The photos back into their sequence, under its lease; returns what came back and the photos left in the trash.</summary>
private async Task<(PhotoRestoreResult, List<TrashedPhoto>)> IntoSequenceAsync(Archive archive, ArchivePaths paths, Sequence sequence, string entryFolder,
List<TrashedPhoto> intact, CancellationToken cancellationToken)
{
var folder = paths.Sequence(sequence.Folder);
var left = new List<TrashedPhoto>();
await using (await _writer.LockAsync(paths, sequence.Id, cancellationToken).ConfigureAwait(false))
{
var manifest = SequenceWriter.ReadLocked(folder, sequence.Id);
var inStep = await _indexer.InStepAsync(archive, folder, manifest, cancellationToken).ConfigureAwait(false);
var photosChanged = !inStep && await _indexer.PhotosChangedAsync(archive, folder, cancellationToken).ConfigureAwait(false);
var ids = manifest.Frames.Select(f => f.Id).ToHashSet();
var held = manifest.Frames.Where(f => f.Sha256 is not null).Select(f => f.Sha256!).ToHashSet(StringComparer.OrdinalIgnoreCase);
var taken = manifest.Frames.Select(f => f.File).ToHashSet(StringComparer.OrdinalIgnoreCase);
var back = new List<SidecarFrame>();
foreach (var photo in intact)
{
cancellationToken.ThrowIfCancellationRequested();
// In the sequence again (restored before, or filed again since): the trash keeps its copy.
if (ids.Contains(photo.Frame.Id) || (photo.Frame.Sha256 is { } sha && held.Contains(sha)))
{
left.Add(photo);
continue;
}
var original = photo.Files[0];
var tails = photo.Files.Skip(1).Select(c => CompanionTail(c.From, original.From)).ToList();
var file = FreeName(folder, original.From, tails, taken);
var stem = file[..^Path.GetExtension(file).Length];
try
{
MoveIn(Path.Combine(entryFolder, original.Path), folder.File(file));
// A companion follows its photo's name: IMG_0001_2.xmp beside IMG_0001_2.JPG.
for (var c = 0; c < tails.Count; c++) MoveIn(Path.Combine(entryFolder, photo.Files[c + 1].Path), folder.File(stem + tails[c]));
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
Log.Warning("archive", $"{original.Path} could not move back into {folder.RelativeFolder}; it stays in the trash", ex);
left.Add(photo);
continue;
}
taken.Add(file);
back.Add(photo.Frame with { File = file, Flags = photo.Frame.Flags & ~FrameFlags.Missing });
}
if (back.Count == 0) return (new PhotoRestoreResult(sequence, 0, [], false), left);
var restored = back.Where(f => f.Sha256 is not null).Select(f => f.Sha256!).ToHashSet(StringComparer.OrdinalIgnoreCase);
var tombstones = manifest.Removed?.Where(r => !restored.Contains(r.Sha256)).ToList();
var updated = SequenceFrames.Insert(manifest, back) with
{
Status = manifest.Status & ~Uncovered,
Removed = tombstones is { Count: > 0 } ? tombstones : null,
};
ManifestStore.WriteSequence(folder.ManifestPath, updated);
await _indexer.SyncAsync(archive, folder, updated, null, Uncovered, photosChanged, CancellationToken.None).ConfigureAwait(false);
ShiftProxies(folder, manifest.Frames, updated.Frames, []);
}
var row = await _db.Sequences.GetAsync(sequence.Id, CancellationToken.None).ConfigureAwait(false) ?? sequence;
return (new PhotoRestoreResult(row, intact.Count - left.Count, [], false), left);
}
/// <summary>
/// The photos of a sequence that is gone into a new one, through the archive ingest (staging, naming templates, a
/// sidecar of its own), one photo at a time so one that fails stays in the trash alone: titled as theirs was, placed at
/// its folder when that is free, and keyed by its id, so every entry of that sequence comes back into the same new
/// one. Companions follow their photo.
/// </summary>
private async Task<(PhotoRestoreResult, List<TrashedPhoto>)> IntoNewSequenceAsync(Archive archive, ArchivePaths paths, PhotoTrashRecord record,
string entryFolder, List<TrashedPhoto> intact, CancellationToken cancellationToken)
{
var left = new List<TrashedPhoto>();
var staging = Path.Combine(paths.StagingDirectory, $"trash-{record.SequenceId:N}");
System.IO.Directory.CreateDirectory(staging);
var target = new SequenceTarget($"trash:{record.SequenceId:N}", record.SequenceTitle, record.SequenceFolder.Length > 0 ? record.SequenceFolder : null, null);
Guid? sequenceId = null;
var restored = 0;
foreach (var photo in intact)
{
cancellationToken.ThrowIfCancellationRequested();
var original = photo.Files[0];
var inEntry = Path.Combine(entryFolder, original.Path);
var path = Path.Combine(staging, Guid.NewGuid().ToString("N") + Path.GetExtension(original.From));
File.Move(inEntry, path, overwrite: false);
IngestResult result;
try
{
var frame = new StagedFrame(path, photo.Frame.Original ?? Path.GetFileName(original.From), original.Size, photo.Frame.Sha256 ?? original.Sha256!,
MetadataReader.Read(path, cancellationToken), photo.Frame.CapturedAt, Path.GetFileName(original.From));
result = (await _ingest.CommitSessionAsync(archive, target, [frame], cancellationToken).ConfigureAwait(false))[0];
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or InvalidDataException)
{
Log.Warning("archive", $"{original.Path} could not be restored into a new sequence; it stays in the trash", ex);
if (File.Exists(path)) File.Move(path, inEntry, overwrite: false);
left.Add(photo);
continue;
}
sequenceId ??= result.SequenceId;
if (File.Exists(path))
{
// A duplicate of a photo the new sequence holds stays in staging: it returns to the entry.
File.Move(path, inEntry, overwrite: false);
left.Add(photo);
continue;
}
restored++;
var placed = paths.FromRelative(result.RelativePath);
foreach (var companion in photo.Files.Skip(1))
{
// Beside its photo; a name taken there (another file of that name) keeps the companion in the trash.
var beside = placed[..^Path.GetExtension(placed).Length] + CompanionTail(companion.From, original.From);
if (!File.Exists(beside)) MoveIn(Path.Combine(entryFolder, companion.Path), beside);
}
}
SequenceTrash.Erase(staging);
if (sequenceId is not { } id) throw new IOException(Core.Localization.Loc.L("Archive.Error.TrashMismatch"));
var sequence = await _db.Sequences.GetAsync(id, CancellationToken.None).ConfigureAwait(false)
?? throw new InvalidOperationException($"The photos of {record.SequenceTitle} were restored but their sequence is not indexed.");
return (new PhotoRestoreResult(sequence, restored, [], true), left);
}
/// <summary>What a companion's name adds to its photo's stem (<c>.xmp</c>, <c>.CR2.xmp</c>).</summary>
private static string CompanionTail(string companion, string photo)
{
var stem = Path.GetFileNameWithoutExtension(Path.GetFileName(photo));
var name = Path.GetFileName(companion);
return name.StartsWith(stem, StringComparison.OrdinalIgnoreCase) ? name[stem.Length..] : Path.GetExtension(name);
}
/// <summary>
/// <paramref name="file"/> when it is free in the sidecar and on disk with its companions (<paramref name="tails"/> after
/// its stem), else <c>stem_2.ext</c>, <c>stem_3.ext</c>…
/// </summary>
private static string FreeName(SequencePaths folder, string file, IReadOnlyList<string> tails, HashSet<string> taken)
{
var extension = Path.GetExtension(file);
var stem = file[..^extension.Length];
var candidate = file;
for (var n = 2; taken.Contains(candidate) || File.Exists(folder.File(candidate)) || tails.Any(t => File.Exists(folder.File(Stem(candidate, extension) + t))); n++)
candidate = string.Create(CultureInfo.InvariantCulture, $"{stem}_{n}{extension}");
return candidate;
static string Stem(string name, string extension) => name[..^extension.Length];
}
private static void MoveIn(string from, string to)
{
System.IO.Directory.CreateDirectory(Path.GetDirectoryName(to)!);
File.Move(from, to, overwrite: false);
}
/// <summary>The sequence id and the time, with a number when an entry of that second exists already.</summary>
private static string EntryName(string trash, Guid sequenceId)
{
var stamp = DateTime.UtcNow.ToString("yyyyMMddHHmmss", CultureInfo.InvariantCulture);
var name = $"{sequenceId:N}-{stamp}";
for (var n = 2; System.IO.Directory.Exists(Path.Combine(trash, name)) || File.Exists(Path.Combine(trash, name) + RecordExtension); n++)
name = string.Create(CultureInfo.InvariantCulture, $"{sequenceId:N}-{stamp}-{n}");
return name;
}
private static TrashEntry Entry(Guid archiveId, string folderName, PhotoTrashRecord record) =>
new(archiveId, EntryPrefix + folderName, record.SequenceId, record.SequenceTitle, record.SequenceFolder, record.Photos.Count,
record.Photos.Sum(p => p.Files.Count), record.Bytes, record.DeletedAt, record.DeletedBy, record.Kind);
private static PhotoTrashRecord? ReadRecord(string path)
{
try
{
return File.Exists(path) ? JsonSerializer.Deserialize(File.ReadAllText(path), TrashJson.Default.PhotoTrashRecord) : null;
}
catch (Exception ex) when (ex is JsonException or IOException or UnauthorizedAccessException)
{
Log.Warning("archive", $"Trash record {path} is unreadable", ex);
return null;
}
}
}
/// <summary>
/// What the trash keeps next to deleted photos (owner review 2, R6): the frame records, where each file was and is, the
/// sequence they came from. <see cref="TrashKind.Replaced"/> entries (a later conversion) name each photo's replacement.
/// </summary>
internal sealed record PhotoTrashRecord(TrashKind Kind, Guid SequenceId, string SequenceTitle, string SequenceFolder, IReadOnlyList<TrashedPhoto> Photos,
long Bytes, DateTimeOffset DeletedAt, string? DeletedBy);
/// <summary>One photo of a photo entry: its frame record, its files (the original first) and, when replaced, the replacement's SHA-256.</summary>
internal sealed record TrashedPhoto(SidecarFrame Frame, IReadOnlyList<TrashedFile> Files, string? Replacement);
/// <param name="From">Where the file was, relative to the sequence folder.</param>
/// <param name="Path">Where it is, relative to the entry's folder.</param>
/// <param name="Sha256">Its SHA-256 when it left the sequence; a restore re-hashes the file against it.</param>
internal sealed record TrashedFile(string From, string Path, long Size, string? Sha256);
@@ -31,6 +31,15 @@ public sealed record BackupParameters(int Keep);
/// </summary>
public sealed record CleanupParameters(IReadOnlyList<string> Steps, int OlderThanDays);
/// <summary>
/// <see cref="JobKind.EmptyTrash"/>: target = the archive; the entries of the confirmed plan, each with its own fingerprint
/// (<see cref="SequenceTrash.EntryFingerprint"/>), and the plan's fingerprint (<see cref="TrashEmptyPlan.Fingerprint"/>).
/// </summary>
public sealed record EmptyTrashParameters(IReadOnlyList<EmptyTrashItem> Entries, string Fingerprint);
/// <summary>One entry of a confirmed emptying: its name and fingerprint when it was planned.</summary>
public sealed record EmptyTrashItem(string Name, string Fingerprint);
/// <summary>A job ready to enqueue.</summary>
public sealed record ArchiveJobRequest(JobKind Kind, IReadOnlyList<Guid> Targets, string? Label, string? ParametersJson, JobPriority Priority);
@@ -42,6 +51,7 @@ public sealed record ArchiveJobRequest(JobKind Kind, IReadOnlyList<Guid> Targets
[JsonSerializable(typeof(ImportJobParameters))]
[JsonSerializable(typeof(BackupParameters))]
[JsonSerializable(typeof(CleanupParameters))]
[JsonSerializable(typeof(EmptyTrashParameters))]
[JsonSerializable(typeof(CardProfile))]
internal sealed partial class ArchiveJobJson : JsonSerializerContext
{
@@ -0,0 +1,37 @@
using System.Globalization;
using Chronos.Core.Localization;
using Chronos.Core.Model;
using Chronos.Data.Housekeeping;
using Chronos.Data.Jobs;
namespace Chronos.Data.Archiving.Jobs;
/// <summary>
/// <see cref="JobKind.EmptyTrash"/> (owner review 2, R6): erases exactly the entries of a confirmed plan
/// (<see cref="EmptyTrashParameters"/>) and fails, erasing nothing, when the trash no longer matches the plan's
/// fingerprint (<see cref="StaleTrashPlanException"/>). Checkpoint: <c>done:&lt;n&gt;</c>, the entries done; a resumed job
/// checks each remaining entry against its own fingerprint. Entries kept (a replacement that no longer matches, an entry
/// changed since) are logged and fail the job at the end, after the others are erased.
/// </summary>
internal sealed class EmptyTrashJobHandler(ChronosDatabase db, SequenceTrash trash) : IJobHandler
{
private const string Prefix = "done:";
public JobKind Kind => JobKind.EmptyTrash;
public async Task RunAsync(JobContext context)
{
var archive = await JobArchive.LoadAsync(db, context.Job, context.Cancellation).ConfigureAwait(false);
var parameters = ArchiveJobJson.Read(context.Job, ArchiveJobJson.Default.EmptyTrashParameters, new EmptyTrashParameters([], string.Empty));
var start = context.Checkpoint is { } checkpoint && checkpoint.StartsWith(Prefix, StringComparison.Ordinal)
&& int.TryParse(checkpoint.AsSpan(Prefix.Length), NumberStyles.None, CultureInfo.InvariantCulture, out var done)
? Math.Min(done, parameters.Entries.Count)
: 0;
await context.ReportAsync(start, parameters.Entries.Count).ConfigureAwait(false);
var result = await trash.EmptyAsync(archive, parameters, start,
(n, total) => context.CheckpointAsync(Prefix + n.ToString(CultureInfo.InvariantCulture), n, total), context.Cancellation).ConfigureAwait(false);
context.Log(Loc.L("Archive.Log.TrashEmptied", result.Erased, CleanupSteps.Megabytes(result.Bytes)));
foreach (var title in result.Refused) context.Log(Loc.L("Archive.Log.TrashKept", title));
if (result.Refused.Count > 0) throw new InvalidOperationException(Loc.Plural("Archive.Error.TrashKept", result.Refused.Count));
}
}
+34 -4
View File
@@ -12,15 +12,19 @@ namespace Chronos.Data.Archiving;
/// Keeps a project's frame positions (exclusions, hero, virtual-camera keyframes; BRIEF §5, §7) on their frames when the
/// index takes a sidecar in which frames were inserted before others: an upload or import of earlier photos, photos a
/// scan found, a sync download, a journalled batch completed after a crash. Positions name the frames in the indexed
/// order (what editors, renders and the API read), so the old order comes from the index rows. Only an insertion is
/// followed: when an indexed frame is no longer in the sidecar, positions cannot be mapped and stay as they are. The move
/// is part of the frames change, not a settings edit, so the settings version stays. Settings synced from another copy
/// order (what editors, renders and the API read), so the old order comes from the index rows. An insertion moves them
/// by position; when an indexed frame is no longer in the sidecar (photos deleted, owner review 2, R6) they are translated
/// by photo, those on the photos that went waiting as pending frames. The move is part of the frames change, not a
/// settings edit, so the settings version stays. Settings synced from another copy
/// arrive translated to this copy's frames (<see cref="ProjectSettings.TranslateFramePositions"/>); their positions on
/// photos that were not here yet (<see cref="ProjectSettings.PendingFrames"/>) take their place when the photos arrive,
/// wherever they land.
/// </summary>
internal static class ProjectPositions
{
/// <summary>Index frames read at once when positions are translated by photo.</summary>
private const int PageSize = 1000;
/// <summary>
/// The index's copy of the project (the one in force) with its positions moved to the order of
/// <paramref name="manifest"/> and its pending frames placed; null when nothing changes. A <c>project.json</c> the
@@ -45,9 +49,35 @@ internal static class ProjectPositions
}
if (index != row.Index) moves[row.Index] = index;
}
return Placed(project, moves is null ? null : ProjectSettings.MoveFramePositions(project, moves), manifest);
if (moves is null) return await RemovedAsync(db, indexed.Id, project, manifest, cancellationToken).ConfigureAwait(false);
return Placed(project, ProjectSettings.MoveFramePositions(project, moves), manifest);
}
/// <summary>
/// Indexed frames are no longer in the sidecar (photos deleted into the trash, here or by another process sharing the
/// archive, owner review 2, R6): the positions are translated by photo from the index's frames to the sidecar's
/// (<see cref="ProjectSettings.TranslateFramePositions"/>), so those on the photos that went wait as pending frames
/// and take their place again when the photos come back (a restore), and the others follow their photos.
/// </summary>
private static async Task<PositionMove?> RemovedAsync(ChronosRepositories db, Guid sequenceId, string project, SequenceManifest manifest,
CancellationToken cancellationToken)
{
var before = new List<(int, FramePhoto)>();
for (var after = -1; ;)
{
var page = await db.Frames.ListBySequenceAsync(sequenceId, after, PageSize, cancellationToken).ConfigureAwait(false);
before.AddRange(page.Select(f => (f.Index, new FramePhoto(f.Sha256, f.Size, f.CapturedAt))));
if (page.Count < PageSize) break;
after = page[^1].Index;
}
var to = new FramePhotos(manifest.Frames.Select(f => (f.I, new FramePhoto(f.Sha256, f.Size, f.CapturedAt))));
var translated = ProjectSettings.TranslateFramePositions(project, new FramePhotos(before), to);
if (translated is null) return null;
var hero = HeroOf(project) is null && HeroOf(translated) is { } index ? manifest.Frames.FirstOrDefault(f => f.I == index)?.Id : null;
return new PositionMove(project, translated, hero);
}
/// <summary>
/// The index's copy of the project with the pending frames whose photos <paramref name="manifest"/> now holds put in
/// place: frames appended in step with the index, which moves no position. Null when nothing changes.
@@ -41,6 +41,13 @@ internal static class SequenceMapping
public static List<Frame> ToFrames(SequenceManifest manifest, SequencePaths sequence) =>
manifest.Frames.Select(f => ToFrame(f, manifest.Id, sequence)).ToList();
/// <summary>The sidecar's tombstones as index rows (owner review 2, R6).</summary>
public static List<FrameRemoval> ToRemovals(SequenceManifest manifest) =>
manifest.Removed is not { Count: > 0 } removed
? []
: removed.Where(r => !string.IsNullOrEmpty(r.Sha256))
.Select(r => new FrameRemoval(manifest.Id, r.Sha256.ToLowerInvariant(), r.Replacement?.ToLowerInvariant(), r.Reason, r.At)).ToList();
/// <param name="existing">The current row; its render, analysis, sync and ownership fields are kept, and so are its
/// title, tags, rating and notes when its settings version is ahead of the sidecar's (edited in the index only).</param>
public static Sequence ToSequence(SequenceManifest m, Guid archiveId, SequencePaths sequence, Sequence? existing)
@@ -0,0 +1,205 @@
using System.Globalization;
using System.Security.Cryptography;
using System.Text;
using Chronos.Core.Archiving;
using Chronos.Core.Diagnostics;
using Chronos.Core.Localization;
using Chronos.Core.Model;
using Chronos.Data.Archiving.Jobs;
namespace Chronos.Data.Archiving;
/// <summary>
/// The dry run of emptying an archive's trash (owner review 2, R6; BRIEF §0.2 rule 8): the entries that would be erased,
/// with the files and bytes their folders hold now, and a fingerprint of exactly those entries. Erasing
/// (<see cref="JobKind.EmptyTrash"/>) refuses a plan whose fingerprint no longer matches the trash.
/// </summary>
/// <param name="Unknown">Names asked for that the trash does not hold.</param>
public sealed record TrashEmptyPlan(Guid ArchiveId, IReadOnlyList<TrashEntry> Entries, long Bytes, string Fingerprint, IReadOnlyList<string> Unknown)
{
public int Files => Entries.Sum(e => e.Files);
public int Photos => Entries.Sum(e => e.Frames);
}
/// <summary>What an emptying erased, and the entries it kept (a replacement that no longer matches, an entry changed since the plan).</summary>
public sealed record TrashEmptyResult(int Erased, long Bytes, IReadOnlyList<string> Refused);
/// <summary>The trash changed after the emptying was planned (an entry came, went or changed); nothing was erased.</summary>
public sealed class StaleTrashPlanException() : InvalidOperationException(Loc.L("Archive.Error.TrashChanged"));
public sealed partial class SequenceTrash
{
/// <summary>Folder inside the trash that entries move into before they are erased, so a listing never sees half an entry.</summary>
private const string ErasingFolder = ".erasing";
/// <summary>The lease that keeps a restore and an erasing of one entry apart.</summary>
internal static string EntryLease(string name) => "trash-" + name;
/// <summary>
/// The dry run of emptying the trash: <paramref name="names"/> of the entries to erase (null: every entry), each
/// measured on disk, and the plan's fingerprint (<see cref="Fingerprint"/>). Reads only.
/// </summary>
public async Task<TrashEmptyPlan> PlanEmptyAsync(Archive archive, IReadOnlyList<string>? names = null, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(archive);
var paths = new ArchivePaths(archive.RootPath);
var listed = await ListAsync(archive, cancellationToken).ConfigureAwait(false);
var wanted = names?.ToHashSet(StringComparer.Ordinal);
var chosen = wanted is null ? listed : [.. listed.Where(e => wanted.Contains(e.Name))];
var measured = await Task.Run(() => chosen.Select(e =>
{
var (folder, _) = Location(paths, e);
var (files, bytes) = Directory.Exists(folder) ? Measure(folder, cancellationToken) : (0, 0L);
return e with { Files = files, Bytes = bytes };
}).ToList(), cancellationToken).ConfigureAwait(false);
var unknown = names?.Where(n => !listed.Any(e => e.Name == n)).Distinct(StringComparer.Ordinal).ToList() ?? [];
return new TrashEmptyPlan(archive.Id, measured, measured.Sum(e => e.Bytes), Fingerprint(measured), unknown);
}
/// <summary>
/// Fingerprint of a set of entries: SHA-256 of each one's <see cref="EntryFingerprint"/> in name order. The same
/// entries with the same files on disk give the same fingerprint whatever order they were listed in.
/// </summary>
public static string Fingerprint(IEnumerable<TrashEntry> entries)
{
ArgumentNullException.ThrowIfNull(entries);
var text = new StringBuilder();
foreach (var entry in entries.OrderBy(e => e.Name, StringComparer.Ordinal)) text.Append(EntryFingerprint(entry)).Append('\n');
return Convert.ToHexStringLower(SHA256.HashData(Encoding.UTF8.GetBytes(text.ToString())));
}
/// <summary>What identifies one entry as planned: its kind, name, files and bytes on disk, and when it was deleted.</summary>
public static string EntryFingerprint(TrashEntry entry)
{
ArgumentNullException.ThrowIfNull(entry);
return string.Create(CultureInfo.InvariantCulture, $"{entry.Kind}|{entry.Name}|{entry.Files}|{entry.Bytes}|{entry.DeletedAt.UtcTicks}");
}
/// <summary>
/// Erases the entries of <paramref name="parameters"/> from <paramref name="start"/> on, one at a time under its lease,
/// each moved aside whole and then deleted (a listing never shows half an entry). From the start, the trash must still
/// hold exactly the planned entries (<see cref="EmptyTrashParameters.Fingerprint"/>), else nothing is erased; a run
/// resumed after a stop checks each remaining entry against its own fingerprint, keeps one that changed and skips one
/// that is gone. A <see cref="TrashKind.Replaced"/> entry is erased only while every replacement still matches its
/// SHA-256 in the sequence (re-hashed now); otherwise it is kept. Leftovers of an interrupted erase are deleted first.
/// </summary>
/// <param name="progress">Entries done so far (the resume point) and their number.</param>
/// <exception cref="StaleTrashPlanException">The trash no longer holds exactly the planned entries; nothing was erased.</exception>
internal async Task<TrashEmptyResult> EmptyAsync(Archive archive, EmptyTrashParameters parameters, int start, Func<int, int, ValueTask> progress,
CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(archive);
ArgumentNullException.ThrowIfNull(parameters);
var paths = new ArchivePaths(archive.RootPath);
ArchiveVolume.EnsureWritable(paths);
SweepErasing(paths);
var items = parameters.Entries;
var current = await PlanEmptyAsync(archive, [.. items.Skip(start).Select(i => i.Name)], cancellationToken).ConfigureAwait(false);
if (start == 0 && (current.Fingerprint != parameters.Fingerprint || current.Unknown.Count > 0)) throw new StaleTrashPlanException();
var refused = new List<string>();
int erased = 0;
long bytes = 0;
for (var i = start; i < items.Count; i++)
{
cancellationToken.ThrowIfCancellationRequested();
var item = items[i];
if (current.Entries.FirstOrDefault(e => e.Name == item.Name) is { } entry)
{
if (EntryFingerprint(entry) != item.Fingerprint)
{
refused.Add(entry.Title);
Log.Warning("archive", $"Trash entry {entry.Name} changed since the emptying was planned; it is kept");
}
else if (await EraseAsync(paths, entry, cancellationToken).ConfigureAwait(false))
{
erased++;
bytes += entry.Bytes;
}
else
{
refused.Add(entry.Title);
}
}
await progress(i + 1, items.Count).ConfigureAwait(false);
}
return new TrashEmptyResult(erased, bytes, refused);
}
/// <summary>Erases one entry under its lease; false (logged) when a replaced entry's replacements no longer match, or it changed.</summary>
private async Task<bool> EraseAsync(ArchivePaths paths, TrashEntry entry, CancellationToken cancellationToken)
{
using (await LeaseFile.AcquireAsync(paths.LocksDirectory, EntryLease(entry.Name), _writer.Options.Owner, _writer.Options.LeaseWait,
_writer.Options.LeaseDuration, cancellationToken).ConfigureAwait(false))
{
var (folder, record) = Location(paths, entry);
if (!Directory.Exists(folder) || !File.Exists(record)) return false;
if (entry.Kind == TrashKind.Replaced && !await ReplacementsHoldAsync(paths, entry, cancellationToken).ConfigureAwait(false))
{
Log.Warning("archive", $"Trash entry {entry.Name} is kept: a replacement of its originals no longer matches");
return false;
}
var aside = Path.Combine(TrashDirectory(paths), ErasingFolder, Guid.NewGuid().ToString("N"));
Directory.CreateDirectory(Path.GetDirectoryName(aside)!);
Directory.Move(folder, aside);
File.Delete(record);
Erase(aside);
Log.Info("archive", $"Trash entry {entry.Name} ({entry.Title}, {entry.Files} files, {entry.Bytes} bytes) erased");
return true;
}
}
/// <summary>
/// Whether every photo of a replaced entry still has its replacement in the sequence: a frame holding the replacement's
/// SHA-256 whose file hashes to it now. The originals are erased only then (a later phase's conversion).
/// </summary>
private async Task<bool> ReplacementsHoldAsync(ArchivePaths paths, TrashEntry entry, CancellationToken cancellationToken)
{
if (FrameTrash.ReadEntry(paths, entry.Name) is not { } record) return false;
foreach (var photo in record.Photos)
{
if (photo.Replacement is not { } replacement) return false;
var holders = (await _db.Frames.FindBySha256Async(replacement.ToLowerInvariant(), cancellationToken).ConfigureAwait(false))
.Where(f => f.SequenceId == record.SequenceId).ToList();
var verified = false;
foreach (var frame in holders)
{
var file = paths.FromRelative(frame.RelativePath);
if (!File.Exists(file)) continue;
if (string.Equals(await ContentHash.Sha256Async(file, null, cancellationToken).ConfigureAwait(false), replacement, StringComparison.OrdinalIgnoreCase))
{
verified = true;
break;
}
}
if (!verified) return false;
}
return true;
}
/// <summary>The folder and record of an entry of either kind.</summary>
private static (string Folder, string Record) Location(ArchivePaths paths, TrashEntry entry)
{
if (FrameTrash.IsPhotoEntry(entry.Name)) return FrameTrash.Location(paths, entry.Name);
var folder = Path.Combine(TrashDirectory(paths), Path.GetFileName(entry.Name));
return (folder, folder + RecordExtension);
}
/// <summary>Deletes what an interrupted erase left aside: those entries were confirmed and had left the listing already.</summary>
private static void SweepErasing(ArchivePaths paths)
{
var erasing = Path.Combine(TrashDirectory(paths), ErasingFolder);
if (!Directory.Exists(erasing)) return;
foreach (var leftover in Directory.EnumerateDirectories(erasing)) Erase(leftover);
}
/// <summary>Deletes a folder and everything in it, read-only files included; one that is gone already is fine.</summary>
internal static void Erase(string folder)
{
if (!Directory.Exists(folder)) return;
foreach (var file in new DirectoryInfo(folder).EnumerateFiles("*", new EnumerationOptions { RecurseSubdirectories = true, AttributesToSkip = 0 }))
{
if ((file.Attributes & FileAttributes.ReadOnly) != 0) file.Attributes &= ~FileAttributes.ReadOnly;
}
Directory.Delete(folder, recursive: true);
}
}
+33 -7
View File
@@ -48,11 +48,27 @@ public sealed record DeletePlan(IReadOnlyList<DeleteStep> Steps, IReadOnlyList<B
public int Renders => Steps.Sum(s => s.Sequence.RenderedCount);
}
/// <summary>A deleted sequence kept in an archive's trash, as <see cref="SequenceTrash.ListAsync"/> lists it.</summary>
/// <param name="Name">Folder name inside the trash; pass it to <see cref="SequenceTrash.RestoreAsync"/>.</param>
/// <summary>What a trash entry holds (owner review 2, R6).</summary>
public enum TrashKind
{
/// <summary>A whole sequence folder (<see cref="SequenceTrash"/>).</summary>
Sequence,
/// <summary>Photos deleted from a sequence (<see cref="FrameTrash"/>).</summary>
Photos,
/// <summary>Originals a conversion replaced (a later phase): erased only while their replacements still match.</summary>
Replaced,
}
/// <summary>An entry of an archive's trash, as <see cref="SequenceTrash.ListAsync"/> lists it: a deleted sequence or deleted photos.</summary>
/// <param name="Name">The entry's name: the folder name inside the trash for a sequence, <c>photos-</c> and the folder name for
/// photos; pass it to <see cref="ArchiveService.RestoreEntryAsync"/>.</param>
/// <param name="Title">The sequence's title (the one the photos came from).</param>
/// <param name="Folder">Archive-relative folder the sequence came from (and returns to when it is free).</param>
/// <param name="Frames">Photos the entry holds.</param>
public sealed record TrashEntry(Guid ArchiveId, string Name, Guid SequenceId, string Title, string Folder, int Frames, int Files, long Bytes,
DateTimeOffset DeletedAt, string? DeletedBy);
DateTimeOffset DeletedAt, string? DeletedBy, TrashKind Kind = TrashKind.Sequence);
/// <summary>The plan no longer matches the index or the jobs (a sequence moved, vanished or got busy since it was made); nothing was deleted.</summary>
public sealed class StaleDeletePlanException(Guid sequenceId) : InvalidOperationException(Loc.L("Archive.Error.StalePlan"))
@@ -75,7 +91,7 @@ public sealed class SequenceInLibraryException(Guid sequenceId, string title) :
/// moved, its index step runs to the end whatever the caller cancels; when that step fails, the folder moves back, so
/// the trash and the index never disagree.
/// </summary>
public sealed class SequenceTrash
public sealed partial class SequenceTrash
{
/// <summary>Folder of the trash inside the archive's <c>.chronos</c>.</summary>
public const string FolderName = "trash";
@@ -168,7 +184,10 @@ public sealed class SequenceTrash
return entries;
}
/// <summary>The sequences in an archive's trash, newest first; records whose folder is gone are left out.</summary>
/// <summary>
/// The entries of an archive's trash, newest first: deleted sequences (<c>trash/*.json</c>) and deleted photos
/// (<c>trash/photos/*.json</c>); records whose folder is gone are left out.
/// </summary>
public async Task<IReadOnlyList<TrashEntry>> ListAsync(Archive archive, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(archive);
@@ -184,7 +203,8 @@ public sealed class SequenceTrash
if (!Directory.Exists(Path.Combine(trash, name)) || ReadRecord(path) is not { } record) continue;
entries.Add(Entry(archive.Id, name, record));
}
return entries.OrderByDescending(e => e.DeletedAt).ToList();
entries.AddRange(FrameTrash.List(archive, cancellationToken));
return entries.OrderByDescending(e => e.DeletedAt).ThenBy(e => e.Name, StringComparer.Ordinal).ToList();
}, cancellationToken).ConfigureAwait(false);
}
@@ -215,8 +235,12 @@ public sealed class SequenceTrash
.ToHashSet(StringComparer.OrdinalIgnoreCase);
var folder = FreeFolder(paths, record.Sequence.Folder, locations);
var sequence = paths.Sequence(folder);
// The entry's lease keeps an emptying of the trash out meanwhile.
using (await LeaseFile.AcquireAsync(paths.LocksDirectory, EntryLease(Path.GetFileName(name)), _writer.Options.Owner, _writer.Options.LeaseWait,
_writer.Options.LeaseDuration, cancellationToken).ConfigureAwait(false))
await using (await _writer.LockAsync(paths, id, cancellationToken).ConfigureAwait(false))
{
if (!Directory.Exists(source)) throw new DirectoryNotFoundException($"{name} is not in the trash of {archive.Name}.");
cancellationToken.ThrowIfCancellationRequested();
Directory.CreateDirectory(Path.GetDirectoryName(sequence.Folder)!);
Directory.Move(source, sequence.Folder);
@@ -269,6 +293,7 @@ public sealed class SequenceTrash
await using var tx = await _db.BeginAsync(cancellationToken).ConfigureAwait(false);
await tx.Sequences.UpsertAsync(SequenceMapping.ToSequence(manifest, archive.Id, sequence, kept), cancellationToken).ConfigureAwait(false);
await tx.Frames.SyncSequenceAsync(deleted.Id, SequenceMapping.ToFrames(manifest, sequence), cancellationToken).ConfigureAwait(false);
await tx.FrameRemovals.SyncSequenceAsync(deleted.Id, SequenceMapping.ToRemovals(manifest), cancellationToken).ConfigureAwait(false);
foreach (var key in manifest.SessionKeys) await tx.Sequences.MapSessionKeyAsync(archive.Id, key, deleted.Id, cancellationToken).ConfigureAwait(false);
foreach (var render in record.Renders)
{
@@ -426,7 +451,7 @@ public sealed class SequenceTrash
/// archives of archive-wide ones (scan, rebuild, import, maintenance, a verify of everything). An import's folders
/// are known only to its plan, so it holds its whole archive; a verify of named sequences holds only those.
/// </summary>
private async Task<IReadOnlySet<Guid>> BusyAsync(CancellationToken cancellationToken)
internal async Task<IReadOnlySet<Guid>> BusyAsync(CancellationToken cancellationToken)
{
var busy = new HashSet<Guid>();
foreach (var state in new[] { JobState.Running, JobState.Paused })
@@ -551,4 +576,5 @@ internal sealed record TrashRecord(Sequence Sequence, IReadOnlyList<Render> Rend
[JsonSourceGenerationOptions(PropertyNamingPolicy = JsonKnownNamingPolicy.CamelCase, DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull,
UseStringEnumConverter = true, IgnoreReadOnlyProperties = true)]
[JsonSerializable(typeof(TrashRecord))]
[JsonSerializable(typeof(PhotoTrashRecord))]
internal sealed partial class TrashJson : JsonSerializerContext;
+3 -1
View File
@@ -88,7 +88,8 @@ internal sealed class SequenceWriter(ArchiveServiceOptions options)
}
/// <summary>
/// Reads the sidecar of a locked sequence, completing an interrupted ingest batch first.
/// Reads the sidecar of a locked sequence, undoing an interrupted photo deletion (<see cref="FrameRemovalJournal"/>) and
/// completing an interrupted ingest batch first.
/// </summary>
/// <exception cref="InvalidDataException">The sidecar in the folder belongs to another sequence.</exception>
public static SequenceManifest ReadLocked(SequencePaths sequence, Guid sequenceId)
@@ -96,6 +97,7 @@ internal sealed class SequenceWriter(ArchiveServiceOptions options)
var manifest = ManifestStore.ReadSequence(sequence.ManifestPath);
if (manifest.Id != sequenceId)
throw new InvalidDataException($"{sequence.ManifestPath} belongs to sequence {manifest.Id}, not {sequenceId}.");
FrameRemovalJournal.Recover(sequence, manifest);
if (IngestJournal.Recover(sequence, manifest) is { } recovered)
{
ManifestStore.WriteSequence(sequence.ManifestPath, recovered);
+4
View File
@@ -23,6 +23,7 @@ public abstract class ChronosRepositories
Audit = new AuditRepository(access);
Uploads = new UploadRepository(access);
Schedules = new ScheduleRepository(access);
FrameRemovals = new FrameRemovalRepository(access);
}
public ArchiveRepository Archives { get; }
@@ -41,6 +42,9 @@ public abstract class ChronosRepositories
/// <summary>Scheduled jobs (owner review 2, R10).</summary>
public ScheduleRepository Schedules { get; }
/// <summary>Tombstones of the photos removed from sequences (owner review 2, R6).</summary>
public FrameRemovalRepository FrameRemovals { get; }
}
/// <summary>
@@ -0,0 +1,14 @@
-- Tombstones of photos removed from sequences (owner review 2, R6): a photo deleted into the archive's trash (reason 0)
-- or replaced by a converted file (reason 1, with the replacement's SHA-256). The sidecar's "removed" list is the truth;
-- the index writes these rows from it, so a rebuild keeps them. Sync never offers a tombstoned photo back, and an upload
-- of that content into the sequence is answered as already there. Mirrors sqlite/0008_frame_removals.sql.
CREATE TABLE frame_removals (
sequence_id uuid NOT NULL REFERENCES sequences (id) ON DELETE CASCADE,
sha256 text NOT NULL,
replacement_sha256 text,
reason integer NOT NULL DEFAULT 0,
removed_at timestamptz NOT NULL,
PRIMARY KEY (sequence_id, sha256)
);
CREATE INDEX ix_frame_removals_sha256 ON frame_removals (sha256);
@@ -0,0 +1,14 @@
-- Tombstones of photos removed from sequences (owner review 2, R6): a photo deleted into the archive's trash (reason 0)
-- or replaced by a converted file (reason 1, with the replacement's SHA-256). The sidecar's "removed" list is the truth;
-- the index writes these rows from it, so a rebuild keeps them. Sync never offers a tombstoned photo back, and an upload
-- of that content into the sequence is answered as already there. Mirrors postgres/0008_frame_removals.sql.
CREATE TABLE frame_removals (
sequence_id TEXT NOT NULL REFERENCES sequences (id) ON DELETE CASCADE,
sha256 TEXT NOT NULL,
replacement_sha256 TEXT,
reason INTEGER NOT NULL DEFAULT 0,
removed_at TEXT NOT NULL,
PRIMARY KEY (sequence_id, sha256)
);
CREATE INDEX ix_frame_removals_sha256 ON frame_removals (sha256);
@@ -0,0 +1,71 @@
using System.Globalization;
using System.Text;
using Chronos.Core.Model;
namespace Chronos.Data.Repositories;
/// <summary>
/// Tombstones of the photos removed from sequences (owner review 2, R6; <c>frame_removals</c>), by sequence and SHA-256.
/// The sidecar's <c>removed</c> list is the truth: the index writes a sequence's rows from it whenever it takes the
/// sidecar (<see cref="SyncSequenceAsync"/>), so a rebuild keeps them, and they go with the sequence's row.
/// </summary>
public sealed class FrameRemovalRepository
{
private const string Columns = "sequence_id, sha256, replacement_sha256, reason, removed_at";
/// <summary>Rows one INSERT writes (five parameters each, well inside both engines' limits).</summary>
private const int InsertRows = 200;
private readonly DbAccess _db;
internal FrameRemovalRepository(DbAccess db) => _db = db;
/// <summary>The tombstones of a sequence, oldest first.</summary>
public Task<IReadOnlyList<FrameRemoval>> ListBySequenceAsync(Guid sequenceId, CancellationToken cancellationToken = default) =>
_db.ListAsync($"SELECT {Columns} FROM frame_removals WHERE sequence_id = $1 ORDER BY removed_at, sha256", [sequenceId], Map, cancellationToken);
/// <summary>Whether <paramref name="sha256"/> was removed from the sequence (any reason).</summary>
public async Task<bool> IsRemovedAsync(Guid sequenceId, string sha256, CancellationToken cancellationToken = default)
{
ArgumentException.ThrowIfNullOrEmpty(sha256);
return await _db.ScalarAsync<long>("SELECT count(*) FROM frame_removals WHERE sequence_id = $1 AND sha256 = $2",
[sequenceId, sha256.ToLowerInvariant()], cancellationToken).ConfigureAwait(false) > 0;
}
/// <summary>
/// Replaces the tombstones of a sequence with <paramref name="removals"/> (the sidecar's list; one per SHA-256, the
/// last one given wins). Returns how many rows the sequence has now.
/// </summary>
public Task<int> SyncSequenceAsync(Guid sequenceId, IReadOnlyList<FrameRemoval> removals, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(removals);
var rows = removals.Where(r => !string.IsNullOrEmpty(r.Sha256)).GroupBy(r => r.Sha256.ToLowerInvariant(), StringComparer.Ordinal)
.Select(g => g.Last() with { Sha256 = g.Key, SequenceId = sequenceId }).ToList();
return _db.InTransactionAsync(async session =>
{
await session.ExecuteAsync("DELETE FROM frame_removals WHERE sequence_id = $1", [sequenceId], cancellationToken).ConfigureAwait(false);
for (var start = 0; start < rows.Count; start += InsertRows)
{
var count = Math.Min(InsertRows, rows.Count - start);
var sql = new StringBuilder($"INSERT INTO frame_removals ({Columns}) VALUES ");
var args = new DbParam[count * 5];
for (var i = 0; i < count; i++)
{
var row = rows[start + i];
sql.Append(i > 0 ? ", (" : "(").Append(string.Join(", ", Enumerable.Range(i * 5 + 1, 5).Select(n => "$" + n.ToString(CultureInfo.InvariantCulture))))
.Append(')');
args[i * 5] = row.SequenceId;
args[i * 5 + 1] = row.Sha256;
args[i * 5 + 2] = row.ReplacementSha256?.ToLowerInvariant();
args[i * 5 + 3] = (int)row.Reason;
args[i * 5 + 4] = row.RemovedAt;
}
await session.ExecuteAsync(sql.ToString(), args, cancellationToken).ConfigureAwait(false);
}
return rows.Count;
}, cancellationToken);
}
private static FrameRemoval Map(DbRow r) =>
new(r.GetGuid(0), r.GetString(1), r.GetStringOrNull(2), (RemovalReason)r.GetInt32(3), r.GetDateTimeOffset(4));
}
@@ -1,3 +1,4 @@
using System.Globalization;
using Chronos.Core.Imaging;
using Chronos.Core.Model;
@@ -103,6 +104,15 @@ public sealed record CameraBucket(string? Make, string? Model, int Sequences, lo
public sealed record FormatBucket(ImageFileFormat Format, long Photos, long Bytes);
/// <summary>
/// A value a Library filter offers, as <see cref="SequenceQuery"/> takes it (a year, an exact camera model, a tag), and
/// how many sequences have it; <see cref="Make"/> is a camera model's make, for its label.
/// </summary>
public sealed record ArchiveFacet(string Value, int Sequences, string? Make = null);
/// <summary>The years of first capture, camera models and tags of an archive's sequences (owner review 2, R6: the panel's filters).</summary>
public sealed record ArchiveFacets(IReadOnlyList<ArchiveFacet> Years, IReadOnlyList<ArchiveFacet> Cameras, IReadOnlyList<ArchiveFacet> Tags);
/// <summary>Health counters: sequences needing attention and flagged frames.</summary>
public sealed record ArchiveHealth(
int Unverified,
@@ -389,6 +399,32 @@ public sealed class SequenceRepository
}, cancellationToken);
}
/// <summary>
/// What the Library's filters offer for <paramref name="archiveId"/>: years of first capture (newest first), camera
/// models (most sequences first; one entry per model, as the camera filter matches the model alone) and the tags in use
/// (by name). Only sequence rows are read, never frames.
/// </summary>
public Task<ArchiveFacets> GetFacetsAsync(Guid archiveId, CancellationToken cancellationToken = default)
{
DbParam[] args = [archiveId];
var year = _db.Sql.Year("s.first_capture");
return _db.RunAsync(async session =>
{
var years = await session.QueryListAsync(
$"SELECT {year}, count(*) FROM sequences s WHERE s.archive_id = $1 AND s.first_capture IS NOT NULL GROUP BY 1 ORDER BY 1 DESC", args,
r => new ArchiveFacet(r.GetInt32(0).ToString(CultureInfo.InvariantCulture), r.GetInt32(1)), cancellationToken).ConfigureAwait(false);
var cameras = await session.QueryListAsync(
"SELECT s.camera_model, MIN(s.camera_make), count(*) FROM sequences s " +
"WHERE s.archive_id = $1 AND s.camera_model IS NOT NULL AND s.camera_model <> '' GROUP BY s.camera_model ORDER BY 3 DESC, 1", args,
r => new ArchiveFacet(r.GetString(0), r.GetInt32(2), r.GetStringOrNull(1)), cancellationToken).ConfigureAwait(false);
var tags = await session.QueryListAsync(
"SELECT MIN(t.name), count(*) FROM sequence_tags st JOIN tags t ON t.id = st.tag_id JOIN sequences s ON s.id = st.sequence_id " +
"WHERE s.archive_id = $1 GROUP BY t.name_key ORDER BY t.name_key", args,
r => new ArchiveFacet(r.GetString(0), r.GetInt32(1)), cancellationToken).ConfigureAwait(false);
return new ArchiveFacets(years, cameras, tags);
}, cancellationToken);
}
/// <summary>
/// The sequences of <paramref name="archiveId"/> a rolling verification checks next (owner review 2, R10): those never
/// verified first, then the longest unverified, at most <paramref name="limit"/>. With <paramref name="verifiedBefore"/>
+14 -3
View File
@@ -24,6 +24,9 @@ internal sealed class SyncPositions(ChronosDatabase db, ISyncRemote remote, Guid
/// <summary>The manifest's frames by hash, and with their capture times once fetched.</summary>
private FramePhotos? _hashed, _timed;
/// <summary>The photos either copy removed: a replaced photo is translated as its replacement (owner review 2, R6).</summary>
private SyncTombstones? _tombstones;
/// <summary>The server's frames version the translation to the server's frames is made against.</summary>
public int ServerFrames => manifest.FramesVersion;
@@ -73,7 +76,10 @@ internal sealed class SyncPositions(ChronosDatabase db, ISyncRemote remote, Guid
var frames = await SequenceFrames.ListAsync(db, localId, cancellationToken).ConfigureAwait(false);
if (await db.Sequences.GetAsync(localId, cancellationToken).ConfigureAwait(false) is not { } after) return null;
if (after.FramesVersion == before.FramesVersion)
return new LocalState(after, new FramePhotos(frames.Select(f => (f.Index, new FramePhoto(f.Sha256, f.Size, f.CapturedAt)))));
{
var tombstones = await TombstonesAsync(cancellationToken).ConfigureAwait(false);
return new LocalState(after, new FramePhotos(frames.Select(f => (f.Index, tombstones.Canonical(new FramePhoto(f.Sha256, f.Size, f.CapturedAt))))));
}
}
return null;
}
@@ -87,20 +93,25 @@ internal sealed class SyncPositions(ChronosDatabase db, ISyncRemote remote, Guid
/// </summary>
private async Task<FramePhotos?> ServerAsync(FramePhotos local, CancellationToken cancellationToken)
{
var tombstones = await TombstonesAsync(cancellationToken).ConfigureAwait(false);
if (_hashed is null)
{
if (!OneList(manifest.Frames)) return null;
_hashed = new FramePhotos(manifest.Frames.Select(f => (f.Index, new FramePhoto(f.Sha256, f.Size, null))));
_hashed = new FramePhotos(manifest.Frames.Select(f => (f.Index, tombstones.Canonical(new FramePhoto(f.Sha256, f.Size, null)))));
}
if (_hashed.SameAs(local)) return _hashed;
if (_timed is null)
{
var captured = (await remote.ListFramesAsync(manifest.SequenceId, cancellationToken).ConfigureAwait(false)).ToDictionary(f => f.Id, f => f.CapturedAt);
_timed = new FramePhotos(manifest.Frames.Select(f => (f.Index, new FramePhoto(f.Sha256, f.Size, captured.GetValueOrDefault(f.Id)))));
_timed = new FramePhotos(manifest.Frames.Select(f => (f.Index, tombstones.Canonical(new FramePhoto(f.Sha256, f.Size, captured.GetValueOrDefault(f.Id))))));
}
return _timed;
}
/// <summary>This copy's tombstones and the server's, read once.</summary>
private async Task<SyncTombstones> TombstonesAsync(CancellationToken cancellationToken) =>
_tombstones ??= new SyncTombstones(await db.FrameRemovals.ListBySequenceAsync(localId, cancellationToken).ConfigureAwait(false), manifest.Removed);
/// <summary>Each frame once, at the indices 0…n-1 a sequence's frames always take.</summary>
private static bool OneList(IReadOnlyList<ManifestFrame> frames)
{
+16
View File
@@ -164,6 +164,22 @@ public static class SyncRules
];
}
/// <summary>
/// <see cref="CompareOriginals(IReadOnlyCollection{FramePhoto}, IReadOnlyCollection{FramePhoto})"/> honouring the photos
/// either side removed (owner review 2, R6): a photo the server deleted is not missing there, one this PC deleted is not
/// missing here, and a photo replaced by a converted file on either side is compared as its replacement.
/// </summary>
public static (int MissingRemote, int MissingLocal) CompareOriginals(IReadOnlyCollection<FramePhoto> local, IReadOnlyCollection<FramePhoto> remote,
SyncTombstones tombstones)
{
ArgumentNullException.ThrowIfNull(local);
ArgumentNullException.ThrowIfNull(remote);
ArgumentNullException.ThrowIfNull(tombstones);
if (tombstones.IsEmpty) return CompareOriginals(local, remote);
return CompareOriginals([.. local.Where(p => !tombstones.DeletedRemotely(p.Sha256)).Select(tombstones.Canonical)],
[.. remote.Where(p => !tombstones.DeletedLocally(p.Sha256)).Select(tombstones.Canonical)]);
}
/// <summary>
/// Frames whose proxy the server asks for (it cannot decode their originals, BRIEF §2.3) that this PC holds and its
/// <paramref name="decoder"/> reads: an upload makes and sends them. A local original not hashed yet (a folder adopted
+3 -1
View File
@@ -528,8 +528,10 @@ public sealed class SyncService
var captured = manifest.Frames.Any(f => f.Sha256.Length == 0) || present.Any(f => f.Sha256 is null)
? (await remote.ListFramesAsync(link.RemoteId, cancellationToken).ConfigureAwait(false)).ToDictionary(f => f.Id, f => f.CapturedAt)
: null;
// Photos either side removed are not offered back; one replaced by a converted file counts as its replacement (owner review 2, R6).
var tombstones = new SyncTombstones(await _db.FrameRemovals.ListBySequenceAsync(local.Id, cancellationToken).ConfigureAwait(false), manifest.Removed);
var (missingRemote, missingLocal) = SyncRules.CompareOriginals([.. present.Select(f => new FramePhoto(f.Sha256, f.Size, f.CapturedAt))],
[.. manifest.Frames.Select(f => new FramePhoto(f.Sha256, f.Size, captured?.GetValueOrDefault(f.Id)))]);
[.. manifest.Frames.Select(f => new FramePhoto(f.Sha256, f.Size, captured?.GetValueOrDefault(f.Id)))], tombstones);
// Proxies the server asks for that this PC can make from its originals travel with an upload too (BRIEF §2.3).
var proxies = policy.CanEdit && manifest.Proxies is not null ? SyncRules.ProxiesToSend(manifest, present, Options.Archive.Decoder, captured) : 0;
// Those change without the server's frame counters moving: while some may be made here, the server's next
+81
View File
@@ -0,0 +1,81 @@
using Chronos.Core.Model;
using Chronos.Core.Project;
using Chronos.Protocol;
namespace Chronos.Data.Sync;
/// <summary>
/// The photos each copy of a linked pair removed (owner review 2, R6; BRIEF §14.5): a photo one side deleted is not
/// offered to it again (no upload of what the server deleted, no download of what this PC deleted; local files are never
/// deleted by sync), and a photo one side replaced by a converted file is the same photo as its replacement on either side
/// (an alias: both are compared, matched and translated as the replacement). No I/O.
/// </summary>
public sealed class SyncTombstones
{
/// <summary>Links a replacement chain may have at most (a conversion of a conversion…); longer ones stop there.</summary>
private const int MaxAliasSteps = 8;
private readonly HashSet<string> _deletedLocally;
private readonly HashSet<string> _deletedRemotely;
private readonly Dictionary<string, string> _aliases;
public SyncTombstones(IEnumerable<FrameRemoval> local, IEnumerable<RemovedPhotoDto>? remote)
{
ArgumentNullException.ThrowIfNull(local);
_deletedLocally = new HashSet<string>(StringComparer.Ordinal);
_deletedRemotely = new HashSet<string>(StringComparer.Ordinal);
_aliases = new Dictionary<string, string>(StringComparer.Ordinal);
foreach (var removal in local) Add(removal.Sha256, removal.ReplacementSha256, removal.Reason == RemovalReason.Replaced, _deletedLocally);
foreach (var removal in remote ?? [])
Add(removal.Sha256, removal.Replacement, string.Equals(removal.Reason, Wire(RemovalReason.Replaced), StringComparison.OrdinalIgnoreCase), _deletedRemotely);
}
/// <summary>No photo removed on either side.</summary>
public static SyncTombstones None { get; } = new([], null);
/// <summary>Whether either side removed or replaced anything.</summary>
public bool IsEmpty => _deletedLocally.Count == 0 && _deletedRemotely.Count == 0 && _aliases.Count == 0;
/// <summary>The wire name of a removal reason (<c>deleted</c>, <c>replaced</c>).</summary>
public static string Wire(RemovalReason reason) => reason.ToString().ToLowerInvariant();
/// <summary>The tombstones of a sequence as the manifest carries them.</summary>
public static IReadOnlyList<RemovedPhotoDto> ToDto(IEnumerable<FrameRemoval> removals) =>
[.. removals.Select(r => new RemovedPhotoDto(r.Sha256, r.ReplacementSha256, Wire(r.Reason), r.RemovedAt))];
/// <summary>
/// The SHA-256 a photo is compared as: the end of its replacement chain on either side, lower-case; null or empty
/// (not hashed yet) stays as it is.
/// </summary>
public string? Canonical(string? sha256)
{
if (string.IsNullOrEmpty(sha256)) return sha256;
var current = sha256.ToLowerInvariant();
for (var step = 0; step < MaxAliasSteps && _aliases.TryGetValue(current, out var next); step++) current = next;
return current;
}
/// <summary>The photo as it is compared (<see cref="Canonical(string?)"/>).</summary>
public FramePhoto Canonical(FramePhoto photo)
{
ArgumentNullException.ThrowIfNull(photo);
return photo.IsHashed && _aliases.Count > 0 ? photo with { Sha256 = Canonical(photo.Sha256) } : photo;
}
/// <summary>This PC deleted the photo (or what replaced it): the server's copy is not downloaded.</summary>
public bool DeletedLocally(string? sha256) => Deleted(sha256, _deletedLocally);
/// <summary>The server deleted the photo (or what replaced it): this PC's copy is not uploaded.</summary>
public bool DeletedRemotely(string? sha256) => Deleted(sha256, _deletedRemotely);
private bool Deleted(string? sha256, HashSet<string> deleted) =>
!string.IsNullOrEmpty(sha256) && deleted.Count > 0 && (deleted.Contains(sha256.ToLowerInvariant()) || deleted.Contains(Canonical(sha256)!));
private void Add(string sha256, string? replacement, bool replaced, HashSet<string> deleted)
{
if (string.IsNullOrEmpty(sha256)) return;
var sha = sha256.ToLowerInvariant();
if (replaced && !string.IsNullOrEmpty(replacement)) _aliases[sha] = replacement.ToLowerInvariant();
else deleted.Add(sha);
}
}
+9 -3
View File
@@ -48,13 +48,15 @@ internal sealed class SyncTransfers(SyncService sync)
var frames = (await SequenceFrames.ListAsync(db, local.Id, ct).ConfigureAwait(false)).Where(f => (f.Flags & FrameFlags.Missing) == 0).ToList();
var manifest = remoteId is { } known ? await remote.GetManifestAsync(known, ct).ConfigureAwait(false) : null;
var present = manifest?.Frames.Where(f => f.Sha256.Length > 0).Select(f => f.Sha256.ToLowerInvariant()).ToHashSet(StringComparer.Ordinal) ?? [];
// A photo the server deleted is not sent back; one it replaced by a converted file is there as its replacement (owner review 2, R6).
var tombstones = new SyncTombstones(await db.FrameRemovals.ListBySequenceAsync(local.Id, ct).ConfigureAwait(false), manifest?.Removed);
var present = manifest?.Frames.Where(f => f.Sha256.Length > 0).Select(f => tombstones.Canonical(f.Sha256)!).ToHashSet(StringComparer.Ordinal) ?? [];
// Originals the server holds without a hash (adopted there, not verified) are the ones of their size and capture
// time: the server could not recognise them by content, so they are not sent again.
var adopted = manifest is not null && manifest.Frames.Any(f => f.Sha256.Length == 0)
? await UnhashedAsync(remote, manifest, ct).ConfigureAwait(false)
: new FramePhotos([]);
var pending = new Queue<Frame>(frames.Where(f => (f.Sha256 is null || !present.Contains(f.Sha256.ToLowerInvariant()))
var pending = new Queue<Frame>(frames.Where(f => (f.Sha256 is null || (!present.Contains(tombstones.Canonical(f.Sha256)!) && !tombstones.DeletedRemotely(f.Sha256)))
&& adopted.IndexOf(new FramePhoto(f.Sha256, f.Size, f.CapturedAt)) is null));
var progress = new TransferProgress(context, frames.Count, frames.Count - pending.Count);
await progress.ReportAsync().ConfigureAwait(false);
@@ -205,12 +207,16 @@ internal sealed class SyncTransfers(SyncService sync)
var manifest = await remote.GetManifestAsync(remoteId, ct).ConfigureAwait(false);
var captured = (await remote.ListFramesAsync(remoteId, ct).ConfigureAwait(false)).ToDictionary(f => f.Id, f => f.CapturedAt);
var (have, restore, photos) = local is null ? ([], [], new FramePhotos([])) : await LocalContentAsync(archive, local, ct).ConfigureAwait(false);
// A photo this PC deleted is not fetched again; one replaced here by a converted file is here as its replacement (owner review 2, R6).
var tombstones = local is null ? SyncTombstones.None
: new SyncTombstones(await db.FrameRemovals.ListBySequenceAsync(local.Id, ct).ConfigureAwait(false), manifest.Removed);
if (!tombstones.IsEmpty) have = [.. have.Select(h => tombstones.Canonical(h)!)];
// An original the server has not hashed yet (adopted there, not verified) is here when an original of its size and
// capture time is; each one is fetched on its own and hashed here.
var wanted = manifest.Frames
.Where(f => f.Sha256.Length == 0
? photos.IndexOf(new FramePhoto(null, f.Size, captured.GetValueOrDefault(f.Id))) is null
: !have.Contains(f.Sha256.ToLowerInvariant()))
: !have.Contains(tombstones.Canonical(f.Sha256)!) && !tombstones.DeletedLocally(f.Sha256))
.DistinctBy(f => f.Sha256.Length == 0 ? f.Id.ToString("N") : f.Sha256.ToLowerInvariant()).ToList();
EnsureSpace(paths.Root, wanted.Sum(f => f.Size));
+6 -1
View File
@@ -9,6 +9,10 @@ public sealed record ApiError(string Code, string Message, string? Details = nul
public sealed record ServerLimits(long MaxUploadBytes, int ChunkSizeBytes, int PasswordMinLength = 10);
/// <summary><c>GET /api/v1/server/info</c>.</summary>
/// <param name="Extensions">
/// File extensions the archive files as photos (lower case, no dot): the admin panel's upload dialog offers and sends only
/// these (owner review 2, R3). Null from servers that do not announce them.
/// </param>
public sealed record ServerInfo(
string Name,
string Version,
@@ -16,7 +20,8 @@ public sealed record ServerInfo(
IReadOnlyList<string> Capabilities,
string? TlsFingerprint,
IReadOnlyList<string> Formats,
ServerLimits Limits);
ServerLimits Limits,
IReadOnlyList<string>? Extensions = null);
/// <summary><c>GET /health</c>.</summary>
public sealed record HealthStatus(string Status, string Version, IReadOnlyDictionary<string, string> Checks);
+79
View File
@@ -0,0 +1,79 @@
namespace Chronos.Protocol;
/// <summary>
/// <c>POST /api/v1/sequences/{id}/frames/delete</c> (owner review 2, R6): the photos to move into the archive's trash.
/// <see cref="ExpectedFramesVersion"/> is the frames version the ids were read at: a sequence whose frames changed since
/// answers 409 <c>frames_conflict</c>. <see cref="DryRun"/> only reports what would happen.
/// </summary>
public sealed record FrameDeleteRequest(IReadOnlyList<Guid> FrameIds, int? ExpectedFramesVersion, bool DryRun);
/// <summary>
/// What a photo deletion does (dry run) or did: the photos and bytes that go, the sequence's frames version (as it is on a
/// dry run, after the deletion otherwise) and the trash entry made (null on a dry run).
/// </summary>
public sealed record FrameDeleteResultDto(Guid SequenceId, int Photos, long Bytes, int FramesVersion, int FrameCount, string? TrashEntry, bool DryRun);
/// <summary>
/// An entry of the archive's trash (<c>GET /api/v1/archive/trash</c>): a deleted sequence (<see cref="Kind"/> <c>sequence</c>)
/// or photos deleted from one (<c>photos</c>; <c>replaced</c> for originals a conversion replaced). <see cref="Name"/>
/// identifies it in restore and empty requests.
/// </summary>
public sealed record TrashEntryDto(string Name, string Kind, Guid SequenceId, string Title, string Folder, int Photos, int Files, long Bytes,
string? DeletedBy, DateTimeOffset DeletedAt);
/// <summary><c>GET /api/v1/archive/trash</c>: the entries, newest first, and their total size.</summary>
public sealed record TrashListDto(IReadOnlyList<TrashEntryDto> Entries, long Bytes);
/// <summary>
/// <c>POST /api/v1/archive/trash/{name}/restore</c>: the sequence the entry went back into (a new one when the photos'
/// sequence is gone: <see cref="NewSequence"/>), how many photos came back, and the files kept in the trash because they
/// no longer match their record.
/// </summary>
public sealed record TrashRestoreDto(string Name, string Kind, Guid SequenceId, int Photos, IReadOnlyList<string> Kept, bool NewSequence);
/// <summary>
/// <c>POST /api/v1/archive/trash/empty</c>: erase the entries <see cref="Names"/> (null: every entry). A dry run answers the
/// plan with its <see cref="TrashEmptyPlanDto.Fingerprint"/>; the erase itself must send that fingerprint back (409
/// <c>trash_changed</c> when the trash changed since) and runs as an <c>empty-trash</c> job (202).
/// </summary>
public sealed record TrashEmptyRequest(IReadOnlyList<string>? Names, bool DryRun, string? Fingerprint);
/// <summary>The dry run of emptying the trash: the entries measured on disk, their totals, the fingerprint, and names not in the trash.</summary>
public sealed record TrashEmptyPlanDto(IReadOnlyList<TrashEntryDto> Entries, int Photos, int Files, long Bytes, string Fingerprint, IReadOnlyList<string> Unknown);
/// <summary><c>POST /api/v1/sequences/bulk/delete</c>: move these sequences into the trash (or, with <see cref="DryRun"/>, say what would).</summary>
public sealed record BulkDeleteRequest(IReadOnlyList<Guid> Ids, bool DryRun);
/// <summary><c>POST /api/v1/sequences/bulk/retag</c>: add and remove tags on these sequences (the same edit as a PATCH of their tags).</summary>
public sealed record BulkRetagRequest(IReadOnlyList<Guid> Ids, IReadOnlyList<string>? Add, IReadOnlyList<string>? Remove);
/// <summary>
/// <c>POST /api/v1/sequences/bulk/jobs</c>: queue one job of <see cref="Kind"/> (<c>analyse</c>, <c>deep</c>, <c>proxies</c>,
/// <c>thumbnails</c>, <c>verify</c>) over these sequences.
/// </summary>
public sealed record BulkJobsRequest(IReadOnlyList<Guid> Ids, string Kind);
/// <summary>
/// One sequence of a bulk operation: <see cref="Outcome"/> <c>ok</c>, or <c>skipped</c> with the error code that says why
/// (<see cref="Reason"/>, e.g. <c>not_found</c>, <c>forbidden</c>, <c>sequence_busy</c>) and its localised sentence.
/// </summary>
/// <param name="TrashFolder">For a delete: where the folder goes (or went) in the trash; null when it has no folder.</param>
public sealed record BulkItemResult(Guid Id, string Outcome, string? Reason = null, string? Message = null, string? TrashFolder = null);
/// <summary>
/// The result of a bulk operation: one item per id asked for, the counts, the photos and bytes a delete moves (or moved),
/// and the job a bulk job request queued (null when nothing was queued).
/// </summary>
public sealed record BulkResultDto(IReadOnlyList<BulkItemResult> Items, int Ok, int Skipped, bool DryRun, int Photos = 0, long Bytes = 0, JobDto? Job = null);
/// <summary>
/// A value a Library filter offers: <see cref="Value"/> as <c>GET /api/v1/sequences</c> takes it (<c>year</c>, <c>camera</c>,
/// <c>tag</c>), the sequences that have it, and the label a menu shows when it differs (a camera model with its make).
/// </summary>
public sealed record FacetDto(string Value, int Sequences, string? Label = null);
/// <summary>
/// <c>GET /api/v1/sequences/facets</c> (owner review 2, R6): the years of first capture (newest first), camera models (most
/// sequences first) and tags in use (by name) of the archive's sequences, for the admin panel's Library filters.
/// </summary>
public sealed record LibraryFacetsDto(IReadOnlyList<FacetDto> Years, IReadOnlyList<FacetDto> Cameras, IReadOnlyList<FacetDto> Tags);
+14
View File
@@ -73,4 +73,18 @@ namespace Chronos.Protocol;
[JsonSerializable(typeof(CreateScheduleRequest))]
[JsonSerializable(typeof(UpdateScheduleRequest))]
[JsonSerializable(typeof(ScheduleRunDto))]
[JsonSerializable(typeof(RemovedPhotoDto))]
[JsonSerializable(typeof(FrameDeleteRequest))]
[JsonSerializable(typeof(FrameDeleteResultDto))]
[JsonSerializable(typeof(TrashEntryDto))]
[JsonSerializable(typeof(TrashListDto))]
[JsonSerializable(typeof(TrashRestoreDto))]
[JsonSerializable(typeof(TrashEmptyRequest))]
[JsonSerializable(typeof(TrashEmptyPlanDto))]
[JsonSerializable(typeof(BulkDeleteRequest))]
[JsonSerializable(typeof(BulkRetagRequest))]
[JsonSerializable(typeof(BulkJobsRequest))]
[JsonSerializable(typeof(BulkItemResult))]
[JsonSerializable(typeof(BulkResultDto))]
[JsonSerializable(typeof(LibraryFacetsDto))]
public sealed partial class ProtocolJson : JsonSerializerContext;
+12 -1
View File
@@ -75,6 +75,10 @@ public sealed record FrameDto(
/// <summary><c>GET /api/v1/sequences/{id}/manifest</c>: what a client needs to diff a sequence (BRIEF §14.5).</summary>
/// <param name="Proxies">How to make the proxies the server asks for (<see cref="ManifestFrame.WantsProxy"/>); null when it makes none.</param>
/// <param name="Removed">
/// Tombstones of the photos removed from the sequence (owner review 2, R6): a client never offers them back, and counts a
/// replaced photo and its replacement as one; null from servers before owner review 2 and when there are none.
/// </param>
public sealed record SequenceManifest(
Guid SequenceId,
int FramesVersion,
@@ -83,7 +87,14 @@ public sealed record SequenceManifest(
IReadOnlyList<string> Tags,
IReadOnlyList<ManifestFrame> Frames,
IReadOnlyList<RenderDto> Renders,
ProxySpec? Proxies = null);
ProxySpec? Proxies = null,
IReadOnlyList<RemovedPhotoDto>? Removed = null);
/// <summary>
/// A photo removed from a sequence (owner review 2, R6): its lower-case hex SHA-256, the replacement's when a conversion
/// replaced it, why (<c>deleted</c>, <c>replaced</c>) and when.
/// </summary>
public sealed record RemovedPhotoDto(string Sha256, string? Replacement, string Reason, DateTimeOffset At);
/// <summary>One frame of a manifest: its content, whether the server has a proxy and thumbnail of it, and its flags.</summary>
/// <param name="Sha256">Lower-case hex SHA-256; empty while the server has not hashed it (a folder adopted and not verified yet).</param>
+129
View File
@@ -25,6 +25,8 @@
--error: light-dark(#c42b1c, #f0625d);
--shadow: light-dark(rgba(0, 0, 0, .18), rgba(0, 0, 0, .4));
--scrim: light-dark(rgba(0, 0, 0, .25), rgba(0, 0, 0, .6));
/* Badges drawn over photos (counts, numbers, the cover mark) read the same on light and dark pages. */
--on-photo: rgba(0, 0, 0, .6);
--radius: 6px;
--radius-card: 8px;
--font: "Segoe UI Variable Text", "Segoe UI", system-ui, -apple-system, "Noto Sans", sans-serif;
@@ -293,6 +295,133 @@ dialog.dialog p { margin: 0; color: var(--text-muted); }
.toast { width: 420px; max-width: calc(100vw - 48px); padding: 12px 14px; color: var(--text); background: var(--card); border: 1px solid var(--stroke); border-inline-start: 3px solid var(--accent); border-radius: var(--radius-card); box-shadow: 0 4px 16px var(--shadow); }
.toast.error { border-inline-start-color: var(--error); }
/* Directional glyphs (icons.js) point along the reading direction; inside a left-to-right island (photos, time) they do not turn. */
svg.directional:dir(rtl) { transform: scaleX(-1); }
.btn svg, .tag svg { flex: none; }
dialog.dialog .dialog-list { margin: 0; padding-block: 8px; padding-inline: 28px 12px; max-height: 200px; overflow: auto; border: 1px solid var(--stroke);
border-radius: var(--radius); background: var(--bg); font-size: 12px; overflow-wrap: anywhere; }
dialog.dialog .dialog-list:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }
dialog.dialog .field-label strong { color: var(--text); }
/* Library (owner review 2, R6): toolbar, cards (DESIGN §4: 16:9 thumbnail, count badge, check box on hover or selection,
selected = accent border and glow), list rows, the selection's bar, a sequence's photos and the photo viewer. */
.toolbar { display: flex; flex-wrap: wrap; align-items: center; gap: 8px; }
.toolbar .input.small { height: 32px; max-width: 200px; }
.toolbar select.active { border-color: var(--accent); color: var(--accent); }
.seq-items { min-width: 0; }
.seq-items.cards { display: grid; grid-template-columns: repeat(auto-fill, minmax(min(220px, 100%), 1fr)); gap: 16px; padding: 16px; }
.seq-items > .empty { grid-column: 1 / -1; }
/* Shift+click picks a range: it selects no text. */
.seq-card, .seq-row, .frame { position: relative; cursor: pointer; outline: none; user-select: none; }
.seq-card { display: flex; flex-direction: column; min-width: 0; background: var(--card); border: 1px solid var(--stroke); border-radius: var(--radius-card); overflow: hidden; }
.seq-card:hover { border-color: var(--stroke-strong); }
.seq-card:focus-visible, .seq-row:focus-visible, .frame:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }
.seq-card[aria-selected="true"], .frame[aria-selected="true"] { border-color: var(--accent); box-shadow: 0 0 0 3px var(--accent-selected); }
.thumb { position: relative; display: block; aspect-ratio: 16 / 9; background: var(--card-pressed); overflow: hidden; }
.thumb .placeholder { position: absolute; inset: 0; display: grid; place-items: center; color: var(--text-faint); }
.thumb .placeholder svg { width: 28px; height: 28px; }
.thumb img { position: relative; display: block; width: 100%; height: 100%; object-fit: cover; }
.thumb img.failed { visibility: hidden; }
.seq-check { position: absolute; top: 8px; inset-inline-start: 8px; width: 18px; height: 18px; z-index: 1; opacity: 0; cursor: pointer; }
.seq-card:hover .seq-check, .seq-card:focus-visible .seq-check, .frame:hover .seq-check, .frame:focus-visible .seq-check,
.selecting .seq-check, [aria-selected="true"] > .seq-check { opacity: 1; }
.seq-card .count { position: absolute; top: 8px; inset-inline-end: 8px; padding: 0 6px; border-radius: 8px; background: var(--on-photo); color: #fff; font-size: 11px; }
.seq-card .info { display: flex; flex-direction: column; gap: 4px; padding: 8px 10px 10px; min-width: 0; }
.seq-card .facts { font-size: 12px; color: var(--text-muted); }
.chips-row { display: flex; flex-wrap: wrap; gap: 4px 8px; font-size: 11px; color: var(--text-muted); }
.st { white-space: nowrap; }
.st.ok { color: var(--success); }
.st.off { color: var(--text-faint); }
.st.warn { color: var(--warning); }
.st.err { color: var(--error); }
/* List: the rows are one grid's subgrids, so every column fits its widest cell (as .table). */
.seq-items.rows { display: grid; grid-template-columns: max-content 64px minmax(160px, 2fr) minmax(80px, 1fr) max-content max-content max-content; column-gap: 12px; }
.seq-items.rows > .seq-head, .seq-items.rows > .seq-row { grid-column: 1 / -1; display: grid; grid-template-columns: subgrid; align-items: center; padding: 0 18px; }
.seq-items.rows > .seq-head { font-size: 11px; color: var(--text-muted); padding-block: 10px; border-bottom: 1px solid var(--stroke); white-space: nowrap; }
.seq-items.rows > .empty { grid-column: 1 / -1; }
.seq-row { min-height: 52px; border-bottom: 1px solid var(--stroke); }
.seq-row:hover { background: var(--card-hover); }
.seq-row[aria-selected="true"] { background: var(--accent-selected); }
.seq-row .seq-check { position: static; opacity: 1; }
.seq-row .thumb { width: 64px; border-radius: 4px; }
.seq-row .thumb .placeholder svg { width: 16px; height: 16px; }
@media (max-width: 900px) {
.seq-items.rows { grid-template-columns: max-content 64px minmax(120px, 1fr) max-content; }
.seq-items.rows .col-camera, .seq-items.rows .col-size, .seq-items.rows .col-date { display: none; }
}
/* The selection's actions stay in view at the foot of the window while the list scrolls. */
.mass-bar { position: sticky; bottom: 16px; z-index: 4; display: flex; flex-wrap: wrap; align-items: center; gap: 8px; padding: 8px 12px;
background: var(--surface); border: 1px solid var(--accent); border-radius: var(--radius-card); box-shadow: 0 4px 16px var(--shadow); }
/* A sequence: cover, editable fields and facts side by side, stacked on narrow screens. */
.seq-detail { grid-template-columns: minmax(180px, 280px) minmax(0, 1fr) minmax(220px, 320px); gap: 20px; align-items: start; }
.seq-cover .thumb { border-radius: var(--radius); }
.input.heading { height: 38px; font-size: 18px; font-weight: 600; border-color: transparent; background: transparent; padding-inline: 8px; margin-inline-start: -8px; }
.input.heading:hover { border-color: var(--stroke); }
.input.heading:focus { background: var(--card); }
textarea.input.notes { height: auto; min-height: 64px; padding: 6px 10px; resize: vertical; font: inherit; }
.tag-editor { display: flex; flex-wrap: wrap; align-items: center; gap: 6px; }
.tag-list { display: contents; }
.tag { display: inline-flex; align-items: center; gap: 2px; height: 24px; padding-inline: 10px 2px; border: 1px solid var(--stroke); border-radius: 12px; background: var(--card); color: var(--text); font-size: 12px; }
.tag-editor .input.small { width: 140px; }
.btn.tiny { width: 20px; min-width: 20px; height: 20px; border-radius: 10px; }
.btn.tiny svg { width: 12px; height: 12px; }
.stars { display: flex; gap: 2px; }
.btn.star { color: var(--text-faint); }
.btn.star[aria-pressed="true"] { color: var(--sun); border-color: transparent; box-shadow: none; }
.seq-facts, .viewer-meta { display: grid; grid-template-columns: max-content minmax(0, 1fr); gap: 6px 14px; margin: 0; font-size: 12px; }
.seq-facts > div, .viewer-meta > div { display: contents; }
.seq-facts dt, .viewer-meta dt { color: var(--text-muted); }
.seq-facts dd, .viewer-meta dd { margin: 0; overflow-wrap: anywhere; min-width: 0; }
.panel-head.wrap { flex-wrap: wrap; }
.frame-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(140px, 1fr)); gap: 8px; padding: 12px 18px; }
.frame-grid > .frame-empty { grid-column: 1 / -1; }
/* Thousands of photos: the browser lays out and paints only those near the view. */
.frame { content-visibility: auto; contain-intrinsic-size: auto 90px; border: 1px solid var(--stroke); border-radius: var(--radius); overflow: hidden; background: var(--card); }
.frame .thumb { aspect-ratio: 3 / 2; }
.frame-no { position: absolute; bottom: 4px; inset-inline-end: 4px; padding: 0 5px; border-radius: 6px; background: var(--on-photo); color: #fff; font-size: 10px; }
.frame-badge { position: absolute; top: 4px; inset-inline-end: 4px; display: grid; place-items: center; width: 22px; height: 22px; border-radius: 11px; background: var(--on-photo); color: #fff; }
.frame-badge.hero { color: var(--sun); }
.frame-badge.warn { top: auto; bottom: 4px; inset-inline: 4px auto; color: var(--warning); }
.table.renders { grid-template-columns: minmax(100px, 1.4fr) max-content max-content max-content max-content max-content; }
.table.trash { grid-template-columns: max-content minmax(140px, 2fr) max-content max-content minmax(60px, 1fr) max-content max-content; }
.table.trash.fit-1 { grid-template-columns: max-content minmax(120px, 2fr) max-content max-content max-content max-content; }
.table.trash.fit-1 .col-by { display: none; }
dialog.viewer { width: min(1100px, calc(100vw - 32px)); padding: 16px 18px; }
dialog.viewer[open] { display: grid; grid-template-columns: minmax(0, 1fr) 240px; grid-template-rows: auto minmax(0, 1fr) auto; gap: 12px 16px; }
.viewer-head { grid-column: 1 / -1; display: flex; align-items: center; gap: 10px; min-width: 0; }
.viewer-stage { position: relative; display: grid; place-items: center; min-height: 240px; max-height: 72vh; background: #000; border-radius: var(--radius); overflow: hidden; }
.viewer-stage img { max-width: 100%; max-height: 72vh; object-fit: contain; display: block; }
.viewer-stage img.failed { display: none; }
.viewer-stage .placeholder { position: absolute; color: var(--text-faint); }
.viewer-stage img:not(.failed) + .placeholder { display: none; }
.viewer-meta { align-content: start; }
dialog.viewer .buttons { grid-column: 1 / -1; }
@media (max-width: 900px) {
.seq-detail { grid-template-columns: minmax(0, 1fr); }
dialog.viewer[open] { grid-template-columns: minmax(0, 1fr); }
}
@media (forced-colors: active) {
.seq-card[aria-selected="true"], .frame[aria-selected="true"], .seq-row[aria-selected="true"] { outline: 3px solid Highlight; }
}
/* Upload dialog (owner review 2, R3, upload.js): the target, a drop zone, the photos with their state, the total. */
dialog.dialog.upload { width: 640px; }
.upload-choice { border: 0; margin: 0; padding: 0; display: flex; flex-wrap: wrap; gap: 8px 20px; }
.upload-choice legend { color: var(--text-muted); padding: 0; margin-block-end: 8px; }
.upload-existing { display: grid; gap: 8px; margin-block-start: 10px; }
.upload-new { display: grid; gap: 6px; margin-block-start: 10px; color: var(--text-muted); }
.input.list { height: auto; padding: 4px 0; }
.input.list option { padding: 3px 10px; }
.drop { display: flex; align-items: center; flex-wrap: wrap; gap: 12px; padding: 14px; border: 1px dashed var(--stroke-strong); border-radius: var(--radius-card); color: var(--text-muted); }
dialog.upload.dragging .drop { border-color: var(--accent); background: var(--accent-selected); color: var(--text); }
.upload-files { list-style: none; margin: 0; padding: 0; max-height: 40vh; overflow-y: auto; display: grid; grid-template-columns: minmax(0, 1fr) max-content minmax(110px, 170px) 28px; column-gap: 12px; align-content: start; }
.upload-file { grid-column: 1 / -1; display: grid; grid-template-columns: subgrid; align-items: center; min-height: 36px; border-bottom: 1px solid var(--stroke); }
.upload-file .status { display: flex; align-items: center; gap: 8px; min-width: 0; font-size: 12px; }
.upload-file .status svg.bar { flex: 1 1 0; min-width: 24px; }
.upload-file .btn.icon.small { width: 28px; min-width: 28px; }
.upload-total { display: flex; align-items: center; gap: 12px; font-size: 12px; }
.upload-total .progress-cell { flex: 1 1 0; }
/* About: the last group of Settings (owner review 2); #/about scrolls to it below the sticky header and focuses its heading. */
.about { scroll-margin-block-start: 84px; }
.about h2:focus { outline: none; }
+11 -4
View File
@@ -17,14 +17,19 @@ function csrfToken() {
return m ? decodeURIComponent(m[1]) : "";
}
async function request(method, url, body) {
/**
* One API call: a JSON body, or with raw the bytes of a Blob (upload chunks, sent as octet-stream). An abort through
* signal rejects with the browser's AbortError; any other failure to reach the server with ApiFailure status 0.
*/
async function request(method, url, body, { raw = false, signal } = {}) {
const headers = { Accept: "application/json", "Accept-Language": culture() };
if (body !== undefined) headers["Content-Type"] = "application/json";
if (body !== undefined) headers["Content-Type"] = raw ? "application/octet-stream" : "application/json";
if (method !== "GET") headers["X-CSRF-Token"] = csrfToken();
let res;
try {
res = await fetch(url, { method, headers, credentials: "same-origin", body: body === undefined ? undefined : JSON.stringify(body) });
} catch {
res = await fetch(url, { method, headers, credentials: "same-origin", signal, body: body === undefined ? undefined : raw ? body : JSON.stringify(body) });
} catch (err) {
if (signal?.aborted) throw err;
throw new ApiFailure(0, "unreachable", "");
}
if (res.status === 401 && url !== "/api/v1/auth/login") {
@@ -49,6 +54,8 @@ export const api = {
put: (url, body) => request("PUT", url, body),
patch: (url, body) => request("PATCH", url, body),
del: (url) => request("DELETE", url),
/** PUT of a Blob's bytes (an upload chunk) with the session's headers: the parsed JSON answer; failures as the calls above. */
putBytes: (url, blob, signal) => request("PUT", url, blob, { raw: true, signal }),
user: () => currentUser,
/** Restores the session from the cookie; null when signed out. */
+3 -2
View File
@@ -5,8 +5,9 @@ import { icons } from "./icons.js";
import { escapeHtml, attr, errorText, nativeName, formatNumber, fitColumns } from "./ui.js";
const app = document.getElementById("app");
// The menu: its pages from the top, then the ones docked at its foot above the account (owner review 2).
const topPages = ["dashboard", "users", "archive", "jobs", "logs"];
// The menu: its pages from the top, then the ones docked at its foot above the account (owner review 2). The Library
// manages sequences and photos without editing them (owner review 2, R6).
const topPages = ["dashboard", "library", "users", "archive", "jobs", "logs"];
const bottomPages = ["settings"];
const pages = [...topPages, ...bottomPages];
/** Routes of old bookmarks and where they open now: About is the last group of Settings (owner review 2). */
+13
View File
@@ -61,6 +61,19 @@ export function detailText(entry) {
const shown = [scheduleNameIn(parts), scheduleAction(action), recurrence ? recurrenceText(recurrence) : code];
return (off ? [...shown, t("Admin.Schedules.Off")] : shown).join(" · ");
}
// Owner review 2, R6: "3 · photos-<entry>", "<entry> · Harbour sunset", "2 · 1048576 · <entries>".
case "frames_deleted": {
const [count] = details.split(" · ");
return /^\d+$/.test(count) ? plural("Admin.Dashboard.PhotoCount", Number(count)) : details;
}
case "trash_restored": {
const [, ...title] = details.split(" · ");
return title.length > 0 ? title.join(" · ") : details;
}
case "trash_emptied": {
const [count, size] = details.split(" · ");
return /^\d+$/.test(count) && /^\d+$/.test(size ?? "") ? `${plural("Admin.Trash.EntryCount", Number(count))} · ${formatBytes(Number(size))}` : details;
}
default:
return details;
}
@@ -0,0 +1,42 @@
// Module worker of the upload dialog (owner review 2, R3): hashes a picked photo off the page's thread, reading it in
// 8 MiB blocks so a large RAW never sits in memory whole. Before its first hash it runs the SHA-256 self-test and, if
// any check fails, refuses every request (fail closed): the dialog then uploads nothing.
//
// Messages in: { id, file } a File or Blob to hash; requests are answered one after the other
// Messages out: { id, type: "progress", done, total }
// { id, type: "done", sha256 } lower-case hex
// { id, type: "error", reason: "self_test" | "read", detail }
import { Sha256, toHex, selfTest } from "./sha256.js";
const BLOCK = 8 * 1024 * 1024;
let verdict = null;
let queue = Promise.resolve();
self.addEventListener("message", (e) => {
const { id, file } = e.data ?? {};
queue = queue.then(() => hash(id, file));
});
async function hash(id, file) {
try {
verdict ??= selfTest().catch(() => "self_test_error");
const failed = await verdict;
if (failed) {
self.postMessage({ id, type: "error", reason: "self_test", detail: failed });
return;
}
const sha = new Sha256();
const total = file.size;
for (let done = 0; done < total;) {
const bytes = new Uint8Array(await file.slice(done, Math.min(done + BLOCK, total)).arrayBuffer());
// A file that shrank while it was read must not end with a digest of part of it.
if (bytes.length === 0) throw new Error("short read");
sha.update(bytes);
done += bytes.length;
self.postMessage({ id, type: "progress", done, total });
}
self.postMessage({ id, type: "done", sha256: toHex(sha.digest()) });
} catch (err) {
self.postMessage({ id, type: "error", reason: "read", detail: String(err?.name ?? err) });
}
}
+17 -2
View File
@@ -1,11 +1,13 @@
// Generated by branding/ui-icons/icons.py (same 16-px set as the desktop apps). Do not edit by hand.
// Glyphs that point along the reading direction carry class="directional" (mirrored in right-to-left pages, admin.css).
export const icons = {
dashboard: `<svg viewBox="0 0 16 16" width="16" height="16" aria-hidden="true"><path d="M2.5 1.5 H6.0 A1 1 0 0 1 7.0 2.5 V6.0 A1 1 0 0 1 6.0 7.0 H2.5 A1 1 0 0 1 1.5 6.0 V2.5 A1 1 0 0 1 2.5 1.5 ZM10 1.5 H13.5 A1 1 0 0 1 14.5 2.5 V6.0 A1 1 0 0 1 13.5 7.0 H10 A1 1 0 0 1 9 6.0 V2.5 A1 1 0 0 1 10 1.5 ZM2.5 9 H6.0 A1 1 0 0 1 7.0 10 V13.5 A1 1 0 0 1 6.0 14.5 H2.5 A1 1 0 0 1 1.5 13.5 V10 A1 1 0 0 1 2.5 9 ZM10 9 H13.5 A1 1 0 0 1 14.5 10 V13.5 A1 1 0 0 1 13.5 14.5 H10 A1 1 0 0 1 9 13.5 V10 A1 1 0 0 1 10 9 Z" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>`,
library: `<svg viewBox="0 0 16 16" width="16" height="16" aria-hidden="true"><path d="M9.600000000000001 5.6 A1.2 1.2 0 1 0 12.0 5.6 A1.2 1.2 0 1 0 9.600000000000001 5.6 Z" fill="currentColor"/><path d="M3.0 2.5 H13.0 A1.5 1.5 0 0 1 14.5 4.0 V12.0 A1.5 1.5 0 0 1 13.0 13.5 H3.0 A1.5 1.5 0 0 1 1.5 12.0 V4.0 A1.5 1.5 0 0 1 3.0 2.5 Z M1.5 11 L5.5 7 L9 10.5 L11 8.5 L14.5 12" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>`,
users: `<svg viewBox="0 0 16 16" width="16" height="16" aria-hidden="true"><path d="M5 5 A3 3 0 1 0 11 5 A3 3 0 1 0 5 5 Z M2.5 14 A5.5 5.5 0 0 1 13.5 14" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>`,
archive: `<svg viewBox="0 0 16 16" width="16" height="16" aria-hidden="true"><path d="M2 4.5 H14 V13.5 H2 Z M2 2 H14 V4.5 H2 Z M6 8 H10" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>`,
jobs: `<svg viewBox="0 0 16 16" width="16" height="16" aria-hidden="true"><path d="M3 8 H13 M3 4 H13 M3 12 H9" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>`,
jobs: `<svg class="directional" viewBox="0 0 16 16" width="16" height="16" aria-hidden="true"><path d="M3 8 H13 M3 4 H13 M3 12 H9" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>`,
settings: `<svg viewBox="0 0 16 16" width="16" height="16" aria-hidden="true"><path d="M7.15 3.48 L7.4 1.53 A6.5 6.5 0 0 1 8.6 1.53 L8.85 3.48 A4.6 4.6 0 0 1 10.6 4.2 L12.15 3 A6.5 6.5 0 0 1 13 3.85 L11.8 5.4 A4.6 4.6 0 0 1 12.52 7.15 L14.47 7.4 A6.5 6.5 0 0 1 14.47 8.6 L12.52 8.85 A4.6 4.6 0 0 1 11.8 10.6 L13 12.15 A6.5 6.5 0 0 1 12.15 13 L10.6 11.8 A4.6 4.6 0 0 1 8.85 12.52 L8.6 14.47 A6.5 6.5 0 0 1 7.4 14.47 L7.15 12.52 A4.6 4.6 0 0 1 5.4 11.8 L3.85 13 A6.5 6.5 0 0 1 3 12.15 L4.2 10.6 A4.6 4.6 0 0 1 3.48 8.85 L1.53 8.6 A6.5 6.5 0 0 1 1.53 7.4 L3.48 7.15 A4.6 4.6 0 0 1 4.2 5.4 L3 3.85 A6.5 6.5 0 0 1 3.85 3 L5.4 4.2 A4.6 4.6 0 0 1 7.15 3.48 Z M6.3 8 A1.7 1.7 0 1 0 9.7 8 A1.7 1.7 0 1 0 6.3 8 Z" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>`,
logs: `<svg viewBox="0 0 16 16" width="16" height="16" aria-hidden="true"><path d="M3.5 1.5 H9.5 L12.5 4.5 V14.5 H3.5 Z M5.5 7 H10.5 M5.5 9.5 H10.5 M5.5 12 H8.5" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>`,
logs: `<svg class="directional" viewBox="0 0 16 16" width="16" height="16" aria-hidden="true"><path d="M3.5 1.5 H9.5 L12.5 4.5 V14.5 H3.5 Z M5.5 7 H10.5 M5.5 9.5 H10.5 M5.5 12 H8.5" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>`,
menu: `<svg viewBox="0 0 16 16" width="16" height="16" aria-hidden="true"><path d="M2.5 4 H13.5 M2.5 8 H13.5 M2.5 12 H13.5" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>`,
power: `<svg viewBox="0 0 16 16" width="16" height="16" aria-hidden="true"><path d="M8 1.8 V7.5 M11.54 4.59 A5.5 5.5 0 1 1 4.46 4.59" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>`,
moon: `<svg viewBox="0 0 16 16" width="16" height="16" aria-hidden="true"><path d="M9.5 1.8 A6.5 6.5 0 1 0 14.2 11.2 A5.5 5.5 0 0 1 9.5 1.8 Z" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>`,
@@ -14,4 +16,17 @@ export const icons = {
plus: `<svg viewBox="0 0 16 16" width="16" height="16" aria-hidden="true"><path d="M8 3 V13 M3 8 H13" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>`,
copy: `<svg viewBox="0 0 16 16" width="16" height="16" aria-hidden="true"><path d="M6.5 5 H13.0 A1.5 1.5 0 0 1 14.5 6.5 V13.0 A1.5 1.5 0 0 1 13.0 14.5 H6.5 A1.5 1.5 0 0 1 5 13.0 V6.5 A1.5 1.5 0 0 1 6.5 5 Z M11 5 V2.5 A1 1 0 0 0 10 1.5 H2.5 A1 1 0 0 0 1.5 2.5 V10 A1 1 0 0 0 2.5 11 H5" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>`,
search: `<svg viewBox="0 0 16 16" width="16" height="16" aria-hidden="true"><path d="M2.5 7 A4.5 4.5 0 1 0 11.5 7 A4.5 4.5 0 1 0 2.5 7 Z M10.4 10.4 L14 14" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>`,
grid: `<svg viewBox="0 0 16 16" width="16" height="16" aria-hidden="true"><path d="M2.5 1.5 H6.0 A1 1 0 0 1 7.0 2.5 V6.0 A1 1 0 0 1 6.0 7.0 H2.5 A1 1 0 0 1 1.5 6.0 V2.5 A1 1 0 0 1 2.5 1.5 ZM10 1.5 H13.5 A1 1 0 0 1 14.5 2.5 V6.0 A1 1 0 0 1 13.5 7.0 H10 A1 1 0 0 1 9 6.0 V2.5 A1 1 0 0 1 10 1.5 ZM2.5 9 H6.0 A1 1 0 0 1 7.0 10 V13.5 A1 1 0 0 1 6.0 14.5 H2.5 A1 1 0 0 1 1.5 13.5 V10 A1 1 0 0 1 2.5 9 ZM10 9 H13.5 A1 1 0 0 1 14.5 10 V13.5 A1 1 0 0 1 13.5 14.5 H10 A1 1 0 0 1 9 13.5 V10 A1 1 0 0 1 10 9 Z" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>`,
list: `<svg class="directional" viewBox="0 0 16 16" width="16" height="16" aria-hidden="true"><path d="M5.5 4 H13.5 M5.5 8 H13.5 M5.5 12 H13.5 M2.5 4 H2.6 M2.5 8 H2.6 M2.5 12 H2.6" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>`,
trash: `<svg viewBox="0 0 16 16" width="16" height="16" aria-hidden="true"><path d="M2.5 4 H13.5 M6 4 V2.5 H10 V4 M3.8 4 L4.6 14 H11.4 L12.2 4 M6.6 6.8 V11.2 M9.4 6.8 V11.2" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>`,
upload: `<svg viewBox="0 0 16 16" width="16" height="16" aria-hidden="true"><path d="M8 10.5 V2.5 M4.5 6 L8 2.5 L11.5 6 M2.5 13.5 H13.5" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>`,
download: `<svg viewBox="0 0 16 16" width="16" height="16" aria-hidden="true"><path d="M8 2 V10 M4.5 6.5 L8 10 L11.5 6.5 M2.5 13.5 H13.5" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>`,
back: `<svg class="directional" viewBox="0 0 16 16" width="16" height="16" aria-hidden="true"><path d="M13 8 H3 M7 4 L3 8 L7 12" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>`,
previous: `<svg class="directional" viewBox="0 0 16 16" width="16" height="16" aria-hidden="true"><path d="M10 4 L6 8 L10 12" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>`,
next: `<svg class="directional" viewBox="0 0 16 16" width="16" height="16" aria-hidden="true"><path d="M6 4 L10 8 L6 12" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>`,
star: `<svg viewBox="0 0 16 16" width="16" height="16" aria-hidden="true"><path d="M8 1.8 L9.9 5.8 L14.2 6.3 L11 9.3 L11.9 13.6 L8 11.4 L4.1 13.6 L5 9.3 L1.8 6.3 L6.1 5.8 Z" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>`,
starFilled: `<svg viewBox="0 0 16 16" width="16" height="16" aria-hidden="true"><path d="M8 1.8 L9.9 5.8 L14.2 6.3 L11 9.3 L11.9 13.6 L8 11.4 L4.1 13.6 L5 9.3 L1.8 6.3 L6.1 5.8 Z" fill="currentColor"/></svg>`,
hero: `<svg viewBox="0 0 16 16" width="16" height="16" aria-hidden="true"><path d="M8 4.8 L8.9 6.9 L11.1 7.1 L9.4 8.5 L9.9 10.7 L8 9.5 L6.1 10.7 L6.6 8.5 L4.9 7.1 L7.1 6.9 Z" fill="currentColor"/><path d="M3.0 2.5 H13.0 A1.5 1.5 0 0 1 14.5 4.0 V12.0 A1.5 1.5 0 0 1 13.0 13.5 H3.0 A1.5 1.5 0 0 1 1.5 12.0 V4.0 A1.5 1.5 0 0 1 3.0 2.5 Z" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>`,
image: `<svg viewBox="0 0 16 16" width="16" height="16" aria-hidden="true"><path d="M9.600000000000001 5.6 A1.2 1.2 0 1 0 12.0 5.6 A1.2 1.2 0 1 0 9.600000000000001 5.6 Z" fill="currentColor"/><path d="M3.0 2.5 H13.0 A1.5 1.5 0 0 1 14.5 4.0 V12.0 A1.5 1.5 0 0 1 13.0 13.5 H3.0 A1.5 1.5 0 0 1 1.5 12.0 V4.0 A1.5 1.5 0 0 1 3.0 2.5 Z M1.5 11 L5.5 7 L9 10.5 L11 8.5 L14.5 12" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>`,
warning: `<svg viewBox="0 0 16 16" width="16" height="16" aria-hidden="true"><path d="M8 1.8 L14.8 13.8 H1.2 Z M8 6.2 V9.6 M8 11.7 V11.8" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>`,
};
@@ -1,4 +1,5 @@
// Archive (BRIEF §14.8): naming templates, proxy policy, scan/rebuild/verify/maintenance, statistics.
// Archive (BRIEF §14.8): naming templates, proxy policy, scan/rebuild/verify/maintenance, statistics, and the way to the
// archive's trash (the Library's trash view, owner review 2, R6).
import { t, plural, applyStrings } from "../i18n.js";
import { escapeHtml, attr, formatBytes, formatNumber, bar, storageTip, writeVolumeLine, columns, toast, errorText, emptyState, markInvalid, clearInvalid, invalidText, escapeReverts } from "../ui.js";
@@ -46,7 +47,8 @@ export async function render(root, { api, setMeta }) {
</form>
<section class="panel" aria-labelledby="maintenance-title">
<h2 id="maintenance-title" data-i18n="Admin.Archive.Maintenance"></h2>
<div class="button-row">${ACTIONS.map((a) => `<button class="btn" data-action="${a}" data-i18n="Admin.Archive.${cap(a)}" data-i18n-title="Admin.Archive.${cap(a)}.Tip"></button>`).join("")}</div>
<div class="button-row">${ACTIONS.map((a) => `<button class="btn" data-action="${a}" data-i18n="Admin.Archive.${cap(a)}" data-i18n-title="Admin.Archive.${cap(a)}.Tip"></button>`).join("")}
<a class="btn" href="#/library?view=trash" data-i18n="Admin.Archive.Trash" data-i18n-title="Admin.Archive.Trash.Tip"></a></div>
<h2 id="cameras-title" data-i18n="Admin.Archive.ByCamera"></h2>
${statsTable(stats.byCamera.slice(0, 8).map((c) => ({ label: c.key || "—", count: c.count, bytes: c.bytes })), "cameras-title")
|| `<p class="muted" data-i18n="Admin.Dashboard.NoData"></p>`}
@@ -0,0 +1,567 @@
// Library (owner review 2, R6; BRIEF §14.8): the panel browses, views and deletes sequences and photos and runs mass
// operations on them, but never edits a video (no settings, no render). #/library lists the sequences with filters in the
// address, #/library?id=<sequence> opens one (library/sequence.js), #/library?view=trash the archive's trash (library/trash.js).
import { t, plural, applyStrings } from "../i18n.js";
import { escapeHtml, attr, formatBytes, formatNumber, toast, errorText, confirmDialog, formDialog, markInvalid, emptyState, routeParams, redraw } from "../ui.js";
import { icons } from "../icons.js";
import { BULK_LIMIT, factsLine, captureText, cameraLabel, statusChips, lazyImage, watchImages, Selection, selectableGrid, chunks, saveFile, sequencesCsv, today, tagList, coverUrl } from "./library/shared.js";
import { renderSequence } from "./library/sequence.js";
import { renderTrash } from "./library/trash.js";
const VIEW_KEY = "chronos.admin.library.view";
const PAGE = 100;
/** The Status menu: its value in the address and the listing's query parameters. */
const STATUS_FILTERS = {
analysed: "status=analyzedLight",
"not-analysed": "status=-analyzedLight",
proxies: "status=proxiesBuilt",
"no-proxies": "status=-proxiesBuilt",
rendered: "rendered=true",
"not-rendered": "rendered=false",
verified: "status=verified",
"not-verified": "status=-verified",
warnings: "status=hasWarnings",
errors: "status=hasErrors",
};
const SORTS = ["newest", "oldest", "title", "frameCount", "size"];
const JOBS = ["analyse", "proxies", "thumbnails", "verify"];
const FILTERS = ["q", "year", "camera", "status", "tag", "sort"];
/** The list's address the last time it was shown, so a sequence's Back returns to the same filters. */
let listHash = "#/library";
/** upload.js of the web upload, once asked for: the module, or null when this server has none. */
let uploadModule;
/**
* The web upload (owner review 2, R3) lives in its own module; the Library offers it only when that module loads, so
* the page works on a panel without it.
*/
export async function loadUpload() {
if (uploadModule === undefined) {
try {
const m = await import("../upload.js");
uploadModule = typeof m.openUpload === "function" ? m : null;
} catch {
uploadModule = null;
}
}
return uploadModule;
}
export async function render(root, context) {
const params = routeParams();
if (params.get("view") === "trash") return renderTrash(root, context, { back: listHash });
const id = params.get("id");
if (id) return renderSequence(root, context, id, { back: listHash, loadUpload });
listHash = location.hash || "#/library";
return renderList(root, context, params);
}
async function renderList(root, { api, setMeta, actions, onEvent }, params) {
const filters = Object.fromEntries(FILTERS.map((f) => [f, params.get(f) ?? ""]));
if (!SORTS.includes(filters.sort)) filters.sort = "newest";
if (!Object.hasOwn(STATUS_FILTERS, filters.status)) filters.status = "";
let view = storedView();
let rows = [];
let cursor = null;
let total = 0;
let facets = { years: [], cameras: [], tags: [] };
/** Every sequence of the filter, once "Select all" fetched them; null otherwise. */
let matching = null;
let generation = 0;
const selection = new Selection();
let refreshTimer = null;
actions.innerHTML = `
<button class="btn" id="upload" hidden>${icons.upload}<span data-i18n="Admin.Library.Upload"></span></button>
<a class="btn" href="#/library?view=trash" data-i18n-title="Admin.Library.Trash.Tip">${icons.trash}<span data-i18n="Admin.Library.Trash"></span></a>
<button class="btn icon" id="refresh" data-i18n-title="Admin.Library.Refresh.Tip">${icons.refresh}</button>`;
applyStrings(actions);
actions.querySelector("#refresh").addEventListener("click", () => load());
loadUpload().then((upload) => {
const button = actions.querySelector("#upload");
if (!upload || !button.isConnected) return;
button.hidden = false;
button.title = t("Admin.Library.Upload.Tip");
button.addEventListener("click", () => upload.openUpload({ api, onDone: () => load() }));
});
root.innerHTML = `
<div class="toolbar" role="search">
<input class="input search" type="search" id="q" dir="auto" value="${attr(filters.q)}" data-i18n-placeholder="Admin.Library.Search"
data-i18n-title="Admin.Library.Search.Tip" aria-label="${attr(t("Admin.Library.Search"))}">
<select class="input small" id="year" data-i18n-title="Admin.Library.Year.Tip"></select>
<select class="input small" id="camera" data-i18n-title="Admin.Library.Camera.Tip"></select>
<select class="input small" id="status" data-i18n-title="Admin.Library.Status.Tip"></select>
<select class="input small" id="tag" data-i18n-title="Admin.Library.Tag.Tip"></select>
<select class="input small" id="sort" data-i18n-title="Admin.Library.Sort.Tip">${SORTS.map((s) =>
`<option value="${s}" ${s === filters.sort ? "selected" : ""}>${escapeHtml(t(`Admin.Library.Sort.${cap(s)}`))}</option>`).join("")}</select>
<span class="spacer"></span>
<div class="segmented" role="group" aria-label="${attr(t("Admin.Library.View"))}">
<button class="btn icon" data-view="grid" aria-pressed="${view === "grid"}" data-i18n-title="Admin.Library.View.Grid.Tip">${icons.grid}</button>
<button class="btn icon" data-view="list" aria-pressed="${view === "list"}" data-i18n-title="Admin.Library.View.List.Tip">${icons.list}</button>
</div>
</div>
<section class="panel flush library" aria-label="${attr(t("Admin.Nav.Library"))}">
<div id="items"></div>
<div class="table-foot" id="foot" hidden><span class="muted" id="shown"></span><span class="spacer"></span>
<button class="btn small" id="more" data-i18n="Admin.Common.More" data-i18n-title="Admin.Common.More.Tip"></button></div>
</section>
<div class="mass-bar" id="mass" role="toolbar" aria-label="${attr(t("Admin.Library.Selection"))}" hidden></div>`;
applyStrings(root);
const itemsHost = root.querySelector("#items");
const mass = root.querySelector("#mass");
let searchTimer = null;
root.querySelector("#q").addEventListener("input", (e) => {
clearTimeout(searchTimer);
searchTimer = setTimeout(() => setFilter("q", e.target.value.trim()), 300);
});
for (const f of ["year", "camera", "status", "tag", "sort"]) root.querySelector(`#${f}`).addEventListener("change", (e) => setFilter(f, e.target.value));
root.querySelectorAll("[data-view]").forEach((b) => b.addEventListener("click", () => {
view = b.dataset.view;
root.querySelectorAll("[data-view]").forEach((x) => x.setAttribute("aria-pressed", String(x === b)));
try {
localStorage.setItem(VIEW_KEY, view);
} catch {
// Only this page keeps the view then.
}
draw();
}));
root.querySelector("#more").addEventListener("click", () => load(true));
// One grid object for the page: the host stays, its items are redrawn.
const grid = selectableGrid(itemsHost, {
selection,
order: () => rows.map((r) => r.id),
open: (key) => {
location.hash = `#/library?id=${encodeURIComponent(key)}`;
},
onChange: syncSelection,
});
function setFilter(name, value) {
if (filters[name] === value) return;
filters[name] = value;
// The address keeps the filters (no hashchange: the page stays), so Back from a sequence finds them again.
const query = new URLSearchParams(Object.entries(filters).filter(([k, v]) => v && !(k === "sort" && v === "newest")));
listHash = `#/library${query.size ? `?${query}` : ""}`;
history.replaceState(null, "", listHash);
selection.clear();
matching = null;
load();
}
function listQuery(limit, after) {
const p = new URLSearchParams({ limit: String(limit), sort: filters.sort });
for (const f of ["q", "year", "camera", "tag"]) if (filters[f]) p.set(f, filters[f]);
if (after) p.set("cursor", after);
const status = STATUS_FILTERS[filters.status];
return `/api/v1/sequences?${p}${status ? `&${status}` : ""}`;
}
async function load(more = false) {
const mine = ++generation;
try {
const [page, f] = await Promise.all([
api.get(listQuery(PAGE, more ? cursor : null)),
more ? Promise.resolve(facets) : api.get("/api/v1/sequences/facets").catch(() => facets),
]);
if (mine !== generation || !root.isConnected) return;
facets = f;
if (!more) total = page.total ?? page.items.length;
cursor = page.nextCursor;
if (more) {
rows = rows.concat(page.items);
appendItems(page.items);
} else {
rows = page.items;
drawFilters();
draw();
}
} catch (err) {
toast(errorText(err), true);
return;
}
setMeta(plural("Admin.Library.Count", total));
drawFoot();
}
/**
* The loaded rows again, as many as are shown (live updates), a thousand per request; the selection and the keyboard
* place stay.
*/
async function refreshVisible() {
const mine = ++generation;
const wanted = Math.max(rows.length, PAGE);
try {
const facetsRead = api.get("/api/v1/sequences/facets").catch(() => facets);
const first = await api.get(listQuery(Math.min(wanted, BULK_LIMIT), null));
let items = first.items;
let after = first.nextCursor;
while (after && items.length < wanted) {
if (mine !== generation || !root.isConnected) return;
const page = await api.get(listQuery(Math.min(wanted - items.length, BULK_LIMIT), after));
items = items.concat(page.items);
after = page.nextCursor;
}
const f = await facetsRead;
if (mine !== generation || !root.isConnected) return;
total = first.total ?? total;
facets = f;
drawFilters();
rows = items;
cursor = after;
const known = new Set(rows.map((r) => r.id));
if (!matching) selection.set([...selection.ids].filter((id) => known.has(id)));
const focused = itemsHost.contains(document.activeElement);
draw();
grid.restore(focused);
setMeta(plural("Admin.Library.Count", total));
drawFoot();
} catch {
// The next event or Refresh tries again.
}
}
function drawFilters() {
const option = (value, label, chosen) => `<option value="${attr(value)}" ${value === chosen ? "selected" : ""}>${escapeHtml(label)}</option>`;
// A value of the address the archive no longer has stays in its menu, so the filter shows what the list does.
const withChosen = (list, chosen) => (chosen && !list.some((f) => f.value === chosen) ? [{ value: chosen, sequences: 0 }, ...list] : list);
const counted = (f, label) => `${label ?? f.label ?? f.value} (${formatNumber(f.sequences)})`;
root.querySelector("#year").innerHTML = option("", t("Admin.Library.AnyYear"), filters.year) +
withChosen(facets.years, filters.year).map((f) => option(f.value, counted(f), filters.year)).join("");
root.querySelector("#camera").innerHTML = option("", t("Admin.Library.AnyCamera"), filters.camera) +
withChosen(facets.cameras, filters.camera).map((f) => option(f.value, counted(f), filters.camera)).join("");
root.querySelector("#tag").innerHTML = option("", t("Admin.Library.AnyTag"), filters.tag) +
withChosen(facets.tags, filters.tag).map((f) => option(f.value, counted(f), filters.tag)).join("");
root.querySelector("#status").innerHTML = option("", t("Admin.Library.AnyStatus"), filters.status) +
Object.keys(STATUS_FILTERS).map((s) => option(s, t(`Admin.Library.Filter.${pascal(s)}`), filters.status)).join("");
root.querySelectorAll(".toolbar select").forEach((s) => s.classList.toggle("active", s.id !== "sort" && s.value !== ""));
}
function draw() {
itemsHost.className = `seq-items ${view === "list" ? "rows" : "cards"}`;
itemsHost.setAttribute("role", "listbox");
itemsHost.setAttribute("aria-multiselectable", "true");
itemsHost.setAttribute("aria-label", t("Admin.Library.Sequences"));
if (rows.length === 0) {
itemsHost.removeAttribute("role");
itemsHost.removeAttribute("aria-multiselectable");
const filtered = FILTERS.some((f) => f !== "sort" && filters[f]);
itemsHost.innerHTML = filtered
? emptyState("Admin.Library.NoMatch", `<button class="btn small" id="clear" data-i18n="Admin.Library.ClearFilters" data-i18n-title="Admin.Library.ClearFilters.Tip"></button>`)
: emptyState("Admin.Library.Empty", `<button class="btn small" id="scan" data-i18n="Admin.Archive.Scan" data-i18n-title="Admin.Archive.Scan.Tip"></button>`);
applyStrings(itemsHost);
itemsHost.querySelector("#clear")?.addEventListener("click", clearFilters);
itemsHost.querySelector("#scan")?.addEventListener("click", scan);
syncSelection();
return;
}
const head = view === "list" ? `<div class="seq-head" aria-hidden="true"><span></span><span></span>
<span data-i18n="Admin.Library.Column.Sequence"></span><span class="col-camera" data-i18n="Admin.Library.Column.Camera"></span>
<span class="end" data-i18n="Admin.Library.Column.Photos"></span><span class="end col-size" data-i18n="Admin.Library.Column.Size"></span>
<span class="col-date" data-i18n="Admin.Library.Column.Date"></span></div>` : "";
itemsHost.innerHTML = head + rows.map(itemHtml).join("");
applyStrings(itemsHost);
watchImages(itemsHost);
grid.restore();
syncSelection();
}
function appendItems(items) {
if (rows.length === items.length) return draw();
itemsHost.insertAdjacentHTML("beforeend", items.map(itemHtml).join(""));
watchImages(itemsHost);
grid.restore();
syncSelection();
}
function itemHtml(s) {
const facts = factsLine(s);
const thumb = lazyImage(coverUrl(s));
const label = [s.displayTitle, facts].filter(Boolean).join(" · ");
const check = `<input type="checkbox" class="seq-check" data-check tabindex="-1" aria-hidden="true" title="${attr(t("Admin.Library.Select.Tip"))}">`;
if (view === "list") {
return `<div class="seq-row" role="option" data-key="${attr(s.id)}" aria-selected="false" tabindex="-1" aria-label="${attr(label)}" title="${attr(t("Admin.Library.Open.Tip"))}">
${check}${thumb}
<span class="stack"><strong class="ellipsis" dir="auto">${escapeHtml(s.displayTitle)}</strong><span class="chips-row">${statusChips(s)}</span></span>
<span class="ellipsis col-camera" dir="auto">${escapeHtml(cameraLabel(s.cameraMake, s.cameraModel) || "—")}</span>
<span class="num end">${formatNumber(s.frameCount)}</span>
<span class="num end col-size">${escapeHtml(formatBytes(s.totalBytes))}</span>
<span class="muted nowrap col-date">${escapeHtml(captureText(s.firstCapture, false))}</span>
</div>`;
}
return `<div class="seq-card" role="option" data-key="${attr(s.id)}" aria-selected="false" tabindex="-1" aria-label="${attr(label)}" title="${attr(t("Admin.Library.Open.Tip"))}">
${thumb}${check}
<span class="count num" aria-hidden="true">${formatNumber(s.frameCount)}</span>
<span class="info"><strong class="ellipsis" dir="auto">${escapeHtml(s.displayTitle)}</strong>
<span class="facts ellipsis" dir="auto">${escapeHtml(facts || "—")}</span>
<span class="chips-row">${statusChips(s)}</span></span>
</div>`;
}
function drawFoot() {
root.querySelector("#foot").hidden = rows.length === 0 || (!cursor && rows.length >= total);
root.querySelector("#more").hidden = !cursor;
root.querySelector("#shown").textContent = t("Admin.Library.Shown", formatNumber(rows.length), formatNumber(total));
}
/** Check boxes, item states and the mass bar for the selection; the items themselves are not drawn again. */
function syncSelection() {
itemsHost.querySelectorAll('[role="option"]').forEach((el) => {
const on = selection.has(el.dataset.key);
el.setAttribute("aria-selected", String(on));
const box = el.querySelector("[data-check]");
if (box) box.checked = on;
});
itemsHost.classList.toggle("selecting", selection.size > 0);
drawMass();
}
function drawMass() {
if (selection.size === 0) {
mass.hidden = true;
mass.innerHTML = "";
return;
}
const selectAll = !matching && total > selection.size
? `<button class="btn small subtle" id="mass-all" data-mass="all" data-i18n-title="Admin.Library.SelectAll.Tip">${escapeHtml(t("Admin.Library.SelectAll", formatNumber(total)))}</button>` : "";
const job = (kind) => `<button class="btn small" id="mass-${kind}" data-mass="job" data-kind="${kind}" data-i18n="Admin.Library.Job.${cap(kind)}" data-i18n-title="Admin.Library.Job.${cap(kind)}.Tip"></button>`;
mass.hidden = false;
// Drawn again at every change of the selection: the keyboard focus stays on its button.
redraw(mass, () => {
mass.innerHTML = `
<strong class="nowrap" role="status">${escapeHtml(plural("Admin.Library.Selected", selection.size))}</strong>${selectAll}
<span class="spacer"></span>
${JOBS.map(job).join("")}
<button class="btn small" id="mass-retag" data-mass="retag" data-i18n="Admin.Library.Retag" data-i18n-title="Admin.Library.Retag.Tip"></button>
<button class="btn small" id="mass-csv" data-mass="csv" data-i18n="Admin.Library.ExportCsv" data-i18n-title="Admin.Library.ExportCsv.Tip"></button>
<button class="btn small destructive" id="mass-delete" data-mass="delete" data-i18n="Admin.Library.Delete" data-i18n-title="Admin.Library.Delete.Tip"></button>
<button class="btn small icon subtle" id="mass-clear" data-mass="clear" data-i18n-title="Admin.Library.ClearSelection.Tip">${icons.close}</button>`;
applyStrings(mass);
});
mass.querySelectorAll("[data-mass]").forEach((b) => b.addEventListener("click", () => massAction(b.dataset.mass, b)));
}
async function massAction(action, button) {
if (action === "clear") {
selection.clear();
matching = null;
syncSelection();
grid.restore(true);
return;
}
if (action === "all") return selectAll();
if (action === "csv") return exportCsv();
button.disabled = true;
try {
if (action === "job") await queueJobs(button.dataset.kind);
else if (action === "retag") await retag();
else if (action === "delete") await deleteSequences();
} finally {
if (button.isConnected) button.disabled = false;
}
}
/** Every sequence of the filter, a thousand per request: they all count as selected. */
async function selectAll() {
const all = [];
let after = null;
try {
do {
const page = await api.get(listQuery(BULK_LIMIT, after));
all.push(...page.items);
after = page.nextCursor;
} while (after);
} catch (err) {
toast(errorText(err), true);
return;
}
matching = all;
selection.set(all.map((s) => s.id));
syncSelection();
}
/** The selected sequences as far as this page knows them (all of them after Select all). */
function selectedRows() {
const known = new Map([...(matching ?? []), ...rows].map((s) => [s.id, s]));
return [...selection.ids].map((id) => known.get(id)).filter(Boolean);
}
/** One job per thousand sequences (a bulk request's limit); the toast counts them, and says those queued before a failure. */
async function queueJobs(kind) {
let queued = 0;
let skipped = 0;
let failure = null;
try {
for (const ids of chunks([...selection.ids])) {
const result = await api.post("/api/v1/sequences/bulk/jobs", { ids, kind });
if (result.job) queued++;
skipped += result.skipped;
}
} catch (err) {
failure = errorText(err);
}
const done = queued > 0 ? plural("Admin.Library.JobsQueued", queued) : failure ? "" : t("Admin.Library.NothingQueued");
toast([done, skipped > 0 ? plural("Admin.Library.Skipped", skipped) : "", failure ?? ""].filter(Boolean).join(" · "), failure !== null);
}
async function retag() {
const datalist = facets.tags.map((f) => `<option value="${attr(f.value)}"></option>`).join("");
const data = await formDialog({
title: plural("Admin.Library.RetagTitle", selection.size),
fields: `
<label><span data-i18n="Admin.Library.AddTags"></span><input class="input" name="add" dir="auto" list="retag-tags" autocomplete="off" data-i18n-title="Admin.Library.AddTags.Tip"></label>
<label><span data-i18n="Admin.Library.RemoveTags"></span><input class="input" name="remove" dir="auto" list="retag-tags" autocomplete="off" data-i18n-title="Admin.Library.RemoveTags.Tip"></label>
<datalist id="retag-tags">${datalist}</datalist>`,
confirm: t("Admin.Library.Apply"),
confirmTip: t("Admin.Library.Apply.Tip"),
cancel: t("Admin.Common.Cancel"),
cancelTip: t("Admin.Common.Cancel.Tip"),
check: (form) => {
const add = tagList(form.elements.add.value);
const remove = tagList(form.elements.remove.value);
const long = [form.elements.add, form.elements.remove].find((f) => tagList(f.value).some((tag) => tag.length > 64));
if (long) {
markInvalid(long, t("Admin.Library.TagTooLong"));
long.focus();
return false;
}
if (add.length + remove.length === 0) {
markInvalid(form.elements.add, t("Admin.Library.NoTags"));
form.elements.add.focus();
return false;
}
return true;
},
});
if (!data) return;
const add = tagList(String(data.get("add")));
const remove = tagList(String(data.get("remove")));
let ok = 0;
const skipped = [];
try {
for (const ids of chunks([...selection.ids])) {
const result = await api.post("/api/v1/sequences/bulk/retag", { ids, add, remove });
ok += result.ok;
skipped.push(...result.items.filter((i) => i.outcome !== "ok"));
}
} catch (err) {
toast(errorText(err), true);
return;
}
toast([plural("Admin.Library.Retagged", ok), skipped.length > 0 ? plural("Admin.Library.Skipped", skipped.length) : ""].filter(Boolean).join(" · "),
skipped.length > 0 && ok === 0);
refreshSoon();
}
/** Dry run, the list of what moves to the trash, then the move; each sequence goes whole or not at all. */
async function deleteSequences() {
const ids = [...selection.ids];
const plan = { items: [], ok: 0, photos: 0, bytes: 0 };
try {
for (const part of chunks(ids)) {
const result = await api.post("/api/v1/sequences/bulk/delete", { ids: part, dryRun: true });
plan.items.push(...result.items);
plan.ok += result.ok;
plan.photos += result.photos;
plan.bytes += result.bytes;
}
} catch (err) {
toast(errorText(err), true);
return;
}
const titles = new Map(selectedRows().map((s) => [s.id, s.displayTitle]));
const going = plan.items.filter((i) => i.outcome === "ok");
const blocked = plan.items.filter((i) => i.outcome !== "ok");
if (going.length === 0) {
toast(blocked[0]?.message || t("Admin.Library.NothingToDelete"), true);
return;
}
const body = [plural("Admin.Library.DeleteBody", going.length, plural("Admin.Dashboard.PhotoCount", plan.photos), formatBytes(plan.bytes)),
blocked.length > 0 ? plural("Admin.Library.DeleteBlocked", blocked.length) : ""].filter(Boolean).join(" ");
const confirmed = await confirmDialog({
title: plural("Admin.Library.DeleteTitle", going.length),
body,
list: [...going.map((i) => titles.get(i.id) ?? i.id), ...blocked.map((i) => t("Admin.Library.BlockedItem", titles.get(i.id) ?? i.id, i.message ?? i.reason))],
confirm: t("Admin.Library.DeleteConfirm"),
confirmTip: t("Admin.Library.DeleteConfirm.Tip"),
cancel: t("Admin.Common.Keep"),
cancelTip: t("Admin.Common.Keep.Tip"),
});
if (!confirmed) return;
let moved = 0;
let photos = 0;
const failed = [];
try {
for (const part of chunks(going.map((i) => i.id))) {
const result = await api.post("/api/v1/sequences/bulk/delete", { ids: part, dryRun: false });
moved += result.ok;
photos += result.photos;
failed.push(...result.items.filter((i) => i.outcome !== "ok"));
}
} catch (err) {
toast(errorText(err), true);
}
toast([plural("Admin.Library.Deleted", moved, plural("Admin.Dashboard.PhotoCount", photos)), failed.length > 0 ? plural("Admin.Library.Skipped", failed.length) : ""]
.filter(Boolean).join(" · "), moved === 0);
selection.clear();
matching = null;
await load();
}
function exportCsv() {
const chosen = selectedRows();
saveFile(`chronos-library-${today()}.csv`, sequencesCsv(chosen));
toast(plural("Admin.Library.Exported", chosen.length));
}
function clearFilters() {
for (const f of FILTERS) filters[f] = f === "sort" ? filters.sort : "";
root.querySelector("#q").value = "";
listHash = filters.sort === "newest" ? "#/library" : `#/library?sort=${filters.sort}`;
history.replaceState(null, "", listHash);
load();
root.querySelector("#q").focus();
}
async function scan() {
try {
await api.post("/api/v1/archive/scan");
toast(t("Admin.Archive.Queued"));
} catch (err) {
toast(errorText(err), true);
}
}
function refreshSoon(delay = 800) {
clearTimeout(refreshTimer);
refreshTimer = setTimeout(() => {
if (root.isConnected) refreshVisible();
}, delay);
}
// Sequences that change (a job finished, an upload landed, someone deleted or retagged) show their new state.
onEvent((e) => {
if (e.type === "sequenceChanged") refreshSoon(800);
else if (e.type === "jobState" && (e.state === "done" || e.state === "failed")) refreshSoon(1500);
});
await load();
}
function storedView() {
try {
return localStorage.getItem(VIEW_KEY) === "list" ? "list" : "grid";
} catch {
return "grid";
}
}
function cap(s) {
return s.charAt(0).toUpperCase() + s.slice(1);
}
function pascal(s) {
return s.split("-").map(cap).join("");
}
@@ -0,0 +1,569 @@
// A sequence on the panel (owner review 2, R6): its title, tags, rating and notes, its facts, its photos in pages of 500
// with lazy thumbnails, a photo viewer, deleting photos into the archive's trash, the cover, the originals and the renders
// to download. Nothing here edits the video: its settings and its renders are the desktop editor's.
import { t, plural, applyStrings } from "../../i18n.js";
import { escapeHtml, attr, formatBytes, formatNumber, formatDateTime, toast, errorText, confirmDialog, emptyState, escapeReverts, redraw } from "../../ui.js";
import { icons } from "../../icons.js";
import { captureText, cameraLabel, spanText, statusChips, lazyImage, watchImages, Selection, selectableGrid, tagList, coverUrl } from "./shared.js";
const FRAME_PAGE = 500;
/** Deleting more photos than this asks for their number to be typed. */
const TYPED_ABOVE = 20;
/** Names a delete dialog lists; the count in its title says how many there are in all. */
const LISTED = 500;
/** FrameFlags bits the viewer and the tiles name. */
const FLAGS = [[1, "Missing"], [2, "Corrupt"], [4, "Duplicate"], [8, "Excluded"]];
const MAX_TAGS = 50;
export async function renderSequence(root, { api, setMeta, actions, onEvent }, id, { back, loadUpload }) {
let seq;
let frames = [];
let cursor = null;
let renders = [];
let generation = 0;
let timer = null;
/** Set once this page deleted the sequence, or saw it go: its deletion event then says nothing more. */
let leaving = false;
const selection = new Selection();
actions.innerHTML = `
<a class="btn" href="${attr(back)}" data-i18n-title="Admin.Sequence.Back.Tip">${icons.back}<span data-i18n="Admin.Sequence.Back"></span></a>`;
applyStrings(actions);
try {
seq = await api.get(`/api/v1/sequences/${encodeURIComponent(id)}`);
} catch (err) {
root.innerHTML = err.status === 404
? `<section class="panel">${emptyState("Admin.Sequence.Gone", `<a class="btn small" href="${attr(back)}" data-i18n="Admin.Sequence.Back" data-i18n-title="Admin.Sequence.Back.Tip"></a>`)}</section>`
: `<div class="panel empty">${escapeHtml(errorText(err))}</div>`;
applyStrings(root);
return;
}
actions.insertAdjacentHTML("beforeend", `
<button class="btn" id="add" hidden>${icons.upload}<span data-i18n="Admin.Sequence.AddPhotos"></span></button>
<button class="btn destructive" id="delete-sequence" data-i18n="Admin.Sequence.Delete" data-i18n-title="Admin.Sequence.Delete.Tip"></button>`);
applyStrings(actions);
actions.querySelector("#delete-sequence").addEventListener("click", deleteSequence);
loadUpload().then((upload) => {
const button = actions.querySelector("#add");
if (!upload || !button?.isConnected) return;
button.hidden = false;
button.title = t("Admin.Sequence.AddPhotos.Tip");
button.addEventListener("click", () => upload.openUpload({ api, sequence: seq, onDone: () => reload(true) }));
});
root.innerHTML = `
<section class="panel seq-detail" aria-label="${attr(t("Admin.Sequence.Details"))}">
<div class="seq-cover" id="cover"></div>
<form class="form seq-fields" novalidate>
<input class="input heading" name="title" id="seq-title" dir="auto" maxlength="200" autocomplete="off"
aria-label="${attr(t("Admin.Sequence.Title"))}" data-i18n-title="Admin.Sequence.Title.Tip">
<div class="field-label"><span id="tags-label" data-i18n="Admin.Sequence.Tags"></span>
<div class="tag-editor" role="group" aria-labelledby="tags-label"><span class="tag-list" id="tags"></span>
<input class="input small" id="tag-add" dir="auto" autocomplete="off" data-i18n-placeholder="Admin.Sequence.AddTag" data-i18n-title="Admin.Sequence.AddTag.Tip"
aria-label="${attr(t("Admin.Sequence.AddTag"))}"></div></div>
<div class="field-label"><span id="rating-label" data-i18n="Admin.Sequence.Rating"></span>
<div class="stars" role="group" aria-labelledby="rating-label" id="rating"></div></div>
<label><span data-i18n="Admin.Sequence.Notes"></span>
<textarea class="input notes" name="notes" dir="auto" rows="3" maxlength="2000" data-i18n-title="Admin.Sequence.Notes.Tip"></textarea></label>
</form>
<dl class="seq-facts" id="facts"></dl>
</section>
<section class="panel flush" aria-labelledby="photos-title">
<div class="panel-head padded wrap"><h2 id="photos-title" data-i18n="Admin.Sequence.Photos"></h2><span class="muted ellipsis" id="photos-meta"></span>
<span class="spacer"></span><span class="button-row" id="frame-actions"></span></div>
<div class="frame-grid" id="frames" dir="ltr" role="listbox" aria-multiselectable="true" aria-labelledby="photos-title"></div>
<div class="table-foot" id="frames-foot" hidden><span class="muted" id="frames-shown"></span><span class="spacer"></span>
<button class="btn small" id="frames-more" data-i18n="Admin.Common.More" data-i18n-title="Admin.Sequence.MorePhotos.Tip"></button></div>
</section>
<section class="panel flush" aria-labelledby="renders-title">
<div class="panel-head padded"><h2 id="renders-title" data-i18n="Admin.Sequence.Renders"></h2></div>
<div id="renders"></div>
</section>`;
applyStrings(root);
const form = root.querySelector("form");
const framesHost = root.querySelector("#frames");
escapeReverts(form);
form.addEventListener("submit", (e) => e.preventDefault());
form.elements.title.addEventListener("change", () => {
const title = form.elements.title.value.trim();
if (title !== (seq.title ?? "")) patch({ title });
});
form.elements.title.addEventListener("keydown", (e) => {
if (e.key === "Enter") form.elements.title.blur();
});
form.elements.notes.addEventListener("change", () => {
const notes = form.elements.notes.value;
if (notes !== (seq.notes ?? "")) patch({ notes });
});
const tagInput = root.querySelector("#tag-add");
tagInput.addEventListener("keydown", (e) => {
if (e.key !== "Enter") return;
e.preventDefault();
const added = tagList(tagInput.value).filter((tag) => !seq.tags.some((s) => s.toLocaleLowerCase() === tag.toLocaleLowerCase()));
if (added.some((tag) => tag.length > 64)) return toast(t("Admin.Library.TagTooLong"), true);
if (seq.tags.length + added.length > MAX_TAGS) return toast(t("Admin.Sequence.TooManyTags"), true);
tagInput.value = "";
if (added.length > 0) patch({ tags: [...seq.tags, ...added] }, "tag-add");
});
root.querySelector("#frames-more").addEventListener("click", () => loadFrames(true));
const grid = selectableGrid(framesHost, {
selection,
order: () => frames.map((f) => f.id),
open: (key) => openViewer(key),
onChange: syncSelection,
});
function drawHeader() {
setMeta(seq.displayTitle);
document.title = `${seq.displayTitle} · Chronos Server`;
const titleField = form.elements.title;
if (document.activeElement !== titleField) titleField.value = titleField.defaultValue = seq.title ?? "";
titleField.placeholder = seq.displayTitle;
const notes = form.elements.notes;
if (document.activeElement !== notes) notes.value = notes.defaultValue = seq.notes ?? "";
// The cover is drawn again only when it changes (another photo, other photos), not at every edit.
const cover = root.querySelector("#cover");
if (cover.dataset.src !== coverUrl(seq)) {
cover.dataset.src = coverUrl(seq);
cover.innerHTML = lazyImage(coverUrl(seq), "cover");
watchImages(cover);
}
const tags = root.querySelector("#tags");
tags.innerHTML = seq.tags.map((tag, i) => `<span class="tag" dir="auto">${escapeHtml(tag)}<button class="btn icon subtle tiny" type="button" data-remove="${i}"
title="${attr(t("Admin.Sequence.RemoveTag.Tip", tag))}" aria-label="${attr(t("Admin.Sequence.RemoveTag.Tip", tag))}">${icons.close}</button></span>`).join("");
tags.querySelectorAll("[data-remove]").forEach((b) => b.addEventListener("click", () =>
patch({ tags: seq.tags.filter((_, i) => i !== Number(b.dataset.remove)) }, "tag-add")));
const rating = root.querySelector("#rating");
rating.innerHTML = [1, 2, 3, 4, 5].map((n) => `<button class="btn icon subtle star" type="button" id="star-${n}" data-star="${n}" aria-pressed="${n <= seq.rating}"
aria-label="${attr(plural("Admin.Sequence.Stars", n))}" title="${attr(t(n === seq.rating ? "Admin.Sequence.Unrate.Tip" : "Admin.Sequence.Rate.Tip", n))}">${n <= seq.rating ? icons.starFilled : icons.star}</button>`).join("");
rating.querySelectorAll("[data-star]").forEach((b) => b.addEventListener("click", () => {
const n = Number(b.dataset.star);
patch({ rating: n === seq.rating ? 0 : n }, `star-${n}`);
}));
const fact = (key, value, { ltr = false, html = false } = {}) => value === null || value === undefined || value === ""
? "" : `<div><dt data-i18n="Admin.Sequence.Fact.${key}"></dt><dd ${ltr ? 'dir="ltr" class="mono"' : 'dir="auto"'}>${html ? value : escapeHtml(value)}</dd></div>`;
const captured = seq.firstCapture ? `${captureText(seq.firstCapture)} – ${captureText(seq.lastCapture)}` : "";
root.querySelector("#facts").innerHTML = [
fact("Camera", cameraLabel(seq.cameraMake, seq.cameraModel)),
fact("Lens", seq.lens),
fact("Captured", captured),
fact("Span", spanText(seq)),
fact("Photos", formatNumber(seq.frameCount)),
fact("Size", formatBytes(seq.totalBytes)),
fact("Interval", seq.medianInterval ? t("Common.Duration.Seconds", formatNumber(Math.round(seq.medianInterval * 10) / 10)) : ""),
fact("Folder", seq.folder, { ltr: true }),
fact("Status", `<span class="chips-row">${statusChips(seq)}</span>`, { html: true }),
fact("Updated", formatDateTime(seq.updatedAt)),
].join("");
applyStrings(root.querySelector("#facts"));
}
/** One field of the sequence changed (the same edit as the desktop's Library makes); a conflict reloads it. */
async function patch(change, focusId = null) {
const hero = seq.heroFrameId;
try {
seq = await api.patch(`/api/v1/sequences/${encodeURIComponent(id)}`, { ...change, expectedSettingsVersion: seq.settingsVersion });
toast(t("Admin.Common.Saved"));
} catch (err) {
toast(errorText(err), true);
if (err.status === 409) await reloadSequence();
}
drawHeader();
// The cover's mark moves to its new photo.
if (seq.heroFrameId !== hero) drawFrames();
if (focusId) root.querySelector(`#${focusId}`)?.focus();
}
async function reloadSequence() {
try {
seq = await api.get(`/api/v1/sequences/${encodeURIComponent(id)}`);
} catch (err) {
if (err.status === 404) gone();
}
}
async function loadFrames(more = false) {
const mine = ++generation;
try {
const page = await api.get(`/api/v1/sequences/${encodeURIComponent(id)}/frames?limit=${FRAME_PAGE}${more && cursor ? `&cursor=${encodeURIComponent(cursor)}` : ""}`);
if (mine !== generation || !root.isConnected) return;
cursor = page.nextCursor;
if (more) {
frames = frames.concat(page.items);
framesHost.insertAdjacentHTML("beforeend", page.items.map(frameHtml).join(""));
watchImages(framesHost);
grid.restore();
syncSelection();
} else {
frames = page.items;
drawFrames();
}
} catch (err) {
toast(errorText(err), true);
}
drawFramesFoot();
}
/** The photos again after they changed, as many as were shown; the selection keeps the photos still there. */
async function reloadFrames() {
const want = Math.max(frames.length, FRAME_PAGE);
const mine = ++generation;
let list = [];
let after = null;
try {
do {
const page = await api.get(`/api/v1/sequences/${encodeURIComponent(id)}/frames?limit=${FRAME_PAGE}${after ? `&cursor=${encodeURIComponent(after)}` : ""}`);
list = list.concat(page.items);
after = page.nextCursor;
} while (after && list.length < want);
} catch (err) {
toast(errorText(err), true);
return;
}
if (mine !== generation || !root.isConnected) return;
frames = list;
cursor = after;
const known = new Set(frames.map((f) => f.id));
selection.set([...selection.ids].filter((f) => known.has(f)));
const focused = framesHost.contains(document.activeElement);
drawFrames();
grid.restore(focused);
drawFramesFoot();
}
function drawFrames() {
framesHost.innerHTML = frames.map(frameHtml).join("") ||
`<div class="frame-empty">${emptyState("Admin.Sequence.NoPhotos")}</div>`;
applyStrings(framesHost);
watchImages(framesHost);
grid.restore();
syncSelection();
}
function frameHtml(f) {
const flags = FLAGS.filter(([bit]) => (f.flags & bit) !== 0).map(([, name]) => t(`Admin.Sequence.Flag.${name}`));
const label = [f.fileName, captureText(f.capturedAt), ...flags].join(" · ");
const hero = f.id === seq.heroFrameId ? `<span class="frame-badge hero" title="${attr(t("Admin.Sequence.Cover.Tip"))}">${icons.hero}</span>` : "";
const flagged = flags.length > 0 ? `<span class="frame-badge warn" title="${attr(flags.join(" · "))}">${icons.warning}</span>` : "";
return `<div class="frame" role="option" data-key="${attr(f.id)}" aria-selected="false" tabindex="-1" aria-label="${attr(label)}" title="${attr(t("Admin.Sequence.Photo.Tip", f.fileName))}">
${lazyImage(`/api/v1/frames/${encodeURIComponent(f.id)}/thumb`)}
<input type="checkbox" class="seq-check" data-check tabindex="-1" aria-hidden="true" title="${attr(t("Admin.Sequence.SelectPhoto.Tip"))}">
<span class="frame-no num" aria-hidden="true">${formatNumber(f.index + 1)}</span>${hero}${flagged}
</div>`;
}
function drawFramesFoot() {
root.querySelector("#photos-meta").textContent = plural("Admin.Dashboard.PhotoCount", seq.frameCount);
root.querySelector("#frames-foot").hidden = !cursor;
root.querySelector("#frames-shown").textContent = t("Admin.Library.Shown", formatNumber(frames.length), formatNumber(seq.frameCount));
}
function syncSelection() {
framesHost.querySelectorAll('[role="option"]').forEach((el) => {
const on = selection.has(el.dataset.key);
el.setAttribute("aria-selected", String(on));
const box = el.querySelector("[data-check]");
if (box) box.checked = on;
});
framesHost.classList.toggle("selecting", selection.size > 0);
drawFrameActions();
}
function drawFrameActions() {
const host = root.querySelector("#frame-actions");
const n = selection.size;
const one = n === 1;
const tip = (key, enabled, why) => attr(t(enabled ? key : why));
redraw(host, () => {
host.innerHTML = `
${n > 0 ? `<span class="muted nowrap" role="status">${escapeHtml(plural("Admin.Library.Selected", n))}</span>` : ""}
<button class="btn small" id="frames-all" data-frames="all" data-i18n="Admin.Sequence.SelectAll" data-i18n-title="Admin.Sequence.SelectAll.Tip" ${frames.length === 0 ? "disabled" : ""}></button>
${n > 0 ? `<button class="btn small" id="frames-clear" data-frames="clear" data-i18n="Admin.Sequence.ClearSelection" data-i18n-title="Admin.Sequence.ClearSelection.Tip"></button>` : ""}
<button class="btn small" id="frames-cover" data-frames="cover" title="${tip("Admin.Sequence.SetCover.Tip", one, "Admin.Sequence.OnePhoto.Tip")}" ${one ? "" : "disabled"}>${icons.hero}<span data-i18n="Admin.Sequence.SetCover"></span></button>
<button class="btn small" id="frames-download" data-frames="download" title="${tip("Admin.Sequence.Download.Tip", one, "Admin.Sequence.OnePhoto.Tip")}" ${one ? "" : "disabled"}>${icons.download}<span data-i18n="Admin.Sequence.Download"></span></button>
<button class="btn small destructive" id="frames-delete" data-frames="delete" title="${tip("Admin.Sequence.DeletePhotos.Tip", n > 0, "Admin.Sequence.SomePhotos.Tip")}" ${n > 0 ? "" : "disabled"}
data-i18n="Admin.Sequence.DeletePhotos"></button>`;
applyStrings(host);
});
host.querySelectorAll("[data-frames]").forEach((b) => b.addEventListener("click", () => frameAction(b.dataset.frames)));
}
function frameAction(action) {
const [only] = selection.ids;
switch (action) {
case "all":
selection.set(frames.map((f) => f.id));
return syncSelection();
case "clear":
selection.clear();
syncSelection();
return grid.restore(true);
case "cover":
return setCover(only);
case "download":
return download(only);
case "delete":
return deletePhotos();
}
}
function setCover(frameId) {
return patch({ heroFrameId: frameId });
}
function download(frameId) {
const frame = frames.find((f) => f.id === frameId);
const a = document.createElement("a");
a.href = `/api/v1/frames/${encodeURIComponent(frameId)}/original`;
a.download = frame?.fileName ?? "";
document.body.appendChild(a);
a.click();
a.remove();
}
/** Dry run, the confirmation (typing the count when many go), then the move into the archive's trash. */
async function deletePhotos() {
const ids = [...selection.ids];
const url = `/api/v1/sequences/${encodeURIComponent(id)}/frames/delete`;
let plan;
try {
plan = await api.post(url, { frameIds: ids, expectedFramesVersion: seq.framesVersion, dryRun: true });
} catch (err) {
return refused(err);
}
const names = frames.filter((f) => selection.has(f.id)).map((f) => f.fileName);
const confirmed = await confirmDialog({
title: plural("Admin.Sequence.DeletePhotosTitle", plan.photos),
body: plural("Admin.Sequence.DeletePhotosBody", plan.photos, formatBytes(plan.bytes)),
list: names.length > LISTED ? [...names.slice(0, LISTED), "…"] : names,
confirm: t("Admin.Sequence.DeletePhotosConfirm"),
confirmTip: t("Admin.Sequence.DeletePhotosConfirm.Tip"),
cancel: t("Admin.Common.Keep"),
cancelTip: t("Admin.Common.Keep.Tip"),
typed: plan.photos > TYPED_ABOVE ? String(plan.photos) : undefined,
typedKind: "count",
});
if (!confirmed) return;
let result;
try {
result = await api.post(url, { frameIds: ids, expectedFramesVersion: plan.framesVersion, dryRun: false });
} catch (err) {
return refused(err);
}
toast(plural("Admin.Sequence.PhotosDeleted", result.photos));
selection.clear();
await reload(true);
}
/** A deletion the server refused: its sentence; photos that changed meanwhile are shown again. */
async function refused(err) {
toast(errorText(err), true);
if (err.code === "frames_conflict") await reload(true);
if (err.status === 404) gone();
}
async function deleteSequence() {
const url = `/api/v1/sequences/${encodeURIComponent(id)}`;
let plan;
try {
plan = await api.del(`${url}?dryRun=true`);
} catch (err) {
return toast(errorText(err), true);
}
const confirmed = await confirmDialog({
title: t("Admin.Sequence.DeleteTitle", seq.displayTitle),
body: plural("Admin.Sequence.DeleteBody", plan.frameCount, formatBytes(plan.totalBytes)),
confirm: t("Admin.Library.DeleteConfirm"),
confirmTip: t("Admin.Sequence.DeleteConfirm.Tip"),
cancel: t("Admin.Common.Keep"),
cancelTip: t("Admin.Common.Keep.Tip"),
});
if (!confirmed) return;
leaving = true;
try {
await api.del(url);
} catch (err) {
leaving = false;
return toast(errorText(err), true);
}
toast(t("Admin.Sequence.Deleted", seq.displayTitle));
location.hash = back;
}
async function loadRenders() {
try {
renders = await api.get(`/api/v1/sequences/${encodeURIComponent(id)}/renders`);
} catch {
renders = [];
}
const host = root.querySelector("#renders");
host.innerHTML = renders.length === 0 ? emptyState("Admin.Sequence.NoRenders") : `
<div class="table renders" role="table" aria-labelledby="renders-title">
<div class="thead" role="row"><span role="columnheader" data-i18n="Admin.Sequence.Render.Preset"></span>
<span role="columnheader" data-i18n="Admin.Sequence.Render.Video"></span><span role="columnheader" class="end" data-i18n="Admin.Sequence.Render.Length"></span>
<span role="columnheader" class="end" data-i18n="Admin.Sequence.Render.Size"></span><span role="columnheader" data-i18n="Admin.Sequence.Render.Created"></span>
<span role="columnheader"><span class="sr-only" data-i18n="Admin.Common.Actions"></span></span></div>
<div role="rowgroup">${renders.map((r) => `
<div class="row" role="row" data-key="${attr(r.id)}">
<span class="ellipsis" role="cell" dir="auto" title="${attr(r.producedBy ?? "")}">${escapeHtml(r.presetName)}</span>
<span class="num nowrap" role="cell" dir="ltr">${escapeHtml(`${r.width} × ${r.height} · ${formatNumber(r.fps)} fps${r.codec ? ` · ${r.codec.toUpperCase()}` : ""}`)}</span>
<span class="num end nowrap" role="cell">${escapeHtml(clock(r.durationSeconds))}</span>
<span class="num end nowrap" role="cell">${escapeHtml(formatBytes(r.bytes))}</span>
<span class="muted nowrap" role="cell">${escapeHtml(formatDateTime(r.created))}</span>
<span class="row-actions" role="cell"><a class="btn small" href="/api/v1/renders/${encodeURIComponent(r.id)}/file" download
data-i18n-title="Admin.Sequence.Render.Download.Tip">${icons.download}<span data-i18n="Admin.Sequence.Render.Download"></span></a></span>
</div>`).join("")}</div>
</div>`;
applyStrings(host);
}
/** The photo viewer: the proxy (the thumbnail when there is none), its facts, ← and → through the photos, Esc closes. */
function openViewer(frameId) {
let index = frames.findIndex((f) => f.id === frameId);
if (index < 0) return;
const opener = document.activeElement;
const dialog = document.createElement("dialog");
dialog.className = "dialog viewer";
dialog.setAttribute("aria-labelledby", "viewer-title");
dialog.innerHTML = `
<div class="viewer-head"><h2 id="viewer-title" class="ellipsis" dir="ltr"></h2><span class="muted num nowrap" id="viewer-position"></span>
<span class="spacer"></span>
<span class="inline" dir="ltr"><button class="btn icon" type="button" data-go="-1" data-i18n-title="Admin.Sequence.Previous.Tip">${icons.previous}</button>
<button class="btn icon" type="button" data-go="1" data-i18n-title="Admin.Sequence.Next.Tip">${icons.next}</button></span>
<button class="btn icon" type="button" data-close data-i18n-title="Admin.Sequence.CloseViewer.Tip">${icons.close}</button></div>
<div class="viewer-stage" dir="ltr"><img alt=""><span class="placeholder" aria-hidden="true">${icons.image}</span></div>
<dl class="viewer-meta" id="viewer-meta"></dl>
<div class="buttons">
<button class="btn" type="button" data-cover data-i18n-title="Admin.Sequence.SetCover.Tip">${icons.hero}<span data-i18n="Admin.Sequence.SetCover"></span></button>
<button class="btn" type="button" data-download data-i18n-title="Admin.Sequence.Download.Tip">${icons.download}<span data-i18n="Admin.Sequence.Download"></span></button>
</div>`;
applyStrings(dialog);
document.body.appendChild(dialog);
const img = dialog.querySelector("img");
img.addEventListener("error", () => {
// No proxy (proxies off, or not built yet): the thumbnail, then the placeholder.
const thumb = `/api/v1/frames/${encodeURIComponent(frames[index].id)}/thumb`;
if (!img.src.endsWith(thumb)) img.src = thumb;
else img.classList.add("failed");
});
img.addEventListener("load", () => img.classList.remove("failed"));
const show = async (to) => {
if (to >= frames.length && cursor) await loadFrames(true);
if (to < 0 || to >= frames.length) return;
index = to;
const f = frames[index];
img.classList.remove("failed");
img.src = `/api/v1/frames/${encodeURIComponent(f.id)}/proxy`;
dialog.querySelector("#viewer-title").textContent = f.fileName;
dialog.querySelector("#viewer-position").textContent = t("Admin.Sequence.Position", formatNumber(f.index + 1), formatNumber(seq.frameCount));
dialog.querySelector("#viewer-meta").innerHTML = frameFacts(f);
applyStrings(dialog.querySelector("#viewer-meta"));
dialog.querySelector('[data-go="-1"]').disabled = index === 0;
dialog.querySelector('[data-go="1"]').disabled = index === frames.length - 1 && !cursor;
dialog.querySelector("[data-cover]").disabled = f.id === seq.heroFrameId;
};
dialog.addEventListener("keydown", (e) => {
if (e.key === "ArrowLeft" || e.key === "ArrowRight") {
e.preventDefault();
show(index + (e.key === "ArrowRight" ? 1 : -1));
}
});
dialog.querySelectorAll("[data-go]").forEach((b) => b.addEventListener("click", () => show(index + Number(b.dataset.go))));
dialog.querySelector("[data-close]").addEventListener("click", () => dialog.close());
dialog.querySelector("[data-cover]").addEventListener("click", async () => {
await setCover(frames[index].id);
show(index);
});
dialog.querySelector("[data-download]").addEventListener("click", () => download(frames[index].id));
dialog.addEventListener("close", () => {
const at = frames[index]?.id;
dialog.remove();
// Back on the photo the viewer ended on.
const tile = at && framesHost.querySelector(`[data-key="${CSS.escape(at)}"]`);
(tile ?? opener)?.focus?.();
});
dialog.showModal();
show(index);
}
function frameFacts(f) {
const fact = (key, value, ltr = false) => value === null || value === undefined || value === ""
? "" : `<div><dt data-i18n="Admin.Sequence.Fact.${key}"></dt><dd ${ltr ? 'dir="ltr"' : 'dir="auto"'}>${escapeHtml(value)}</dd></div>`;
const swapped = f.orientation >= 5 && f.orientation <= 8;
const [w, h] = swapped ? [f.height, f.width] : [f.width, f.height];
const offset = f.utcOffsetMinutes == null ? "" : ` UTC${f.utcOffsetMinutes < 0 ? "−" : "+"}${String(Math.floor(Math.abs(f.utcOffsetMinutes) / 60)).padStart(2, "0")}:${String(Math.abs(f.utcOffsetMinutes) % 60).padStart(2, "0")}`;
const flags = FLAGS.filter(([bit]) => (f.flags & bit) !== 0).map(([, name]) => t(`Admin.Sequence.Flag.${name}`)).join(" · ");
return [
fact("Time", f.capturedAt ? captureText(f.capturedAt) + offset : ""),
fact("Exposure", exposure(f.exposureTime), true),
fact("Aperture", f.fNumber ? `f/${formatNumber(f.fNumber)}` : "", true),
fact("Iso", f.iso ? formatNumber(f.iso) : "", true),
fact("Focal", f.focalLength ? `${formatNumber(f.focalLength)} mm` : "", true),
fact("Dimensions", w > 0 && h > 0 ? `${w} × ${h}` : "", true),
fact("Size", formatBytes(f.size)),
fact("Format", f.format.toUpperCase(), true),
fact("Flags", flags),
fact("Sha256", f.sha256 ?? "", true),
].join("");
}
/** Everything again after a change elsewhere; with frames, the photos too. */
async function reload(withFrames) {
const before = seq.framesVersion;
const hero = seq.heroFrameId;
await reloadSequence();
if (!root.isConnected || leaving) return;
drawHeader();
if (withFrames || seq.framesVersion !== before) await reloadFrames();
else if (seq.heroFrameId !== hero) drawFrames();
await loadRenders();
}
function gone() {
if (leaving) return;
leaving = true;
toast(t("Admin.Sequence.Gone"), true);
location.hash = back;
}
onEvent((e) => {
if (e.type !== "sequenceChanged" || e.sequenceId !== id) return;
if (e.change === "deleted") {
gone();
return;
}
clearTimeout(timer);
timer = setTimeout(() => {
if (root.isConnected) reload(false);
}, 800);
});
drawHeader();
await Promise.all([loadFrames(), loadRenders()]);
drawFrameActions();
}
/** 1/250 s, 0.5 s, 30 s. */
function exposure(seconds) {
if (!seconds || seconds <= 0) return "";
if (seconds < 0.5) return `1/${Math.round(1 / seconds)} s`;
return `${Math.round(seconds * 10) / 10} s`;
}
/** A video length as 1:05 or 1:02:05. */
function clock(seconds) {
const s = Math.max(0, Math.round(seconds ?? 0));
const hh = Math.floor(s / 3600);
const mm = Math.floor((s % 3600) / 60);
const ss = String(s % 60).padStart(2, "0");
return hh > 0 ? `${hh}:${String(mm).padStart(2, "0")}:${ss}` : `${mm}:${ss}`;
}
@@ -0,0 +1,283 @@
// What the Library's views share (owner review 2, R6): sequence facts and status chips as the desktop cards show them,
// a selection with Shift ranges, the keyboard of a grid of selectable items, chunked bulk calls and file downloads.
import { t, plural, culture } from "../../i18n.js";
import { escapeHtml, attr, formatNumber, formatDuration } from "../../ui.js";
import { icons } from "../../icons.js";
/** SequenceStatus bits (Chronos.Core.Model). */
export const STATUS = { analysed: 1, deep: 2, proxies: 4, thumbs: 8, verified: 16, warnings: 32, errors: 64 };
/** Ids one bulk request may name (LibraryEndpoints.MaxBulkIds). */
export const BULK_LIMIT = 1000;
/**
* A camera's name as the desktop and the server's facets give it (PathTemplate.CameraName): the make's brand once,
* "Canon EOS R5" (Canon + Canon EOS R5), "Nikon Z 8" (NIKON CORPORATION + NIKON Z 8), "SONY ILCE-7M4".
*/
export function cameraLabel(make, model) {
make = make?.trim();
model = model?.trim();
if (!model) return make ?? "";
if (!make) return model;
let brand = make.split(" ").find(Boolean);
if (brand.toUpperCase() === "NIKON") brand = "Nikon";
return model.toLowerCase().startsWith(brand.toLowerCase()) ? brand + model.slice(brand.length) : `${brand} ${model}`;
}
/** How long the sequence lasts, from its first capture to its last ("2 h 0 m"); "" without captures. */
export function spanText(s) {
if (!s.firstCapture || !s.lastCapture) return "";
return formatDuration((new Date(s.lastCapture) - new Date(s.firstCapture)) / 1000);
}
/** A capture time as the camera recorded it (stored without zone, so read and shown as it was taken). */
export function captureText(iso, withTime = true) {
if (!iso) return "—";
const options = withTime ? { dateStyle: "medium", timeStyle: "short" } : { dateStyle: "medium" };
return new Intl.DateTimeFormat(culture(), options).format(new Date(iso));
}
/** The line under a card's title: "3,600 · Canon EOS R5 · 2 h 0 m". */
export function factsLine(s) {
return [formatNumber(s.frameCount), cameraLabel(s.cameraMake, s.cameraModel), spanText(s)].filter(Boolean).join(" · ");
}
/**
* Status glyphs as DESIGN §4 draws them: ● analysed (○ not yet), ● proxies (○ none), ▶ n renders, ▲ n warnings, ✕ errors,
* ✓ verified. Each chip has its words for screen readers and its tooltip; the glyph alone is decoration.
*/
export function statusChips(s) {
const chip = (cls, glyph, key, text, tipKey) =>
`<span class="st ${cls}" title="${attr(t(tipKey))}"><span aria-hidden="true">${glyph}</span> ${escapeHtml(text ?? t(key))}</span>`;
const on = (bit) => (s.status & bit) !== 0;
const chips = [
on(STATUS.analysed) ? chip("ok", "●", "Admin.Library.Status.Analysed", null, "Admin.Library.Status.Analysed.Tip")
: chip("off", "○", "Admin.Library.Status.NotAnalysed", null, "Admin.Library.Status.NotAnalysed.Tip"),
on(STATUS.proxies) ? chip("", "●", "Admin.Library.Status.Proxies", null, "Admin.Library.Status.Proxies.Tip")
: chip("off", "○", "Admin.Library.Status.NoProxies", null, "Admin.Library.Status.NoProxies.Tip"),
];
if (on(STATUS.verified)) chips.push(chip("ok", "✓", "Admin.Library.Status.Verified", null, "Admin.Library.Status.Verified.Tip"));
if (s.renderedCount > 0) chips.push(chip("", "▶", null, plural("Admin.Library.Status.Renders", s.renderedCount), "Admin.Library.Status.Renders.Tip"));
if (s.warningCount > 0 || on(STATUS.warnings))
chips.push(chip("warn", "▲", null, plural("Admin.Library.Status.Warnings", Math.max(1, s.warningCount)), "Admin.Library.Status.Warnings.Tip"));
if (on(STATUS.errors)) chips.push(chip("err", "✕", "Admin.Library.Status.Errors", null, "Admin.Library.Status.Errors.Tip"));
return chips.join("");
}
/**
* An image the browser loads when it nears the view, with the photo icon in its place while it has none: before it
* arrives, when the thumbnail is not built yet (404) or cannot be read. watchImages() hooks the error up (no inline
* handlers under the panel's policy).
*/
export function lazyImage(src, cls = "") {
return `<span class="thumb ${cls}"><span class="placeholder" aria-hidden="true">${icons.image}</span>` +
`<img loading="lazy" decoding="async" alt="" src="${attr(src)}" data-fallback></span>`;
}
export function watchImages(root) {
root.querySelectorAll("img[data-fallback]").forEach((img) => {
img.removeAttribute("data-fallback");
img.addEventListener("error", () => img.classList.add("failed"), { once: true });
img.addEventListener("load", () => img.classList.add("loaded"), { once: true });
});
}
/** A sequence's cover thumbnail; its address changes with the cover and the photos, so a browser's copy never shows an old one. */
export function coverUrl(s) {
return `/api/v1/sequences/${encodeURIComponent(s.id)}/thumb?v=${s.heroFrameId ?? "first"}-${s.framesVersion}`;
}
/** Items picked by click, Space and Shift ranges over the order shown; the anchor is where the next range starts. */
export class Selection {
constructor() {
this.ids = new Set();
this.anchor = null;
}
get size() {
return this.ids.size;
}
has(id) {
return this.ids.has(id);
}
toggle(id) {
if (!this.ids.delete(id)) this.ids.add(id);
this.anchor = id;
}
/** Selects every item from the anchor to id in order (the anchor stays), or id alone without an anchor in view. */
range(id, order) {
const from = order.indexOf(this.anchor);
const to = order.indexOf(id);
if (from < 0 || to < 0) return this.toggle(id);
const [a, b] = from < to ? [from, to] : [to, from];
for (let i = a; i <= b; i++) this.ids.add(order[i]);
}
set(ids) {
this.ids = new Set(ids);
}
clear() {
this.ids.clear();
this.anchor = null;
}
}
/**
* The keyboard and pointer of a grid of selectable items (role="option" with data-key, in a role="listbox"): one tab
* stop (the current item), arrows move along the reading direction and between rows, Home and End, Space selects
* (Shift+Space: the range from the last one picked), Enter opens, Ctrl+A selects everything shown, Esc clears the
* selection. A click on an item's check box selects (with Shift, a range), Ctrl+click too; a plain click opens.
* The caller redraws through onChange after the selection changed.
*/
export function selectableGrid(host, { selection, order, open, onChange }) {
let current = null;
const items = () => [...host.querySelectorAll('[role="option"]')];
const focusItem = (el) => {
if (!el) return;
items().forEach((i) => (i.tabIndex = i === el ? 0 : -1));
current = el.dataset.key;
el.focus();
};
const pick = (key, shift) => {
if (shift) selection.range(key, order());
else selection.toggle(key);
onChange();
};
host.addEventListener("focusin", (e) => {
const el = e.target.closest?.('[role="option"]');
if (el && host.contains(el)) {
current = el.dataset.key;
items().forEach((i) => (i.tabIndex = i === el ? 0 : -1));
}
});
host.addEventListener("click", (e) => {
const el = e.target.closest('[role="option"]');
if (!el || !host.contains(el)) return;
if (e.target.closest("[data-check]") || e.ctrlKey || e.metaKey || e.shiftKey) {
// A check box keeps its own click (a cancelled one would put its old state back after onChange drew the new one).
if (!e.target.matches("input[data-check]")) e.preventDefault();
pick(el.dataset.key, e.shiftKey);
return;
}
if (e.target.closest("a, button")) return;
open(el.dataset.key);
});
host.addEventListener("keydown", (e) => {
const el = e.target.closest?.('[role="option"]');
if (!el || e.altKey) return;
const list = items();
const index = list.indexOf(el);
const rtl = getComputedStyle(host).direction === "rtl";
let next = null;
switch (e.key) {
case "ArrowRight": next = list[index + (rtl ? -1 : 1)]; break;
case "ArrowLeft": next = list[index + (rtl ? 1 : -1)]; break;
case "ArrowDown": next = list[index + columns(list)]; break;
case "ArrowUp": next = list[index - columns(list)]; break;
case "Home": next = list[0]; break;
case "End": next = list[list.length - 1]; break;
case " ":
e.preventDefault();
pick(el.dataset.key, e.shiftKey);
return;
case "Enter":
e.preventDefault();
open(el.dataset.key);
return;
case "Escape":
if (selection.size === 0) return;
e.preventDefault();
selection.clear();
onChange();
return;
case "a":
case "A":
if (!(e.ctrlKey || e.metaKey)) return;
e.preventDefault();
selection.set(list.map((i) => i.dataset.key));
onChange();
return;
default:
return;
}
e.preventDefault();
focusItem(next);
});
return {
/** After a redraw: the current item keeps the tab stop (the first one when it is gone). */
restore(focus = false) {
const list = items();
const el = list.find((i) => i.dataset.key === current) ?? list[0];
list.forEach((i) => (i.tabIndex = i === el ? 0 : -1));
if (focus && el) el.focus();
},
};
}
/** Items per row of a wrapping grid: those on the first item's line. */
function columns(list) {
const top = list[0]?.offsetTop;
const n = list.findIndex((i) => i.offsetTop !== top);
return n < 0 ? list.length || 1 : n;
}
/** Tags typed as "night, roof; sky": trimmed, once each (case-insensitive), none empty. */
export function tagList(text) {
const seen = new Set();
return String(text ?? "").split(/[,;]/).map((s) => s.trim()).filter((s) => {
const key = s.toLocaleLowerCase();
if (!s || seen.has(key)) return false;
seen.add(key);
return true;
});
}
/** The ids in requests of at most BULK_LIMIT, in their order. */
export function chunks(ids, size = BULK_LIMIT) {
const out = [];
for (let i = 0; i < ids.length; i += size) out.push(ids.slice(i, i + size));
return out;
}
/** Hands the browser a file to save (a Blob made here; nothing leaves the page). */
export function saveFile(name, blob) {
const url = URL.createObjectURL(blob);
const a = document.createElement("a");
a.href = url;
a.download = name;
document.body.appendChild(a);
a.click();
a.remove();
setTimeout(() => URL.revokeObjectURL(url), 1000);
}
/**
* Sequences as CSV (comma separated, UTF-8 with a byte-order mark for spreadsheets): title, camera, photos, size in
* bytes, first and last capture (ISO, as the camera recorded them) and tags. A cell a spreadsheet would run as a formula
* starts with an apostrophe.
*/
export function sequencesCsv(sequences) {
const cell = (value) => {
let text = String(value ?? "");
if (/^[=+\-@\t\r]/.test(text)) text = `'${text}`;
return /[",\n\r]/.test(text) ? `"${text.replaceAll('"', '""')}"` : text;
};
const head = ["Admin.Library.Csv.Title", "Admin.Library.Csv.Camera", "Admin.Library.Csv.Photos", "Admin.Library.Csv.Bytes",
"Admin.Library.Csv.First", "Admin.Library.Csv.Last", "Admin.Library.Csv.Tags"].map((key) => cell(t(key)));
const rows = sequences.map((s) => [s.displayTitle, cameraLabel(s.cameraMake, s.cameraModel), s.frameCount, s.totalBytes,
s.firstCapture ?? "", s.lastCapture ?? "", (s.tags ?? []).join("; ")].map(cell).join(","));
return new Blob(["" + [head.join(","), ...rows].join("\r\n") + "\r\n"], { type: "text/csv;charset=utf-8" });
}
/** "2026-10-27" in the file names of exports. */
export function today() {
const d = new Date();
return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}-${String(d.getDate()).padStart(2, "0")}`;
}
@@ -0,0 +1,156 @@
// The archive's trash on the panel (owner review 2, R6; #/library?view=trash, reached from the Library and the Archive):
// deleted sequences and photos deleted from sequences, each restorable; emptying it is the panel's only erase of user
// files, so it measures the trash first (dry run), names what goes, asks for the word "empty" to be typed and sends the
// plan's fingerprint, which the server's job checks again before it erases anything.
import { t, plural, applyStrings } from "../../i18n.js";
import { escapeHtml, attr, formatBytes, formatNumber, formatDateTime, toast, errorText, confirmDialog, emptyState, redraw, fitColumns } from "../../ui.js";
import { icons } from "../../icons.js";
export async function renderTrash(root, { api, setMeta, actions, onEvent }, { back }) {
let entries = [];
let bytes = 0;
/** The empty-trash job this page queued, followed until it ends. */
let emptyJob = null;
let timer = null;
actions.innerHTML = `
<a class="btn" href="${attr(back)}" data-i18n-title="Admin.Trash.Back.Tip">${icons.back}<span data-i18n="Admin.Trash.Back"></span></a>
<button class="btn destructive" id="empty" data-i18n="Admin.Trash.Empty" data-i18n-title="Admin.Trash.Empty.Tip"></button>`;
applyStrings(actions);
const emptyButton = actions.querySelector("#empty");
emptyButton.addEventListener("click", emptyTrash);
root.innerHTML = `
<section class="panel flush" aria-labelledby="trash-title">
<div class="panel-head padded"><h2 id="trash-title" data-i18n="Admin.Trash.Title"></h2><span class="muted ellipsis" id="trash-meta"></span></div>
<div class="table trash" data-levels="1" role="table" aria-labelledby="trash-title">
<div class="thead" role="row"><span role="columnheader" data-i18n="Admin.Trash.Kind"></span><span role="columnheader" data-i18n="Admin.Trash.Sequence"></span>
<span role="columnheader" class="end" data-i18n="Admin.Trash.Photos"></span><span role="columnheader" class="end" data-i18n="Admin.Trash.Size"></span>
<span role="columnheader" class="col-by" data-i18n="Admin.Trash.DeletedBy"></span><span role="columnheader" data-i18n="Admin.Trash.DeletedAt"></span>
<span role="columnheader"><span class="sr-only" data-i18n="Admin.Common.Actions"></span></span></div>
<div id="rows" role="rowgroup"></div>
</div>
</section>`;
applyStrings(root);
const table = root.querySelector(".table");
async function load() {
try {
const list = await api.get("/api/v1/archive/trash");
entries = list.entries;
bytes = list.bytes;
} catch (err) {
toast(errorText(err), true);
return;
}
if (!root.isConnected) return;
const summary = entries.length === 0 ? "" : `${plural("Admin.Trash.EntryCount", entries.length)} · ${formatBytes(bytes)}`;
setMeta(t("Admin.Trash.Title"));
root.querySelector("#trash-meta").textContent = summary;
emptyButton.disabled = entries.length === 0 || emptyJob !== null;
emptyButton.title = t(entries.length === 0 ? "Admin.Trash.NothingToEmpty.Tip" : emptyJob ? "Admin.Trash.Emptying.Tip" : "Admin.Trash.Empty.Tip");
draw();
}
function draw() {
const host = root.querySelector("#rows");
redraw(host, () => {
host.innerHTML = entries.map((e) => `
<div class="row" role="row" data-key="${attr(e.name)}">
<span class="nowrap" role="cell">${escapeHtml(kindLabel(e.kind))}</span>
<span class="stack" role="cell"><strong class="ellipsis" dir="auto" title="${attr(e.title)}">${escapeHtml(e.title)}</strong>
<small dir="ltr" class="mono" title="${attr(e.folder)}">${escapeHtml(e.folder)}</small></span>
<span class="num end" role="cell">${formatNumber(e.photos)}</span>
<span class="num end nowrap" role="cell">${escapeHtml(formatBytes(e.bytes))}</span>
<span class="col-by ellipsis" role="cell" dir="auto">${escapeHtml(e.deletedBy ?? "—")}</span>
<span class="muted nowrap" role="cell">${escapeHtml(formatDateTime(e.deletedAt))}</span>
<span class="row-actions" role="cell"><button class="btn small" data-restore="${attr(e.name)}" data-i18n="Admin.Trash.Restore"
data-i18n-title="${e.kind === "sequence" ? "Admin.Trash.RestoreSequence.Tip" : "Admin.Trash.RestorePhotos.Tip"}"></button></span>
</div>`).join("")
|| `<div class="row" role="row"><div class="wide" role="cell">${emptyState("Admin.Trash.IsEmpty",
`<a class="btn small" href="${attr(back)}" data-i18n="Admin.Trash.Back" data-i18n-title="Admin.Trash.Back.Tip"></a>`)}</div></div>`;
applyStrings(host);
});
host.querySelectorAll("[data-restore]").forEach((b) => b.addEventListener("click", () => restore(entries.find((e) => e.name === b.dataset.restore), b)));
fitColumns(table);
}
async function restore(entry, button) {
if (!entry) return;
button.disabled = true;
let result;
try {
result = await api.post(`/api/v1/archive/trash/${encodeURIComponent(entry.name)}/restore`);
} catch (err) {
toast(errorText(err), true);
if (button.isConnected) button.disabled = false;
return;
}
const lines = [result.kind === "sequence" ? t("Admin.Trash.RestoredSequence", entry.title)
: result.newSequence ? plural("Admin.Trash.RestoredNew", result.photos) : plural("Admin.Trash.RestoredPhotos", result.photos, entry.title)];
if (result.kept.length > 0) lines.push(plural("Admin.Trash.Kept", result.kept.length));
toast(lines.join(" "), result.kept.length > 0);
await load();
}
/** Measure (dry run), name what goes, have "empty" typed, then queue the erase with the plan's fingerprint. */
async function emptyTrash() {
emptyButton.disabled = true;
try {
let plan;
try {
plan = await api.post("/api/v1/archive/trash/empty", { names: null, dryRun: true, fingerprint: null });
} catch (err) {
toast(errorText(err), true);
return;
}
if (plan.entries.length === 0) {
toast(t("Admin.Trash.IsEmpty"));
await load();
return;
}
const confirmed = await confirmDialog({
title: t("Admin.Trash.EmptyTitle"),
body: [plural("Admin.Trash.EmptyBody", plan.files, formatBytes(plan.bytes)), t("Admin.Trash.EmptyFinal")].join(" "),
list: plan.entries.map((e) => t("Admin.Trash.PlanItem", kindLabel(e.kind), e.title, formatBytes(e.bytes))),
confirm: t("Admin.Trash.EmptyConfirm"),
confirmTip: t("Admin.Trash.EmptyConfirm.Tip"),
cancel: t("Admin.Common.Keep"),
cancelTip: t("Admin.Common.Keep.Tip"),
typed: t("Admin.Trash.EmptyWord"),
typedKind: "word",
});
if (!confirmed) return;
try {
const job = await api.post("/api/v1/archive/trash/empty", { names: null, dryRun: false, fingerprint: plan.fingerprint });
emptyJob = job.id;
toast(t("Admin.Trash.EmptyQueued"));
} catch (err) {
// trash_changed: something entered or left the trash since it was measured; it is shown as it is now.
toast(errorText(err), true);
}
} finally {
await load();
}
}
onEvent((e) => {
if (e.type === "jobState" && e.jobId === emptyJob && (e.state === "done" || e.state === "failed" || e.state === "cancelled")) {
emptyJob = null;
if (e.state === "done") toast(t("Admin.Trash.Emptied"));
else toast(e.error || t("Admin.Trash.EmptyFailed"), true);
load();
} else if (e.type === "sequenceChanged") {
// A deletion or a restore elsewhere changes what the trash holds.
clearTimeout(timer);
timer = setTimeout(() => {
if (root.isConnected) load();
}, 800);
}
});
await load();
}
function kindLabel(kind) {
return t(kind === "sequence" ? "Admin.Trash.Kind.Sequence" : kind === "replaced" ? "Admin.Trash.Kind.Replaced" : "Admin.Trash.Kind.Photos");
}
+185
View File
@@ -0,0 +1,185 @@
// Incremental SHA-256 (FIPS 180-4) for the upload dialog (owner review 2, R3): photos are hashed while they are read in
// blocks, which crypto.subtle cannot do (it digests one buffer). In-house like everything else; the hash worker checks it
// against known answers and crypto.subtle before using it (selfTest), and the server verifies every upload again.
const K = new Int32Array([
0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2,
]);
const INITIAL = [0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19];
/** Hashes the whole 64-byte blocks of bytes[pos, end) into state h; returns where the first unprocessed byte is. */
function blocks(h, w, bytes, pos, end) {
let h0 = h[0], h1 = h[1], h2 = h[2], h3 = h[3], h4 = h[4], h5 = h[5], h6 = h[6], h7 = h[7];
while (end - pos >= 64) {
for (let i = 0; i < 16; i++, pos += 4) w[i] = (bytes[pos] << 24) | (bytes[pos + 1] << 16) | (bytes[pos + 2] << 8) | bytes[pos + 3];
for (let i = 16; i < 64; i++) {
const x = w[i - 15];
const y = w[i - 2];
const s0 = ((x >>> 7) | (x << 25)) ^ ((x >>> 18) | (x << 14)) ^ (x >>> 3);
const s1 = ((y >>> 17) | (y << 15)) ^ ((y >>> 19) | (y << 13)) ^ (y >>> 10);
w[i] = (w[i - 16] + s0 + w[i - 7] + s1) | 0;
}
let a = h0, b = h1, c = h2, d = h3, e = h4, f = h5, g = h6, k = h7;
for (let i = 0; i < 64; i++) {
const s1 = ((e >>> 6) | (e << 26)) ^ ((e >>> 11) | (e << 21)) ^ ((e >>> 25) | (e << 7));
const t1 = (k + s1 + ((e & f) ^ (~e & g)) + K[i] + w[i]) | 0;
const s0 = ((a >>> 2) | (a << 30)) ^ ((a >>> 13) | (a << 19)) ^ ((a >>> 22) | (a << 10));
const t2 = (s0 + ((a & b) ^ (a & c) ^ (b & c))) | 0;
k = g;
g = f;
f = e;
e = (d + t1) | 0;
d = c;
c = b;
b = a;
a = (t1 + t2) | 0;
}
h0 = (h0 + a) | 0;
h1 = (h1 + b) | 0;
h2 = (h2 + c) | 0;
h3 = (h3 + d) | 0;
h4 = (h4 + e) | 0;
h5 = (h5 + f) | 0;
h6 = (h6 + g) | 0;
h7 = (h7 + k) | 0;
}
h[0] = h0; h[1] = h1; h[2] = h2; h[3] = h3; h[4] = h4; h[5] = h5; h[6] = h6; h[7] = h7;
return pos;
}
function asBytes(data) {
if (data instanceof Uint8Array) return data;
if (data instanceof ArrayBuffer) return new Uint8Array(data);
if (ArrayBuffer.isView(data)) return new Uint8Array(data.buffer, data.byteOffset, data.byteLength);
throw new TypeError("SHA-256 hashes bytes");
}
/** SHA-256 fed in pieces of any size: update(bytes) as often as needed, then digest() once. */
export class Sha256 {
constructor() {
this.h = new Int32Array(INITIAL);
this.w = new Int32Array(64);
this.buffer = new Uint8Array(64);
this.buffered = 0;
this.length = 0;
this.finished = false;
}
/** Adds bytes (Uint8Array, another typed array or an ArrayBuffer) to the message. */
update(data) {
if (this.finished) throw new Error("SHA-256 already digested");
const bytes = asBytes(data);
this.length += bytes.length;
let pos = 0;
if (this.buffered > 0) {
const take = Math.min(64 - this.buffered, bytes.length);
this.buffer.set(bytes.subarray(0, take), this.buffered);
this.buffered += take;
pos = take;
if (this.buffered < 64) return this;
blocks(this.h, this.w, this.buffer, 0, 64);
this.buffered = 0;
}
pos = blocks(this.h, this.w, bytes, pos, bytes.length);
if (pos < bytes.length) {
this.buffer.set(bytes.subarray(pos), 0);
this.buffered = bytes.length - pos;
}
return this;
}
/** The 32-byte digest; the hash takes no more input afterwards. */
digest() {
if (this.finished) throw new Error("SHA-256 already digested");
this.finished = true;
const tail = new Uint8Array(this.buffered < 56 ? 64 : 128);
tail.set(this.buffer.subarray(0, this.buffered));
tail[this.buffered] = 0x80;
// The message length in bits as a 64-bit big-endian number, split without losing precision above 2^32.
const high = Math.floor(this.length / 0x20000000);
const low = (this.length % 0x20000000) * 8;
const view = new DataView(tail.buffer);
view.setUint32(tail.length - 8, high);
view.setUint32(tail.length - 4, low);
blocks(this.h, this.w, tail, 0, tail.length);
const out = new Uint8Array(32);
const result = new DataView(out.buffer);
for (let i = 0; i < 8; i++) result.setUint32(i * 4, this.h[i] >>> 0);
return out;
}
}
/** Lower-case hexadecimal, as the upload API takes a SHA-256. */
export function toHex(bytes) {
let hex = "";
for (const b of bytes) hex += (b < 16 ? "0" : "") + b.toString(16);
return hex;
}
/** The hex SHA-256 of one buffer. */
export function sha256Hex(data) {
return toHex(new Sha256().update(data).digest());
}
const ascii = (text) => new TextEncoder().encode(text);
/** FIPS 180-4 examples (and the NIST long-message test): message and expected digest. */
const KNOWN_ANSWERS = [
["", "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"],
["abc", "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"],
["abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq", "248d6a61d20638b8e5c026930c3e6039a33ce45964ff2167f6ecedd419db06c1"],
[
"abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghijklmnhijklmnoijklmnopjklmnopqklmnopqrlmnopqrsmnopqrstnopqrstu",
"cf5b16a778af8380036ce59e7b0492370b249b11e8f07a51afac45037afee9d1",
],
];
const MILLION_A = "cdc76e5c9914fb9281a1c7e284d73e67f1809a48a497200e046d39ccc7112cd0";
/** Feeds bytes in pieces of uneven sizes, so the partial-block buffer is exercised at every offset. */
function piecewise(bytes) {
const hash = new Sha256();
const sizes = [1, 63, 64, 65, 0, 127, 128, 129, 1000, 4096, 55, 56, 57];
let pos = 0;
for (let i = 0; pos < bytes.length; i++) {
const size = Math.min(sizes[i % sizes.length], bytes.length - pos);
hash.update(bytes.subarray(pos, pos + size));
pos += size;
}
return toHex(hash.digest());
}
/**
* Runs the known-answer tests (whole and piece by piece) and, where crypto.subtle exists (secure pages), compares a 1 MiB
* random buffer with it. Resolves to null when every check passes, else to the name of the first one that failed: the
* caller refuses to hash then (fail closed).
*/
export async function selfTest() {
for (const [message, expected] of KNOWN_ANSWERS) {
const bytes = ascii(message);
if (sha256Hex(bytes) !== expected || piecewise(bytes) !== expected) return `kat:${message.length}`;
}
const million = new Uint8Array(1_000_000).fill(0x61);
if (sha256Hex(million) !== MILLION_A || piecewise(million) !== MILLION_A) return "kat:million";
const subtle = globalThis.crypto?.subtle;
if (subtle) {
const random = new Uint8Array(1 << 20);
// getRandomValues fills at most 64 KiB per call.
for (let pos = 0; pos < random.length; pos += 65536) globalThis.crypto.getRandomValues(random.subarray(pos, pos + 65536));
let reference;
try {
reference = toHex(new Uint8Array(await subtle.digest("SHA-256", random)));
} catch {
reference = null;
}
if (reference !== null && (sha256Hex(random) !== reference || piecewise(random) !== reference)) return "subtle";
}
return null;
}
+69 -8
View File
@@ -1,5 +1,5 @@
// Small DOM and formatting helpers shared by the admin pages. No inline styles: the panel runs under a strict CSP.
import { t, culture } from "./i18n.js";
import { t, culture, applyStrings } from "./i18n.js";
export function escapeHtml(s) {
return String(s ?? "").replace(/[&<>"']/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" }[c]));
@@ -145,33 +145,53 @@ export function toast(message, isError = false) {
let dialogs = 0;
/** What a typed confirmation asks for: its field's tooltip, the confirm button's while it waits, and how a value matches. */
const TYPED = {
// A name (an account), exactly as shown.
name: { tip: "Admin.Common.TypeToConfirm.Tip", first: "Admin.Common.TypeFirst.Tip", matches: (value, typed) => value === typed },
// A word of the interface (the localised "empty"), whatever its case.
word: { tip: "Admin.Common.TypeWord.Tip", first: "Admin.Common.TypeWordFirst.Tip",
matches: (value, typed) => value.trim().toLocaleLowerCase() === typed.toLocaleLowerCase() },
// A count (the photos a deletion moves), its digits whatever the separators typed between them.
count: { tip: "Admin.Common.TypeCount.Tip", first: "Admin.Common.TypeCountFirst.Tip",
matches: (value, typed) => value.replace(/[\s.,'’  ]/g, "") === typed },
};
/**
* Two-button confirmation dialog (safe action left and default, Esc keeps). Resolves true when the destructive action
* is chosen; with `typed`, that button stays disabled until the text is typed into the labelled field.
* is chosen; with `typed`, that button stays disabled until the text is typed into the labelled field, as `typedKind`
* says: a name exactly, a word whatever its case, or a count. `list` adds the items the action concerns (titles,
* entries) under the body, in a scrolling box; user text, so each keeps its own direction.
*/
export function confirmDialog({ title, body, confirm, confirmTip, cancel, cancelTip, typed }) {
export function confirmDialog({ title, body, list, confirm, confirmTip, cancel, cancelTip, typed, typedKind = "name" }) {
return new Promise((resolve) => {
const id = `dialog-${++dialogs}`;
const dialog = document.createElement("dialog");
dialog.className = "dialog";
dialog.setAttribute("aria-labelledby", `${id}-title`);
if (body) dialog.setAttribute("aria-describedby", `${id}-body`);
const kind = TYPED[typedKind] ?? TYPED.name;
const firstTip = t(kind.first);
const matches = (value) => kind.matches(value, String(typed));
// The text to type stands out of its sentence, and keeps its own direction.
const typedLabel = typed ? escapeHtml(t("Admin.Common.TypeToConfirm", "\u0001")).replace("\u0001", `<strong dir="auto">${escapeHtml(typed)}</strong>`) : "";
dialog.innerHTML = `
<form method="dialog">
<h2 id="${id}-title" dir="auto">${escapeHtml(title)}</h2>
${body ? `<p id="${id}-body">${escapeHtml(body)}</p>` : ""}
${typed ? `<label class="field-label"><span>${escapeHtml(t("Admin.Common.TypeToConfirm", typed))}</span>
<input class="input" name="typed" autocomplete="off" spellcheck="false" dir="auto" title="${attr(t("Admin.Common.TypeToConfirm.Tip"))}"></label>` : ""}
${list?.length ? `<ul class="dialog-list" tabindex="0" aria-label="${attr(title)}">${list.map((item) => `<li dir="auto">${escapeHtml(item)}</li>`).join("")}</ul>` : ""}
${typed ? `<label class="field-label"><span>${typedLabel}</span>
<input class="input" name="typed" autocomplete="off" spellcheck="false" dir="auto" ${typedKind === "count" ? 'inputmode="numeric"' : ""} title="${attr(t(kind.tip))}"></label>` : ""}
<div class="buttons">
<button class="btn" value="cancel" title="${attr(cancelTip)}" autofocus>${escapeHtml(cancel)}</button>
<button class="btn destructive" value="ok" title="${attr(typed ? t("Admin.Common.TypeFirst.Tip") : confirmTip)}" ${typed ? "disabled" : ""}>${escapeHtml(confirm)}</button>
<button class="btn destructive" value="ok" title="${attr(typed ? firstTip : confirmTip)}" ${typed ? "disabled" : ""}>${escapeHtml(confirm)}</button>
</div>
</form>`;
document.body.appendChild(dialog);
const ok = dialog.querySelector('button[value="ok"]');
dialog.querySelector('input[name="typed"]')?.addEventListener("input", (e) => {
ok.disabled = e.target.value !== typed;
ok.title = ok.disabled ? t("Admin.Common.TypeFirst.Tip") : confirmTip;
ok.disabled = !matches(e.target.value);
ok.title = ok.disabled ? firstTip : confirmTip;
});
dialog.addEventListener("close", () => {
resolve(dialog.returnValue === "ok");
@@ -181,6 +201,47 @@ export function confirmDialog({ title, body, confirm, confirmTip, cancel, cancel
});
}
/**
* A dialog of form fields (fields: HTML whose data-i18n attributes are filled here) with the action on the right, which
* Enter in a field chooses too; Esc or the safe button cancels. Resolves the FormData once confirmed, null when cancelled.
* check(form) may refuse the values: it marks the field (markInvalid) and returns false, and the dialog stays open.
*/
export function formDialog({ title, fields, confirm, confirmTip, cancel, cancelTip, check }) {
return new Promise((resolve) => {
const id = `dialog-${++dialogs}`;
const dialog = document.createElement("dialog");
dialog.className = "dialog";
dialog.setAttribute("aria-labelledby", `${id}-title`);
dialog.innerHTML = `
<form method="dialog" class="form" novalidate>
<h2 id="${id}-title" dir="auto">${escapeHtml(title)}</h2>
${fields}
<div class="buttons">
<button class="btn" type="button" value="cancel" title="${attr(cancelTip)}">${escapeHtml(cancel)}</button>
<button class="btn primary" value="ok" title="${attr(confirmTip)}">${escapeHtml(confirm)}</button>
</div>
</form>`;
applyStrings(dialog);
document.body.appendChild(dialog);
const form = dialog.querySelector("form");
let result = null;
form.addEventListener("submit", (e) => {
if (check && !check(form)) {
e.preventDefault();
return;
}
result = new FormData(form);
});
dialog.querySelector('button[value="cancel"]').addEventListener("click", () => dialog.close());
dialog.addEventListener("close", () => {
resolve(result);
dialog.remove();
});
dialog.showModal();
form.querySelector("input, select, textarea")?.focus();
});
}
/** The localised message of an API failure, or the generic one when the server was not reached. */
export function errorText(err) {
return err?.message && err.status ? err.message : t("Admin.Error.Unreachable");
+693
View File
@@ -0,0 +1,693 @@
// Upload dialog of the admin panel (owner review 2, R3; BRIEF §14.4, §14.8): photos from this computer into an existing
// or a new sequence, chosen with the file picker or dropped on the dialog. Folders are not taken: importing a whole folder
// stays a feature of the desktop app. Each photo is hashed in a module worker (hash-worker.js, which self-tests its
// SHA-256 first and refuses to hash when a check fails), started, sent in the chunks the server does not have yet and
// completed; the server verifies the hash again before it files the photo.
import { ApiFailure } from "./api.js";
import { t, plural, applyStrings, culture } from "./i18n.js";
import { escapeHtml, attr, bar, formatBytes, formatNumber, errorText } from "./ui.js";
import { icons } from "./icons.js";
/** Photos sent at once, and chunks in flight for each: four requests, half of what the server takes from one account. */
const FILES_AT_ONCE = 2;
const CHUNKS_AT_ONCE = 2;
/** Retries of a call that failed for a passing reason (no answer, 429, 503), after 1, 2 and 4 seconds. */
const RETRIES = 3;
const SEARCH_DELAY = 250;
const LIST_LIMIT = 50;
/** States of a photo already on the server: a later run leaves it alone. */
const FINISHED = new Set(["done", "exists", "deleted"]);
/** States of a photo a run is sending. */
const ACTIVE = new Set(["hashing", "starting", "uploading", "verifying"]);
/** A failure of the hash worker: kind self_test (its SHA-256 failed a check), worker (it did not run), read or stopped. */
class HashError extends Error {
constructor(kind, detail = "") {
super(`${kind} ${detail}`.trim());
this.kind = kind;
}
}
let dialogs = 0;
/**
* Opens the upload dialog. With sequence ({ id, title } or a SequenceDto) the photos go into it; without, the dialog
* lets the user pick an existing sequence or name a new one. onDone() runs after every run that changed the library
* (photos uploaded or a sequence created), so the page can refresh. Resolves when the dialog closes.
*/
export function openUpload({ api, sequence, onDone } = {}) {
return new Promise((resolve) => {
const id = `upload-${++dialogs}`;
let target = sequence?.id ? { id: sequence.id, title: sequence.displayTitle ?? sequence.title ?? "" } : null;
let extensions = null;
let maxBytes = 0;
let running = false;
let controller = null;
let broken = null;
let hasher = null;
let searchTimer = null;
let searchToken = 0;
let frame = 0;
const items = [];
const skipped = { folders: 0, formats: 0, size: 0 };
const titles = new Map();
const dialog = document.createElement("dialog");
dialog.className = "dialog upload";
dialog.setAttribute("aria-labelledby", `${id}-title`);
dialog.innerHTML = `
<form novalidate>
<h2 id="${id}-title" data-i18n="Admin.Upload.Title"></h2>
<div class="upload-target" id="${id}-target"></div>
<div class="drop">
<button class="btn" type="button" data-act="add" data-i18n="Admin.Upload.Add" data-i18n-title="Admin.Upload.Add.Tip"></button>
<span data-i18n="Admin.Upload.Drop"></span>
<input type="file" multiple hidden tabindex="-1">
</div>
<div class="chips upload-notes" hidden></div>
<ul class="upload-files" aria-label="${attr(t("Admin.Upload.Photos"))}" hidden></ul>
<div class="upload-total" hidden></div>
<div class="error" role="alert"></div>
<div class="buttons">
<button class="btn" type="button" data-act="close" data-i18n="Admin.Upload.Close" data-i18n-title="Admin.Upload.Close.Tip"></button>
<button class="btn primary" type="submit" data-act="start" data-i18n="Admin.Upload.Start" data-i18n-title="Admin.Upload.Start.Tip"></button>
</div>
</form>`;
document.body.appendChild(dialog);
applyStrings(dialog);
const form = dialog.querySelector("form");
const targetHost = dialog.querySelector(`#${id}-target`);
const input = dialog.querySelector('input[type="file"]');
const addButton = dialog.querySelector('[data-act="add"]');
const closeButton = dialog.querySelector('[data-act="close"]');
const startButton = dialog.querySelector('[data-act="start"]');
const notes = dialog.querySelector(".upload-notes");
const list = dialog.querySelector(".upload-files");
const total = dialog.querySelector(".upload-total");
const errorLine = dialog.querySelector(".error");
drawTarget();
drawButtons();
addButton.addEventListener("click", () => input.click());
input.addEventListener("change", () => {
take([...input.files], 0);
input.value = "";
});
form.addEventListener("submit", (e) => {
e.preventDefault();
run();
});
closeButton.addEventListener("click", () => {
if (running) cancel();
else dialog.close();
});
list.addEventListener("click", (e) => {
const button = e.target.closest('[data-act="remove"]');
if (!button || running) return;
const index = items.findIndex((i) => i.key === button.closest("[data-key]").dataset.key);
if (index < 0) return;
const [item] = items.splice(index, 1);
const next = item.row.nextElementSibling ?? item.row.previousElementSibling;
item.row.remove();
(next?.querySelector('[data-act="remove"]:not([hidden])') ?? addButton).focus();
drawList();
});
// Drops: photos are taken, folders only counted (BRIEF §14.8: no folder upload on the web).
const hasFiles = (e) => [...(e.dataTransfer?.types ?? [])].includes("Files");
dialog.addEventListener("dragover", (e) => {
if (!hasFiles(e)) return;
e.preventDefault();
e.dataTransfer.dropEffect = running || extensions === null ? "none" : "copy";
dialog.classList.add("dragging");
});
dialog.addEventListener("dragleave", (e) => {
if (!dialog.contains(e.relatedTarget)) dialog.classList.remove("dragging");
});
dialog.addEventListener("drop", (e) => {
if (!hasFiles(e)) return;
e.preventDefault();
dialog.classList.remove("dragging");
if (running || extensions === null) return;
const { files, folders } = dropped(e.dataTransfer);
take(files, folders);
});
// Esc closes only while nothing is being sent; Cancel stops a run.
dialog.addEventListener("cancel", (e) => {
if (running) e.preventDefault();
});
// Leaving the page while photos are sent asks first (returnValue for browsers before preventDefault counted).
const guard = (e) => {
e.preventDefault();
e.returnValue = true;
};
const signedOut = () => {
controller?.abort();
dialog.close();
};
window.addEventListener("chronos:signed-out", signedOut);
dialog.addEventListener("close", () => {
controller?.abort();
hasher?.stop();
clearTimeout(searchTimer);
cancelAnimationFrame(frame);
window.removeEventListener("beforeunload", guard);
window.removeEventListener("chronos:signed-out", signedOut);
dialog.remove();
resolve();
});
dialog.showModal();
targetHost.querySelector('input[type="search"]')?.focus();
const firstFocus = document.activeElement;
// The photo extensions and the size limit the server announces: only those are offered and sent.
api.get("/api/v1/server/info").then((info) => {
extensions = new Set((info?.extensions ?? []).map((e) => String(e).toLowerCase()));
maxBytes = info?.limits?.maxUploadBytes ?? 0;
input.accept = [...extensions].map((e) => `.${e}`).join(",");
drawButtons();
// Into a given sequence the first step is adding photos, once the button can be used.
if (target && document.activeElement === firstFocus) addButton.focus();
}).catch((err) => showError(errorText(err)));
/** The target: fixed (given, or chosen when the first run started), else the choice of an existing or a new sequence. */
function drawTarget() {
if (target) {
targetHost.innerHTML = `<div class="field-label"><span data-i18n="Admin.Upload.Target"></span>
<strong class="ellipsis" dir="auto" title="${attr(target.title)}">${escapeHtml(target.title)}</strong></div>`;
applyStrings(targetHost);
return;
}
targetHost.innerHTML = `
<fieldset class="upload-choice"><legend data-i18n="Admin.Upload.Target"></legend>
<label class="check"><input type="radio" name="mode" value="existing" checked data-i18n-title="Admin.Upload.Existing.Tip"><span data-i18n="Admin.Upload.Existing"></span></label>
<label class="check"><input type="radio" name="mode" value="new" data-i18n-title="Admin.Upload.New.Tip"><span data-i18n="Admin.Upload.New"></span></label>
</fieldset>
<div class="upload-existing">
<input class="input" type="search" name="q" autocomplete="off" dir="auto" aria-label="${attr(t("Admin.Upload.Search"))}"
data-i18n-placeholder="Admin.Upload.Search" data-i18n-title="Admin.Upload.Search.Tip">
<select class="input list" name="sequence" size="5" aria-label="${attr(t("Admin.Upload.Sequences"))}" data-i18n-title="Admin.Upload.Sequences.Tip"></select>
</div>
<label class="upload-new" hidden><span data-i18n="Admin.Upload.NewTitle"></span>
<input class="input" name="title" maxlength="200" autocomplete="off" dir="auto" data-i18n-title="Admin.Upload.NewTitle.Tip"></label>`;
applyStrings(targetHost);
const existing = targetHost.querySelector(".upload-existing");
const fresh = targetHost.querySelector(".upload-new");
targetHost.querySelectorAll('input[name="mode"]').forEach((radio) => radio.addEventListener("change", () => {
const isNew = form.elements.mode.value === "new";
existing.hidden = isNew;
fresh.hidden = !isNew;
showError("");
}));
const search = targetHost.querySelector('input[name="q"]');
search.addEventListener("input", () => {
clearTimeout(searchTimer);
searchTimer = setTimeout(() => loadSequences(search.value.trim()), SEARCH_DELAY);
});
// Enter in the search box picks nothing and sends nothing.
search.addEventListener("keydown", (e) => {
if (e.key === "Enter") e.preventDefault();
});
targetHost.querySelector("select").addEventListener("change", () => showError(""));
loadSequences("");
}
async function loadSequences(q) {
const token = ++searchToken;
const query = new URLSearchParams({ limit: String(LIST_LIMIT) });
if (q) query.set("q", q);
let page;
try {
page = await api.get(`/api/v1/sequences?${query}`);
} catch (err) {
if (token === searchToken) showError(errorText(err));
return;
}
const select = targetHost.querySelector("select");
if (token !== searchToken || !select) return;
const chosen = select.value;
for (const s of page.items) titles.set(s.id, s.displayTitle);
select.innerHTML = page.items.map((s) => `<option value="${attr(s.id)}" dir="auto" ${s.id === chosen ? "selected" : ""}>` +
`${escapeHtml(s.displayTitle)} · ${escapeHtml(plural("Admin.Upload.PhotoCount", s.frameCount))}</option>`).join("") ||
`<option disabled>${escapeHtml(t("Admin.Upload.NoMatch"))}</option>`;
}
/** Adds picked or dropped files: photos once each; folders, other files and files above the limit are counted. */
function take(files, folders) {
skipped.folders += folders;
for (const file of files) {
const dot = file.name.lastIndexOf(".");
const extension = dot < 0 ? "" : file.name.slice(dot + 1).toLowerCase();
if (file.size === 0 || !extensions?.has(extension)) {
skipped.formats++;
continue;
}
if (maxBytes > 0 && file.size > maxBytes) {
skipped.size++;
continue;
}
const key = `${file.name}\u0000${file.size}\u0000${file.lastModified}`;
if (items.some((i) => i.key === key)) continue;
const item = { key, file, state: "waiting", hashed: 0, sent: 0, uploadId: null, message: "", row: null };
item.row = document.createElement("li");
item.row.className = "upload-file";
item.row.dataset.key = key;
item.row.innerHTML = `<span class="name ellipsis" dir="auto" title="${attr(file.name)}">${escapeHtml(file.name)}</span>
<span class="size num muted">${escapeHtml(formatBytes(file.size))}</span><span class="status"></span>
<button class="btn icon small subtle" type="button" data-act="remove" title="${attr(t("Admin.Upload.Remove.Tip"))}"
aria-label="${attr(t("Admin.Upload.Remove", file.name))}">${icons.close}</button>`;
list.appendChild(item.row);
items.push(item);
drawItem(item);
}
drawNotes();
drawList();
}
function drawNotes() {
const chip = (count, key, tip) => count === 0 ? "" : `<span class="chip warn" title="${attr(tip)}">${escapeHtml(t(key, formatNumber(count)))}</span>`;
notes.innerHTML = chip(skipped.folders, "Admin.Upload.Skipped.Folders", t("Admin.Upload.Skipped.Folders.Tip")) +
chip(skipped.formats, "Admin.Upload.Skipped.Formats", t("Admin.Upload.Skipped.Formats.Tip")) +
chip(skipped.size, "Admin.Upload.Skipped.Size", t("Admin.Upload.Skipped.Size.Tip", formatBytes(maxBytes)));
notes.hidden = notes.innerHTML === "";
}
function drawList() {
list.hidden = items.length === 0;
drawTotal();
drawButtons();
}
/** One photo's row: its state, a bar while it is hashed or sent, and the reason of a failure as the tooltip. */
function drawItem(item) {
const status = item.row.querySelector(".status");
const percent = (fraction) => new Intl.NumberFormat(culture(), { style: "percent", maximumFractionDigits: 0 }).format(fraction);
let text;
let tip = "";
let tone = "queued";
let fraction = null;
switch (item.state) {
case "hashing":
text = t("Admin.Upload.State.Hashing", percent(item.hashed));
fraction = item.hashed;
tone = "running";
break;
case "starting":
text = t("Admin.Upload.State.Starting");
tone = "running";
break;
case "uploading":
fraction = item.file.size > 0 ? item.sent / item.file.size : 1;
text = t("Admin.Upload.State.Uploading", percent(fraction));
tone = "running";
break;
case "verifying":
text = t("Admin.Upload.State.Verifying");
tone = "running";
break;
case "done":
text = t("Admin.Upload.State.Done");
tip = t("Admin.Upload.State.Done.Tip");
tone = "done";
break;
case "exists":
text = t("Admin.Upload.State.Exists");
tip = t("Admin.Upload.State.Exists.Tip");
tone = "done";
break;
case "deleted":
text = t("Admin.Upload.State.Deleted");
tip = t("Admin.Upload.State.Deleted.Tip");
tone = "paused";
break;
case "failed":
text = t("Admin.Upload.State.Failed");
tip = item.message;
tone = "failed";
break;
case "cancelled":
text = t("Admin.Upload.State.Cancelled");
tone = "cancelled";
break;
case "notSent":
text = t("Admin.Upload.State.NotSent");
tip = t("Admin.Upload.State.NotSent.Tip");
tone = "cancelled";
break;
default:
text = t("Admin.Upload.State.Waiting");
}
status.innerHTML = (fraction === null ? "" : bar(fraction)) +
`<span class="state ${tone} ellipsis"${tip ? ` title="${attr(tip)}"` : ""}>${escapeHtml(text)}</span>`;
item.row.querySelector('[data-act="remove"]').hidden = !removable(item);
}
/** A photo comes off the list only between runs, and only while it is not on the server. */
function removable(item) {
return !running && !FINISHED.has(item.state) && !ACTIVE.has(item.state);
}
/** Progress redraws at most once a frame: the worker reports every 8 MiB, chunks finish four at a time. */
function update(item) {
item.dirty = true;
if (frame) return;
frame = requestAnimationFrame(() => {
frame = 0;
for (const i of items) {
if (!i.dirty) continue;
i.dirty = false;
drawItem(i);
}
drawTotal();
});
}
function setState(item, state, message = "") {
item.state = state;
item.message = message;
drawItem(item);
drawTotal();
}
function drawTotal() {
total.hidden = items.length === 0;
if (items.length === 0) return;
let bytes = 0;
let done = 0;
let sent = 0;
let failed = 0;
for (const item of items) {
bytes += item.file.size;
if (FINISHED.has(item.state)) {
done++;
sent += item.file.size;
} else if (item.state === "uploading" || item.state === "verifying") {
sent += item.sent;
} else if (item.state === "failed") {
failed++;
}
}
const text = `${t("Admin.Upload.Count", formatNumber(done), formatNumber(items.length))} · ${t("Admin.Upload.Bytes", formatBytes(sent), formatBytes(bytes))}`;
total.innerHTML = `<div class="progress-cell">${bar(bytes > 0 ? sent / bytes : 0)}<span class="num" title="${attr(text)}">${escapeHtml(text)}</span></div>` +
(failed > 0 ? `<span class="state failed nowrap">${escapeHtml(t("Admin.Upload.Failed", formatNumber(failed)))}</span>` : "");
}
function drawButtons() {
const pending = items.some((i) => !FINISHED.has(i.state));
startButton.disabled = running || !pending || broken !== null || extensions === null;
addButton.disabled = running || extensions === null;
closeButton.textContent = t(running ? "Admin.Upload.Cancel" : "Admin.Upload.Close");
closeButton.title = t(running ? "Admin.Upload.Cancel.Tip" : "Admin.Upload.Close.Tip");
for (const item of items) item.row.querySelector('[data-act="remove"]').hidden = !removable(item);
targetHost.querySelectorAll("input, select").forEach((field) => {
field.disabled = running;
});
}
function showError(text) {
errorLine.textContent = text;
}
/** Sends every photo not on the server yet, two at a time; a quota, space or permission refusal stops the rest. */
async function run() {
if (running) return;
const todo = items.filter((i) => !FINISHED.has(i.state));
if (todo.length === 0 || extensions === null) return;
if (broken) return showError(broken);
showError("");
running = true;
controller = new AbortController();
const signal = controller.signal;
window.addEventListener("beforeunload", guard);
drawButtons();
let changed = false;
try {
const into = await resolveTarget();
if (!into) return;
changed = into.created;
if (signal.aborted) return;
todo.forEach((i) => setState(i, "waiting"));
let next = 0;
let stop = null;
const lane = async () => {
while (stop === null && !signal.aborted && next < todo.length) {
const item = todo[next++];
try {
changed = (await send(item, into.id, signal)) || changed;
} catch (err) {
// A completion cut short may still have filed the photo: the page refreshes to find out.
if (item.state === "verifying") changed = true;
if (signal.aborted) {
setState(item, "cancelled");
continue;
}
setState(item, "failed", messageOf(err));
if (stops(err)) stop = err;
}
}
};
await Promise.all(Array.from({ length: FILES_AT_ONCE }, lane));
if (signal.aborted) {
await discard(todo);
todo.filter((i) => i.state === "waiting").forEach((i) => setState(i, "cancelled"));
} else if (stop !== null) {
if (stop instanceof HashError) broken = messageOf(stop);
showError(messageOf(stop));
todo.filter((i) => i.state === "waiting").forEach((i) => setState(i, "notSent"));
}
} finally {
running = false;
controller = null;
window.removeEventListener("beforeunload", guard);
todo.filter((i) => ACTIVE.has(i.state)).forEach((i) => setState(i, "cancelled"));
drawButtons();
drawTotal();
if (changed) onDone?.();
}
}
/** Stops the run: requests are aborted, the hash worker stopped and the server's unfinished uploads discarded. */
function cancel() {
controller?.abort();
hasher?.stop();
hasher = null;
}
/** DELETE of the uploads a cancelled run started and did not complete, so the server frees their space now. */
async function discard(todo) {
await Promise.all(todo.filter((i) => i.uploadId !== null && !FINISHED.has(i.state)).map(async (item) => {
try {
await api.del(`/api/v1/uploads/${item.uploadId}`);
} catch {
// Committed meanwhile, or already gone: nothing left to free.
}
item.uploadId = null;
}));
}
/**
* The sequence the run fills: the fixed one, the one picked, or a new one created now; from then on it is the
* dialog's fixed target, also when the run was cancelled meanwhile. Null (with the reason shown) when there is none.
*/
async function resolveTarget() {
if (target) return { id: target.id, created: false };
const mode = form.elements.mode.value;
if (mode === "existing") {
const select = targetHost.querySelector("select");
if (!select.value) {
showError(t("Admin.Upload.PickFirst"));
select.focus();
return null;
}
target = { id: select.value, title: titles.get(select.value) ?? "" };
drawTarget();
return { id: target.id, created: false };
}
const title = form.elements.title.value.trim();
try {
// Not retried: a lost answer must not create the sequence twice.
const created = await api.post("/api/v1/sequences", { title: title || null, cameraHint: null });
target = { id: created.id, title: created.displayTitle };
} catch (err) {
showError(errorText(err));
return null;
}
drawTarget();
return { id: target.id, created: true };
}
/**
* One photo: hashed, started (the server may already have it, or have had it before it was deleted), the missing
* chunks sent two at a time, completed. True when the library changed.
*/
async function send(item, sequenceId, signal) {
const file = item.file;
item.hashed = 0;
setState(item, "hashing");
hasher ??= createHasher();
const sha256 = await hasher.hash(file, (done, size) => {
item.hashed = size > 0 ? done / size : 1;
update(item);
});
if (signal.aborted) throw signal.reason;
setState(item, "starting");
const start = await retry(() => api.post("/api/v1/uploads", {
sequenceId, fileName: file.name, size: file.size, sha256, capturedAt: null, sessionKey: null,
}), signal);
if (start.alreadyExists) {
// No frame: the photo was deleted from this sequence; a restore from the trash brings it back (R6).
setState(item, start.frameId ? "exists" : "deleted");
return false;
}
item.uploadId = start.uploadId;
const chunk = start.chunkSize;
const count = Math.ceil(file.size / chunk);
const received = new Set(start.received ?? []);
const length = (index) => Math.min(chunk, file.size - index * chunk);
item.sent = [...received].reduce((sum, index) => sum + length(index), 0);
const missing = [];
for (let index = 0; index < count; index++) if (!received.has(index)) missing.push(index);
setState(item, "uploading");
let cursor = 0;
let failure = null;
const lane = async () => {
while (failure === null && cursor < missing.length) {
const index = missing[cursor++];
const blob = file.slice(index * chunk, index * chunk + length(index));
try {
await retry(() => api.putBytes(`/api/v1/uploads/${item.uploadId}/chunks/${index}`, blob, signal), signal);
} catch (err) {
failure ??= err;
return;
}
item.sent += blob.size;
update(item);
}
};
await Promise.all(Array.from({ length: Math.min(CHUNKS_AT_ONCE, missing.length) }, lane));
if (failure !== null) throw failure;
setState(item, "verifying");
await retry(() => api.post(`/api/v1/uploads/${item.uploadId}/complete`), signal);
item.uploadId = null;
setState(item, "done");
return true;
}
});
}
/** What dropped: the files, and how many folders were left out (the entries API tells them apart where it exists). */
function dropped(transfer) {
const files = [];
let folders = 0;
const entries = [...(transfer.items ?? [])].filter((i) => i.kind === "file");
if (entries.length > 0) {
for (const item of entries) {
if (item.webkitGetAsEntry?.()?.isDirectory) {
folders++;
continue;
}
const file = item.getAsFile();
if (file) files.push(file);
}
} else {
files.push(...(transfer.files ?? []));
}
return { files, folders };
}
/** Refusals that would refuse the next photos as well: quota, space, permission, a target gone, a broken hash. */
function stops(err) {
if (err instanceof HashError) return err.kind === "self_test" || err.kind === "worker";
if (!(err instanceof ApiFailure)) return false;
return err.status === 401 || err.status === 403 || err.status === 507 || (err.status === 404 && err.details === "sequence");
}
function messageOf(err) {
if (err instanceof HashError) {
if (err.kind === "self_test") return t("Admin.Upload.SelfTestFailed");
if (err.kind === "read") return t("Admin.Upload.ReadFailed");
return t("Admin.Upload.HashFailed");
}
return errorText(err);
}
/** Calls again after 1, 2 and 4 seconds when the server was not reached, was busy (429) or unavailable (503). */
async function retry(call, signal) {
for (let attempt = 0; ; attempt++) {
try {
return await call();
} catch (err) {
const passing = err instanceof ApiFailure && (err.status === 0 || err.status === 429 || err.status === 503);
if (signal.aborted || !passing || attempt >= RETRIES) throw err;
await sleep(1000 * 2 ** attempt, signal);
}
}
}
function sleep(ms, signal) {
return new Promise((resolve, reject) => {
const timer = setTimeout(resolve, ms);
signal.addEventListener("abort", () => {
clearTimeout(timer);
reject(signal.reason);
}, { once: true });
});
}
/**
* The hash worker behind a promise per file. A worker that fails to load or run rejects every request (worker); its
* refusal after a failed self-test is self_test. stop() ends the worker and rejects what it still had (stopped).
*/
function createHasher() {
let worker = null;
let failure = null;
let next = 0;
const pending = new Map();
const fail = (error) => {
for (const request of pending.values()) request.reject(error);
pending.clear();
};
const start = () => {
try {
worker = new Worker(new URL("./hash-worker.js", import.meta.url), { type: "module" });
} catch (err) {
failure = new HashError("worker", String(err?.name ?? err));
return;
}
worker.addEventListener("message", (e) => {
const message = e.data ?? {};
const request = pending.get(message.id);
if (!request) return;
if (message.type === "progress") {
request.progress(message.done, message.total);
return;
}
pending.delete(message.id);
if (message.type === "done" && /^[0-9a-f]{64}$/.test(message.sha256 ?? "")) request.resolve(message.sha256);
else request.reject(new HashError(message.reason === "self_test" ? "self_test" : message.reason === "read" ? "read" : "worker", message.detail));
});
worker.addEventListener("error", (e) => {
e.preventDefault();
failure = new HashError("worker", e.message ?? "");
fail(failure);
});
};
return {
hash(file, progress) {
if (!worker && !failure) start();
if (failure) return Promise.reject(failure);
return new Promise((resolve, reject) => {
const id = ++next;
pending.set(id, { resolve, reject, progress });
worker.postMessage({ id, file });
});
},
stop() {
worker?.terminate();
worker = null;
fail(new HashError("stopped"));
},
};
}
+8
View File
@@ -114,6 +114,14 @@ public static class JobEndpoints
return ApiErrors.BadRequest(context, "invalid_parameters", "parametersJson");
}
if (kind == JobKind.Verify)
{
// A verify of sequences targets their archive and names them in its parameters, as its handler reads it.
var verify = LibraryEndpoints.SequenceJob(kind, archive.Current, targets, label);
targets = verify.Targets;
queue = [(label, verify.ParametersJson)];
}
Job? first = null;
foreach (var (jobLabel, parameters) in queue)
{
+393
View File
@@ -0,0 +1,393 @@
using System.Globalization;
using Microsoft.AspNetCore.Mvc;
using Chronos.Core.Archiving;
using Chronos.Core.Imaging.Decoders;
using Chronos.Core.Model;
using Chronos.Core.Naming;
using Chronos.Data;
using Chronos.Data.Archiving;
using Chronos.Data.Archiving.Jobs;
using Chronos.Data.Jobs;
using Chronos.Data.Processing;
using Chronos.Data.Repositories;
using Chronos.Protocol;
using Chronos.Server.Events;
using Chronos.Server.Jobs;
using Chronos.Server.Security;
using Chronos.Server.Storage;
namespace Chronos.Server.Api;
/// <summary>
/// The library the admin panel manages without editing (owner review 2, R6): a sequence's cover thumbnail, deleting photos
/// of a sequence into the archive's trash (<see cref="FrameTrash"/>), and mass operations on many sequences at once —
/// delete into the trash, retag, queue analysis, proxies, thumbnails or a verify — each answering per sequence whether it
/// was done or skipped, and why.
/// </summary>
public static class LibraryEndpoints
{
/// <summary>Sequences one bulk request may name.</summary>
public const int MaxBulkIds = 1000;
/// <summary>Photos one delete request may name.</summary>
public const int MaxFrameIds = 100_000;
private const string Ok = "ok";
private const string Skipped = "skipped";
private const string Regenerable = "private, max-age=3600";
public static void Map(RouteGroupBuilder api)
{
var sequences = api.MapGroup("/sequences");
sequences.MapGet("/facets", FacetsAsync).Requires(Permissions.Read);
sequences.MapGet("/{id:guid}/thumb", ThumbAsync).Requires(Permissions.Read);
sequences.MapPost("/{id:guid}/frames/delete", DeleteFramesAsync).Requires(Permissions.Delete);
sequences.MapPost("/bulk/delete", BulkDeleteAsync).Requires(Permissions.Delete);
sequences.MapPost("/bulk/retag", BulkRetagAsync).Requires(Permissions.Edit);
sequences.MapPost("/bulk/jobs", BulkJobsAsync).Requires(Permissions.Edit);
}
/// <summary>The archive engine behind these operations: the host's, or one of its own (a test host that replaces the archive module).</summary>
internal static ArchiveService Engine(ArchiveService? archives, ChronosDatabase db) =>
archives ?? new ArchiveService(db, new ArchiveServiceOptions { Decoder = DecoderFactory.CreateServer(), Owner = ArchiveModule.Owner, ImagesAfterScan = true });
/// <summary>
/// What the Library's filters offer (the panel's Year, Camera and Tag menus): the years of first capture, the camera
/// models and the tags of this archive's sequences, each with its count. A camera's label is the name the desktop
/// shows (<see cref="PathTemplate.CameraName"/>: brand and model, the brand once).
/// </summary>
private static async Task<IResult> FacetsAsync(HttpContext context, ChronosDatabase db, ServerArchive archive)
{
var facets = await db.Sequences.GetFacetsAsync(archive.Id, context.RequestAborted);
return Results.Json(new LibraryFacetsDto(
[.. facets.Years.Select(y => new FacetDto(y.Value, y.Sequences))],
[.. facets.Cameras.Select(c => new FacetDto(c.Value, c.Sequences, PathTemplate.CameraName(c.Make, c.Value)))],
[.. facets.Tags.Select(t => new FacetDto(t.Value, t.Sequences))]), ProtocolJson.Default.LibraryFacetsDto);
}
/// <summary>
/// The thumbnail of the sequence's hero frame, else of its first frame, streamed like <c>/frames/{id}/thumb</c> with an
/// ETag (304 when unchanged); 404 <c>not_found</c> (<c>thumbnail</c>) when the sequence has no frame or that thumbnail
/// is not built yet.
/// </summary>
private static async Task<IResult> ThumbAsync(HttpContext context, Guid id, ChronosDatabase db, ServerArchive archive, IFrameAssetLocator locator)
{
var ct = context.RequestAborted;
if (await db.Sequences.GetAsync(id, ct) is not { } sequence) return ApiErrors.NotFound(context, "sequence");
var frame = sequence.HeroFrameId is { } hero && await db.Frames.GetAsync(hero, ct) is { } chosen && chosen.SequenceId == id
? chosen
: (await db.Frames.ListBySequenceAsync(id, limit: 1, cancellationToken: ct)).FirstOrDefault();
if (frame is null) return ApiErrors.NotFound(context, "thumbnail");
var location = await locator.LocateAsync(archive.Current, sequence, frame, FrameAsset.Thumbnail, ct);
if (location is null || !ArchivePathGuard.IsInside(archive.Root, location.Path)) return ApiErrors.NotFound(context, "thumbnail");
var file = new FileInfo(location.Path);
if (!file.Exists || file.LinkTarget is not null) return ApiErrors.NotFound(context, "thumbnail");
var etag = string.Create(CultureInfo.InvariantCulture, $"s-{frame.Id:N}-{file.LastWriteTimeUtc.Ticks}-{location.Offset}");
return FileResponses.Serve(context, file, location.Offset, location.Length, location.ContentType, Regenerable, etag)
?? ApiErrors.NotFound(context, "thumbnail");
}
/// <summary>
/// Moves photos of a sequence into the archive's trash (<see cref="FrameTrash"/>; BRIEF §0.2 rule 8: nothing is erased),
/// or with <c>dryRun</c> says what would go. Owners and admins only, like deleting the sequence. 400 <c>bad_request</c>
/// (<c>frameIds</c>); 409 <c>frames_conflict</c> (the frames changed since <c>expectedFramesVersion</c>, or a photo named
/// is not the sequence's; details: the frames version now), <c>sequence_busy</c>, <c>would_empty</c> (every photo would
/// go: delete the sequence instead), <c>folder_in_use</c>; 503 <c>archive_offline</c>. Publishes <c>sequenceChanged</c>
/// <c>frames</c>; the thumbnails, proxies and analyses follow as jobs.
/// </summary>
private static async Task<IResult> DeleteFramesAsync(HttpContext context, Caller caller, Guid id, FrameDeleteRequest request, ChronosDatabase db,
[FromServices] ArchiveService? archives, JobEngineHost host, AuditLog audit, EventHub events, IHostApplicationLifetime lifetime)
{
var ct = context.RequestAborted;
if (request.FrameIds is not { Count: > 0 and <= MaxFrameIds } ids) return ApiErrors.BadRequest(context, "bad_request", "frameIds");
if (await db.Sequences.GetAsync(id, ct) is not { } sequence) return ApiErrors.NotFound(context, "sequence");
if (!caller.IsAdmin && sequence.OwnerUserId != caller.Id) return ApiErrors.Forbidden(context);
var engine = Engine(archives, db).FrameTrash;
FrameDeletePlan plan;
try
{
plan = await engine.PlanDeleteAsync(id, ids, request.ExpectedFramesVersion, ct);
}
catch (ArgumentException)
{
return ApiErrors.NotFound(context, "sequence");
}
if (plan.Blocked.Count > 0) return Refused(context, plan.Blocked[0], plan.Sequence);
if (request.DryRun)
return Results.Json(new FrameDeleteResultDto(id, plan.Frames.Count, plan.Bytes, plan.Sequence.FramesVersion, plan.Sequence.FrameCount, null, true),
ProtocolJson.Default.FrameDeleteResultDto);
FrameDeleteResult result;
try
{
// Once confirmed the deletion runs to the end even if the client goes away meanwhile.
result = await engine.DeleteAsync(plan, caller.User.Username, host.Engine, lifetime.ApplicationStopping);
}
catch (ArchiveOfflineException)
{
return Refused(context, FrameDeleteBlock.Offline, plan.Sequence);
}
catch (Exception ex) when (ex is StaleDeletePlanException or LeaseUnavailableException)
{
var again = await engine.PlanDeleteAsync(id, ids, plan.Sequence.FramesVersion, ct);
return Refused(context, again.Blocked.Count > 0 ? again.Blocked[0] : ex is LeaseUnavailableException ? FrameDeleteBlock.Busy : FrameDeleteBlock.FramesChanged,
again.Sequence);
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
// A photo is open in another program: nothing moved.
return ApiErrors.Conflict(context, "folder_in_use");
}
await audit.WriteAsync(caller, context, "frames_deleted", "sequence", id.ToString(), $"{plan.Frames.Count} · {result.Entry.Name}");
events.Publish(new SequenceChangedEvent(id, "frames", result.Sequence.FramesVersion, result.Sequence.SettingsVersion));
return Results.Json(new FrameDeleteResultDto(id, plan.Frames.Count, plan.Bytes, result.Sequence.FramesVersion, result.Sequence.FrameCount,
result.Entry.Name, false), ProtocolJson.Default.FrameDeleteResultDto);
}
private static IResult Refused(HttpContext context, FrameDeleteBlock reason, Sequence sequence) => reason switch
{
FrameDeleteBlock.Offline => ApiErrors.Result(context, StatusCodes.Status503ServiceUnavailable, "archive_offline"),
FrameDeleteBlock.Busy => ApiErrors.Conflict(context, "sequence_busy"),
FrameDeleteBlock.WouldEmpty => ApiErrors.Conflict(context, "would_empty"),
_ => ApiErrors.Conflict(context, "frames_conflict", sequence.FramesVersion.ToString(CultureInfo.InvariantCulture)),
};
/// <summary>
/// Moves many sequences into the trash as <c>DELETE /sequences/{id}</c> does each (or, with <c>dryRun</c>, plans them):
/// one item per id, <c>ok</c> with the trash folder, or <c>skipped</c> with the code that says why (<c>not_found</c>,
/// <c>forbidden</c> for a sequence of another user, <c>sequence_busy</c>, <c>archive_root</c>, <c>contains_sequences</c>,
/// <c>sidecar_mismatch</c>, <c>folder_missing</c>, <c>archive_offline</c>, <c>folder_in_use</c>). Each sequence moves whole
/// or not at all. 400 <c>bad_request</c> (<c>ids</c>).
/// </summary>
private static async Task<IResult> BulkDeleteAsync(HttpContext context, Caller caller, BulkDeleteRequest request, ChronosDatabase db,
[FromServices] ArchiveService? archives, AuditLog audit, EventHub events, IHostApplicationLifetime lifetime)
{
var ct = context.RequestAborted;
if (Ids(request.Ids) is not { } ids) return ApiErrors.BadRequest(context, "bad_request", "ids");
var trash = Engine(archives, db).Trash;
var items = new Dictionary<Guid, BulkItemResult>();
var allowed = new List<Sequence>();
foreach (var id in ids)
{
if (await db.Sequences.GetAsync(id, ct) is not { } sequence) items[id] = Skip(context, id, "not_found");
else if (!caller.IsAdmin && sequence.OwnerUserId != caller.Id) items[id] = Skip(context, id, "forbidden");
else allowed.Add(sequence);
}
var steps = new List<DeleteStep>();
foreach (var (sequence, reason, step) in await PlanEachAsync(trash, allowed, ct))
{
if (step is not null) steps.Add(step);
else items[sequence.Id] = Skip(context, sequence.Id, reason!);
}
var photos = 0;
long bytes = 0;
foreach (var step in steps)
{
var sequence = step.Sequence;
if (!request.DryRun)
{
try
{
await trash.DeleteAsync(new DeletePlan([step], []), caller.User.Username, null, lifetime.ApplicationStopping);
}
catch (ArchiveOfflineException)
{
items[sequence.Id] = Skip(context, sequence.Id, "archive_offline");
continue;
}
catch (Exception ex) when (ex is StaleDeletePlanException or LeaseUnavailableException)
{
items[sequence.Id] = Skip(context, sequence.Id, "sequence_busy");
continue;
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
items[sequence.Id] = Skip(context, sequence.Id, "folder_in_use");
continue;
}
await audit.WriteAsync(caller, context, "sequence_deleted", "sequence", sequence.Id.ToString(), sequence.DisplayTitle);
events.Publish(new SequenceChangedEvent(sequence.Id, "deleted", sequence.FramesVersion, sequence.SettingsVersion));
}
items[sequence.Id] = new BulkItemResult(sequence.Id, Ok, TrashFolder: step.TrashFolder);
photos += sequence.FrameCount;
bytes += step.Bytes;
}
return Results.Json(Result(ids, items, request.DryRun, photos, bytes), ProtocolJson.Default.BulkResultDto);
}
/// <summary>Each sequence's delete plan: its step, or the code of why it cannot go.</summary>
private static async Task<List<(Sequence Sequence, string? Reason, DeleteStep? Step)>> PlanEachAsync(SequenceTrash trash, List<Sequence> sequences,
CancellationToken ct)
{
var planned = new List<(Sequence, string?, DeleteStep?)>();
if (sequences.Count == 0) return planned;
DeletePlan plan;
try
{
plan = await trash.PlanAsync([.. sequences.Select(s => s.Id)], null, ct);
}
catch (ArgumentException) when (sequences.Count == 1)
{
return [(sequences[0], "not_found", null)];
}
catch (ArgumentException)
{
// One left the index meanwhile: planned one by one, so the others still go.
foreach (var sequence in sequences) planned.AddRange(await PlanEachAsync(trash, [sequence], ct));
return planned;
}
catch (ArchiveOfflineException)
{
return [.. sequences.Select(s => (s, (string?)"archive_offline", (DeleteStep?)null))];
}
foreach (var step in plan.Steps) planned.Add((step.Sequence, null, step));
foreach (var blocked in plan.Blocked) planned.Add((blocked.Sequence, BlockCode(blocked.Reason), null));
return planned;
}
/// <summary>The error code of a sequence that cannot go to the trash, as <c>DELETE /sequences/{id}</c> answers it.</summary>
internal static string BlockCode(DeleteBlock reason) => reason switch
{
DeleteBlock.Offline => "archive_offline",
DeleteBlock.Busy => "sequence_busy",
DeleteBlock.ArchiveRoot => "archive_root",
DeleteBlock.ContainsSequences => "contains_sequences",
DeleteBlock.ForeignSidecar => "sidecar_mismatch",
_ => "folder_missing",
};
/// <summary>
/// Adds and removes tags on many sequences, each with the same edit as a PATCH of its tags (case-insensitive, the first
/// spelling kept; settings version + 1 when they change). Skipped: <c>not_found</c>, <c>bad_request</c> (more than 50
/// tags then). 400 <c>bad_request</c> (<c>ids</c>, <c>tags</c>). Publishes <c>sequenceChanged</c> <c>settings</c>.
/// </summary>
private static async Task<IResult> BulkRetagAsync(HttpContext context, Caller caller, BulkRetagRequest request, ChronosDatabase db, AuditLog audit,
EventHub events)
{
var ct = context.RequestAborted;
if (Ids(request.Ids) is not { } ids) return ApiErrors.BadRequest(context, "bad_request", "ids");
if (Tags(request.Add) is not { } add || Tags(request.Remove) is not { } remove || add.Count + remove.Count == 0)
return ApiErrors.BadRequest(context, "bad_request", "tags");
var items = new Dictionary<Guid, BulkItemResult>();
foreach (var id in ids)
{
items[id] = await RetagAsync(context, caller, db, audit, events, id, add, remove, ct);
}
return Results.Json(Result(ids, items, false, 0, 0), ProtocolJson.Default.BulkResultDto);
}
private static async Task<BulkItemResult> RetagAsync(HttpContext context, Caller caller, ChronosDatabase db, AuditLog audit, EventHub events, Guid id,
IReadOnlyList<string> add, IReadOnlyList<string> remove, CancellationToken ct)
{
for (var attempt = 0; attempt < 3; attempt++)
{
if (await db.Sequences.GetAsync(id, ct) is not { } sequence) return Skip(context, id, "not_found");
var tags = sequence.Tags.Where(t => !remove.Contains(t, StringComparer.OrdinalIgnoreCase)).ToList();
tags.AddRange(add.Where(t => !tags.Contains(t, StringComparer.OrdinalIgnoreCase)));
if (tags.Count > SequenceEndpoints.MaxTags) return Skip(context, id, "bad_request");
if (tags.ToHashSet(StringComparer.OrdinalIgnoreCase).SetEquals(sequence.Tags)) return new BulkItemResult(id, Ok);
var result = await db.Sequences.EditAsync(id, new SequenceEdit { Tags = tags }, sequence.SettingsVersion, ct);
if (result.Outcome == SequenceEditOutcome.NotFound) return Skip(context, id, "not_found");
// Edited meanwhile: the tags apply again on top of that edit.
if (result.Outcome == SequenceEditOutcome.Conflict) continue;
var updated = result.Sequence!;
await audit.WriteAsync(caller, context, "sequence_updated", "sequence", id.ToString(), "tags");
events.Publish(new SequenceChangedEvent(id, "settings", updated.FramesVersion, updated.SettingsVersion));
return new BulkItemResult(id, Ok);
}
return Skip(context, id, "settings_conflict");
}
/// <summary>
/// Queues one job over many sequences: <c>analyse</c> (light analysis), <c>deep</c> (deep analysis), <c>proxies</c>,
/// <c>thumbnails</c> or <c>verify</c> (a verify of those sequences in their archive), at user priority. Sequences not in
/// the index are skipped (<c>not_found</c>). 202 with the job when one was queued; 400 <c>invalid_job_kind</c>,
/// <c>bad_request</c> (<c>ids</c>); 409 <c>job_unavailable</c> when this server cannot run that kind.
/// </summary>
private static async Task<IResult> BulkJobsAsync(HttpContext context, Caller caller, BulkJobsRequest request, ChronosDatabase db, ServerArchive archive,
JobEngineHost host, AuditLog audit)
{
var ct = context.RequestAborted;
if (Ids(request.Ids) is not { } ids) return ApiErrors.BadRequest(context, "bad_request", "ids");
if (BulkKind(request.Kind) is not { } kind) return ApiErrors.BadRequest(context, "invalid_job_kind");
if (!host.CanRun(kind)) return ApiErrors.Conflict(context, "job_unavailable", JobWire.Kind(kind));
var items = new Dictionary<Guid, BulkItemResult>();
var found = new List<Sequence>();
foreach (var id in ids)
{
if (await db.Sequences.GetAsync(id, ct) is { } sequence && sequence.ArchiveId == archive.Id)
{
found.Add(sequence);
items[id] = new BulkItemResult(id, Ok);
}
else
{
items[id] = Skip(context, id, "not_found");
}
}
if (found.Count == 0) return Results.Json(Result(ids, items, false, 0, 0), ProtocolJson.Default.BulkResultDto);
var targets = found.Select(s => s.Id).ToList();
var label = Label(found);
var job = await host.Engine.EnqueueAsync(SequenceJob(kind, archive.Current, targets, label) with { Priority = JobPriority.User }, caller.Id, ct);
await audit.WriteAsync(caller, context, "job_created", "job", job.Id.ToString(), $"{JobWire.Kind(kind)} · {label}");
return Results.Json(Result(ids, items, false, 0, 0) with { Job = Dto.Job(job) }, ProtocolJson.Default.BulkResultDto,
statusCode: StatusCodes.Status202Accepted);
}
/// <summary>The kinds a bulk job request names.</summary>
private static JobKind? BulkKind(string? kind) => kind?.Trim().ToLowerInvariant() switch
{
"analyse" => JobKind.LightAnalyse,
"deep" => JobKind.DeepAnalyse,
"proxies" => JobKind.Proxies,
"thumbnails" => JobKind.Thumbs,
"verify" => JobKind.Verify,
_ => null,
};
/// <summary>
/// The job of a sequence kind over <paramref name="sequenceIds"/>. A verify targets the archive and names the sequences
/// in its parameters (<see cref="ArchiveJobs.Verify"/>), as its handler reads it.
/// </summary>
internal static ArchiveJobRequest SequenceJob(JobKind kind, Archive archive, IReadOnlyList<Guid> sequenceIds, string label) => kind switch
{
JobKind.Verify => ArchiveJobs.Verify(archive, sequenceIds) with { Label = label },
JobKind.LightAnalyse => ProcessingJobs.LightAnalysis(sequenceIds, label),
JobKind.DeepAnalyse => ProcessingJobs.DeepAnalysis(sequenceIds, label),
JobKind.Proxies => ArchiveJobs.Proxies(sequenceIds, label),
JobKind.Thumbs => ArchiveJobs.Thumbnails(sequenceIds, label),
_ => throw new ArgumentOutOfRangeException(nameof(kind), kind, "Not a sequence job."),
};
/// <summary>"Harbour sunset", or the first three titles and "…".</summary>
internal static string Label(IReadOnlyList<Sequence> sequences) =>
sequences.Count == 1 ? sequences[0].DisplayTitle
: string.Join(", ", sequences.Take(3).Select(s => s.DisplayTitle)) + (sequences.Count > 3 ? " …" : string.Empty);
/// <summary>The ids of a bulk request, once each in their order; null when there are none or too many.</summary>
private static List<Guid>? Ids(IReadOnlyList<Guid>? ids) =>
ids is { Count: > 0 and <= MaxBulkIds } ? [.. ids.Distinct()] : null;
/// <summary>Tags as a request names them, trimmed, once each; null when one is blank or too long.</summary>
private static List<string>? Tags(IReadOnlyList<string>? tags)
{
if (tags is null) return [];
var list = new List<string>();
foreach (var tag in tags)
{
var trimmed = tag?.Trim();
if (string.IsNullOrEmpty(trimmed) || trimmed.Length > TagRepository.MaxLength) return null;
if (!list.Contains(trimmed, StringComparer.OrdinalIgnoreCase)) list.Add(trimmed);
}
return list.Count > SequenceEndpoints.MaxTags ? null : list;
}
private static BulkItemResult Skip(HttpContext context, Guid id, string code) => new(id, Skipped, code, ApiErrors.Message(context, code));
private static BulkResultDto Result(List<Guid> ids, Dictionary<Guid, BulkItemResult> items, bool dryRun, int photos, long bytes)
{
var ordered = ids.Select(id => items[id]).ToList();
var ok = ordered.Count(i => i.Outcome == Ok);
return new BulkResultDto(ordered, ok, ordered.Count - ok, dryRun, photos, bytes);
}
}
+12 -3
View File
@@ -25,7 +25,8 @@ public static class SequenceEndpoints
{
private const int MaxTitle = 200;
private const int MaxNotes = 2000;
private const int MaxTags = 50;
/// <summary>Tags a sequence may carry.</summary>
internal const int MaxTags = 50;
/// <summary>Listings of a sequence's frames read without a lock before one is read under its row lock (<see cref="SnapshotAsync"/>).</summary>
private const int SnapshotAttempts = 3;
@@ -57,8 +58,13 @@ public static class SequenceEndpoints
.Requires(Permissions.Edit);
}
/// <summary>
/// One page of the library. Filters: <c>year</c>, <c>camera</c> (the exact model), <c>status</c> (flags, <c>-</c> for
/// cleared ones), <c>rendered</c> (<c>true</c>: with a render, <c>false</c>: without; the admin panel's Library), <c>tag</c>,
/// <c>q</c> (title, camera or tag), <c>owner</c> (<c>me</c> or an id); <c>sort</c>, <c>cursor</c>, <c>limit</c>.
/// </summary>
private static async Task<IResult> ListAsync(HttpContext context, ChronosDatabase db, ServerArchive archive, int? year, string? camera, string? status,
string? tag, string? q, string? owner, string? sort, string? cursor, int? limit, Caller caller)
bool? rendered, string? tag, string? q, string? owner, string? sort, string? cursor, int? limit, Caller caller)
{
if (!TryParseStatus(status, out var with, out var without)) return ApiErrors.BadRequest(context, "invalid_filter", "status");
if (!TryParseSort(sort, out var order)) return ApiErrors.BadRequest(context, "invalid_filter", "sort");
@@ -74,6 +80,7 @@ public static class SequenceEndpoints
Camera = string.IsNullOrWhiteSpace(camera) ? null : camera,
WithStatus = with,
WithoutStatus = without,
Rendered = rendered,
Tag = string.IsNullOrWhiteSpace(tag) ? null : tag,
Text = string.IsNullOrWhiteSpace(q) ? null : q,
OwnerUserId = ownerId,
@@ -238,9 +245,11 @@ public static class SequenceEndpoints
if (context.Request.Headers.IfNoneMatch == etag) return Results.StatusCode(StatusCodes.Status304NotModified);
var renders = await db.Renders.ListBySequenceAsync(id, ct);
// Tombstones change only with the frames (a deletion bumps the frames version), so the ETag covers them.
var removed = await db.FrameRemovals.ListBySequenceAsync(id, ct);
context.Response.Headers.ETag = etag;
return Results.Json(new SequenceManifest(id, sequence.FramesVersion, sequence.SettingsVersion, sequence.SettingsJson, sequence.Tags, frames,
[.. renders.Select(Dto.Render)], spec), ProtocolJson.Default.SequenceManifest);
[.. renders.Select(Dto.Render)], spec, removed.Count == 0 ? null : Data.Sync.SyncTombstones.ToDto(removed)), ProtocolJson.Default.SequenceManifest);
}
/// <summary>
+6 -1
View File
@@ -1,5 +1,6 @@
using System.Globalization;
using System.Reflection;
using Chronos.Core.Imaging;
using Chronos.Core.Localization;
using Chronos.Data;
using Chronos.Protocol;
@@ -28,6 +29,9 @@ public static class SystemEndpoints
}
})));
/// <summary>The extensions the archive scanner files as photos (BRIEF §8.1), which the admin panel's uploads keep to.</summary>
private static readonly string[] PhotoExtensions = [.. ImageFormatInfo.Known.SelectMany(f => f.Extensions)];
public static string Version { get; } =
typeof(SystemEndpoints).Assembly.GetCustomAttribute<AssemblyInformationalVersionAttribute>()?.InformationalVersion ?? "0.0.0";
@@ -42,7 +46,8 @@ public static class SystemEndpoints
state.Capabilities,
state.TlsFingerprint,
["jpeg", "png", "tiff", "dng", "cr2", "cr3", "nef", "arw", "raf", "orf", "rw2", "pef", "heic", "webp"],
new ServerLimits(options.MaxUploadBytes, options.ChunkSizeBytes, PasswordHasher.MinimumLength)), ProtocolJson.Default.ServerInfo)).AllowAnonymousCaller();
new ServerLimits(options.MaxUploadBytes, options.ChunkSizeBytes, PasswordHasher.MinimumLength),
PhotoExtensions), ProtocolJson.Default.ServerInfo)).AllowAnonymousCaller();
api.MapGet("/i18n/{culture}", (string culture) =>
{
+122
View File
@@ -0,0 +1,122 @@
using System.Text.RegularExpressions;
using Microsoft.AspNetCore.Mvc;
using Chronos.Core.Archiving;
using Chronos.Core.Model;
using Chronos.Data;
using Chronos.Data.Archiving;
using Chronos.Data.Jobs;
using Chronos.Protocol;
using Chronos.Server.Events;
using Chronos.Server.Jobs;
using Chronos.Server.Security;
using Chronos.Server.Storage;
namespace Chronos.Server.Api;
/// <summary>
/// <c>/api/v1/archive/trash</c> (owner review 2, R6; administrators of the archive): the entries of the archive's trash —
/// deleted sequences and photos deleted from sequences —, restoring one, and emptying it: a dry run that measures the
/// entries and fingerprints them, then an <c>empty-trash</c> job that erases exactly those entries and refuses when the
/// trash changed since (BRIEF §0.2 rule 8: the only erase of user files, always an explicit, confirmed action).
/// </summary>
public static partial class TrashEndpoints
{
public static void Map(RouteGroupBuilder api)
{
var trash = api.MapGroup("/archive/trash").Requires(Permissions.ManageArchive);
trash.MapGet("", ListAsync);
trash.MapPost("/{name}/restore", RestoreAsync);
trash.MapPost("/empty", EmptyAsync);
}
/// <summary>Whether <paramref name="name"/> has the shape of an entry name (a sequence id, a time, <c>photos-</c>): never a path.</summary>
public static bool IsEntryName(string? name) => name is not null && EntryName().IsMatch(name);
public static TrashEntryDto Entry(TrashEntry e) =>
new(e.Name, e.Kind.ToString().ToLowerInvariant(), e.SequenceId, e.Title, e.Folder, e.Frames, e.Files, e.Bytes, e.DeletedBy, e.DeletedAt);
/// <summary>The entries newest first with their total size; an archive offline lists none.</summary>
private static async Task<IResult> ListAsync(HttpContext context, ChronosDatabase db, ServerArchive archive, [FromServices] ArchiveService? archives)
{
var entries = await LibraryEndpoints.Engine(archives, db).Trash.ListAsync(archive.Current, context.RequestAborted);
return Results.Json(new TrashListDto([.. entries.Select(Entry)], entries.Sum(e => e.Bytes)), ProtocolJson.Default.TrashListDto);
}
/// <summary>
/// Brings an entry back: a sequence into its folder and the library, photos into their sequence (a new one when it is
/// gone), each photo re-hashed against its record first. 404 <c>not_found</c> (<c>trash_entry</c>); 409
/// <c>sequence_in_library</c> (that sequence is in the library already), <c>sequence_busy</c>, <c>folder_in_use</c>; 422
/// <c>trash_mismatch</c> (no file matches its record any more); 503 <c>archive_offline</c>. Publishes
/// <c>sequenceChanged</c>: <c>created</c> for a sequence, <c>frames</c> for photos.
/// </summary>
private static async Task<IResult> RestoreAsync(HttpContext context, Caller caller, string name, ChronosDatabase db, ServerArchive archive,
[FromServices] ArchiveService? archives, JobEngineHost host, AuditLog audit, EventHub events, IHostApplicationLifetime lifetime)
{
if (!IsEntryName(name)) return ApiErrors.NotFound(context, "trash_entry");
TrashRestoreResult result;
try
{
result = await LibraryEndpoints.Engine(archives, db).RestoreEntryAsync(archive.Id, name, host.Engine, lifetime.ApplicationStopping);
}
catch (DirectoryNotFoundException)
{
return ApiErrors.NotFound(context, "trash_entry");
}
catch (SequenceInLibraryException)
{
return ApiErrors.Conflict(context, "sequence_in_library");
}
catch (ArchiveOfflineException)
{
return ApiErrors.Result(context, StatusCodes.Status503ServiceUnavailable, "archive_offline");
}
catch (LeaseUnavailableException)
{
return ApiErrors.Conflict(context, "sequence_busy");
}
catch (InvalidDataException)
{
return ApiErrors.Result(context, StatusCodes.Status422UnprocessableEntity, "trash_mismatch");
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
return ApiErrors.Conflict(context, "folder_in_use");
}
var sequence = result.Sequence;
await audit.WriteAsync(caller, context, "trash_restored", "sequence", sequence.Id.ToString(), $"{name} · {sequence.DisplayTitle}");
events.Publish(new SequenceChangedEvent(sequence.Id, result.Kind == TrashKind.Sequence || result.NewSequence ? "created" : "frames",
sequence.FramesVersion, sequence.SettingsVersion));
return Results.Json(new TrashRestoreDto(name, result.Kind.ToString().ToLowerInvariant(), sequence.Id, result.Kind == TrashKind.Sequence ? sequence.FrameCount : result.Photos,
result.Kept, result.NewSequence), ProtocolJson.Default.TrashRestoreDto);
}
/// <summary>
/// Empties the trash, or the entries <c>names</c> names. With <c>dryRun</c> the plan: the entries measured on disk, their
/// totals and a fingerprint, nothing touched. Otherwise the request carries that fingerprint, and the server queues an
/// <c>empty-trash</c> job (202) that erases exactly those entries; the job fails, erasing nothing, when the trash changed
/// before it ran. 400 <c>bad_request</c> (<c>names</c>, <c>fingerprint</c>); 409 <c>trash_changed</c> (details: the
/// fingerprint now), <c>job_unavailable</c>.
/// </summary>
private static async Task<IResult> EmptyAsync(HttpContext context, Caller caller, TrashEmptyRequest request, ChronosDatabase db, ServerArchive archive,
[FromServices] ArchiveService? archives, JobEngineHost host, AuditLog audit)
{
var ct = context.RequestAborted;
if (request.Names is { } names && (names.Count == 0 || names.Any(n => !IsEntryName(n)))) return ApiErrors.BadRequest(context, "bad_request", "names");
var plan = await LibraryEndpoints.Engine(archives, db).PlanEmptyTrashAsync(archive.Id, request.Names, ct);
if (request.DryRun)
{
return Results.Json(new TrashEmptyPlanDto([.. plan.Entries.Select(Entry)], plan.Photos, plan.Files, plan.Bytes, plan.Fingerprint, plan.Unknown),
ProtocolJson.Default.TrashEmptyPlanDto);
}
if (string.IsNullOrWhiteSpace(request.Fingerprint)) return ApiErrors.BadRequest(context, "bad_request", "fingerprint");
if (plan.Fingerprint != request.Fingerprint || plan.Unknown.Count > 0) return ApiErrors.Conflict(context, "trash_changed", plan.Fingerprint);
if (!host.CanRun(JobKind.EmptyTrash)) return ApiErrors.Conflict(context, "job_unavailable", JobWire.Kind(JobKind.EmptyTrash));
var job = await host.Engine.EnqueueAsync(ArchiveJobs.EmptyTrash(archive.Current, plan), caller.Id, ct);
await audit.WriteAsync(caller, context, "trash_emptied", "job", job.Id.ToString(),
$"{plan.Entries.Count} · {plan.Bytes} · {string.Join(", ", plan.Entries.Take(5).Select(e => e.Name))}");
return Results.Json(Dto.Job(job), ProtocolJson.Default.JobDto, statusCode: StatusCodes.Status202Accepted);
}
[GeneratedRegex("^(photos-)?[0-9a-f]{32}(-[0-9]{14}(-[0-9]{1,6})?)?$", RegexOptions.CultureInvariant)]
private static partial Regex EntryName();
}
@@ -26,6 +26,7 @@ public sealed class ServerSettingsStore(ServerOptions options, ServerLogging log
[
JobKind.Render, JobKind.Import, JobKind.Scan, JobKind.Rebuild, JobKind.Verify, JobKind.LightAnalyse, JobKind.DeepAnalyse, JobKind.Thumbs,
JobKind.Proxies, JobKind.Maintenance, JobKind.Duplicates, JobKind.Orphans, JobKind.Adopt, JobKind.Move, JobKind.Backup, JobKind.Cleanup,
JobKind.EmptyTrash,
];
private readonly Lock _gate = new();
@@ -1,6 +1,7 @@
using System.Collections.Frozen;
using System.Reflection;
using System.Security.Cryptography;
using Microsoft.Extensions.Primitives;
namespace Chronos.Server.Hosting;
@@ -8,6 +9,12 @@ namespace Chronos.Server.Hosting;
/// Serves the admin panel from embedded resources named <c>admin/…</c> (no build step, single-file friendly),
/// with strong ETags, conditional GET and SPA fallback to <c>index.html</c>.
/// </summary>
/// <remarks>
/// Every file, the modules included, is sent with <c>Cache-Control: no-cache</c>: the browser keeps it but asks again
/// before each use, and an unchanged file costs a 304 without a body. The ETag is a hash of the content, so an upgrade
/// changes the ETag of exactly the files it changed and a browser never runs new modules next to cached old ones (with
/// <c>max-age</c> it could, until the cache expired).
/// </remarks>
public sealed class EmbeddedStaticFiles
{
private static readonly FrozenDictionary<string, string> ContentTypes = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase)
@@ -55,9 +62,9 @@ public sealed class EmbeddedStaticFiles
}
var response = context.Response;
response.Headers.ETag = file.ETag;
response.Headers.CacheControl = path.EndsWith(".html", StringComparison.OrdinalIgnoreCase) ? "no-cache" : "public, max-age=3600";
response.Headers.CacheControl = "no-cache";
response.Headers.XContentTypeOptions = "nosniff";
if (context.Request.Headers.IfNoneMatch == file.ETag)
if (NoneMatchHolds(context.Request.Headers.IfNoneMatch, file.ETag))
{
response.StatusCode = StatusCodes.Status304NotModified;
return true;
@@ -67,4 +74,23 @@ public sealed class EmbeddedStaticFiles
if (!HttpMethods.IsHead(context.Request.Method)) await response.Body.WriteAsync(file.Content, context.RequestAborted);
return true;
}
/// <summary>
/// Whether an <c>If-None-Match</c> header names <paramref name="etag"/>: <c>*</c>, or one of its entity tags under the
/// weak comparison GET uses (RFC 9110 §13.1.2), so a tag a proxy marked <c>W/</c> still matches.
/// </summary>
internal static bool NoneMatchHolds(StringValues header, string etag)
{
foreach (var value in header)
{
if (string.IsNullOrEmpty(value)) continue;
foreach (var part in value.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries))
{
if (part == "*") return true;
var tag = part.StartsWith("W/", StringComparison.Ordinal) ? part[2..] : part;
if (string.Equals(tag, etag, StringComparison.Ordinal)) return true;
}
}
return false;
}
}
+2
View File
@@ -173,12 +173,14 @@ public static class ServerHost
AuthEndpoints.Map(api);
UserEndpoints.Map(api);
SequenceEndpoints.Map(api);
LibraryEndpoints.Map(api);
FileEndpoints.Map(api);
UploadEndpoints.Map(api);
JobEndpoints.Map(api);
ScheduleEndpoints.Map(api);
NodeEndpoints.Map(api);
ArchiveEndpoints.Map(api);
TrashEndpoints.Map(api);
AdminEndpoints.Map(api);
DiagnosticsEndpoints.Map(api);
EventEndpoints.Map(api);
@@ -56,6 +56,14 @@ public static class UploadRules
return intact.FirstOrDefault(f => f.SequenceId == target) ?? intact.FirstOrDefault();
}
/// <summary>
/// Whether <paramref name="target"/> tombstoned <paramref name="sha256"/> (owner review 2, R6): a photo deleted from that
/// sequence (or replaced by a converted file) that an upload must not bring back. The upload is answered as
/// <c>alreadyExists</c> without a frame, so a client neither sends the file nor treats the answer as a failure.
/// </summary>
public static async Task<bool> RemovedFromTargetAsync(ChronosDatabase db, string sha256, Guid? target, CancellationToken cancellationToken) =>
target is { } sequence && await db.FrameRemovals.IsRemovedAsync(sequence, sha256, cancellationToken).ConfigureAwait(false);
/// <summary>
/// The sequence an upload files into: its own, or the one its session key names (the user's own key without one);
/// null while that sequence does not exist yet.
+5 -1
View File
@@ -60,7 +60,11 @@ public sealed class UploadService(
var sha = request.Sha256.ToLowerInvariant();
var sessionKey = string.IsNullOrWhiteSpace(request.SessionKey) ? null : request.SessionKey.Trim();
var copies = await db.Frames.FindBySha256Async(sha, cancellationToken);
var target = copies.Count == 0 ? null : await UploadRules.TargetAsync(db, archive.Id, request.SequenceId, sessionKey, caller.Id, cancellationToken);
var target = await UploadRules.TargetAsync(db, archive.Id, request.SequenceId, sessionKey, caller.Id, cancellationToken);
// A photo deleted from the target sequence is not filed into it again: an old client syncing a copy that still holds
// it, or a watch folder sending it again, hears that the server has it (owner review 2, R6). A restore brings it back.
if (await UploadRules.RemovedFromTargetAsync(db, sha, target, cancellationToken))
return new StartUploadResponse(null, options.ChunkSizeBytes, [], AlreadyExists: true, null);
// Only a copy that is still whole stands for the upload: a client may delete its file on this answer.
if (UploadRules.StandIn(archive.Root, copies, target) is { } known)
return new StartUploadResponse(null, options.ChunkSizeBytes, [], AlreadyExists: true, known.Id);
@@ -0,0 +1,123 @@
using System.Globalization;
using System.IO;
using Chronos.App.Archiving;
using Chronos.App.Infrastructure;
using Chronos.Core.Localization;
using Chronos.Core.Model;
using Chronos.Data;
using Chronos.Data.Archiving;
using Chronos.Data.Archiving.Jobs;
using Chronos.Testing;
namespace Chronos.App.Tests.Archiving;
/// <summary>The trash dialog (owner review 2, R6): photo entries next to sequences, and Empty… behind a dry run and a typed confirmation.</summary>
public sealed class TrashDialogTests(TestContext context)
{
private static readonly DateTimeOffset Deleted = new(2026, 10, 27, 9, 30, 0, TimeSpan.Zero);
private static TrashEntry Entry(string title, TrashKind kind, int photos, long bytes) =>
new(Guid.CreateVersion7(), (kind == TrashKind.Sequence ? string.Empty : FrameTrash.EntryPrefix) + Guid.CreateVersion7().ToString("N"),
Guid.CreateVersion7(), title, "2026/" + title, photos, photos, bytes, Deleted, "alberto", kind);
[Test]
public void EveryKindOfEntryHasWordsAndTheRowSaysWhatItHolds()
{
Loc.SetCulture(CultureInfo.GetCultureInfo("en"));
foreach (var kind in Enum.GetValues<TrashKind>())
Assert.NotEqual("Archive.Trash.Kind." + kind, TrashEmptyPlans.KindText(kind), "every kind has words");
var row = new TrashRowViewModel(Entry("Harbour sunset", TrashKind.Photos, 12, 340_000_000), new Chronos.Ui.Mvvm.RelayCommand(() => { }));
Assert.Equal(Loc.L("Archive.Trash.Kind.Photos"), row.KindText);
Assert.True(row.Detail.StartsWith(row.KindText, StringComparison.Ordinal), row.Detail);
Assert.Contains(Loc.Plural("Shell.Status.Photos", 12), row.Detail);
}
[Test]
public void EmptyingAsksToTypeHowManyEntriesAreErased()
{
Loc.SetCulture(CultureInfo.GetCultureInfo("en"));
var entries = new[] { Entry("Harbour sunset", TrashKind.Photos, 12, 340_000_000), Entry("Comet", TrashKind.Sequence, 1_005, 21_000_000_000) };
var plan = new TrashEmptyPlan(Guid.CreateVersion7(), entries, 21_340_000_000, "f1", []);
var request = Assert.NotNull(TrashEmptyPlans.Request(plan));
Assert.True(request.IsDestructive, "the action is outlined, never primary");
Assert.Equal("2", request.TypedConfirmation);
Assert.Equal(Loc.L("Archive.Delete.Type", "2"), request.TypedPrompt);
Assert.Equal(Loc.Plural("Archive.Trash.EmptyHeading", 2), request.Heading);
Assert.Equal(Loc.L("Archive.Trash.EmptyMessage", Loc.Plural("Shell.Status.Photos", 1_017), Loc.Plural("Archive.Delete.Files", 1_017),
Formatting.Bytes(21_340_000_000)), request.Message);
Assert.Equal(Loc.L("Archive.Trash.Erase"), request.ActionText);
Assert.Equal(Loc.L("Archive.Delete.Keep"), request.SafeText);
var lines = request.Detail!.Split(Environment.NewLine);
Assert.Equal(2, lines.Length);
Assert.Contains(Loc.L("Archive.Trash.Kind.Photos"), lines[0]);
Assert.Null(TrashEmptyPlans.Request(plan with { Entries = [] }), "nothing to erase: no confirmation");
}
[Test]
public async Task EmptyQueuesTheJobOfTheConfirmedPlanOnly()
{
Loc.SetCulture(CultureInfo.GetCultureInfo("en"));
var directory = context.CreateTempDirectory("trash-dialog");
await using var db = await ChronosDatabase.OpenAsync(DatabaseOptions.Sqlite(Path.Combine(directory, "index.db")));
var archives = new ArchiveService(db, new ArchiveServiceOptions { Owner = "test", LeaseWait = TimeSpan.FromSeconds(TestTiming.Budget(20)) });
var archive = await archives.CreateAsync(Path.Combine(directory, "archive"), "Main");
// A sequence deleted earlier: its folder and its record in the archive's trash.
var id = Guid.CreateVersion7();
var trash = SequenceTrash.TrashDirectory(new Core.Archiving.ArchivePaths(archive.RootPath));
Directory.CreateDirectory(Path.Combine(trash, id.ToString("N")));
await File.WriteAllBytesAsync(Path.Combine(trash, id.ToString("N"), "IMG_0001.JPG"), [1, 2, 3]);
await File.WriteAllTextAsync(Path.Combine(trash, id.ToString("N") + ".json"),
$$"""{"sequence":{"id":"{{id}}","archiveId":"{{archive.Id}}","title":"Harbour sunset","folder":"2026/Harbour","frameCount":1},"renders":[],"files":1,"bytes":3,"deletedAt":"2026-10-27T09:30:00+00:00","deletedBy":"alberto"}""");
var plain = new TrashDialogViewModel(archives, archive, () => Task.CompletedTask, _ => { });
await plain.LoadAsync();
Assert.Count(1, plain.Rows);
Assert.False(plain.CanEmpty, "a host without a job engine offers no emptying");
ConfirmRequest? asked = null;
var answer = false;
var queued = new TaskCompletionSource<ArchiveJobRequest>(TaskCreationOptions.RunContinuationsAsynchronously);
var closed = false;
var dialog = new TrashDialogViewModel(archives, archive, () => Task.CompletedTask, _ => closed = true, r =>
{
asked = r;
return answer;
}, r =>
{
queued.TrySetResult(r);
return Task.CompletedTask;
});
await dialog.LoadAsync();
Assert.True(dialog.CanEmpty);
Assert.Equal(Loc.Plural("Archive.Trash.Entries", 1) + Loc.Separator + Formatting.Bytes(3), dialog.SummaryText);
// Kept: the confirmation was dismissed, nothing is queued.
dialog.EmptyCommand.Execute(null);
await UntilAsync(() => asked is not null && !dialog.IsBusy);
Assert.Equal("1", asked!.TypedConfirmation);
Assert.False(queued.Task.IsCompleted);
Assert.False(closed);
answer = true;
dialog.EmptyCommand.Execute(null);
var request = await queued.Task.WaitAsync(TimeSpan.FromSeconds(TestTiming.Budget(20)));
Assert.Equal(JobKind.EmptyTrash, request.Kind);
Assert.SequenceEqual([archive.Id], request.Targets);
Assert.Contains(id.ToString("N"), request.ParametersJson);
await UntilAsync(() => closed);
Assert.Count(1, await archives.ListTrashAsync(archive.Id), "the job erases, not the dialog");
}
private static async Task UntilAsync(Func<bool> condition)
{
var until = DateTime.UtcNow + TimeSpan.FromSeconds(TestTiming.Budget(20));
while (!condition())
{
Assert.True(DateTime.UtcNow < until, "timed out");
await Task.Delay(20);
}
}
}
@@ -118,7 +118,7 @@ public sealed class LibraryScreenSmokeTests
await ArchiveScenes.ShowAsync(app.Shell, "trash");
var trash = Assert.NotNull(app.Shell.Archive.Dialog as TrashDialogViewModel, "Maintenance › Trash… opens the trash");
Assert.Equal(2, trash.Rows.Count, "the sample's deleted sequences");
Assert.Equal(2, trash.Rows.Count, "the sample's deleted sequence and photos");
Assert.True(trash.HasRows);
await app.ExpectAsync<ArchiveView>("archive-trash-sample");
trash.CloseCommand.Execute(null);
@@ -58,6 +58,43 @@ public sealed class ManifestStoreTests(TestContext context)
Assert.Contains(field, json);
}
[Test]
public void TombstonesAndConversionSourcesRoundTripWhileASidecarWithoutThemStaysAsItWas()
{
var path = SidecarPath();
var plain = Sample();
ManifestStore.WriteSequence(path, plain);
var before = File.ReadAllText(path);
Assert.False(before.Contains("\"removed\"", StringComparison.Ordinal), "no tombstones, no field");
Assert.False(before.Contains("\"source\"", StringComparison.Ordinal), "an original has no source");
var at = new DateTimeOffset(2026, 10, 27, 10, 0, 0, TimeSpan.Zero);
var changed = plain with
{
Removed =
[
new RemovedPhoto { Sha256 = new string('b', 64), Reason = RemovalReason.Deleted, At = at },
new RemovedPhoto { Sha256 = new string('c', 64), Replacement = new string('d', 64), Reason = RemovalReason.Replaced, At = at },
],
Frames =
[
plain.Frames[0] with
{
Source = new FrameSource { Sha256 = new string('e', 64), Format = ImageFileFormat.Cr2, File = "originals/IMG_0001.CR2", Size = 25_000_000 },
},
],
};
ManifestStore.WriteSequence(path, changed);
var read = ManifestStore.ReadSequence(path);
Assert.Equal(Canonical(changed), Canonical(read));
Assert.Equal(RemovalReason.Replaced, Assert.NotNull(read.Removed)[1].Reason);
Assert.Equal(new string('d', 64), read.Removed[1].Replacement);
Assert.Equal(ImageFileFormat.Cr2, Assert.NotNull(read.Frames[0].Source).Format);
var json = File.ReadAllText(path);
foreach (var field in new[] { "\"removed\":", "\"replacement\":", "\"reason\":\"Replaced\"", "\"at\":", "\"source\":" }) Assert.Contains(field, json);
}
[Test]
public void ASidecarBeingReadIsReplacedOnceTheReaderIsDone()
{
@@ -0,0 +1,456 @@
using System.Security.Cryptography;
using System.Text.Json;
using Chronos.Core.Archiving;
using Chronos.Core.Import;
using Chronos.Core.Model;
using Chronos.Core.Project;
using Chronos.Data.Archiving;
using Chronos.Data.Archiving.Jobs;
using Chronos.Data.Repositories;
using Chronos.Data.Tests.Infrastructure;
using Chronos.Testing;
using static Chronos.Data.Tests.Archiving.ArchiveFixture;
namespace Chronos.Data.Tests.Archiving;
/// <summary>Deleting photos of a sequence into the archive's trash, restoring them and emptying the trash (owner review 2, R6).</summary>
[Category("archive")]
public abstract class FrameTrashTests(TestContext context) : DatabaseTest(context)
{
private async Task<ArchiveFixture> FixtureAsync() => Own(await CreateAsync(Context, database: await NewOptionsAsync(multiConnection: true)));
/// <summary>A sequence of <paramref name="count"/> uploaded photos (hashed, under <c>originals/</c>), ten seconds apart.</summary>
private static async Task<(Sequence Sequence, List<Frame> Frames)> UploadedAsync(ArchiveFixture fx, int count, string session = "upload-1", int seed = 100)
{
Guid? id = null;
for (var i = 0; i < count; i++)
{
var (path, size, sha) = fx.Stage(Start.AddSeconds(10 * i), seed + i);
var result = await fx.Service.Ingest.CommitAsync(new IngestRequest(fx.Archive.Id, id, null, id is null ? session : null, path, $"IMG_{i + 1:0000}.JPG",
size, sha, null, null), fx.Ct);
id = result.SequenceId;
}
return ((await fx.Db.Sequences.GetAsync(id!.Value))!, [.. await fx.Db.Frames.ListBySequenceAsync(id.Value)]);
}
private static async Task<FrameDeleteResult> DeleteAsync(ArchiveFixture fx, Sequence sequence, params Frame[] frames)
{
var plan = await fx.Service.FrameTrash.PlanDeleteAsync(sequence.Id, [.. frames.Select(f => f.Id)], sequence.FramesVersion, fx.Ct);
Assert.True(plan.CanDelete, string.Join(", ", plan.Blocked));
return await fx.Service.FrameTrash.DeleteAsync(plan, "alberto", null, fx.Ct);
}
private static Job Running(JobKind kind, IReadOnlyList<Guid> targets) => new()
{
Id = Guid.CreateVersion7(),
Kind = kind,
TargetIds = targets,
State = JobState.Running,
NodeId = "test#0",
Created = DateTimeOffset.UtcNow,
Started = DateTimeOffset.UtcNow,
};
private static string Sha(string path) => Convert.ToHexStringLower(SHA256.HashData(File.ReadAllBytes(path)));
[Test]
public async Task TheDryRunCountsThePhotosAndChangesNothing()
{
var fx = await FixtureAsync();
var (sequence, frames) = await UploadedAsync(fx, 5);
var before = await Photos.DumpIndexAsync(fx.Db, fx.Archive.Id);
var plan = await fx.Service.FrameTrash.PlanDeleteAsync(sequence.Id, [frames[1].Id, frames[3].Id], sequence.FramesVersion, fx.Ct);
Assert.True(plan.CanDelete);
Assert.SequenceEqual([frames[1].Id, frames[3].Id], plan.Frames.Select(f => f.Id));
Assert.Equal(frames[1].Size + frames[3].Size, plan.Bytes);
Assert.Equal(before, await Photos.DumpIndexAsync(fx.Db, fx.Archive.Id));
Assert.False(Directory.Exists(FrameTrash.Directory(fx.Paths)), "a dry run moves nothing");
foreach (var frame in frames) Assert.FileExists(fx.Paths.FromRelative(frame.RelativePath));
}
[Test]
public async Task APlanSaysWhyPhotosCannotGo()
{
var fx = await FixtureAsync();
var (sequence, frames) = await UploadedAsync(fx, 3);
var trash = fx.Service.FrameTrash;
Assert.SequenceEqual([FrameDeleteBlock.WouldEmpty], (await trash.PlanDeleteAsync(sequence.Id, [.. frames.Select(f => f.Id)], null, fx.Ct)).Blocked);
Assert.SequenceEqual([FrameDeleteBlock.FramesChanged], (await trash.PlanDeleteAsync(sequence.Id, [frames[0].Id], sequence.FramesVersion - 1, fx.Ct)).Blocked);
Assert.SequenceEqual([FrameDeleteBlock.FramesChanged], (await trash.PlanDeleteAsync(sequence.Id, [frames[0].Id, Guid.CreateVersion7()], null, fx.Ct)).Blocked);
await Assert.ThrowsAsync<ArgumentException>(() => trash.PlanDeleteAsync(Guid.CreateVersion7(), [frames[0].Id], null, fx.Ct));
// A job on the sequence, or on its whole archive, holds it.
await fx.Db.Jobs.EnqueueAsync(Running(JobKind.Render, [sequence.Id]));
var busy = await trash.PlanDeleteAsync(sequence.Id, [frames[0].Id], null, fx.Ct);
Assert.SequenceEqual([FrameDeleteBlock.Busy], busy.Blocked);
Assert.False(busy.CanDelete);
await Assert.ThrowsAsync<StaleDeletePlanException>(() => trash.DeleteAsync(busy, null, null, fx.Ct));
Assert.Count(3, await fx.Db.Frames.ListBySequenceAsync(sequence.Id));
}
[Test]
public async Task DeletingMovesThePhotosToTheTrashAndTombstonesThem()
{
var fx = await FixtureAsync();
var (sequence, frames) = await UploadedAsync(fx, 5);
var folder = fx.Paths.Sequence(sequence.Folder);
// Proxies are named by frame index: they follow their frames.
Directory.CreateDirectory(folder.Proxies);
for (var i = 0; i < frames.Count; i++) File.WriteAllBytes(folder.Proxy(i), [(byte)i]);
await fx.Db.Sequences.UpdateStatusAsync(sequence.Id, SequenceStatus.AnalyzedLight | SequenceStatus.ThumbsBuilt, SequenceStatus.None);
var result = await DeleteAsync(fx, sequence, frames[1], frames[3]);
foreach (var gone in new[] { frames[1], frames[3] }) Assert.FileMissing(fx.Paths.FromRelative(gone.RelativePath));
var entry = result.Entry;
Assert.Equal(TrashKind.Photos, entry.Kind);
Assert.True(FrameTrash.IsPhotoEntry(entry.Name));
Assert.Equal(2, entry.Frames);
Assert.Equal(frames[1].Size + frames[3].Size, entry.Bytes);
var entryFolder = Path.Combine(FrameTrash.Directory(fx.Paths), entry.Name[FrameTrash.EntryPrefix.Length..]);
Assert.Equal(frames[1].Sha256, Sha(Path.Combine(entryFolder, "originals", Path.GetFileName(frames[1].RelativePath))));
Assert.FileMissing(folder.RemovalJournalPath);
var manifest = ManifestStore.ReadSequence(folder.ManifestPath);
Assert.SequenceEqual([frames[0].Id, frames[2].Id, frames[4].Id], manifest.Frames.Select(f => f.Id));
Assert.SequenceEqual([0, 1, 2], manifest.Frames.Select(f => f.I));
Assert.Equal(sequence.FramesVersion + 1, manifest.Versions.Frames);
Assert.SequenceEqual([frames[1].Sha256, frames[3].Sha256], Assert.NotNull(manifest.Removed).Select(r => r.Sha256));
Assert.True(manifest.Removed.All(r => r.Reason == RemovalReason.Deleted));
var row = result.Sequence;
Assert.Equal(3, row.FrameCount);
Assert.Equal(manifest.Versions.Frames, row.FramesVersion);
Assert.Equal(SequenceStatus.None, row.Status & (SequenceStatus.AnalyzedLight | SequenceStatus.ThumbsBuilt));
Assert.SequenceEqual([frames[0].Id, frames[2].Id, frames[4].Id], (await fx.Db.Frames.ListBySequenceAsync(sequence.Id)).Select(f => f.Id));
Assert.SequenceEqual([frames[1].Sha256, frames[3].Sha256], (await fx.Db.FrameRemovals.ListBySequenceAsync(sequence.Id)).Select(r => r.Sha256).Order());
Assert.True(await fx.Db.FrameRemovals.IsRemovedAsync(sequence.Id, frames[3].Sha256!.ToUpperInvariant()));
Assert.SequenceEqual<byte>([0, 2, 4], Enumerable.Range(0, 3).Select(i => File.ReadAllBytes(folder.Proxy(i))[0]));
Assert.FileMissing(folder.Proxy(3));
Assert.FileMissing(folder.Proxy(4));
var listed = Assert.Contains(await fx.Service.ListTrashAsync(fx.Archive.Id, fx.Ct), e => e.Name == entry.Name);
Assert.Equal(sequence.DisplayTitle, listed.Title);
Assert.Equal("alberto", listed.DeletedBy);
}
[Test]
public async Task PositionsOnDeletedPhotosWaitAndComeBackWithThem()
{
var fx = await FixtureAsync();
var (sequence, frames) = await UploadedAsync(fx, 5);
var folder = fx.Paths.Sequence(sequence.Folder);
var project = new ProjectSettings { ExcludedFrames = [1, 4], HeroFrame = 3 }.ToJson();
var version = (await fx.Db.Sequences.EditAsync(sequence.Id, new SequenceEdit { SettingsJson = project, HeroFrameId = frames[3].Id }, null, fx.Ct))
.Sequence!.SettingsVersion;
var deleted = await DeleteAsync(fx, (await fx.Db.Sequences.GetAsync(sequence.Id))!, frames[1], frames[3]);
var row = deleted.Sequence;
var parked = ProjectSettings.FromJson(row.SettingsJson!);
Assert.SequenceEqual([2], parked.ExcludedFrames, "the exclusion of the fifth photo follows it");
Assert.Null(parked.HeroFrame);
Assert.Count(2, Assert.NotNull(parked.PendingFrames));
Assert.True(parked.HeroPending, "the hero waits for its photo");
Assert.Null(row.HeroFrameId);
Assert.Equal(version, row.SettingsVersion);
Assert.True(File.Exists(folder.ProjectPath), "project.json mirrors the index");
var restored = await fx.Service.RestoreEntryAsync(fx.Archive.Id, deleted.Entry.Name, null, fx.Ct);
Assert.Equal(TrashKind.Photos, restored.Kind);
Assert.Equal(2, restored.Photos);
Assert.Empty(restored.Kept);
var back = (await fx.Db.Sequences.GetAsync(sequence.Id))!;
var placed = ProjectSettings.FromJson(back.SettingsJson!);
Assert.SequenceEqual([1, 4], placed.ExcludedFrames);
Assert.Equal(3, placed.HeroFrame);
Assert.Null(placed.PendingFrames);
Assert.Equal(frames[3].Id, back.HeroFrameId);
Assert.Equal(version, back.SettingsVersion);
}
[Test]
public async Task ARestorePutsThePhotosBackWithTheirIdsAndDropsTheirTombstones()
{
var fx = await FixtureAsync();
var (sequence, frames) = await UploadedAsync(fx, 4);
var folder = fx.Paths.Sequence(sequence.Folder);
Directory.CreateDirectory(folder.Proxies);
for (var i = 0; i < frames.Count; i++) File.WriteAllBytes(folder.Proxy(i), [(byte)i]);
var deleted = await DeleteAsync(fx, sequence, frames[0], frames[2]);
var restored = await fx.Service.RestoreEntryAsync(fx.Archive.Id, deleted.Entry.Name, null, fx.Ct);
Assert.False(restored.NewSequence);
Assert.Equal(sequence.Id, restored.Sequence.Id);
var now = await fx.Db.Frames.ListBySequenceAsync(sequence.Id);
Assert.SequenceEqual(frames.Select(f => f.Id), now.Select(f => f.Id));
Assert.SequenceEqual(frames.Select(f => f.RelativePath), now.Select(f => f.RelativePath));
Assert.SequenceEqual(frames.Select(f => f.Sha256), now.Select(f => f.Sha256));
foreach (var frame in frames) Assert.Equal(frame.Sha256, Sha(fx.Paths.FromRelative(frame.RelativePath)));
Assert.Null(ManifestStore.ReadSequence(folder.ManifestPath).Removed);
Assert.Empty(await fx.Db.FrameRemovals.ListBySequenceAsync(sequence.Id));
Assert.Equal(sequence.FramesVersion + 2, restored.Sequence.FramesVersion);
Assert.DoesNotContain(deleted.Entry.Name, (await fx.Service.ListTrashAsync(fx.Archive.Id, fx.Ct)).Select(e => e.Name));
Assert.False(Directory.Exists(Path.Combine(FrameTrash.Directory(fx.Paths), deleted.Entry.Name[FrameTrash.EntryPrefix.Length..])));
// The proxies of the frames that stayed are back at their index; those of the photos that went are made again.
Assert.SequenceEqual<byte>([1], File.ReadAllBytes(folder.Proxy(1)));
Assert.SequenceEqual<byte>([3], File.ReadAllBytes(folder.Proxy(3)));
Assert.FileMissing(folder.Proxy(0));
}
[Test]
public async Task ARestoreKeepsAPhotoWhoseFileNoLongerMatchesItsRecord()
{
var fx = await FixtureAsync();
var (sequence, frames) = await UploadedAsync(fx, 4);
var deleted = await DeleteAsync(fx, sequence, frames[1], frames[2]);
var entryFolder = Path.Combine(FrameTrash.Directory(fx.Paths), deleted.Entry.Name[FrameTrash.EntryPrefix.Length..]);
var damaged = Path.Combine(entryFolder, "originals", Path.GetFileName(frames[2].RelativePath));
var bytes = File.ReadAllBytes(damaged);
bytes[^10] ^= 0x01;
File.WriteAllBytes(damaged, bytes);
var restored = await fx.Service.RestoreEntryAsync(fx.Archive.Id, deleted.Entry.Name, null, fx.Ct);
Assert.Equal(1, restored.Photos);
Assert.SequenceEqual([frames[2].OriginalFileName!], restored.Kept);
Assert.SequenceEqual([frames[0].Id, frames[1].Id, frames[3].Id], (await fx.Db.Frames.ListBySequenceAsync(sequence.Id)).Select(f => f.Id));
Assert.SequenceEqual([frames[2].Sha256], (await fx.Db.FrameRemovals.ListBySequenceAsync(sequence.Id)).Select(r => r.Sha256));
var left = Assert.Contains(await fx.Service.ListTrashAsync(fx.Archive.Id, fx.Ct), e => e.Name == deleted.Entry.Name);
Assert.Equal(1, left.Frames);
Assert.FileExists(damaged);
// Nothing left that matches: the entry stays as it is.
await Assert.ThrowsAsync<InvalidDataException>(() => fx.Service.RestoreEntryAsync(fx.Archive.Id, deleted.Entry.Name, null, fx.Ct));
Assert.FileExists(damaged);
}
[Test]
public async Task PhotosOfASequenceThatIsGoneComeBackAsANewOne()
{
var fx = await FixtureAsync();
var (sequence, frames) = await UploadedAsync(fx, 3);
var deleted = await DeleteAsync(fx, sequence, frames[1]);
var whole = await fx.Service.PlanDeleteAsync([sequence.Id], null, fx.Ct);
await fx.Service.DeleteAsync(whole, null, null, fx.Ct);
var restored = await fx.Service.RestoreEntryAsync(fx.Archive.Id, deleted.Entry.Name, null, fx.Ct);
Assert.True(restored.NewSequence);
Assert.NotEqual(sequence.Id, restored.Sequence.Id);
Assert.Equal(sequence.DisplayTitle, restored.Sequence.DisplayTitle);
var frame = (await fx.Db.Frames.ListBySequenceAsync(restored.Sequence.Id)).Single();
Assert.Equal(frames[1].Sha256, frame.Sha256);
Assert.Equal(frames[1].Sha256, Sha(fx.Paths.FromRelative(frame.RelativePath)));
// The whole sequence is still in the trash, restorable on its own.
Assert.Contains(await fx.Service.ListTrashAsync(fx.Archive.Id, fx.Ct), e => e.Kind == TrashKind.Sequence && e.SequenceId == sequence.Id);
}
[Test]
public async Task TombstonesSurviveARebuildFromTheSidecars()
{
var fx = await FixtureAsync();
var (sequence, frames) = await UploadedAsync(fx, 3);
await DeleteAsync(fx, sequence, frames[0]);
await fx.ReopenWithEmptyIndexAsync();
await fx.ScanAsync(ScanMode.Rebuild);
var removals = await fx.Db.FrameRemovals.ListBySequenceAsync(sequence.Id);
Assert.SequenceEqual([frames[0].Sha256], removals.Select(r => r.Sha256));
Assert.Equal(RemovalReason.Deleted, removals[0].Reason);
Assert.Count(2, await fx.Db.Frames.ListBySequenceAsync(sequence.Id));
}
[Test]
public async Task TombstonesAreReplacedWholeAndGoWithTheirSequence()
{
var fx = await FixtureAsync();
var (sequence, _) = await UploadedAsync(fx, 1);
var at = new DateTimeOffset(2026, 10, 27, 10, 0, 0, TimeSpan.Zero);
var many = Enumerable.Range(0, 450).Select(i => new FrameRemoval(sequence.Id, i.ToString("x64", System.Globalization.CultureInfo.InvariantCulture),
i % 2 == 0 ? null : new string('A', 64), i % 2 == 0 ? RemovalReason.Deleted : RemovalReason.Replaced, at)).ToList();
Assert.Equal(450, await fx.Db.FrameRemovals.SyncSequenceAsync(sequence.Id, many, fx.Ct));
var stored = await fx.Db.FrameRemovals.ListBySequenceAsync(sequence.Id, fx.Ct);
Assert.Count(450, stored);
Assert.Equal((new string('a', 64), RemovalReason.Replaced), (stored.Single(r => r.Sha256 == many[1].Sha256).ReplacementSha256, stored[1].Reason));
Assert.Equal(1, await fx.Db.FrameRemovals.SyncSequenceAsync(sequence.Id, [many[3], many[3]], fx.Ct));
Assert.Count(1, await fx.Db.FrameRemovals.ListBySequenceAsync(sequence.Id, fx.Ct));
await fx.Db.Sequences.DeleteAsync(sequence.Id, fx.Ct);
Assert.Empty(await fx.Db.FrameRemovals.ListBySequenceAsync(sequence.Id, fx.Ct));
}
[Test]
public async Task ADeletionACrashInterruptedIsUndoneByTheNextWriter()
{
var fx = await FixtureAsync();
var (sequence, frames) = await UploadedAsync(fx, 3);
var folder = fx.Paths.Sequence(sequence.Folder);
// The journal was written and one of two files moved when the process died; the sidecar still lists both frames.
var entry = Path.Combine(FrameTrash.Directory(fx.Paths), $"{sequence.Id:N}-20261027120000");
var record = entry + ".json";
Directory.CreateDirectory(Path.Combine(entry, "originals"));
File.WriteAllText(record, "{}");
var moves = frames.Take(2).Select(f => new FrameRemovalMove(f.RelativePath[(sequence.Folder.Length + 1)..],
fx.Paths.ToRelative(Path.Combine(entry, "originals", Path.GetFileName(f.RelativePath))))).ToList();
FrameRemovalJournal.Write(folder, new FrameRemovalJournal(fx.Paths.ToRelative(record), fx.Paths.ToRelative(entry), [frames[0].Id, frames[1].Id], moves));
File.Move(fx.Paths.FromRelative(frames[0].RelativePath), fx.Paths.FromRelative(moves[0].To));
// Any writer of the sequence reads its sidecar under the lease first.
await fx.Service.SetSequenceInfoAsync(sequence.Id, "Harbour", [], 0, null, fx.Ct);
foreach (var frame in frames) Assert.Equal(frame.Sha256, Sha(fx.Paths.FromRelative(frame.RelativePath)));
Assert.FileMissing(folder.RemovalJournalPath);
Assert.FileMissing(record);
Assert.False(Directory.Exists(entry));
Assert.Count(3, ManifestStore.ReadSequence(folder.ManifestPath).Frames);
}
[Test]
public async Task ErasingTheCardKeepsTheCardCopyOfADeletedPhoto()
{
var fx = await FixtureAsync();
var card = Context.CreateTempDirectory("card");
Photos.WriteSeries(Path.Combine(card, "DCIM", "100CANON"), Start, 4);
var media = await fx.Service.Imports.RegisterCardAsync(new CardVolume("3F2A9C11-EOS_DIGITAL-127865454592", 0x3F2A9C11, "EOS_DIGITAL", 127_865_454_592), fx.Ct);
var plan = await fx.Service.PlanImportAsync(fx.Archive.Id, card, new ImportOptions(), media.Id, null, fx.Ct);
await fx.Service.Imports.ExecuteAsync(new ImportJobParameters(fx.Archive.Id, plan, media.Id, true, null), Guid.NewGuid(), 0,
_ => ValueTask.CompletedTask, null, fx.Ct);
var id = (await fx.Db.Sequences.FindBySessionKeyAsync(fx.Archive.Id, plan.Sessions.Single().SessionKey))!.Value;
var frames = await fx.Db.Frames.ListBySequenceAsync(id);
await DeleteAsync(fx, (await fx.Db.Sequences.GetAsync(id))!, frames[2]);
var erase = await fx.Service.PlanCardEraseAsync(fx.Archive.Id, media.Id, card, null, fx.Ct);
CardEraser.Execute(erase);
// The deleted photo has no frame any more: nothing in the archive vouches for its card copy, which stays.
Assert.Equal(3, erase.ToDelete.Count());
var left = Directory.EnumerateFiles(card, "*.JPG", SearchOption.AllDirectories).Select(f => Path.GetFileName(f)).ToList();
Assert.SequenceEqual([frames[2].OriginalFileName!], left);
}
[Test]
public async Task EmptyingErasesExactlyThePlannedEntries()
{
var fx = await FixtureAsync();
var (sequence, frames) = await UploadedAsync(fx, 3);
var (other, _) = await UploadedAsync(fx, 2, "upload-2", 200);
var photos = await DeleteAsync(fx, sequence, frames[1]);
await fx.Service.DeleteAsync(await fx.Service.PlanDeleteAsync([other.Id], null, fx.Ct), null, null, fx.Ct);
var engine = await fx.StartEngineAsync();
var plan = await fx.Service.PlanEmptyTrashAsync(fx.Archive.Id, null, fx.Ct);
Assert.Count(2, plan.Entries);
Assert.Equal(3, plan.Photos);
Assert.True(plan.Bytes > 0);
Assert.Equal(plan.Fingerprint, (await fx.Service.PlanEmptyTrashAsync(fx.Archive.Id, null, fx.Ct)).Fingerprint, "the plan reads only");
Assert.SequenceEqual(["nope"], (await fx.Service.PlanEmptyTrashAsync(fx.Archive.Id, [photos.Entry.Name, "nope"], fx.Ct)).Unknown);
var job = await engine.EnqueueAsync(ArchiveJobs.EmptyTrash(fx.Archive, plan), cancellationToken: fx.Ct);
var done = await fx.WaitForAsync(job.Id, JobState.Done);
Assert.Empty(await fx.Service.ListTrashAsync(fx.Archive.Id, fx.Ct));
Assert.Empty(Directory.EnumerateFileSystemEntries(FrameTrash.Directory(fx.Paths)));
Assert.Empty(Directory.EnumerateFiles(SequenceTrash.TrashDirectory(fx.Paths), "*", SearchOption.AllDirectories));
Assert.Contains(Chronos.Core.Localization.Loc.L("Archive.Log.TrashEmptied", 2, Housekeeping.CleanupSteps.Megabytes(plan.Bytes)), done.LogTail);
// Tombstones outlive the trash: the deleted photo is still not offered back.
Assert.True(await fx.Db.FrameRemovals.IsRemovedAsync(sequence.Id, frames[1].Sha256!));
}
[Test]
public async Task AnEmptyingPlannedBeforeTheTrashChangedErasesNothing()
{
var fx = await FixtureAsync();
var (sequence, frames) = await UploadedAsync(fx, 4);
var first = await DeleteAsync(fx, sequence, frames[1]);
var second = await DeleteAsync(fx, (await fx.Db.Sequences.GetAsync(sequence.Id))!, frames[2]);
var plan = await fx.Service.PlanEmptyTrashAsync(fx.Archive.Id, null, fx.Ct);
var engine = await fx.StartEngineAsync();
// A planned entry came back (restored) before the job ran.
await fx.Service.RestoreEntryAsync(fx.Archive.Id, first.Entry.Name, null, fx.Ct);
var job = await engine.EnqueueAsync(ArchiveJobs.EmptyTrash(fx.Archive, plan), cancellationToken: fx.Ct);
var failed = await fx.WaitForAsync(job.Id, JobState.Failed);
Assert.Equal(Chronos.Core.Localization.Loc.L("Archive.Error.TrashChanged"), failed.Error);
Assert.Contains(await fx.Service.ListTrashAsync(fx.Archive.Id, fx.Ct), e => e.Name == second.Entry.Name);
// A planned entry whose folder changed since makes the plan stale too.
var again = await fx.Service.PlanEmptyTrashAsync(fx.Archive.Id, null, fx.Ct);
var folder = Path.Combine(FrameTrash.Directory(fx.Paths), second.Entry.Name[FrameTrash.EntryPrefix.Length..]);
File.WriteAllBytes(Path.Combine(folder, "added.bin"), [1, 2, 3]);
Assert.NotEqual(again.Fingerprint, (await fx.Service.PlanEmptyTrashAsync(fx.Archive.Id, null, fx.Ct)).Fingerprint);
var stale = await engine.EnqueueAsync(ArchiveJobs.EmptyTrash(fx.Archive, again), cancellationToken: fx.Ct);
await fx.WaitForAsync(stale.Id, JobState.Failed);
Assert.Contains(await fx.Service.ListTrashAsync(fx.Archive.Id, fx.Ct), e => e.Name == second.Entry.Name);
Assert.FileExists(Path.Combine(folder, "added.bin"));
}
[Test]
public async Task AReplacedEntryIsErasedOnlyWhileItsReplacementMatches()
{
var fx = await FixtureAsync();
var (sequence, frames) = await UploadedAsync(fx, 2);
var replacement = frames[1];
var good = WriteReplaced(fx, sequence, "20261027100000", replacement.Sha256!);
var bad = WriteReplaced(fx, sequence, "20261027110000", new string('a', 64));
var engine = await fx.StartEngineAsync();
var listed = await fx.Service.ListTrashAsync(fx.Archive.Id, fx.Ct);
Assert.True(listed.All(e => e.Kind == TrashKind.Replaced));
var plan = await fx.Service.PlanEmptyTrashAsync(fx.Archive.Id, null, fx.Ct);
var job = await engine.EnqueueAsync(ArchiveJobs.EmptyTrash(fx.Archive, plan), cancellationToken: fx.Ct);
var failed = await fx.WaitForAsync(job.Id, JobState.Failed);
Assert.Equal(Chronos.Core.Localization.Loc.Plural("Archive.Error.TrashKept", 1), failed.Error);
var left = Assert.Contains(await fx.Service.ListTrashAsync(fx.Archive.Id, fx.Ct), e => e.Name == FrameTrash.EntryPrefix + bad);
Assert.Equal(TrashKind.Replaced, left.Kind);
Assert.DoesNotContain(FrameTrash.EntryPrefix + good, (await fx.Service.ListTrashAsync(fx.Archive.Id, fx.Ct)).Select(e => e.Name));
// A replacement whose file no longer hashes to it keeps its originals too.
var other = WriteReplaced(fx, sequence, "20261027120000", replacement.Sha256!);
var file = fx.Paths.FromRelative(replacement.RelativePath);
var bytes = File.ReadAllBytes(file);
bytes[^10] ^= 0x01;
File.WriteAllBytes(file, bytes);
var again = await fx.Service.PlanEmptyTrashAsync(fx.Archive.Id, [FrameTrash.EntryPrefix + other], fx.Ct);
var second = await engine.EnqueueAsync(ArchiveJobs.EmptyTrash(fx.Archive, again), cancellationToken: fx.Ct);
await fx.WaitForAsync(second.Id, JobState.Failed);
Assert.Contains(await fx.Service.ListTrashAsync(fx.Archive.Id, fx.Ct), e => e.Name == FrameTrash.EntryPrefix + other);
}
/// <summary>An entry of originals a conversion replaced (a later phase), its one photo replaced by <paramref name="replacement"/>.</summary>
private static string WriteReplaced(ArchiveFixture fx, Sequence sequence, string stamp, string replacement)
{
var name = $"{sequence.Id:N}-{stamp}";
var folder = Path.Combine(FrameTrash.Directory(fx.Paths), name);
Directory.CreateDirectory(Path.Combine(folder, "originals"));
var bytes = Photos.Jpeg(Start, 999);
File.WriteAllBytes(Path.Combine(folder, "originals", "IMG_0001.CR2"), bytes);
var sha = Convert.ToHexStringLower(SHA256.HashData(bytes));
var frame = new SidecarFrame { Id = Guid.CreateVersion7(), File = "originals/IMG_0001.CR2", Size = bytes.Length, Sha256 = sha };
var record = new PhotoTrashRecord(TrashKind.Replaced, sequence.Id, sequence.DisplayTitle, sequence.Folder,
[new TrashedPhoto(frame, [new TrashedFile(frame.File, "originals/IMG_0001.CR2", bytes.Length, sha)], replacement)], bytes.Length,
DateTimeOffset.UtcNow, "converter");
File.WriteAllText(folder + ".json", JsonSerializer.Serialize(record, TrashJson.Default.PhotoTrashRecord));
return name;
}
}
public sealed class SqliteFrameTrashTests(TestContext context) : FrameTrashTests(context)
{
protected override Backend Backend => Backend.SqliteFile;
}
[RequiresEnvironment(PgTestServer.Variable)]
public sealed class PostgresFrameTrashTests(TestContext context) : FrameTrashTests(context)
{
protected override Backend Backend => Backend.Postgres;
}
@@ -9,7 +9,7 @@ public abstract class MigrationTests(TestContext context) : RepositoryTest(conte
private static readonly string[] Tables =
[
"archives", "sequences", "frames", "renders", "jobs", "media_cards", "import_history", "users", "tokens",
"render_nodes", "settings", "tags", "sequence_tags", "audit_log", "uploads", "schedules",
"render_nodes", "settings", "tags", "sequence_tags", "audit_log", "uploads", "schedules", "frame_removals",
];
[Test]
@@ -230,6 +230,34 @@ public abstract class CatalogRepositoryTests(TestContext context) : RepositoryTe
Assert.Equal(2023, everything.ByYear[0].Year);
}
[Test]
public async Task FacetsListTheYearsCamerasAndTagsOfOneArchive()
{
// The admin panel's Library filters (owner review 2, R6): what one archive has, with counts, as the listing filters take it.
var db = await OpenChronosAsync();
var main = TestData.Archive();
var other = TestData.Archive("Other");
await db.Archives.UpsertAsync(main, Ct);
await db.Archives.UpsertAsync(other, Ct);
var seqs = new[]
{
TestData.Sequence(main.Id, new DateTime(2024, 3, 10), camera: "EOS R5") with { Tags = ["Night", "roof"] },
TestData.Sequence(main.Id, new DateTime(2025, 7, 1), camera: "EOS R5") with { Tags = ["night"] },
TestData.Sequence(main.Id, new DateTime(2025, 1, 2), camera: "Z 8") with { CameraMake = "NIKON CORPORATION" },
TestData.Sequence(main.Id, null, camera: "") with { CameraMake = null },
TestData.Sequence(other.Id, new DateTime(2023, 1, 1), camera: "X-T5") with { Tags = ["elsewhere"] },
};
foreach (var s in seqs) await db.Sequences.UpsertAsync(s, Ct);
var facets = await db.Sequences.GetFacetsAsync(main.Id, Ct);
Assert.SequenceEqual([new ArchiveFacet("2025", 2), new ArchiveFacet("2024", 1)], facets.Years);
Assert.SequenceEqual([new ArchiveFacet("EOS R5", 2, "Canon"), new ArchiveFacet("Z 8", 1, "NIKON CORPORATION")], facets.Cameras);
Assert.SequenceEqual([new ArchiveFacet("Night", 2), new ArchiveFacet("roof", 1)], facets.Tags);
foreach (var facet in facets.Cameras)
Assert.Equal(facet.Sequences, await db.Sequences.CountAsync(new SequenceQuery { ArchiveId = main.Id, Camera = facet.Value }, Ct));
Assert.Equal(2, await db.Sequences.CountAsync(new SequenceQuery { ArchiveId = main.Id, Tag = facets.Tags[0].Value }, Ct));
}
[Test]
public async Task FramesBulkInsertPageAndFindDuplicates()
{
@@ -274,6 +274,9 @@ internal sealed class FakeSequence
public List<FakeFrame> Frames { get; } = [];
public List<FakeRender> Renders { get; } = [];
/// <summary>Tombstones of photos removed on the server (owner review 2, R6), as its manifest lists them.</summary>
public List<RemovedPhotoDto> Removed { get; } = [];
/// <summary>Like the server, the capture time comes from the photo's Exif data when none is given.</summary>
public FakeFrame AddFrame(byte[] bytes, string? name = null, DateTime? capturedAt = null) => InsertFrame(Frames.Count, bytes, name, capturedAt);
@@ -295,7 +298,7 @@ internal sealed class FakeSequence
public SequenceManifest Manifest(Func<Guid, bool> proxySent) => new(Id, FramesVersion, SettingsVersion, SettingsJson, Tags,
[.. Frames.Select((f, i) => new ManifestFrame(f.Id, i, f.FileName, f.Bytes.Length, Unhashed ? string.Empty : f.Sha256,
(Status & SequenceStatus.ProxiesBuilt) != 0 || proxySent(f.Id), (Status & SequenceStatus.ThumbsBuilt) != 0, WantsProxy: Undecodable && !proxySent(f.Id)))],
[.. Renders.Select(r => r.Dto())], Undecodable ? new ProxySpec(1280, 90) : null);
[.. Renders.Select(r => r.Dto())], Undecodable ? new ProxySpec(1280, 90) : null, Removed.Count == 0 ? null : [.. Removed]);
public FrameDto FrameDto(FakeFrame frame) => frame.Dto(Id, Frames.IndexOf(frame), Unhashed);
}
@@ -67,6 +67,36 @@ public sealed class SyncRulesTests
Assert.Equal((1, 0), SyncRules.CompareOriginals([null, null], ["bb"]));
}
[Test]
public void PhotosEitherSideRemovedAreNotOfferedBack()
{
static FramePhoto Photo(string sha) => new(sha, 100, null);
var at = new DateTimeOffset(2026, 10, 27, 10, 0, 0, TimeSpan.Zero);
var localId = Guid.CreateVersion7();
// The server deleted "cc", which this PC still holds; this PC deleted "dd", which the server still holds.
var tombstones = new SyncTombstones([new FrameRemoval(localId, "DD", null, RemovalReason.Deleted, at)],
[new RemovedPhotoDto("cc", null, "deleted", at)]);
Assert.Equal((0, 0), SyncRules.CompareOriginals([Photo("aa"), Photo("bb"), Photo("cc")], [Photo("aa"), Photo("bb"), Photo("dd")], tombstones));
Assert.Equal((1, 1), SyncRules.CompareOriginals([Photo("aa"), Photo("cc")], [Photo("aa"), Photo("dd")], SyncTombstones.None));
Assert.True(tombstones.DeletedRemotely("CC"));
Assert.True(tombstones.DeletedLocally("dd"));
Assert.False(tombstones.DeletedLocally("cc"));
// A photo replaced by a converted file on either side is the same photo as its replacement, and so is a chain of them.
var replaced = new SyncTombstones([], [new RemovedPhotoDto("aa", "a2", "replaced", at), new RemovedPhotoDto("a2", "a3", "replaced", at)]);
Assert.Equal("a3", replaced.Canonical("AA"));
Assert.Equal((0, 0), SyncRules.CompareOriginals([Photo("aa"), Photo("bb")], [Photo("a3"), Photo("bb")], replaced));
Assert.False(replaced.DeletedRemotely("aa"), "a replaced photo is there as its replacement");
var replacedHere = new SyncTombstones([new FrameRemoval(localId, "bb", "b2", RemovalReason.Replaced, at)], null);
Assert.Equal((0, 0), SyncRules.CompareOriginals([Photo("b2")], [Photo("bb")], replacedHere));
// A replacement deleted since: neither the photo nor its replacement is offered back.
var gone = new SyncTombstones([], [new RemovedPhotoDto("aa", "a2", "replaced", at), new RemovedPhotoDto("a2", null, "deleted", at)]);
Assert.Equal((0, 0), SyncRules.CompareOriginals([Photo("aa")], [], gone));
Assert.True(SyncTombstones.None.IsEmpty);
Assert.SequenceEqual(["deleted", "replaced"], SyncTombstones.ToDto([new FrameRemoval(localId, "aa", null, RemovalReason.Deleted, at),
new FrameRemoval(localId, "bb", "b2", RemovalReason.Replaced, at)]).Select(r => r.Reason));
}
[Test]
public void FramesEitherSideHasNotHashedAreMatchedBySizeAndCaptureTime()
{
@@ -6,6 +6,7 @@ using Chronos.Core.Model;
using Chronos.Core.Project;
using Chronos.Core.Render;
using Chronos.Data.Sync;
using Chronos.Protocol;
using Chronos.Testing;
namespace Chronos.Data.Tests.Sync;
@@ -116,6 +117,40 @@ public sealed class SyncTransferTests(TestContext context)
Assert.Equal((SyncStatus.InSync, 0), (entry.Status, entry.Link!.MissingRemote));
}
[Test]
public async Task PhotosOneSideDeletedAreNeitherSentNorFetchedAgain()
{
await using var f = await SyncFixture.CreateAsync(context);
var photos = f.NewPhotos(4);
var local = await f.LocalAsync("Comet", photos);
// The server holds the first three and deleted the fourth, which this PC still holds.
var remote = f.Remote.Add("Comet", photos[..3]);
remote.Removed.Add(new RemovedPhotoDto(Sha(photos[3]), null, "deleted", DateTimeOffset.UtcNow));
await f.Sync.LinkAsync(f.Server, remote.Id, local.Id, f.Ct);
await f.RefreshAsync();
Assert.Equal(0, (await f.EntryAsync("Comet")).Link!.MissingRemote);
var engine = await f.StartEngineAsync();
var upload = await f.Sync.EnqueueUploadAsync(engine, f.Server, local);
await f.Archive.WaitForAsync(upload.Id, JobState.Done);
Assert.Equal(3, remote.Frames.Count);
Assert.Count(4, await f.Db.Frames.ListBySequenceAsync(local.Id, cancellationToken: f.Ct));
// This PC deletes the first photo, which the server still holds: it is not fetched back, and nothing local is deleted.
var frames = await f.Db.Frames.ListBySequenceAsync(local.Id, cancellationToken: f.Ct);
var sequence = (await f.Db.Sequences.GetAsync(local.Id, f.Ct))!;
var plan = await f.Archive.Service.FrameTrash.PlanDeleteAsync(local.Id, [frames[0].Id], sequence.FramesVersion, f.Ct);
await f.Archive.Service.FrameTrash.DeleteAsync(plan, null, null, f.Ct);
await f.RefreshAsync();
var entry = await f.EntryAsync("Comet");
Assert.Equal((0, 0), (entry.Link!.MissingRemote, entry.Link.MissingLocal));
var download = await f.Sync.EnqueueDownloadAsync(engine, f.Server, remote.Id, "Comet", SyncDownloadMode.Originals, null);
await f.Archive.WaitForAsync(download.Id, JobState.Done);
var kept = await f.Db.Frames.ListBySequenceAsync(local.Id, cancellationToken: f.Ct);
Assert.SequenceEqual(photos[1..].Select(Sha), kept.Select(k => k.Sha256!));
}
[Test]
public async Task AResumedUploadSendsOnlyWhatTheServerLacks()
{
@@ -0,0 +1,344 @@
using System.Net;
using System.Net.Http.Headers;
using System.Net.Http.Json;
using Microsoft.Extensions.DependencyInjection;
using Chronos.Core.Codecs.Jpeg;
using Chronos.Core.Model;
using Chronos.Protocol;
using Chronos.Server.Storage;
using Chronos.Testing;
namespace Chronos.Server.Tests.Api;
/// <summary>
/// The library the admin panel manages (owner review 2, R6): sequence thumbnails, photos deleted into the trash, the trash
/// listed, restored and emptied, and bulk operations, against the real archive engine.
/// </summary>
[Category("server")]
public sealed class LibraryTests(TestContext context)
{
private static readonly TimeSpan Wait = TimeSpan.FromSeconds(TestTiming.Budget(30));
[Test]
public async Task PhotosAreDeletedIntoTheTrashAndRestoredThroughTheApi()
{
await using var server = await TestServer.StartAsync(context, services: ArchiveModule.Register);
var (editor, _, _) = await server.UserAsync("alberto", "editor");
var (other, _, _) = await server.UserAsync("giulia", "editor");
var admin = await server.AdminAsync();
var photos = Enumerable.Range(0, 3).Select(Photo).ToList();
Guid? id = null;
for (var i = 0; i < photos.Count; i++) id = (await Uploads.UploadAsync(editor, photos[i], $"IMG_{i + 1:0000}.JPG", sessionKey: "roof")).SequenceId;
await UntilIdleAsync(server);
var sequence = (await server.Database.Sequences.GetAsync(id!.Value))!;
var frames = await server.Database.Frames.ListBySequenceAsync(sequence.Id);
var url = $"/api/v1/sequences/{sequence.Id}/frames/delete";
using (var forbidden = await other.PostAsJsonAsync(url, new FrameDeleteRequest([frames[1].Id], null, false), ProtocolJson.Default.FrameDeleteRequest))
await forbidden.ExpectErrorAsync(HttpStatusCode.Forbidden, "forbidden");
using (var none = await editor.PostAsJsonAsync(url, new FrameDeleteRequest([], null, false), ProtocolJson.Default.FrameDeleteRequest))
await none.ExpectErrorAsync(HttpStatusCode.BadRequest, "bad_request");
using (var stale = await editor.PostAsJsonAsync(url, new FrameDeleteRequest([frames[1].Id], sequence.FramesVersion - 1, false),
ProtocolJson.Default.FrameDeleteRequest))
Assert.Equal(sequence.FramesVersion.ToString(System.Globalization.CultureInfo.InvariantCulture),
(await stale.ExpectErrorAsync(HttpStatusCode.Conflict, "frames_conflict")).Details);
using (var all = await editor.PostAsJsonAsync(url, new FrameDeleteRequest([.. frames.Select(f => f.Id)], null, false), ProtocolJson.Default.FrameDeleteRequest))
await all.ExpectErrorAsync(HttpStatusCode.Conflict, "would_empty");
using (var dry = await editor.PostAsJsonAsync(url, new FrameDeleteRequest([frames[1].Id], sequence.FramesVersion, true), ProtocolJson.Default.FrameDeleteRequest))
{
var plan = await dry.ReadAsync(ProtocolJson.Default.FrameDeleteResultDto);
Assert.True(plan.DryRun);
Assert.Equal((1, frames[1].Size, 3), (plan.Photos, plan.Bytes, plan.FrameCount));
Assert.Null(plan.TrashEntry);
}
Assert.Count(3, await server.Database.Frames.ListBySequenceAsync(sequence.Id));
FrameDeleteResultDto done;
using (var deleted = await editor.PostAsJsonAsync(url, new FrameDeleteRequest([frames[1].Id], sequence.FramesVersion, false),
ProtocolJson.Default.FrameDeleteRequest))
done = await deleted.ReadAsync(ProtocolJson.Default.FrameDeleteResultDto);
Assert.False(done.DryRun);
Assert.Equal((2, sequence.FramesVersion + 1), (done.FrameCount, done.FramesVersion));
var name = Assert.NotNull(done.TrashEntry);
Assert.FileMissing(Path.Combine(server.Options.ArchivePath, frames[1].RelativePath));
// The manifest names the deleted photo, so clients do not send it back; an upload of it is answered as already there.
using (var manifest = await editor.GetAsync($"/api/v1/sequences/{sequence.Id}/manifest"))
Assert.SequenceEqual([Uploads.Sha(photos[1])], Assert.NotNull((await manifest.ReadAsync(ProtocolJson.Default.SequenceManifest)).Removed).Select(r => r.Sha256));
var again = await Uploads.StartAsync(editor, photos[1], "IMG_0002.JPG", sequence.Id, expected: HttpStatusCode.OK);
Assert.True(again.AlreadyExists);
Assert.Null(again.FrameId);
Assert.Count(2, await server.Database.Frames.ListBySequenceAsync(sequence.Id));
using (var notAdmin = await editor.GetAsync("/api/v1/archive/trash")) await notAdmin.ExpectErrorAsync(HttpStatusCode.Forbidden, "forbidden");
using (var list = await admin.GetAsync("/api/v1/archive/trash"))
{
var trash = await list.ReadAsync(ProtocolJson.Default.TrashListDto);
var entry = Assert.Contains(trash.Entries, e => e.Name == name);
Assert.Equal(("photos", 1, sequence.Id, "alberto"), (entry.Kind, entry.Photos, entry.SequenceId, entry.DeletedBy));
Assert.Equal(frames[1].Size, trash.Bytes);
}
await UntilIdleAsync(server);
using (var restored = await admin.PostAsync($"/api/v1/archive/trash/{name}/restore", null))
{
var result = await restored.ReadAsync(ProtocolJson.Default.TrashRestoreDto);
Assert.Equal(("photos", sequence.Id, 1, false), (result.Kind, result.SequenceId, result.Photos, result.NewSequence));
Assert.Empty(result.Kept);
}
Assert.SequenceEqual(frames.Select(f => f.Id), (await server.Database.Frames.ListBySequenceAsync(sequence.Id)).Select(f => f.Id));
using (var gone = await admin.PostAsync($"/api/v1/archive/trash/{name}/restore", null)) await gone.ExpectErrorAsync(HttpStatusCode.NotFound, "not_found");
using (var bad = await admin.PostAsync("/api/v1/archive/trash/..%2F..%2Fsecret/restore", null)) Assert.Equal(HttpStatusCode.NotFound, bad.StatusCode);
}
[Test]
public async Task TheTrashIsEmptiedByAJobAfterADryRunAndItsFingerprint()
{
await using var server = await TestServer.StartAsync(context, services: ArchiveModule.Register);
var (editor, _, _) = await server.UserAsync("alberto", "editor");
var admin = await server.AdminAsync();
var a = (await Uploads.UploadAsync(editor, Photo(10), "a.jpg", sessionKey: "a")).SequenceId;
Guid b = default;
for (var i = 0; i < 2; i++) b = (await Uploads.UploadAsync(editor, Photo(20 + i), $"b{i}.jpg", sessionKey: "b")).SequenceId;
await UntilIdleAsync(server);
using (var deleted = await editor.DeleteAsync($"/api/v1/sequences/{a}")) await deleted.ExpectAsync(HttpStatusCode.OK);
var frames = await server.Database.Frames.ListBySequenceAsync(b);
using (var photo = await editor.PostAsJsonAsync($"/api/v1/sequences/{b}/frames/delete", new FrameDeleteRequest([frames[0].Id], null, false),
ProtocolJson.Default.FrameDeleteRequest))
await photo.ExpectAsync(HttpStatusCode.OK);
await UntilIdleAsync(server);
TrashEmptyPlanDto plan;
using (var dry = await admin.PostAsJsonAsync("/api/v1/archive/trash/empty", new TrashEmptyRequest(null, true, null), ProtocolJson.Default.TrashEmptyRequest))
plan = await dry.ReadAsync(ProtocolJson.Default.TrashEmptyPlanDto);
Assert.Equal(2, plan.Entries.Count);
Assert.SequenceEqual(["photos", "sequence"], plan.Entries.Select(e => e.Kind).Order());
Assert.Equal(2, plan.Photos);
using (var noPrint = await admin.PostAsJsonAsync("/api/v1/archive/trash/empty", new TrashEmptyRequest(null, false, null), ProtocolJson.Default.TrashEmptyRequest))
await noPrint.ExpectErrorAsync(HttpStatusCode.BadRequest, "bad_request");
using (var wrong = await admin.PostAsJsonAsync("/api/v1/archive/trash/empty", new TrashEmptyRequest(null, false, "0123"), ProtocolJson.Default.TrashEmptyRequest))
Assert.Equal(plan.Fingerprint, (await wrong.ExpectErrorAsync(HttpStatusCode.Conflict, "trash_changed")).Details);
using (var names = await admin.PostAsJsonAsync("/api/v1/archive/trash/empty", new TrashEmptyRequest(["../x"], true, null), ProtocolJson.Default.TrashEmptyRequest))
await names.ExpectErrorAsync(HttpStatusCode.BadRequest, "bad_request");
JobDto job;
using (var empty = await admin.PostAsJsonAsync("/api/v1/archive/trash/empty", new TrashEmptyRequest(null, false, plan.Fingerprint),
ProtocolJson.Default.TrashEmptyRequest))
{
await empty.ExpectAsync(HttpStatusCode.Accepted);
job = await empty.ReadAsync(ProtocolJson.Default.JobDto);
}
Assert.Equal("empty-trash", job.Kind);
await UntilJobAsync(admin, job.Id, "done");
using (var list = await admin.GetAsync("/api/v1/archive/trash")) Assert.Empty((await list.ReadAsync(ProtocolJson.Default.TrashListDto)).Entries);
Assert.Empty(Directory.EnumerateFiles(server.Options.TrashPath, "*", SearchOption.AllDirectories));
Assert.Count(1, await server.Database.Frames.ListBySequenceAsync(b));
}
[Test]
public async Task BulkOperationsAnswerForEachSequence()
{
await using var server = await TestServer.StartAsync(context, services: ArchiveModule.Register);
var archive = server.Services.GetRequiredService<ServerArchive>();
var (editor, _, _) = await server.UserAsync("alberto", "editor");
var (other, _, _) = await server.UserAsync("giulia", "editor");
var a = (await Uploads.UploadAsync(editor, Photo(30), "a.jpg", sessionKey: "a")).SequenceId;
var b = (await Uploads.UploadAsync(editor, Photo(31), "b.jpg", sessionKey: "b")).SequenceId;
var c = (await Uploads.UploadAsync(other, Photo(32), "c.jpg", sessionKey: "c")).SequenceId;
var unknown = Guid.CreateVersion7();
await UntilIdleAsync(server);
using (var retag = await editor.PostAsJsonAsync("/api/v1/sequences/bulk/retag", new BulkRetagRequest([a, b, unknown], ["Night", "roof"], null),
ProtocolJson.Default.BulkRetagRequest))
{
var result = await retag.ReadAsync(ProtocolJson.Default.BulkResultDto);
Assert.Equal((2, 1), (result.Ok, result.Skipped));
Assert.Equal("not_found", result.Items.Single(i => i.Id == unknown).Reason);
}
using (var untag = await editor.PostAsJsonAsync("/api/v1/sequences/bulk/retag", new BulkRetagRequest([a], ["sky"], ["NIGHT"]),
ProtocolJson.Default.BulkRetagRequest))
await untag.ExpectAsync(HttpStatusCode.OK);
Assert.SequenceEqual(["roof", "sky"], (await server.Database.Sequences.GetAsync(a))!.Tags.Order());
Assert.SequenceEqual(["Night", "roof"], (await server.Database.Sequences.GetAsync(b))!.Tags.Order());
using (var noTags = await editor.PostAsJsonAsync("/api/v1/sequences/bulk/retag", new BulkRetagRequest([a], null, null), ProtocolJson.Default.BulkRetagRequest))
await noTags.ExpectErrorAsync(HttpStatusCode.BadRequest, "bad_request");
// A verify of sequences targets their archive (it once targeted the sequences, which its handler cannot read).
using (var verify = await editor.PostAsJsonAsync("/api/v1/sequences/bulk/jobs", new BulkJobsRequest([a, b, unknown], "verify"),
ProtocolJson.Default.BulkJobsRequest))
{
await verify.ExpectAsync(HttpStatusCode.Accepted);
var result = await verify.ReadAsync(ProtocolJson.Default.BulkResultDto);
var job = Assert.NotNull(result.Job);
Assert.Equal(("verify", 2, 1), (job.Kind, result.Ok, result.Skipped));
Assert.SequenceEqual([archive.Id], job.TargetIds);
await UntilJobAsync(editor, job.Id, "done");
}
using (var single = await editor.PostAsJsonAsync("/api/v1/jobs", new CreateJobRequest("verify", [a], null), ProtocolJson.Default.CreateJobRequest))
{
var job = await single.ReadAsync(ProtocolJson.Default.JobDto);
Assert.SequenceEqual([archive.Id], job.TargetIds);
await UntilJobAsync(editor, job.Id, "done");
}
using (var thumbs = await editor.PostAsJsonAsync("/api/v1/sequences/bulk/jobs", new BulkJobsRequest([a, b], "thumbnails"), ProtocolJson.Default.BulkJobsRequest))
{
var job = Assert.NotNull((await thumbs.ReadAsync(ProtocolJson.Default.BulkResultDto)).Job);
Assert.Equal("thumbs", job.Kind);
Assert.SequenceEqual([a, b], job.TargetIds);
}
using (var bogus = await editor.PostAsJsonAsync("/api/v1/sequences/bulk/jobs", new BulkJobsRequest([a], "render"), ProtocolJson.Default.BulkJobsRequest))
await bogus.ExpectErrorAsync(HttpStatusCode.BadRequest, "invalid_job_kind");
await UntilIdleAsync(server);
using (var dry = await editor.PostAsJsonAsync("/api/v1/sequences/bulk/delete", new BulkDeleteRequest([a, c, unknown], true), ProtocolJson.Default.BulkDeleteRequest))
{
var result = await dry.ReadAsync(ProtocolJson.Default.BulkResultDto);
Assert.True(result.DryRun);
Assert.Equal(".chronos/trash/" + a.ToString("N"), result.Items[0].TrashFolder);
Assert.SequenceEqual(["ok", "skipped", "skipped"], result.Items.Select(i => i.Outcome));
Assert.SequenceEqual<string?>([null, "forbidden", "not_found"], result.Items.Select(i => i.Reason));
Assert.Equal(1, result.Photos);
}
Assert.NotNull(await server.Database.Sequences.GetAsync(a));
using (var deleted = await editor.PostAsJsonAsync("/api/v1/sequences/bulk/delete", new BulkDeleteRequest([a, b], false), ProtocolJson.Default.BulkDeleteRequest))
Assert.Equal(2, (await deleted.ReadAsync(ProtocolJson.Default.BulkResultDto)).Ok);
Assert.Null(await server.Database.Sequences.GetAsync(a));
Assert.Null(await server.Database.Sequences.GetAsync(b));
Assert.NotNull(await server.Database.Sequences.GetAsync(c));
}
[Test]
public async Task ASequenceThumbnailIsItsHeroFramesOrItsFirst()
{
await using var server = await TestServer.StartAsync(context, services: ArchiveModule.Register);
var (editor, _, _) = await server.UserAsync("alberto", "editor");
var first = await Uploads.UploadAsync(editor, Photo(40), "IMG_0001.JPG", sessionKey: "t");
var second = await Uploads.UploadAsync(editor, Photo(41), "IMG_0002.JPG", sessionKey: "t");
var id = first.SequenceId;
var thumbs = new Dictionary<Guid, byte[]>();
foreach (var frame in new[] { first.FrameId, second.FrameId }) thumbs[frame] = await ThumbnailAsync(editor, $"/api/v1/frames/{frame}/thumb");
using (var cover = await editor.GetAsync($"/api/v1/sequences/{id}/thumb"))
{
await cover.ExpectAsync(HttpStatusCode.OK);
var bytes = await cover.Content.ReadAsByteArrayAsync();
Assert.BytesEqual(thumbs[first.FrameId], bytes);
var etag = Assert.NotNull(cover.Headers.ETag);
using var request = new HttpRequestMessage(HttpMethod.Get, $"/api/v1/sequences/{id}/thumb");
request.Headers.IfNoneMatch.Add(etag);
using var cached = await editor.SendAsync(request);
Assert.Equal(HttpStatusCode.NotModified, cached.StatusCode);
}
using (var hero = await editor.PatchAsJsonAsync($"/api/v1/sequences/{id}", new UpdateSequenceRequest(null, null, null, null, null, null, second.FrameId),
ProtocolJson.Default.UpdateSequenceRequest))
await hero.ExpectAsync(HttpStatusCode.OK);
var heroThumb = await ThumbnailAsync(editor, $"/api/v1/sequences/{id}/thumb");
Assert.BytesEqual(thumbs[second.FrameId], heroThumb);
using var created = await editor.PostAsJsonAsync("/api/v1/sequences", new CreateSequenceRequest("Empty", null), ProtocolJson.Default.CreateSequenceRequest);
var empty = await created.ReadAsync(ProtocolJson.Default.SequenceDto);
using (var none = await editor.GetAsync($"/api/v1/sequences/{empty.Id}/thumb")) await none.ExpectErrorAsync(HttpStatusCode.NotFound, "not_found");
using (var unknown = await editor.GetAsync($"/api/v1/sequences/{Guid.CreateVersion7()}/thumb")) await unknown.ExpectErrorAsync(HttpStatusCode.NotFound, "not_found");
}
[Test]
public async Task TheLibraryFiltersOfferTheArchivesYearsCamerasAndTags()
{
// The panel's Year, Camera and Tag menus list what the archive has, each with its count, in the values the listing takes.
await using var server = await TestServer.StartAsync(context);
var archive = server.Services.GetRequiredService<ServerArchive>();
var (viewer, _, _) = await server.UserAsync("vera", "viewer");
Sequence Seq(DateTime? first, string? make, string? model, params string[] tags) => new()
{
Id = Guid.CreateVersion7(),
ArchiveId = archive.Id,
Folder = $"2026/{Guid.NewGuid():N}",
CameraMake = make,
CameraModel = model,
FirstCapture = first,
LastCapture = first?.AddHours(1),
Tags = tags,
UpdatedAt = DateTimeOffset.UtcNow,
};
var sony = Seq(new DateTime(2025, 3, 4), "SONY", "ILCE-7M4") with { RenderedCount = 2 };
foreach (var s in new[]
{
Seq(new DateTime(2024, 5, 1), "Canon", "Canon EOS R5", "Night", "roof"), Seq(new DateTime(2025, 1, 2), "Canon", "Canon EOS R5", "night"), sony,
Seq(new DateTime(2023, 8, 9), "NIKON CORPORATION", "NIKON Z 8"), Seq(null, null, null),
})
await server.Database.Sequences.UpsertAsync(s);
LibraryFacetsDto facets;
using (var response = await viewer.GetAsync("/api/v1/sequences/facets")) facets = await response.ReadAsync(ProtocolJson.Default.LibraryFacetsDto);
Assert.SequenceEqual([new FacetDto("2025", 2), new FacetDto("2024", 1), new FacetDto("2023", 1)], facets.Years);
// Labelled as the desktop names cameras: the brand once.
Assert.SequenceEqual([new FacetDto("Canon EOS R5", 2, "Canon EOS R5"), new FacetDto("ILCE-7M4", 1, "SONY ILCE-7M4"), new FacetDto("NIKON Z 8", 1, "Nikon Z 8")],
facets.Cameras);
Assert.SequenceEqual([new FacetDto("Night", 2), new FacetDto("roof", 1)], facets.Tags);
async Task<int> CountAsync(string query)
{
using var page = await viewer.GetAsync($"/api/v1/sequences?{query}");
return (await page.ReadAsync(ProtocolJson.Default.PageSequenceDto)).Items.Count;
}
Assert.Equal(2, await CountAsync("year=2025"));
Assert.Equal(1, await CountAsync("camera=ILCE-7M4"));
Assert.Equal(2, await CountAsync("tag=night"));
// The Status menu's Rendered and Not rendered.
Assert.Equal(1, await CountAsync("rendered=true"));
Assert.Equal(4, await CountAsync("rendered=false"));
using var unknown = await viewer.GetAsync("/api/v1/sequences/facets/x");
Assert.Equal(HttpStatusCode.NotFound, unknown.StatusCode);
}
/// <summary>A thumbnail once its pass has drawn it (404 until then).</summary>
private static async Task<byte[]> ThumbnailAsync(HttpClient client, string url)
{
var until = DateTime.UtcNow + Wait;
while (true)
{
using var response = await client.GetAsync(url);
if (response.StatusCode == HttpStatusCode.OK) return await response.Content.ReadAsByteArrayAsync();
Assert.True(DateTime.UtcNow < until, $"{url}: {(int)response.StatusCode}");
await Task.Delay(50);
}
}
private static async Task UntilJobAsync(HttpClient client, Guid id, string state)
{
var until = DateTime.UtcNow + Wait;
while (true)
{
using var response = await client.GetAsync($"/api/v1/jobs/{id}");
var job = await response.ReadAsync(ProtocolJson.Default.JobDto);
if (job.State == state) return;
if (job.State is "failed" or "cancelled") Assert.Fail($"job {job.Kind} {job.State}: {job.Error}\n{job.LogTail}");
Assert.True(DateTime.UtcNow < until, $"job {job.Kind} still {job.State}");
await Task.Delay(50);
}
}
/// <summary>Waits until no job is queued or running (the thumbnails, proxies and analyses uploads queue).</summary>
private static async Task UntilIdleAsync(TestServer server)
{
var until = DateTime.UtcNow + Wait;
foreach (var state in new[] { JobState.Queued, JobState.Running, JobState.Queued, JobState.Running })
{
while ((await server.Database.Jobs.ListAsync(state)).Items.Count > 0)
{
Assert.True(DateTime.UtcNow < until, $"jobs still {state}");
await Task.Delay(50);
}
}
}
private static byte[] Photo(int seed)
{
const int width = 96, height = 64;
var pixels = new byte[width * height * 3];
for (var i = 0; i < pixels.Length; i++) pixels[i] = (byte)((i * 7 + seed * 31) % 251);
return JpegEncoder.Encode(pixels, width, height, 3, new JpegEncodeOptions { Quality = 90 });
}
}
@@ -1,5 +1,7 @@
using System.Net;
using System.Net.Http.Headers;
using System.Net.Http.Json;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Text.RegularExpressions;
using Microsoft.AspNetCore.Hosting.Server;
@@ -12,7 +14,7 @@ using Chronos.Testing;
namespace Chronos.Server.Tests.Hosting;
[Category("server")]
public sealed class SystemEndpointTests(TestContext context)
public sealed partial class SystemEndpointTests(TestContext context)
{
[Test]
public async Task HealthReportsOk()
@@ -93,6 +95,44 @@ public sealed class SystemEndpointTests(TestContext context)
Assert.Equal(HttpStatusCode.NotModified, cached.StatusCode);
}
[Test]
public async Task AdminPanelFilesAreRevalidatedSoAnUpgradeNeverMixesOldAndNewModules()
{
// A browser that kept app.js from before an upgrade must not run it next to a new ui.js: every file is kept but
// asked for again before each use, and its ETag follows its content, so only what the upgrade changed is sent.
await using var server = await TestServer.StartAsync(context);
foreach (var path in new[] { "/admin/", "/admin/app.js", "/admin/ui.js", "/admin/admin.css", "/admin/icons.js", "/admin/pages/library.js", "/admin/upload.js" })
{
using var response = await server.Client.GetAsync(path);
Assert.Equal(HttpStatusCode.OK, response.StatusCode, path);
var cache = Assert.NotNull(response.Headers.CacheControl);
Assert.True(cache.NoCache && cache.MaxAge is null && !cache.Public, $"{path}: {cache}");
var etag = Assert.NotNull(response.Headers.ETag);
Assert.False(etag.IsWeak, path);
var bytes = await response.Content.ReadAsByteArrayAsync();
Assert.Equal($"\"{Convert.ToHexString(SHA256.HashData(bytes).AsSpan(0, 12))}\"", etag.Tag, path);
foreach (var sent in new[] { etag, new EntityTagHeaderValue(etag.Tag, isWeak: true), EntityTagHeaderValue.Any })
{
using var again = new HttpRequestMessage(HttpMethod.Get, path);
again.Headers.IfNoneMatch.Add(new EntityTagHeaderValue("\"0123\""));
again.Headers.IfNoneMatch.Add(sent);
using var notModified = await server.Client.SendAsync(again);
Assert.Equal(HttpStatusCode.NotModified, notModified.StatusCode, $"{path} with {sent}");
Assert.Equal(etag, notModified.Headers.ETag, path);
Assert.True(Assert.NotNull(notModified.Headers.CacheControl).NoCache, path);
}
// A file the browser holds from another build has another ETag: the new content comes back.
using var stale = new HttpRequestMessage(HttpMethod.Get, path);
stale.Headers.IfNoneMatch.Add(new EntityTagHeaderValue("\"0123456789ABCDEF01234567\""));
using var fresh = await server.Client.SendAsync(stale);
Assert.Equal(HttpStatusCode.OK, fresh.StatusCode, path);
var resent = await fresh.Content.ReadAsByteArrayAsync();
Assert.BytesEqual(bytes, resent, path);
}
}
[Test]
public async Task PlainHttpFromAnotherMachineGoesToThePublicHttpsPort()
{
@@ -141,21 +181,111 @@ public sealed class SystemEndpointTests(TestContext context)
var index = await server.Client.GetStringAsync("/admin/");
// The page container is not a live region: only toasts and form errors announce themselves.
Assert.True(!index.Contains("aria-live", StringComparison.Ordinal), index);
var seen = await ModulesAsync(server);
Assert.True(seen.Count >= 20, string.Join(", ", seen.Keys));
// The Library's views (owner review 2, R6) are modules of their own under pages/library; the web upload (R3) is the
// dialog, its hash worker and the in-house SHA-256 the worker imports.
foreach (var module in new[] { "pages/library.js", "pages/library/sequence.js", "pages/library/trash.js", "pages/library/shared.js", "upload.js", "hash-worker.js", "sha256.js" })
Assert.True(seen.ContainsKey(module), module);
}
[Test]
public async Task AdminPanelListsTheLibraryAndLoadsTheWebUploadOnDemand()
{
// Owner review 2, R6: the Library comes right after the Dashboard. The web upload (R3) is a module of its own that the
// Library imports on demand (Upload, and a sequence's Add photos), so a page that never uploads never loads it.
await using var server = await TestServer.StartAsync(context);
var app = await server.Client.GetStringAsync("/admin/app.js");
var pending = new Queue<string>(MenuPages(app).SelectMany(group => group).Select(p => $"pages/{p}.js").Prepend("app.js"));
var seen = new HashSet<string>(StringComparer.Ordinal);
var top = MenuPages(app)[0];
Assert.SequenceEqual(["dashboard", "library"], top.Take(2));
var icons = await server.Client.GetStringAsync("/admin/icons.js");
var strings = Assert.NotNull(await server.Client.GetFromJsonAsync("/api/v1/i18n/it", ProtocolJson.Default.DictionaryStringString));
foreach (var page in MenuPages(app).SelectMany(group => group))
{
Assert.Contains($" {page}: `<svg", icons);
var name = $"Admin.Nav.{char.ToUpperInvariant(page[0])}{page[1..]}";
Assert.True(strings.ContainsKey(name) && strings.ContainsKey(name + ".Tip"), name);
}
var modules = await ModulesAsync(server);
Assert.Contains(@"import(""../upload.js"")", modules["pages/library.js"]);
foreach (var (module, source) in modules)
{
var folder = module.Contains('/', StringComparison.Ordinal) ? module[..(module.LastIndexOf('/') + 1)] : string.Empty;
foreach (Match import in StaticImport().Matches(source))
Assert.True(Resolve(folder, import.Groups[1].Value) != "upload.js", $"{module} imports upload.js statically");
}
// The module the dynamic import names is there (no 404 in the browser) and exports what the Library calls.
Assert.Equal("upload.js", Resolve("pages/", "../upload.js"));
Assert.True(Regex.IsMatch(modules["upload.js"], @"export (?:async )?function openUpload\(\{ api, sequence, onDone \}"), "upload.js exports openUpload({ api, sequence, onDone })");
Assert.Contains("openUpload({ api, onDone: ", modules["pages/library.js"]);
Assert.Contains("openUpload({ api, sequence: seq, onDone: ", modules["pages/library/sequence.js"]);
}
/// <summary>The admin panel's modules from app.js and the menu's pages along their static imports, with their source.</summary>
private static async Task<Dictionary<string, string>> ModulesAsync(TestServer server)
{
var app = await server.Client.GetStringAsync("/admin/app.js");
// The upload dialog is a module the Library opens on demand (owner review 2, R3); its hash worker is named by a URL.
var pending = new Queue<string>(MenuPages(app).SelectMany(group => group).Select(p => $"pages/{p}.js").Prepend("upload.js").Prepend("app.js"));
var seen = new Dictionary<string, string>(StringComparer.Ordinal);
while (pending.TryDequeue(out var module))
{
if (!seen.Add(module)) continue;
if (seen.ContainsKey(module)) continue;
using var response = await server.Client.GetAsync("/admin/" + module);
Assert.Equal(HttpStatusCode.OK, response.StatusCode, module);
Assert.Equal("text/javascript", response.Content.Headers.ContentType?.MediaType, module);
var source = await response.Content.ReadAsStringAsync();
seen[module] = source;
var folder = module.Contains('/', StringComparison.Ordinal) ? module[..(module.LastIndexOf('/') + 1)] : string.Empty;
foreach (Match import in Regex.Matches(await response.Content.ReadAsStringAsync(), @"from ""(\.{1,2}/[^""]+)"""))
foreach (Match import in ModuleReference().Matches(source))
pending.Enqueue(Resolve(folder, import.Groups[1].Value));
}
Assert.True(seen.Count >= 13, string.Join(", ", seen));
return seen;
}
[GeneratedRegex(@"from ""(\.{1,2}/[^""]+)""")]
private static partial Regex StaticImport();
/// <summary>A module's static imports and the module workers it starts (<c>new URL("./…", import.meta.url)</c>).</summary>
[GeneratedRegex(@"(?:from |new URL\()""(\.{1,2}/[^""]+)""")]
private static partial Regex ModuleReference();
[Test]
public async Task TheUploadDialogsHashWorkerRunsUnderThePanelPolicy()
{
await using var server = await TestServer.StartAsync(context);
using var page = await server.Client.GetAsync("/admin/");
// CSP 3: a worker is allowed by worker-src, else child-src, else script-src, else default-src.
var policy = Directives(page);
var workers = new[] { "worker-src", "child-src", "script-src", "default-src" }.Select(d => policy.GetValueOrDefault(d)).First(v => v is not null);
Assert.SequenceEqual(["'self'"], Assert.NotNull(workers));
using var worker = await server.Client.GetAsync("/admin/hash-worker.js");
Assert.Equal(HttpStatusCode.OK, worker.StatusCode);
Assert.Equal("text/javascript", worker.Content.Headers.ContentType?.MediaType);
Assert.Equal("nosniff", worker.Headers.GetValues("X-Content-Type-Options").First());
// The worker runs under its own response's policy, which lets it import the hash from the same origin.
Assert.SequenceEqual(["'self'"], Assert.NotNull(Directives(worker).GetValueOrDefault("script-src")));
Assert.Contains(@"from ""./sha256.js""", await worker.Content.ReadAsStringAsync());
var upload = await server.Client.GetStringAsync("/admin/upload.js");
Assert.Contains(@"new Worker(new URL(""./hash-worker.js"", import.meta.url), { type: ""module"" })", upload);
Assert.Contains("api.putBytes(", upload);
// No folder picking on the web: importing a whole folder is a desktop feature (owner review 2, R9).
foreach (var picker in new[] { "webkitdirectory", "showDirectoryPicker", "mozdirectory" })
Assert.True(!upload.Contains(picker, StringComparison.OrdinalIgnoreCase), picker);
// The panel has no inline handlers for the policy to block (and none to allow).
Assert.True(!Regex.IsMatch(upload, @"\son[a-z]+="""), "inline handler");
}
/// <summary>The directives of a response's Content-Security-Policy, each with its sources.</summary>
private static Dictionary<string, string[]> Directives(HttpResponseMessage response) =>
string.Join(';', response.Headers.GetValues("Content-Security-Policy"))
.Split(';', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries)
.Select(d => d.Split(' ', StringSplitOptions.RemoveEmptyEntries))
.ToDictionary(d => d[0], d => d[1..], StringComparer.OrdinalIgnoreCase);
[Test]
public async Task AdminPanelDocksSettingsAtTheFootAndFoldsAboutIntoIt()
{
@@ -0,0 +1,201 @@
using System.Globalization;
using System.Net;
using System.Net.Http.Headers;
using System.Net.Http.Json;
using System.Text;
using Microsoft.Extensions.DependencyInjection;
using Chronos.Core.Codecs.Jpeg;
using Chronos.Core.Localization;
using Chronos.Core.Model;
using Chronos.Protocol;
using Chronos.Server.Storage;
using Chronos.Testing;
namespace Chronos.Server.Tests.Storage;
/// <summary>
/// The admin panel's upload dialog (owner review 2, R3; <c>Admin/web/upload.js</c>) speaks the upload API through the
/// cookie session: requests shaped like <c>api.js</c> sends them (JSON bodies written as the page writes them, the
/// page's language, the CSRF header on every unsafe call, chunks as octet-stream), against the real archive engine.
/// </summary>
[Category("server")]
public sealed class BrowserUploadTests(TestContext context)
{
private const int Chunk = 64 * 1024;
private static readonly TimeSpan Wait = TimeSpan.FromSeconds(TestTiming.Budget(30));
[Test]
public async Task TheUploadDialogFilesPhotosThroughTheCookieSession()
{
await using var server = await TestServer.StartAsync(context, o => o.ChunkSizeBytes = Chunk, ArchiveModule.Register);
var browser = await Browser.SignInAsync(server);
// What the dialog offers and checks before it hashes anything.
ServerInfo info;
using (var response = await browser.SendAsync(HttpMethod.Get, "/api/v1/server/info"))
info = await response.ReadAsync(ProtocolJson.Default.ServerInfo);
var extensions = Assert.NotNull(info.Extensions);
foreach (var extension in new[] { "jpg", "jpeg", "tif", "dng", "cr3", "nef", "heic" }) Assert.Contains(extension, extensions);
Assert.True(extensions.All(e => e.Length > 0 && e == e.ToLowerInvariant() && !e.StartsWith('.')), string.Join(",", extensions));
// New sequence: the title as typed, no camera hint.
SequenceDto sequence;
using (var created = await browser.SendAsync(HttpMethod.Post, "/api/v1/sequences", Json("""{"title":"Roof","cameraHint":null}""")))
{
await created.ExpectAsync(HttpStatusCode.Created);
sequence = await created.ReadAsync(ProtocolJson.Default.SequenceDto);
}
var photos = new[] { Photo(1), Photo(2) };
var frames = new List<CompleteUploadResponse>();
for (var i = 0; i < photos.Length; i++)
{
var photo = photos[i];
var start = await StartAsync(browser, sequence.Id, $"IMG_{i + 1:0000}.JPG", photo, HttpStatusCode.Created);
var id = Assert.NotNull(start.UploadId);
Assert.Equal(Chunk, start.ChunkSize);
var count = (photo.Length + Chunk - 1) / Chunk;
Assert.True(count >= 2, $"{photo.Length} bytes make one chunk");
// putBytes sends the session's headers: a chunk without the CSRF header is refused like any other change.
using (var refused = await browser.SendAsync(HttpMethod.Put, $"/api/v1/uploads/{id}/chunks/0", Bytes(photo, 0), csrf: false))
await refused.ExpectErrorAsync(HttpStatusCode.Forbidden, "csrf_failed");
// Two chunks in flight, finishing in any order.
for (var last = count - 1; last >= 0; last -= 2)
{
var pair = new[] { last, last - 1 }.Where(n => n >= 0).Select(async n =>
{
using var put = await browser.SendAsync(HttpMethod.Put, $"/api/v1/uploads/{id}/chunks/{n}", Bytes(photo, n));
return await put.ReadAsync(ProtocolJson.Default.ChunkReceived);
});
foreach (var received in await Task.WhenAll(pair)) Assert.Contains(received.Index, received.Received);
}
using var complete = await browser.SendAsync(HttpMethod.Post, $"/api/v1/uploads/{id}/complete", Json("{}"));
var frame = await complete.ReadAsync(ProtocolJson.Default.CompleteUploadResponse);
Assert.Equal(sequence.Id, frame.SequenceId);
frames.Add(frame);
}
var stored = await server.Database.Frames.ListBySequenceAsync(sequence.Id);
Assert.SequenceEqual(frames.Select(f => f.FrameId).Order(), stored.Select(f => f.Id).Order());
for (var i = 0; i < photos.Length; i++)
{
var file = Path.Combine(server.Options.ArchivePath, stored.Single(f => f.Id == frames[i].FrameId).RelativePath);
await Http.BytesEqualAsync(photos[i], File.ReadAllBytesAsync(file));
}
// Picked again: already there, with its frame.
var again = await StartAsync(browser, sequence.Id, "IMG_0001.JPG", photos[0], HttpStatusCode.OK);
Assert.True(again.AlreadyExists);
Assert.Equal(frames[0].FrameId, again.FrameId);
// Deleted from the sequence: also answered as there, without a frame ("deleted before; restore it from the trash").
await UntilIdleAsync(server);
var current = Assert.NotNull(await server.Database.Sequences.GetAsync(sequence.Id));
using (var delete = await browser.SendAsync(HttpMethod.Post, $"/api/v1/sequences/{sequence.Id}/frames/delete",
Json($$"""{"frameIds":["{{frames[1].FrameId}}"],"expectedFramesVersion":{{current.FramesVersion}},"dryRun":false}""")))
Assert.NotNull((await delete.ReadAsync(ProtocolJson.Default.FrameDeleteResultDto)).TrashEntry);
var deleted = await StartAsync(browser, sequence.Id, "IMG_0002.JPG", photos[1], HttpStatusCode.OK);
Assert.True(deleted.AlreadyExists);
Assert.Null(deleted.UploadId);
Assert.Null(deleted.FrameId);
// Cancel: an upload the dialog started is discarded on the server.
var cancelled = Photo(3);
var started = await StartAsync(browser, sequence.Id, "IMG_0003.JPG", cancelled, HttpStatusCode.Created);
var cancelledId = Assert.NotNull(started.UploadId);
using (var put = await browser.SendAsync(HttpMethod.Put, $"/api/v1/uploads/{cancelledId}/chunks/0", Bytes(cancelled, 0)))
await put.ExpectAsync(HttpStatusCode.OK);
using (var discard = await browser.SendAsync(HttpMethod.Delete, $"/api/v1/uploads/{cancelledId}"))
await discard.ExpectAsync(HttpStatusCode.NoContent);
using (var state = await browser.SendAsync(HttpMethod.Get, $"/api/v1/uploads/{cancelledId}"))
Assert.Equal("cancelled", (await state.ReadAsync(ProtocolJson.Default.UploadState)).State);
using (var late = await browser.SendAsync(HttpMethod.Put, $"/api/v1/uploads/{cancelledId}/chunks/1", Bytes(cancelled, 1)))
await late.ExpectErrorAsync(HttpStatusCode.Conflict, "upload_state");
Assert.False(server.Services.GetRequiredService<UploadStore>().Exists(cancelledId), "the partial file is gone");
}
[Test]
public async Task AQuotaRefusalCarriesTheMessageTheDialogShows()
{
// A quota or space refusal stops the dialog's run with the server's message, in the page's language.
await using var server = await TestServer.StartAsync(context, o => o.ChunkSizeBytes = Chunk);
var browser = await Browser.SignInAsync(server);
Guid me;
using (var response = await browser.SendAsync(HttpMethod.Get, "/api/v1/auth/me")) me = (await response.ReadAsync(ProtocolJson.Default.UserDto)).Id;
using (var quota = await browser.SendAsync(HttpMethod.Patch, $"/api/v1/users/{me}", Json("""{"quotaBytes":1000}""")))
await quota.ExpectAsync(HttpStatusCode.OK);
using var start = await browser.SendAsync(HttpMethod.Post, "/api/v1/uploads", StartBody(null, "IMG_0001.JPG", Uploads.Photo(Chunk + 10, 7)));
var error = await start.ExpectErrorAsync(HttpStatusCode.Forbidden, "quota_exceeded");
Assert.Equal(Loc.Get("Server.Error.QuotaExceeded", CultureInfo.GetCultureInfo("it")), error.Message);
}
/// <summary>The bootstrap administrator signed in to the panel (a cookie session over HTTPS), calling as <c>api.js</c> does.</summary>
private sealed class Browser(HttpClient client, string csrfToken)
{
public static async Task<Browser> SignInAsync(TestServer server)
{
await server.AdminAsync();
var cookies = new CookieContainer();
var client = server.NewCookieClient(cookies);
using var login = await client.PostAsJsonAsync("/api/v1/auth/login", new LoginRequest("admin", TestServer.Password, "admin-web", Cookie: true),
ProtocolJson.Default.LoginRequest);
await login.ExpectAsync(HttpStatusCode.OK);
return new Browser(client, Assert.NotNull(cookies.GetCookies(Assert.NotNull(server.HttpsBase))["chronos_csrf"]).Value);
}
/// <summary>JSON accepted, the page's language (Italian here), and the CSRF header on every call but a GET.</summary>
public async Task<HttpResponseMessage> SendAsync(HttpMethod method, string url, HttpContent? content = null, bool csrf = true)
{
using var request = new HttpRequestMessage(method, url) { Content = content };
request.Headers.Accept.ParseAdd("application/json");
request.Headers.AcceptLanguage.ParseAdd("it");
if (method != HttpMethod.Get && csrf) request.Headers.Add("X-CSRF-Token", csrfToken);
return await client.SendAsync(request);
}
}
private static StringContent Json(string json) => new(json, Encoding.UTF8, "application/json");
/// <summary>A chunk as <c>putBytes</c> sends a <c>File.slice()</c>: its bytes, octet-stream.</summary>
private static ByteArrayContent Bytes(byte[] data, int index)
{
var content = new ByteArrayContent(Uploads.Chunk(data, Chunk, index).ToArray());
content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
return content;
}
/// <summary>The start body upload.js writes: no capture time (the server reads it from the photo), no session key.</summary>
private static StringContent StartBody(Guid? sequenceId, string fileName, byte[] data) =>
Json($$"""{"sequenceId":{{(sequenceId is { } id ? $"\"{id}\"" : "null")}},"fileName":"{{fileName}}","size":{{data.Length}},"sha256":"{{Uploads.Sha(data)}}","capturedAt":null,"sessionKey":null}""");
private static async Task<StartUploadResponse> StartAsync(Browser browser, Guid sequenceId, string fileName, byte[] data, HttpStatusCode expected)
{
using var response = await browser.SendAsync(HttpMethod.Post, "/api/v1/uploads", StartBody(sequenceId, fileName, data));
await response.ExpectAsync(expected);
return await response.ReadAsync(ProtocolJson.Default.StartUploadResponse);
}
/// <summary>Waits until no job is queued or running (the thumbnails, proxies and analyses uploads queue).</summary>
private static async Task UntilIdleAsync(TestServer server)
{
var until = DateTime.UtcNow + Wait;
foreach (var state in new[] { JobState.Queued, JobState.Running, JobState.Queued, JobState.Running })
{
while ((await server.Database.Jobs.ListAsync(state)).Items.Count > 0)
{
Assert.True(DateTime.UtcNow < until, $"jobs still {state}");
await Task.Delay(50);
}
}
}
/// <summary>A JPEG of a few chunks: noise does not compress below the chunk size.</summary>
private static byte[] Photo(int seed)
{
const int width = 512, height = 384;
var pixels = new byte[width * height * 3];
new Random(seed).NextBytes(pixels);
return JpegEncoder.Encode(pixels, width, height, 3, new JpegEncodeOptions { Quality = 95 });
}
}