Compare commits

...
Author SHA1 Message Date
spark ef35c2e569 Desktop 0.3.26: USB card list with chosen downloads only (#141)
ci / rust (push) Successful in 7m57s
ci / typescript (push) Successful in 10m32s
desktop-release / build (--target universal-apple-darwin, dmg,app, darwin-universal, macos) (push) Successful in 24m0s
desktop-release / build (deb,appimage, linux-x86_64, ubuntu-latest) (push) Successful in 28m9s
Desktop 0.3.26: USB card list with chosen downloads only
2026-11-03 11:46:20 +00:00
spark 107e4be5e3 Desktop 0.3.26: USB card list with chosen downloads only
ci / rust (pull_request) Successful in 3m54s
ci / typescript (pull_request) Successful in 7m54s
Stop auto-pulling tethered shots. List the card (and new frames as they
appear) and download only what the photographer selects, including RAW
sidecars. Open the PTP session after deviceDidBecomeReady so Canon bodies
do not hang on “A ligar…”.
2026-11-03 11:33:51 +00:00
spark d9ca281706 Merge pull request 'fix(delivery): sweep rejected photos left on destinations' (#137) from task/BIT-retract-orphan-reconcile into main
ci / rust (push) Successful in 3m53s
ci / typescript (push) Successful in 8m7s
2026-11-03 00:32:55 +00:00
spark 0afa84c211 Merge branch 'main' into task/BIT-retract-orphan-reconcile
ci / rust (pull_request) Successful in 3m55s
ci / typescript (pull_request) Successful in 7m38s
2026-11-03 00:16:33 +00:00
spark 0ef50c98cd Merge pull request 'fix(desktop): reject update manifests whose signature version disagrees' (#139) from task/BIT-desktop-update-sig-guard into main
ci / rust (push) Successful in 3m59s
ci / typescript (push) Successful in 7m25s
2026-11-02 23:02:35 +00:00
spark 985188812a fix(desktop): reject update manifests whose signature version disagrees
ci / rust (pull_request) Successful in 4m4s
ci / typescript (pull_request) Successful in 8m25s
A retagged desktop-v* on the wrong commit announced 0.3.25 while the
binary was still signed as 0.3.24. Prefer the newest asset, skip mismatched
releases, and refuse to write such a manifest at build time.
2026-11-02 22:37:35 +00:00
spark 3751589db0 fix(delivery): sweep rejected photos left on destinations
ci / rust (pull_request) Failing after 1m44s
ci / typescript (pull_request) Successful in 9m7s
A REJECT that bypasses the library PATCH (or races the upload) could leave
the file on Nextcloud; reclaim those on the worker tick and cover reject/un-pick in tests.
2026-11-02 21:57:05 +00:00
spark 0179e2bd86 Desktop 0.3.25: USB tether and FTP machine labels (BIT-134) (#135)
ci / rust (push) Successful in 6m35s
ci / typescript (push) Successful in 11m23s
desktop-release / build (deb,appimage, linux-x86_64, ubuntu-latest) (push) Successful in 28m22s
desktop-release / build (--target universal-apple-darwin, dmg,app, darwin-universal, macos) (push) Successful in 25m53s
Desktop 0.3.25: USB tether and FTP machine labels (BIT-134)
2026-11-02 21:46:58 +00:00
spark 73b3b65925 Desktop 0.3.25: USB tether for PTP cameras and machine labels on local FTP (BIT-134).
ci / rust (pull_request) Successful in 5m36s
ci / typescript (pull_request) Successful in 10m26s
When a body is on the cable, new shots go to the open event and the clock syncs to
this Mac; FTP local shows one connection per machine. EOS Utility must release the
cable first.
2026-11-02 21:32:57 +00:00
spark 7a552e2c81 Merge pull request 'fix(desktop): dont 500 the installer download when Gitea releases is unreachable (BIT-31961)' (#133) from fix/BIT-31961-desktop-download-fetch-failed into main
ci / rust (push) Successful in 4m22s
ci / typescript (push) Successful in 7m42s
desktop-release / build (--target universal-apple-darwin, dmg,app, darwin-universal, macos) (push) Successful in 23m14s
desktop-release / build (deb,appimage, linux-x86_64, ubuntu-latest) (push) Successful in 31m17s
2026-11-01 01:02:46 +00:00
paula-alves c652715707 fix(desktop): don't 500 the installer download when Gitea releases is unreachable (BIT-31961)
ci / rust (pull_request) Successful in 3m54s
ci / typescript (pull_request) Successful in 8m1s
GET /v1/desktop/download/:releaseId/:name called DesktopReleases.file()
with no try/catch, unlike the sibling update-check route. A transient
network failure fetching the release/asset from Gitea threw a bare
undici TypeError (no file/line in its stack, since it originates
inside undici) straight through the route handler, landing on the
error hub as an unlocatable "TypeError: fetch failed" and a 500 to the
desktop app instead of a graceful retry signal.

Paperclip-Agent: José Alves (urlKey jos-alves; id 11179220-3cec-4f0f-880d-2771ff64fce8)
Paperclip-Issue: BIT-31961
Paperclip-Run: 431a287c-0cb3-4f73-9288-ac8d20e18df8
2026-11-01 00:24:18 +00:00
spark b1561da69a Merge pull request 'fix(archive): classify libvips sequential-JPEG SOS errors as corrupt source (BIT-31700)' (#132) from task/BIT-31700-vips-sos-corrupt-source into main
ci / rust (push) Successful in 3m49s
ci / typescript (push) Successful in 7m8s
2026-10-29 11:12:25 +00:00
jos-alves b540ab447b fix(archive): classify libvips sequential-JPEG SOS errors as corrupt source (BIT-31700)
ci / rust (pull_request) Successful in 3m51s
ci / typescript (pull_request) Successful in 7m31s
VipsJpeg: Invalid SOS parameters for sequential JPEG is another shape of the
same truncated/corrupted cloud-archive JPEG that premature end and corrupt
header already cover; isCorruptSourceMessage didn't match it, so it fell
through to the generic failure path and reached the error hub as a warning
instead of being marked corrupt_source at info level.

Paperclip-Agent: José Alves (urlKey jos-alves; id 11179220-3cec-4f0f-880d-2771ff64fce8)
Paperclip-Issue: BIT-31700
Paperclip-Run: 6435a4c4-0daa-41c4-8641-a0431c981ee8
2026-10-29 11:03:19 +00:00
spark 0b7af4f992 Merge pull request 'fix(sports): tell FPA homonyms apart by licence instead of a 409 (BIT-31898)' (#131) from fix/BIT-31898-fpa-associate-name-collision into main
ci / rust (push) Successful in 4m50s
ci / typescript (push) Successful in 8m50s
2026-10-28 02:02:58 +00:00
paula-alves 018cefaf7a fix(sports): tell FPA homonyms apart by licence instead of a 409 (BIT-31898)
ci / rust (pull_request) Successful in 4m3s
ci / typescript (pull_request) Successful in 7m58s
Two different people can share the exact same full name in the FPA
register; personFromFpaAssociate (full club register sync) and
personFromFpaLicence (add-by-licence) both threw person_name_taken in
that case, which fpaAssociates only logged and swallowed, but which
silently dropped that associate from the sync. The federation's
licence number is always free for this, so suffix it onto the name
instead of giving up.

Paperclip-Agent: José Alves (urlKey jos-alves; id 11179220-3cec-4f0f-880d-2771ff64fce8)
Paperclip-Issue: BIT-31898
Paperclip-Run: aa809c11-1594-449d-bc49-93e96efbe4e5
2026-10-28 01:49:30 +00:00
spark f847cbff56 Site: câmara in-page para Tirar foto (iPhone) (#130)
ci / rust (push) Successful in 3m47s
ci / typescript (push) Successful in 7m27s
Site: câmara in-page para Tirar foto (iPhone) (#130)
2026-10-28 01:21:27 +00:00
spark 1b1dadda6c Site: open the front camera in-page for Tirar foto
ci / rust (pull_request) Successful in 5m30s
ci / typescript (pull_request) Successful in 8m27s
iPhone file+capture often returns HEIC or fails the hidden input.
Use getUserMedia like the kiosk so the probe is always JPEG.
2026-10-28 01:10:29 +00:00
spark 1dbd4156df Merge pull request 'Arquivo: procura pela ficha FPA (registo do clube) e câmara no telemóvel' (#129) from task/126-find-registry-first into main
ci / rust (push) Successful in 5m2s
ci / typescript (push) Successful in 9m34s
2026-10-28 01:02:24 +00:00
spark c5e90e6d89 Expect club-register people in the FPA squad sync test.
ci / rust (pull_request) Successful in 5m10s
ci / typescript (pull_request) Successful in 8m31s
2026-10-28 00:49:22 +00:00
spark 9d0b19d1f0 Reset FPA retry clocks between sports tests after a DB wipe.
ci / rust (pull_request) Successful in 5m0s
ci / typescript (pull_request) Failing after 7m24s
2026-10-28 00:32:31 +00:00
spark faaa3406d2 Arquivo: procura pela ficha FPA (registo do clube) e câmara no telemóvel
ci / rust (pull_request) Successful in 3m52s
ci / typescript (pull_request) Failing after 7m11s
Match the probe to FPA licence photos from getCipClubeEpoca first, then
load that person's archive photos — not only people named on match sheets.
On phones, open the front camera and convert HEIC to JPEG before upload so
"Tirar foto" works on iPhone.
2026-10-28 00:22:51 +00:00
spark 697676de56 Arquivo: acelerar procura por foto (HNSW + cache) (#128)
ci / rust (push) Successful in 4m10s
ci / typescript (push) Successful in 7m31s
Speed up archive find with pgvector HNSW and short event-id caches.
2026-10-27 23:04:37 +00:00
spark 7edac9dae1 Do not cache the archive find toggle; keep only the event-id cache.
ci / rust (pull_request) Successful in 3m54s
ci / typescript (pull_request) Successful in 7m14s
The enabled flag must take effect immediately when an admin turns it off.
2026-10-27 22:56:58 +00:00
spark 602c64ca0d Speed up archive search-by-photo with HNSW and short caches.
ci / rust (pull_request) Successful in 3m49s
ci / typescript (pull_request) Failing after 6m53s
Rank face groups via pgvector instead of a full cosine scan, cache the
viewer's event ids and source settings, and warm the face engine when an
editor opens the archive so the first upload is not cold.
2026-10-27 22:48:59 +00:00
spark a8e5d97954 Arquivo: procura por foto (editores cloud / FPA) (#127)
ci / rust (push) Successful in 3m55s
ci / typescript (push) Successful in 7m16s
Arquivo: procura por foto para editores cloud (FPA).

Closes #126
2026-10-27 21:29:01 +00:00
spark ea669672d4 Add archive search-by-photo for cloud editors (FPA news desk).
ci / rust (pull_request) Successful in 3m45s
ci / typescript (pull_request) Successful in 7m17s
Editors with folder edit rights can upload a portrait and find matching
faces across the archive they can see. The option is per cloud source
(on by default for FPA), requires biometrics, and never stores the probe.
2026-10-27 21:17:42 +00:00
spark ece55190c3 Merge pull request 'Arquivo: abrir torneio no próprio sítio e adicionar pessoas pela licença FPA' (#123) from task/archive-licence into main
ci / rust (push) Successful in 3m58s
ci / typescript (push) Successful in 7m58s
2026-10-27 18:33:01 +00:00
paula-alves 824ca7ae49 Merge main into task/archive-licence: resolve viewer.ts, sports/service.ts, Browse.tsx
ci / rust (pull_request) Successful in 5m28s
ci / typescript (pull_request) Successful in 8m46s
Bring the archive-licence branch up to date with main (videos, stored directory, EHF provider, squad linking) while keeping the PR delta: the FPA-licence person flow (sports.service.personFromFpaLicence + fpaLatestRole/fpaClubName), the sports dep wired through the archive viewer and review routes, and the site LicenceAdd UI.

Conflicts resolved keeping main behaviour and adding only the PR delta:
- apps/api/src/archive/viewer.ts: keep main video/directory rewrite; add SportsService dep and pass sports to registerArchiveReviewRoutes.
- apps/api/src/sports/service.ts: keep main EHF/squads/identity changes; add AppError import, FpaMember/FpaRegistration/fpaShortName imports, licence match in linkSquadPerson, personFromFpaLicence, fpaLatestRole, fpaClubName.
- apps/site/src/app/arquivo/[id]/Browse.tsx: keep main eventLayout/teamGroups/peopleSeason; add addFromLicence + FpaCard import, fpa prop, openGroup reset on filter change, LicenceAdd component.
- apps/api/src/archive/review.ts: rename FPA member cache to memberCache to avoid shadowing main SQL members() helper.

Paperclip-Issue: BIT-31882
Paperclip-Run: d2cbc1f6-e181-4c2e-a3ce-7ca8e15b2279
2026-10-27 18:00:10 +00:00
spark 21e33ba0c6 Keep folder edits local and upload originals without waiting on detection
ci / rust (push) Successful in 4m42s
ci / typescript (push) Successful in 7m53s
The contact sheet writes the JPEG and XMP beside the file. Merged DNGs pin D50. Local FTP uploads four originals at once.
2026-10-25 13:54:49 +00:00
spark 66ac11621c Keep folder edits on this computer and upload camera originals without waiting on detection.
ci / rust (pull_request) Successful in 4m32s
ci / typescript (pull_request) Successful in 7m46s
The contact sheet can develop a frame and write the JPEG and XMP beside it. Merged DNGs pin D50 so the colour tags stay. Local FTP sends four originals at once and runs detection off that path.
2026-10-25 13:46:28 +00:00
spark eb81f69fb8 Merge pull request 'Write folder merges through LightCraft Photo Merge' (#122) from task/folder-merge-dng into main
ci / rust (push) Successful in 5m8s
ci / typescript (push) Successful in 14m14s
desktop-release / build (--target universal-apple-darwin, dmg,app, darwin-universal, macos) (push) Successful in 28m59s
desktop-release / build (deb,appimage, linux-x86_64, ubuntu-latest) (push) Successful in 31m5s
A camera raw with no matrix of its own was saved as a linear DNG that other raw tools refused.
2026-10-24 01:02:32 +01:00
spark cb67b0c329 Write folder merges through LightCraft Photo Merge so the DNG keeps colour tags.
ci / rust (pull_request) Successful in 5m3s
ci / typescript (pull_request) Successful in 10m50s
A camera raw with no matrix of its own was saved as a linear DNG that other raw tools refused.
2026-10-24 00:50:39 +01:00
spark e096c6153e Merge pull request 'chore(runtime): upgrade PhotoReport monorepo to Node.js 24.22.1 (BIT-31725)' (#121) from task/BIT-31725-node24-upgrade into main
ci / rust (push) Successful in 9m7s
ci / typescript (push) Successful in 12m45s
Merge PR #121 (BIT-31725)
2026-10-23 18:20:44 +01:00
spark fa2e494d99 Merge pull request 'Open a dropped folder from the window drop event' (#120) from task/folder-drop-window into main
ci / rust (push) Successful in 4m18s
ci / typescript (push) Failing after 11m48s
2026-10-23 17:59:17 +01:00
spark a8a887e82f Remember a dropped folder from the window event, so the contact sheet can open it.
ci / rust (pull_request) Successful in 11m30s
ci / typescript (pull_request) Successful in 15m21s
desktop-release / build (--target universal-apple-darwin, dmg,app, darwin-universal, macos) (push) Successful in 23m40s
desktop-release / build (deb,appimage, linux-x86_64, ubuntu-latest) (push) Successful in 41m54s
The main window delivers the drop as a window event. Recording it only on the webview event left the folder unknown, and opening it was refused.
2026-10-23 17:36:34 +01:00
spark 3a2828e4ca Merge pull request 'Contact sheet, remove from event, and local filmstrip thumbs' (#119) from task/contact-sheet-remove into main
ci / rust (push) Successful in 9m15s
ci / typescript (push) Successful in 13m39s
desktop-release / build (--target universal-apple-darwin, dmg,app, darwin-universal, macos) (push) Successful in 24m54s
desktop-release / build (deb,appimage, linux-x86_64, ubuntu-latest) (push) Successful in 29m41s
Closes #118
2026-10-23 16:57:59 +01:00
spark b3fc08935e Name the work folder from the pinned event when it is not in the cache.
ci / rust (pull_request) Successful in 4m45s
ci / typescript (pull_request) Successful in 9m15s
The camera feed still files into that event, but the move into the dated folder had no title to use.
2026-10-23 16:47:17 +01:00
spark 9a067262d5 Keep arriving photos in the event they were taken in, and cull without deleting them.
ci / rust (pull_request) Successful in 5m25s
ci / typescript (pull_request) Failing after 9m35s
A leftover pin no longer swallows the next day's files. Delete removes a photo from the open event after a confirm, and a dropped folder opens as a contact sheet on this computer. The develop filmstrip reads unedited originals from disk. Desktop shell 0.3.22 carries the folder and thumbnail commands.
2026-10-23 16:33:31 +01:00
sparkandClaude Opus 5.5 9d79270859 Archive: open a tournament in place, and add people by their FPA licence.
ci / rust (pull_request) Successful in 2m46s
ci / typescript (pull_request) Successful in 11m38s
- A tournament's tile opens its galleries in place of the tiles (they opened below the whole list, out of sight).
- The FPA licence (CIPA) is not the id the federation keeps registrations under: the portal page gives that id,
  then every registration (season, role, club) is read. A person can be added by licence number from Pessoas or
  while naming a face in the review ("198159" offers the federation's person); the licence photo becomes the
  reference, so coaches, delegates and staff are recognised in event photos no match report covers.
- people.licence: the same licence is always the same person, also when a match report names them later.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_017sovZz1NXBwx4VySojoyA1
2026-10-19 10:55:15 +00:00
116 changed files with 10361 additions and 354 deletions

No files matched your search

Generated
+1702 -5
View File
File diff suppressed because it is too large. Load diff
+4
View File
@@ -20,6 +20,10 @@ lightcraft-merge = { git = "https://github.com/storytold/lightcraft", rev = "5fe
lightcraft-raw = { git = "https://github.com/storytold/lightcraft", rev = "5fe74557eca64638b1f9015c9769f7e52a889fa2" }
lightcraft-color = { git = "https://github.com/storytold/lightcraft", rev = "5fe74557eca64638b1f9015c9769f7e52a889fa2" }
lightcraft-meta = { git = "https://github.com/storytold/lightcraft", rev = "5fe74557eca64638b1f9015c9769f7e52a889fa2" }
# Photo Merge only. The develop crates do not export the colour-tag step a raw without matrices
# needs before write_linear_dng. Desktop turns this on; the browser engine does not.
lightcraft-engine = { git = "https://github.com/storytold/lightcraft", rev = "5fe74557eca64638b1f9015c9769f7e52a889fa2" }
lightcraft-catalog = { git = "https://github.com/storytold/lightcraft", rev = "5fe74557eca64638b1f9015c9769f7e52a889fa2" }
serde = { version = "1", features = ["derive"] }
serde_json = "1"
thiserror = "2"
@@ -0,0 +1,3 @@
-- Handball: a person's federation licence number (CIPA).
ALTER TABLE "people" ADD COLUMN "licence" TEXT;
CREATE UNIQUE INDEX "people_organization_id_licence_key" ON "people"("organization_id", "licence");
@@ -0,0 +1,4 @@
-- Editors on the cloud: search the archive by uploading a photo of a person (news desk). Off by default;
-- on for FPA archives already connected with that look.
ALTER TABLE "cloud_sources" ADD COLUMN "photo_find_enabled" BOOLEAN NOT NULL DEFAULT false;
UPDATE "cloud_sources" SET "photo_find_enabled" = true WHERE "look" = 'fpa';
+5
View File
@@ -659,6 +659,8 @@ model Person {
referenceEmbedding Float[] @default([]) @map("reference_embedding")
/// The squad entry this person came from (kept in step when squads change).
sportsPlayerId String? @map("sports_player_id") @db.Uuid
/// Handball: the federation licence number (CIPA), when the person was added by it or seen on a match report.
licence String?
/// Face recognition turned off for this person (an archive editor): no centroid, no reference, never suggested;
/// still named by hand.
recognitionOffAt DateTime? @map("recognition_off_at")
@@ -673,6 +675,7 @@ model Person {
@@unique([organizationId, name])
@@unique([organizationId, sportsPlayerId])
@@unique([organizationId, licence])
@@map("people")
}
@@ -1631,6 +1634,8 @@ model CloudSource {
status String @default("LOGIN")
/// How the archive's site looks: "liga" (Liga Portugal), "fpa" (Federação de Andebol), or null (PhotoReport).
look String?
/// Editors on the cloud may upload a photo and search for that face across the archive (news desk). Off by default.
photoFindEnabled Boolean @default(false) @map("photo_find_enabled")
/// The archive's own address ("arquivo.ligaportugal.pt"): the site serves this archive at its root there.
hostname String? @unique
/// Nextcloud login flow v2: where to poll for the app password while status is LOGIN (sealed token).
+23 -11
View File
@@ -146,17 +146,7 @@ export async function buildApp({ config, db, realtime, fetchImpl, reporter: give
await registerArchiveRoutes(app, { db, sessions, archive, storageRoot: config.STORAGE_ROOT, minFreeBytes: config.ARCHIVE_MIN_FREE_GB * 1e9 });
// The API never runs the face engine: it confirms and merges groups; the worker detects and groups.
const faces = new FaceService({ db, storage, broadcaster, log: app.log });
await registerArchiveViewerRoutes(app, { db, secrets, signer, archive, tokens: new ViewerTokens(config.JWT_SECRET), faces, storage, secret: config.JWT_SECRET, fetchImpl });
await registerCompositionRoutes(app, { db, sessions, storage, storageRoot: config.STORAGE_ROOT });
await registerSearchRoutes(app, { db, sessions, signer });
await registerFtpRoutes(app, { db, sessions, ingestRoot: config.INGEST_ROOT, hookSecret: config.SFTPGO_HOOK_KEY });
const ingest = new IngestService({ db, storage, signer, broadcaster, ingestRoot: config.INGEST_ROOT, log: app.log });
ingest.arrivals = (photo) => delivery.queueArrival(photo);
await registerUploadRoutes(app, { db, sessions, ingest, storage, signer });
// The worker writes the heartbeat. Tests have no worker, so they say the engine is on unless a case says otherwise.
const facesOnline = engineOnline ?? (() => (config.NODE_ENV === "test" ? true : faceEnginePaths(config) !== null && faceWorkerLive(config.STORAGE_ROOT)));
await registerFaceRoutes(app, { db, sessions, faces, signer, storage, engineOnline: facesOnline });
// Search by photo (library and "Encontra-te" on the sites): the API's own face engine, started on demand.
// Search by photo (library, archive editors, "Encontra-te"): the API's own face engine, started on demand.
const facePaths = faceEnginePaths(config);
const slots = scanSlots();
const lookupEngine = new IdleEngine(
@@ -168,6 +158,28 @@ export async function buildApp({ config, db, realtime, fetchImpl, reporter: give
);
app.addHook("onClose", async () => (faceEngine ? undefined : lookupEngine.close()));
const lookup = new FaceLookup({ db, engine: () => lookupEngine.get() });
await registerArchiveViewerRoutes(app, {
db,
secrets,
signer,
archive,
tokens: new ViewerTokens(config.JWT_SECRET),
faces,
storage,
secret: config.JWT_SECRET,
fetchImpl,
sports,
lookup,
});
await registerCompositionRoutes(app, { db, sessions, storage, storageRoot: config.STORAGE_ROOT });
await registerSearchRoutes(app, { db, sessions, signer });
await registerFtpRoutes(app, { db, sessions, ingestRoot: config.INGEST_ROOT, hookSecret: config.SFTPGO_HOOK_KEY });
const ingest = new IngestService({ db, storage, signer, broadcaster, ingestRoot: config.INGEST_ROOT, log: app.log });
ingest.arrivals = (photo) => delivery.queueArrival(photo);
await registerUploadRoutes(app, { db, sessions, ingest, storage, signer });
// The worker writes the heartbeat. Tests have no worker, so they say the engine is on unless a case says otherwise.
const facesOnline = engineOnline ?? (() => (config.NODE_ENV === "test" ? true : faceEnginePaths(config) !== null && faceWorkerLive(config.STORAGE_ROOT)));
await registerFaceRoutes(app, { db, sessions, faces, signer, storage, engineOnline: facesOnline });
let jerseyOnce: Promise<JerseyReader | null> | null = null;
const jerseyOf = (): Promise<JerseyReader | null> => {
if (jersey !== undefined) return Promise.resolve(jersey);
@@ -26,6 +26,7 @@ describe("corrupt / incomplete archive sources (BIT-31621)", () => {
expect(isCorruptSourceMessage("premature end of JPEG")).toBe(true);
expect(isCorruptSourceMessage("Input file contains unsupported image format")).toBe(true);
expect(isCorruptSourceMessage("VipsForeignLoad: \"/tmp/x/original.jpg\" is not a known file format")).toBe(true);
expect(isCorruptSourceMessage("VipsJpeg: Invalid SOS parameters for sequential JPEG")).toBe(true);
expect(isCorruptSourceMessage("ffmpeg exited 234: Stream map '0:v:0' matches no streams")).toBe(false);
expect(isCorruptSourceMessage("GET /a failed: 503")).toBe(false);
});
+1 -1
View File
@@ -24,7 +24,7 @@ export class IncompleteDownload extends Error {
/** ffprobe/ffmpeg/sharp messages that mean the cloud file itself is damaged, not our pipeline. */
export function isCorruptSourceMessage(message: string): boolean {
return /moov atom not found|premature end|not a known file format|corrupt (?:jpeg )?header|Corrupt JPEG|Input file has corrupt header|Input file contains unsupported image format|unsupported image format|Invalid data found when processing input/i.test(
return /moov atom not found|premature end|not a known file format|corrupt (?:jpeg )?header|Corrupt JPEG|Input file has corrupt header|Input file contains unsupported image format|unsupported image format|Invalid data found when processing input|Invalid SOS parameters/i.test(
message,
);
}
+321
View File
@@ -0,0 +1,321 @@
import type { FastifyInstance, FastifyRequest } from "fastify";
import { eventName } from "@photoreport/metadata";
import { z } from "zod";
import { Prisma } from "../generated/prisma/client.js";
import type { Db } from "../db.js";
import { facesOut, lookupFailed, lookupImage, LookupQuery } from "../faces/lookupRoutes.js";
import type { FaceLookup } from "../faces/lookup.js";
import { cosine, POSSIBLE_BELOW, THRESHOLDS } from "../faces/math.js";
import { conflict, forbidden, notFound } from "../lib/errors.js";
import type { UrlSigner } from "../storage/storage.js";
import { faceBox } from "./people.js";
import { publishedPhotos } from "./gallery.js";
import type { Viewer } from "./viewer.js";
/**
* Search the archive by a photo: for editors on the cloud (same rights as "Rever rostos"), when the archive has
* the option on and the organization has biometrics on. The search photo is read in memory and never kept.
*
* Registry first: the probe is compared to registered people (FPA licence / Liga headshot centroids). A clear
* match loads that person's archive photos by person_id — no blind scan of every face group. Only when nobody
* in the registry is sure enough do we fall back to HNSW over the viewer's face groups.
*/
interface Deps {
db: Db;
signer: UrlSigner;
lookup: FaceLookup;
viewerOf: (req: FastifyRequest, sourceId?: string) => Viewer;
visibleFolders: (v: Viewer) => Promise<string[] | "all">;
editableFolders: (v: Viewer) => Promise<string[] | "all">;
}
const SourceParams = z.object({ sourceId: z.uuid() });
const EVENTS_TTL_MS = 5 * 60_000;
const NEAREST = 400;
const MAX_PHOTOS = 500;
/** How many registry candidates to keep for the editor (strong + possible). */
const PEOPLE_LIMIT = 8;
type CardLevel = "confirmed" | "probable" | "similar";
type Via = "registry" | "faces";
const levelOf = (score: number, match: number): CardLevel => (score >= match ? "probable" : "similar");
export async function registerArchiveFindRoutes(app: FastifyInstance, deps: Deps) {
const { db, signer, lookup, viewerOf, visibleFolders, editableFolders } = deps;
/** Event ids of a viewer's archive scope: the heavy DISTINCT over cloud_files, reused while they search. */
const eventsCache = new Map<string, { at: number; ids: string[] }>();
const scopeOf = async (v: Viewer): Promise<{ sql: Prisma.Sql; key: string } | null> => {
const visible = await visibleFolders(v);
if (visible !== "all" && !visible.length) return null;
const key = visible === "all" ? "all" : [...visible].sort().join(",");
const sql =
visible === "all"
? Prisma.sql`cf.source_id = ${v.s}::uuid AND cf.status = 'DONE' AND cf.photo_id IS NOT NULL AND ${publishedPhotos}`
: Prisma.sql`cf.source_id = ${v.s}::uuid AND cf.status = 'DONE' AND cf.photo_id IS NOT NULL AND cf.folder_id = ANY(${visible}::uuid[]) AND ${publishedPhotos}`;
return { sql, key };
};
const requireFind = async (v: Viewer) => {
const editable = await editableFolders(v);
if (editable !== "all" && !editable.length) throw forbidden("archive_edit_required");
const source = await db.cloudSource.findUnique({
where: { id: v.s },
select: { id: true, organizationId: true, photoFindEnabled: true, organization: { select: { biometricsEnabled: true } } },
});
if (!source) throw notFound("source_not_found");
if (!source.photoFindEnabled || !source.organization.biometricsEnabled) throw conflict("find_unavailable");
return source;
};
const eventsInScope = async (sourceId: string, scope: Prisma.Sql, cacheKey: string): Promise<string[]> => {
const key = `${sourceId}:${cacheKey}`;
const hit = eventsCache.get(key);
if (hit && Date.now() - hit.at < EVENTS_TTL_MS) return hit.ids;
const rows = await db.$queryRaw<{ event_id: string }[]>`
SELECT DISTINCT ph.event_id AS event_id
FROM photos ph
JOIN cloud_files cf ON cf.photo_id = ph.id AND ${scope}
WHERE ph.event_id IS NOT NULL`;
const ids = rows.map((r) => r.event_id);
eventsCache.set(key, { at: Date.now(), ids });
return ids;
};
/**
* Face groups in the viewer's events like the probe. Production (512-d) uses the HNSW index; shorter test
* vectors fall back to a cosine over the float array. Used only when the registry has no sure person.
*/
const nearGroups = async (eventIds: string[], embedding: number[], model: string) => {
if (!eventIds.length) return [] as { id: string; personId: string | null; score: number }[];
const match = (THRESHOLDS[model] ?? { match: 0.5 }).match;
const floor = match - POSSIBLE_BELOW;
if (embedding.length === 512) {
const literal = `[${embedding.map((n) => (Number.isFinite(n) ? n : 0)).join(",")}]`;
const rows = await db.$queryRaw<{ id: string; person_id: string | null; score: number }[]>`
SELECT id, person_id, score FROM (
SELECT g.id, g.person_id, (1 - (g.centroid_vec <=> ${literal}::vector))::float AS score
FROM face_groups g
WHERE g.ignored_at IS NULL AND g.model = ${model} AND g.centroid_vec IS NOT NULL AND g.size > 0
AND g.event_id = ANY(${eventIds}::uuid[])
ORDER BY g.centroid_vec <=> ${literal}::vector
LIMIT ${NEAREST}
) ranked
WHERE score >= ${floor}`;
return rows.map((r) => ({ id: r.id, personId: r.person_id, score: Number(r.score) }));
}
const groups = await db.$queryRaw<{ id: string; centroid: unknown; person_id: string | null }[]>`
SELECT g.id, g.centroid, g.person_id
FROM face_groups g
WHERE g.ignored_at IS NULL AND g.model = ${model} AND g.size > 0 AND cardinality(g.centroid) > 0
AND g.event_id = ANY(${eventIds}::uuid[])`;
const asVector = (v: unknown): number[] =>
Array.isArray(v) ? v.map(Number) : typeof v === "string" ? v.replace(/[{}]/g, "").split(",").filter(Boolean).map(Number) : [];
return groups
.map((g) => ({ id: g.id, personId: g.person_id, score: cosine(embedding, asVector(g.centroid)) }))
.filter((x) => x.score >= floor)
.sort((a, b) => b.score - a.score)
.slice(0, NEAREST);
};
/** Licence / headshot / federation label for the people the registry returned. */
const enrichPeople = async (ids: string[]) => {
if (!ids.length) return new Map<string, { licence: string | null; reference: string | null; registry: "fpa" | "liga" | "uefa" | "ehf" | "fpf" | null }>();
const rows = await db.$queryRaw<{ id: string; licence: string | null; reference: boolean; provider: string | null }[]>`
SELECT p.id, p.licence, p.reference_key IS NOT NULL AS reference, t.provider
FROM people p
LEFT JOIN sports_players sp ON sp.id = p.sports_player_id
LEFT JOIN sports_teams t ON t.id = sp.team_id
WHERE p.id = ANY(${ids}::uuid[])`;
const asRegistry = (provider: string | null, licence: string | null): "fpa" | "liga" | "uefa" | "ehf" | "fpf" | null => {
if (licence || provider === "FPA") return "fpa";
if (provider === "LIGA" || provider === "LPFP") return "liga";
if (provider === "UEFA") return "uefa";
if (provider === "EHF") return "ehf";
if (provider === "FPF") return "fpf";
return null;
};
return new Map(
rows.map((r) => [
r.id,
{
licence: r.licence,
reference: r.reference ? signer.personUrl(r.id) : null,
registry: asRegistry(r.provider, r.licence),
},
]),
);
};
const photoCards = async (
shown: { photoId: string; faceId: string; score: number; level: CardLevel; sharpness: number | null }[],
scope: Prisma.Sql,
) => {
if (!shown.length) return [];
const ids = shown.map((h) => h.photoId);
const faceIds = shown.map((h) => h.faceId);
const [links, photos, faceRows] = await Promise.all([
db.$queryRaw<{ photo_id: string; folder_id: string }[]>`
SELECT DISTINCT ON (cf.photo_id) cf.photo_id, cf.folder_id
FROM cloud_files cf
WHERE cf.photo_id = ANY(${ids}::uuid[]) AND ${scope}
ORDER BY cf.photo_id, cf.path`,
db.photo.findMany({
where: { id: { in: ids } },
select: { id: true, width: true, height: true, players: true, capturedAt: true, renderedSeq: true, developSnapshot: true, originalName: true },
}),
db.face.findMany({ where: { id: { in: faceIds } }, select: { id: true, x0: true, y0: true, x1: true, y1: true } }),
]);
const folderOf = new Map(links.map((r) => [r.photo_id, r.folder_id]));
const folders = await db.cloudFolder.findMany({ where: { id: { in: [...new Set(folderOf.values())] } }, include: { event: true } });
const galleries = new Map(
folders.map((f) => [f.id, { id: f.id, title: f.event ? eventName(f.event) : (f.path.split("/").pop() ?? ""), startsAt: f.event?.startsAt ?? null, competition: f.event?.competition ?? null }]),
);
const byId = new Map(photos.map((p) => [p.id, p]));
const faceById = new Map(faceRows.map((f) => [f.id, f]));
return shown
.filter((h) => byId.has(h.photoId) && folderOf.has(h.photoId))
.map((h) => {
const p = byId.get(h.photoId)!;
const f = faceById.get(h.faceId);
return {
id: p.id,
name: p.originalName,
width: p.width,
height: p.height,
players: p.players,
capturedAt: p.capturedAt,
thumb: signer.url(p.id, "thumb", p.renderedSeq),
preview: signer.url(p.id, "preview", p.renderedSeq),
level: h.level,
score: h.score,
face: f ? faceBox(f, p) : null,
gallery: galleries.get(folderOf.get(h.photoId)!) ?? null,
};
});
};
/** Starts the face engine so the first real search does not wait on model load. */
app.get("/v1/archive/:sourceId/find/ready", async (req) => {
const { sourceId } = SourceParams.parse(req.params);
const v = viewerOf(req, sourceId);
await requireFind(v);
return { ready: lookup.available };
});
/**
* A photo of the person against the registry, then their archive photos (or a blind face-group search when
* nobody in the registry is sure). The uploaded file is not stored.
*/
app.post("/v1/archive/:sourceId/find", { config: { rateLimit: { max: 30, timeWindow: "1 minute" } } }, async (req) => {
const { sourceId } = SourceParams.parse(req.params);
const q = LookupQuery.parse(req.query);
const v = viewerOf(req, sourceId);
const source = await requireFind(v);
const scoped = await scopeOf(v);
if (!scoped) return { faces: [], used: 0, via: "faces" as Via, identity: null, people: [], total: 0, photos: [] };
const { sql: scope, key: scopeKey } = scoped;
const image = await lookupImage(req);
const read = await lookup.facesIn(image).catch(lookupFailed);
const used = Math.min(q.face, read.faces.length - 1);
const probe = read.faces[used]!;
const match = (THRESHOLDS[read.model] ?? { match: 0.5 }).match;
// 1) Registry first: FPA / Liga / UEFA people with a face on file (smaller set than every photo).
const matched = await lookup.people(source.organizationId, probe.embedding, read.model, PEOPLE_LIMIT);
const extra = await enrichPeople(matched.map((p) => p.id));
const people = matched.map((p) => {
const e = extra.get(p.id);
return {
id: p.id,
name: p.name,
club: p.club,
number: p.number,
score: p.score,
level: p.level,
licence: e?.licence ?? null,
reference: e?.reference ?? null,
registry: e?.registry ?? null,
};
});
const sure = people.filter((p) => p.level === "strong");
const best = new Map<string, { faceId: string; score: number; level: CardLevel; sharpness: number | null }>();
const keep = (photoId: string, faceId: string, score: number, level: CardLevel, sharpness: number | null) => {
const was = best.get(photoId);
if (!was || score > was.score) best.set(photoId, { faceId, score, level, sharpness });
};
let via: Via = "faces";
if (sure.length) {
// 2a) Known person: archive photos already named (or suggested) as them — no blind group scan.
via = "registry";
const sureIds = sure.map((p) => p.id);
const scoreOf = new Map(sure.map((p) => [p.id, p.score]));
const named = await db.$queryRaw<{ id: string; photo_id: string; sharpness: number | null; person_id: string | null; suggested_person_id: string | null }[]>`
SELECT f.id, f.photo_id, f.sharpness, g.person_id, g.suggested_person_id
FROM faces f
JOIN face_groups g ON g.id = f.group_id
JOIN cloud_files cf ON cf.photo_id = f.photo_id AND ${scope}
WHERE g.ignored_at IS NULL
AND (g.person_id = ANY(${sureIds}::uuid[]) OR g.suggested_person_id = ANY(${sureIds}::uuid[]))`;
for (const f of named) {
const personId = f.person_id ?? f.suggested_person_id!;
const score = scoreOf.get(personId) ?? sure[0]!.score;
keep(f.photo_id, f.id, score, f.person_id ? "confirmed" : "probable", f.sharpness);
}
} else {
// 2b) Nobody sure in the registry: fall back to face groups in the viewer's galleries.
const eventIds = await eventsInScope(sourceId, scope, scopeKey);
if (!eventIds.length) {
return { faces: facesOut(read.faces), used, via, identity: null, people, total: 0, photos: [] };
}
const groups = await nearGroups(eventIds, probe.embedding, read.model);
if (groups.length) {
const faces = await db.$queryRaw<{ id: string; photo_id: string; group_id: string; sharpness: number | null }[]>`
SELECT f.id, f.photo_id, f.group_id, f.sharpness
FROM faces f
JOIN cloud_files cf ON cf.photo_id = f.photo_id AND ${scope}
WHERE f.group_id = ANY(${groups.map((g) => g.id)}::uuid[])`;
const byGroup = new Map(groups.map((g) => [g.id, g]));
for (const f of faces) {
const g = byGroup.get(f.group_id)!;
const level: CardLevel = g.personId && g.score >= match ? "confirmed" : levelOf(g.score, match);
keep(f.photo_id, f.id, g.score, level, f.sharpness);
}
}
}
const hits = [...best.entries()]
.map(([photoId, h]) => ({ photoId, ...h }))
.sort((a, b) => b.score - a.score || (b.sharpness ?? 0) - (a.sharpness ?? 0));
const shown = hits.slice(0, MAX_PHOTOS);
const top = sure[0] ?? null;
const identity = top
? {
id: top.id,
name: top.name,
club: top.club,
number: top.number,
licence: top.licence,
reference: top.reference,
registry: top.registry,
score: top.score,
}
: null;
return {
faces: facesOut(read.faces),
used,
via,
identity,
people,
total: hits.length,
photos: await photoCards(shown, scope),
};
});
}
+80 -7
View File
@@ -6,6 +6,8 @@ import type { Db } from "../db.js";
import { FaceRejected, type FaceService } from "../faces/service.js";
import { AppError, forbidden, notFound } from "../lib/errors.js";
import type { UrlSigner } from "../storage/storage.js";
import { fpaLatestRole, type SportsService } from "../sports/service.js";
import type { FpaMember } from "../sports/providers.js";
import { galleryMemberIds } from "./gallery.js";
import { clubKey, faceBox } from "./people.js";
import type { Viewer } from "./viewer.js";
@@ -27,6 +29,8 @@ interface Deps {
faces: FaceService;
viewerOf: (req: FastifyRequest, sourceId?: string) => Viewer;
editableFolders: (v: Viewer) => Promise<string[] | "all">;
/** Handball: people by their federation licence (CIPA), for FPA archives. */
sports?: Pick<SportsService, "fpa" | "personFromFpaLicence"> | undefined;
/** After "Juntar nomes": lists built with the old names are dropped. */
onClubsChanged?: (sourceId: string) => void | Promise<void>;
}
@@ -46,6 +50,7 @@ const ReviewQuery = z.object({
const Act = z.object({ action: z.enum(["confirm", "reject", "ignore", "undo"]), personId: z.uuid().optional() });
const ChooseQuery = z.object({ q: z.string().trim().min(2).max(80) });
const Merge = z.object({ into: z.string().trim().min(1).max(120), names: z.array(z.string().trim().min(1).max(120)).min(1).max(20) });
const Licence = z.object({ licence: z.string().trim().regex(/^\d{3,9}$/) });
const Unmerge = z.object({ name: z.string().trim().min(1).max(120) });
const Recognition = z.object({ enabled: z.boolean(), removeConfirmed: z.boolean().default(false) });
@@ -77,12 +82,17 @@ export async function registerArchiveReviewRoutes(app: FastifyInstance, deps: De
const log = (v: Viewer, action: string, data: { personId?: string | null; groupId?: string | null; faces?: number }) =>
db.archiveFaceAction.create({ data: { sourceId: v.s, viewer: v.n, action, personId: data.personId ?? null, groupId: data.groupId ?? null, faces: data.faces ?? 0 } });
/** What this viewer may do: review faces (some folder with edit rights), act on people (edits everything). */
/** What this viewer may do: review faces (some folder with edit rights), act on people (edits everything), search by photo. */
app.get("/v1/archive/:sourceId/me", async (req) => {
const { sourceId } = SourceParams.parse(req.params);
const v = viewerOf(req, sourceId);
const editable = await editableFolders(v);
const canReview = editable === "all" || editable.length > 0;
const source = await db.cloudSource.findUnique({
where: { id: sourceId },
select: { photoFindEnabled: true, organization: { select: { biometricsEnabled: true } } },
});
const canFind = canReview && !!source?.photoFindEnabled && !!source.organization.biometricsEnabled;
const pending = canReview
? await (async () => {
const scope = await editScope(v);
@@ -95,7 +105,7 @@ export async function registerArchiveReviewRoutes(app: FastifyInstance, deps: De
return row?.n ?? 0;
})()
: 0;
return { name: v.n, canReview, canManagePeople: editable === "all", pending };
return { name: v.n, canReview, canManagePeople: editable === "all", canFind, pending };
});
/**
@@ -107,11 +117,11 @@ export async function registerArchiveReviewRoutes(app: FastifyInstance, deps: De
const v = viewerOf(req, sourceId);
const { q } = ChooseQuery.parse(req.query);
if (!(await editScope(v))) throw forbidden("archive_edit_required");
const source = await db.cloudSource.findUnique({ where: { id: sourceId }, select: { organizationId: true } });
const source = await db.cloudSource.findUnique({ where: { id: sourceId }, select: { organizationId: true, look: true } });
if (!source) throw notFound("source_not_found");
const like = `%${q.replace(/[\\%_]/g, "")}%`;
const rows = await db.$queryRaw<{ id: string; name: string; club: string | null; number: string | null; reference: boolean }[]>`
SELECT p.id, p.name,
const rows = await db.$queryRaw<{ id: string; name: string; club: string | null; number: string | null; reference: boolean; licence: string | null }[]>`
SELECT p.id, p.name, p.licence,
COALESCE(p.club, t.name) AS club,
COALESCE(p.number, sp.number) AS number,
p.reference_key IS NOT NULL AS reference
@@ -127,14 +137,77 @@ export async function registerArchiveReviewRoutes(app: FastifyInstance, deps: De
OR COALESCE(sp.full_name, '') ILIKE ${like}
OR p.number = ${q}
OR sp.number = ${q}
OR p.licence = ${q}
OR sp.external_id = ${q}
)
ORDER BY (p.number = ${q} OR sp.number = ${q}) DESC, (p.reference_key IS NOT NULL) DESC, length(p.name)
ORDER BY (p.licence = ${q} OR sp.external_id = ${q}) DESC, (p.number = ${q} OR sp.number = ${q}) DESC, (p.reference_key IS NOT NULL) DESC, length(p.name)
LIMIT 8`;
// A licence number nobody here has yet: who the federation says it is, to add them.
const fpa = fpaArchive(source) && /^\d{5,9}$/.test(q) && !rows.some((r) => r.licence === q) ? await memberOf(q) : null;
return {
people: rows.map((r) => ({ id: r.id, name: r.name, club: r.club, number: r.number, reference: r.reference ? signer.personUrl(r.id) : null })),
people: rows.map((r) => ({ id: r.id, name: r.name, club: r.club, number: r.number, reference: r.reference ? signer.personUrl(r.id) : null, ...(r.licence && { licence: r.licence }) })),
...(fpa && { fpa: memberOut(fpa) }),
};
});
/** Handball archives look people up by licence. Kept a while: typing a number asks once per number. */
const fpaArchive = (source: { look: string | null }) => !!deps.sports && source.look === "fpa";
const memberCache = new Map<string, { at: number; member: Promise<FpaMember | null> }>();
const memberOf = (licence: string): Promise<FpaMember | null> => {
const hit = memberCache.get(licence);
if (hit && Date.now() - hit.at < 30 * 60_000) return hit.member;
const member = deps.sports!.fpa.member(licence).catch(() => null);
memberCache.set(licence, { at: Date.now(), member });
if (memberCache.size > 500) for (const [k, m] of memberCache) if (Date.now() - m.at > 30 * 60_000) memberCache.delete(k);
return member;
};
const memberOut = (m: FpaMember) => {
const latest = fpaLatestRole(m);
return {
licence: m.licence,
name: m.name,
photo: m.photo,
club: latest?.club ?? null,
role: latest ? `${latest.role} · ${latest.season}` : m.registeredAs,
// Every season, newest first, as "2024/25 · Treinador · Estarreja AC" (no birth date: not needed here).
history: [...m.registrations]
.sort((a, b) => b.season.localeCompare(a.season))
.slice(0, 12)
.map((r) => [r.season, r.level ? `${r.role} ${r.level}` : r.role, r.club].filter(Boolean).join(" · ")),
};
};
/** Who a licence number is, for those who review (to add them before naming a face). */
app.get("/v1/archive/:sourceId/fpa/:licence", async (req) => {
const { sourceId } = SourceParams.parse(req.params);
const { licence } = Licence.parse(req.params);
const v = viewerOf(req, sourceId);
if (!(await editScope(v))) throw forbidden("archive_edit_required");
const source = await db.cloudSource.findUnique({ where: { id: sourceId }, select: { organizationId: true, look: true } });
if (!source || !fpaArchive(source)) throw notFound("fpa_not_available");
const member = await memberOf(licence);
if (!member) throw notFound("fpa_member_not_found");
const person = await db.person.findFirst({ where: { organizationId: source.organizationId, licence }, select: { id: true, name: true } });
return { member: memberOut(member), person };
});
/**
* Adds (or brings up to date) a person from their licence: name, club, and the licence photo as the reference,
* so recognition finds them in event photos where no match report names them.
*/
app.post("/v1/archive/:sourceId/people/from-licence", async (req) => {
const { sourceId } = SourceParams.parse(req.params);
const v = viewerOf(req, sourceId);
if (!(await editScope(v))) throw forbidden("archive_edit_required");
const { licence } = Licence.parse(req.body);
const source = await db.cloudSource.findUnique({ where: { id: sourceId }, select: { organizationId: true, look: true } });
if (!source || !fpaArchive(source)) throw notFound("fpa_not_available");
const done = await deps.sports!.personFromFpaLicence(source.organizationId, licence);
memberCache.delete(licence);
await log(v, done.created ? "person_from_licence" : "person_licence_update", { personId: done.person.id });
return { person: { ...done.person, licence, reference: done.reference }, created: done.created, member: memberOut(done.member) };
});
/**
* Face groups to review in the viewer's editable folders, one card per group: its sharpest faces, who it is
* (named) or might be (suggested, with how sure), its event; and the people with suggestions waiting.
+4
View File
@@ -23,6 +23,8 @@ const Update = z.object({
rootPath: z.string().trim().min(1).max(500).optional(),
paused: z.boolean().optional(),
look: z.enum(ARCHIVE_LOOKS).nullable().optional(),
/** Editors on the cloud may search the archive by uploading a photo of a person. */
photoFindEnabled: z.boolean().optional(),
/** The archive's own address (a host name, no scheme or path); empty or null takes it away. */
hostname: z
.string()
@@ -116,6 +118,7 @@ export async function registerArchiveRoutes(app: FastifyInstance, deps: { db: Db
baseUrl: s.baseUrl,
rootPath: s.rootPath,
look: s.look,
photoFindEnabled: s.photoFindEnabled,
hostname: s.hostname,
account: s.username || null,
status: s.status,
@@ -193,6 +196,7 @@ export async function registerArchiveRoutes(app: FastifyInstance, deps: { db: Db
...(status && { status }),
...(status === "READY" && { nextScanAt: new Date() }),
...(body.look !== undefined && { look: body.look }),
...(body.photoFindEnabled !== undefined && { photoFindEnabled: body.photoFindEnabled }),
...(hostname !== undefined && { hostname }),
},
});
+4 -1
View File
@@ -221,6 +221,7 @@ export class ArchiveService {
if (!/^https?:\/\/[^/]+/i.test(baseUrl)) throw new ArchiveRejected("invalid_url");
const box = this.box();
const flow = await startLogin(baseUrl, this.fetchImpl);
const look = lookFor(input.name, input.rootPath);
const source = await this.deps.db.cloudSource.create({
data: {
organizationId,
@@ -228,7 +229,9 @@ export class ArchiveService {
name: input.name.trim() || new URL(baseUrl).hostname,
baseUrl,
rootPath: normalisePath(input.rootPath),
look: lookFor(input.name, input.rootPath),
look,
// FPA news desk: editors on the cloud may search by photo from day one; other archives stay off.
photoFindEnabled: look === "fpa",
status: "LOGIN",
loginPoll: box.seal(JSON.stringify({ endpoint: flow.endpoint, token: flow.token, loginUrl: flow.loginUrl } satisfies LoginState)),
loginExpires: new Date(Date.now() + LOGIN_TTL_MS),
+21 -1
View File
@@ -10,12 +10,15 @@ import { AppError, badRequest, notFound, unauthorized } from "../lib/errors.js";
import type { LocalStorage, UrlSigner } from "../storage/storage.js";
import { CloudClient, pollLogin, startLogin } from "./nextcloud.js";
import { GALLERY_KINDS, galleryMemberIds, gallerySeasons, listStoredGalleries, publishedPhotos, seasonOf } from "./gallery.js";
import type { SportsService } from "../sports/service.js";
import { readStoredRaws, readStoredTeams } from "./directory.js";
import type { FaceService } from "../faces/service.js";
import { clubKind, faceBox, facesOfPhotos, registerArchivePeopleRoutes } from "./people.js";
import { registerArchiveDownloadRoutes } from "./downloads.js";
import { registerArchiveFindRoutes } from "./find.js";
import { registerArchiveReviewRoutes } from "./review.js";
import type { ArchiveService } from "./service.js";
import type { FaceLookup } from "../faces/lookup.js";
import { sendFile, VIDEO_FILES, VIDEO_VARIANTS } from "./video.js";
import { peopleInVideos } from "./video-faces.js";
@@ -109,7 +112,20 @@ const ListQuery = z.object({
export async function registerArchiveViewerRoutes(
app: FastifyInstance,
deps: { db: Db; secrets: SecretBox | undefined; signer: UrlSigner; archive: ArchiveService; tokens: ViewerTokens; faces: FaceService; storage: LocalStorage; secret: string; fetchImpl?: typeof fetch | undefined },
deps: {
db: Db;
secrets: SecretBox | undefined;
signer: UrlSigner;
archive: ArchiveService;
tokens: ViewerTokens;
faces: FaceService;
storage: LocalStorage;
secret: string;
fetchImpl?: typeof fetch | undefined;
sports?: Pick<SportsService, "fpa" | "personFromFpaLicence"> | undefined;
/** Search by photo for editors (absent → find route not registered). */
lookup?: FaceLookup;
},
) {
const { db, signer, tokens } = deps;
const fetchImpl = deps.fetchImpl ?? fetch;
@@ -730,12 +746,16 @@ export async function registerArchiveViewerRoutes(
faces: deps.faces,
viewerOf,
editableFolders,
sports: deps.sports,
onClubsChanged: async (sourceId) => {
forgetLists(sourceId, "teams");
await deps.archive.markDirectoryDirty(sourceId);
await deps.archive.rebuildDirectory(sourceId);
},
});
if (deps.lookup) {
await registerArchiveFindRoutes(app, { db, signer, lookup: deps.lookup, viewerOf, visibleFolders, editableFolders });
}
await registerArchiveDownloadRoutes(app, { db, storage: deps.storage, secret: deps.secret, viewerOf, visibleFolders });
}
+23 -7
View File
@@ -24,6 +24,18 @@ import { detailForCrop, lookValues } from "./look.js";
const STALE_RUNNING_MS = 10 * 60_000;
/** A burst is decided once no new frame of it has arrived for this long. */
const BURST_SETTLE_MS = 15_000;
/** A photo taken outside the event's ingest window does not belong in that event's client folders. No capture time: the event it was filed in is all we know. */
function takenDuring(capturedAt: Date | null | undefined, event: { ingestFrom: Date; ingestUntil: Date }): boolean {
if (!capturedAt) return true;
const t = capturedAt.getTime();
return t >= event.ingestFrom.getTime() && t <= event.ingestUntil.getTime();
}
function takenHere(ids: readonly string[], when: ReadonlyMap<string, Date | null>, event: { ingestFrom: Date; ingestUntil: Date }): string[] {
return ids.filter((id) => takenDuring(when.get(id), event));
}
export interface AutopilotRecord {
score: number;
reason: string | null;
@@ -185,7 +197,7 @@ export class AutopilotService {
WHERE autopilot_status = 'DONE' AND event_id IS NOT NULL AND (autopilot->>'decided') IS NULL`;
let picked = 0;
for (const { event_id: eventId } of undecided) {
const event = await db.event.findUnique({ where: { id: eventId }, select: { id: true, organizationId: true, autopilot: true, createdById: true, away: true, fixtureId: true } });
const event = await db.event.findUnique({ where: { id: eventId }, select: { id: true, organizationId: true, autopilot: true, createdById: true, away: true, fixtureId: true, ingestFrom: true, ingestUntil: true } });
if (!event) continue;
const settings = AutopilotSettings.parse(event.autopilot ?? {});
const busy = await db.photo.count({ where: { eventId, autopilotStatus: { in: ["PENDING", "RUNNING"] } } });
@@ -274,9 +286,11 @@ export class AutopilotService {
await db.photo.update({ where: { id: f.id }, data: { autopilot: { ...(f.rec ?? {}), decided: true, picked: pickedIds.has(f.id) } as object } });
}
// "Only the best" delivers per window of the match instead (below), not every burst's picks.
if (settings.selection === "bursts" && settings.deliverTargetId && toFlag.length && this.deps.deliveries && event.createdById) {
// A photo taken outside this event (yesterday's pin still receiving today's arrival) is not this client's.
const here = takenHere(toFlag, new Map(photos.map((p) => [p.id, p.capturedAt])), event);
if (settings.selection === "bursts" && settings.deliverTargetId && here.length && this.deps.deliveries && event.createdById) {
await this.deps.deliveries
.enqueue({ organizationId: event.organizationId, targetId: settings.deliverTargetId, photoIds: toFlag, again: false, requestedById: event.createdById })
.enqueue({ organizationId: event.organizationId, targetId: settings.deliverTargetId, photoIds: here, again: false, requestedById: event.createdById })
.catch((err: unknown) => log.warn({ err }, "autopilot: delivery not queued"));
}
}
@@ -302,7 +316,7 @@ export class AutopilotService {
*/
private async curateEvent(eventId: string, settings: AutopilotSettings, now: Date): Promise<number> {
const { db, log } = this.deps;
const event = await db.event.findUnique({ where: { id: eventId }, select: { organizationId: true, startsAt: true, sport: true, createdById: true } });
const event = await db.event.findUnique({ where: { id: eventId }, select: { organizationId: true, startsAt: true, sport: true, createdById: true, ingestFrom: true, ingestUntil: true } });
if (!event) return 0;
const photos = await db.photo.findMany({ where: { eventId, autopilotStatus: "DONE" }, select: CANDIDATE_SELECT });
const look = await sequenceWeights(db, photos, settings.burstGapSec * 1000, (photo) => this.previewFile(photo));
@@ -336,16 +350,18 @@ export class AutopilotService {
nowCurated.push(id);
}
// Everything else picked in this window goes to the second client: never a photo the gallery got.
const rest = restOf(nowCurated, chosen, flags);
const when = new Map(photos.map((p) => [p.id, p.capturedAt]));
const rest = takenHere(restOf(nowCurated, chosen, flags), when, event);
if (restTarget && rest.length && this.deps.deliveries && event.createdById) {
await this.deps.deliveries
.enqueue({ organizationId: event.organizationId, targetId: restTarget, photoIds: rest, again: false, requestedById: event.createdById })
.catch((err: unknown) => log.warn({ err }, "autopilot: delivery to the second client not queued"));
}
const gallery = takenHere([...chosen], when, event);
chosenCount += chosen.size;
if (chosen.size && settings.deliverTargetId && this.deps.deliveries && event.createdById) {
if (gallery.length && settings.deliverTargetId && this.deps.deliveries && event.createdById) {
await this.deps.deliveries
.enqueue({ organizationId: event.organizationId, targetId: settings.deliverTargetId, photoIds: [...chosen], again: false, requestedById: event.createdById })
.enqueue({ organizationId: event.organizationId, targetId: settings.deliverTargetId, photoIds: gallery, again: false, requestedById: event.createdById })
.catch((err: unknown) => log.warn({ err }, "autopilot: delivery not queued"));
}
if (d.window >= 0) log.info({ eventId, window: d.window, candidates: d.ids.length, chosen: chosen.size }, "autopilot: best of the window");
+36 -1
View File
@@ -274,6 +274,28 @@ export class DeliveryService {
private editsCheckedAt = 0;
/**
* Deliveries still on a destination whose photo was rejected without going through the library PATCH (a direct
* DB update, an emergency script): queue them for removal. Un-picked (NONE) photos are not swept here — a
* destination may have been given a non-pick on purpose; only the library PATCH (PICK → NONE) retracts those.
*/
async queueOrphanRetracts(): Promise<number> {
const rows = await this.deps.db.$queryRaw<{ id: string; organization_id: string }[]>`
UPDATE delivery_items di SET status = 'QUEUED', retract = true, attempts = 0, next_attempt_at = now(),
last_error = NULL, finished_at = NULL, updated_at = now()
FROM photos p
WHERE p.id = di.photo_id
AND di.status IN ('DONE', 'WAITING') AND di.retract = false
AND p.flag = 'REJECT'
RETURNING di.id, di.organization_id`;
for (const r of rows) {
const item = await this.deps.db.deliveryItem.findUnique({ where: { id: r.id } });
if (item) this.deps.broadcaster.library(item.organizationId, { type: "delivery.updated", item: toItemSummary(item) });
}
if (rows.length) this.deps.log.info({ count: rows.length }, "delivery: rejected photos still on a destination, taken back");
return rows.length;
}
/**
* Delivered photos edited again since (a crop put right, a colour fixed), once the edits have paused for a
* minute: sent again to where they went, with the same name (a file is replaced; on ZeroZero the new one goes up
@@ -321,10 +343,11 @@ export class DeliveryService {
/** Atomically takes up to `limit` due items (safe with several workers). */
async claim(limit: number): Promise<string[]> {
// Every half minute: delivered photos edited again join the queue.
// Every half minute: edited re-sends and rejected photos left on a destination join the queue.
if (Date.now() - this.editsCheckedAt > 30_000) {
this.editsCheckedAt = Date.now();
await this.queueEdited().catch((err) => this.deps.log.warn({ err }, "delivery: edited photos not checked"));
await this.queueOrphanRetracts().catch((err) => this.deps.log.warn({ err }, "delivery: orphan retracts not checked"));
}
if (limit <= 0) return [];
const rows = await this.deps.db.$queryRaw<{ id: string }[]>`
@@ -424,6 +447,18 @@ export class DeliveryService {
this.deps.broadcaster.library(saved.organizationId, { type: "delivery.updated", item: toItemSummary(saved) });
return saved;
}
// Rejected after this item was queued (or a flag flip that skipped retractPhotos): never upload; the next claim
// removes anything already on the destination.
if (item.photo.flag === "REJECT") {
const saved = await db.deliveryItem.update({
where: { id: itemId },
data: item.remotePath || item.target.kind === "LOCAL"
? { status: "QUEUED", retract: true, attempts: Math.max(0, item.attempts - 1), nextAttemptAt: new Date(), lastError: null, finishedAt: null }
: { status: "RETRACTED", retract: false, finishedAt: new Date() },
});
this.deps.broadcaster.library(saved.organizationId, { type: "delivery.updated", item: toItemSummary(saved) });
return saved;
}
let update: Partial<DeliveryItem>;
// The players' names come from the faces (who is where, face and shirt number): give their reading a moment,
// so a photo does not leave without names. Waiting does not count as an attempt.
+50 -28
View File
@@ -62,6 +62,27 @@ export function newer(candidate: string, current: string): boolean {
/** The full installer a person downloads and opens, per platform. */
const INSTALLER: Record<string, RegExp> = { darwin: /\.dmg$/, windows: /\.msi$|-setup\.exe$/, linux: /\.AppImage$/ };
/** Version embedded in a Tauri minisign trusted comment, if any (`file:…\tversion:X.Y.Z`). */
export function signedVersion(signature: string): string | null {
for (const line of signature.split(/\r?\n/)) {
let raw: Buffer;
try {
raw = Buffer.from(line, "base64");
} catch {
continue;
}
const text = raw.toString("utf8");
const m = /\bversion:([0-9]+\.[0-9]+\.[0-9]+(?:[-.+][\w.-]+)?)/.exec(text);
if (m) return m[1]!;
}
return null;
}
/** Newest asset with this name (Gitea keeps duplicates when a tag is rebuilt). */
function latestAsset(assets: GiteaAsset[], name: string): GiteaAsset | undefined {
return assets.filter((a) => a.name === name).sort((a, b) => b.id - a.id)[0];
}
export class DesktopReleases {
private cache: { at: number; releases: GiteaRelease[] } | null = null;
@@ -85,17 +106,6 @@ export class DesktopReleases {
return all;
}
/** The newest release that has this platform's update (a newer one may still be building, or wait for its Mac). */
private async forPlatform(target: string, arch: string): Promise<{ release: GiteaRelease; manifest: GiteaAsset } | null> {
// Universal macOS builds serve both Apple chips.
const names = [`update-${target}-${arch}.json`, ...(target === "darwin" ? ["update-darwin-universal.json"] : [])];
for (const release of await this.releases()) {
const manifest = names.map((n) => release.assets.find((a) => a.name === n)).find(Boolean);
if (manifest) return { release, manifest };
}
return null;
}
private async download(asset: GiteaAsset): Promise<Response> {
const res = await this.fetchImpl(asset.browser_download_url, { headers: { authorization: `token ${this.config.token}` } });
if (!res.ok) throw new Error(`gitea asset ${asset.name}: ${res.status}`);
@@ -111,28 +121,34 @@ export class DesktopReleases {
arch: string,
current: string,
): Promise<{ version: string; notes: string; pub_date?: string; url: string; signature: string; installer?: string } | null> {
const found = await this.forPlatform(target, arch);
if (!found) return null;
const { release } = found;
const manifest = Manifest.parse(await (await this.download(found.manifest)).json());
if (!newer(manifest.version, current)) return null;
if (!release.assets.some((a) => a.name === manifest.file)) return null;
const installer = release.assets.find((a) => INSTALLER[target]?.test(a.name));
return {
version: manifest.version,
notes: manifest.notes ?? release.body ?? "",
...(manifest.pub_date ?? release.published_at ? { pub_date: (manifest.pub_date ?? release.published_at)! } : {}),
url: `/v1/desktop/download/${release.id}/${encodeURIComponent(manifest.file)}`,
signature: manifest.signature,
...(installer ? { installer: `/v1/desktop/download/${release.id}/${encodeURIComponent(installer.name)}` } : {}),
};
// Walk newest → older: a release whose manifest/signature disagree (re-tagged build) is skipped.
const names = [`update-${target}-${arch}.json`, ...(target === "darwin" ? ["update-darwin-universal.json"] : [])];
for (const release of await this.releases()) {
const manifestAsset = names.map((n) => latestAsset(release.assets, n)).find(Boolean);
if (!manifestAsset) continue;
const manifest = Manifest.parse(await (await this.download(manifestAsset)).json());
if (!newer(manifest.version, current)) return null;
const signed = signedVersion(manifest.signature);
if (signed && signed !== manifest.version) continue;
if (!latestAsset(release.assets, manifest.file)) continue;
const installer = [...release.assets].filter((a) => INSTALLER[target]?.test(a.name)).sort((a, b) => b.id - a.id)[0];
return {
version: manifest.version,
notes: manifest.notes ?? release.body ?? "",
...(manifest.pub_date ?? release.published_at ? { pub_date: (manifest.pub_date ?? release.published_at)! } : {}),
url: `/v1/desktop/download/${release.id}/${encodeURIComponent(manifest.file)}`,
signature: manifest.signature,
...(installer ? { installer: `/v1/desktop/download/${release.id}/${encodeURIComponent(installer.name)}` } : {}),
};
}
return null;
}
/** The installer itself, streamed from a desktop release. */
async file(releaseId: number, name: string): Promise<{ body: Readable; size: string | null } | null> {
const release = (await this.releases()).find((r) => r.id === releaseId);
if (!release) return null;
const asset = release.assets.find((a) => a.name === name);
const asset = latestAsset(release.assets, name);
if (!asset || /\.json$/.test(name)) return null;
const res = await this.download(asset);
if (!res.body) return null;
@@ -165,7 +181,13 @@ export async function registerDesktopRoutes(app: FastifyInstance, deps: { releas
app.get("/v1/desktop/download/:releaseId/:name", async (req, reply) => {
const { releaseId, name } = z.object({ releaseId: z.coerce.number().int().positive(), name: z.string().min(1).max(200) }).parse(req.params);
const file = releases ? await releases.file(releaseId, name) : null;
let file: { body: Readable; size: string | null } | null;
try {
file = releases ? await releases.file(releaseId, name) : null;
} catch (err) {
req.log.warn({ err }, "desktop download failed");
return reply.code(503).send({ error: "download_unavailable" });
}
if (!file) return reply.code(404).send({ error: "not_found" });
if (file.size) reply.header("content-length", file.size);
return reply.header("content-type", "application/octet-stream").header("content-disposition", `attachment; filename="${name.replace(/[^\w.-]+/g, "_")}"`).send(file.body);
+1
View File
@@ -180,6 +180,7 @@ export class FaceLookup {
/ NULLIF(sqrt((SELECT sum(a * a) FROM unnest(p.centroid) AS u(a))), 0) AS score
FROM people p
WHERE p.organization_id = ${orgId}::uuid AND p.model = ${model} AND cardinality(p.centroid) = ${embedding.length}
AND p.recognition_off_at IS NULL
AND (${only}::uuid[] IS NULL OR p.id = ANY(${only}::uuid[]))
) s
WHERE score >= ${match - POSSIBLE_BELOW}
+11
View File
@@ -116,9 +116,20 @@ export async function registerPhotoRoutes(
: patch.flag === "NONE"
? (await db.photo.findMany({ where: { id: { in: ids }, organizationId: orgId, flag: "PICK" }, select: { id: true } })).map((p) => p.id)
: [];
// Leaving an event: files already sent in that event's folders come back. The new event sends its own, if it does.
const leaving =
patch.eventId !== undefined
? (
await db.photo.findMany({
where: { id: { in: ids }, organizationId: orgId, ...(patch.eventId === null ? { eventId: { not: null } } : { NOT: { eventId: patch.eventId } }) },
select: { id: true },
})
).map((p) => p.id)
: [];
const result = await db.photo.updateMany({ where: { id: { in: ids }, organizationId: orgId }, data });
if (result.count !== ids.length) throw notFound("photo_not_found");
if (retractIds.length) await retractPhotos(db, orgId, retractIds);
if (leaving.length) await retractPhotos(db, orgId, leaving);
// Moved to another event: arrival names, faces and the autopilot follow it.
if (patch.eventId) await joinedEvent(db, patch.eventId, ids);
broadcaster.library(orgId, { type: "photo.updated", ids, patch });
+147 -2
View File
@@ -344,8 +344,9 @@ const FPA_GAME_OFFICIAL: [RegExp, string][] = [
/**
* The FPA's public pages, the same the portal links to: the agenda (JSON), a club's games of a season and level
* (JSON), the match report ("Boletim do Jogo": every player with shirt number and licence number, the bench officials
* with their letter, the referees), a match page (the referees, published before the match) and an athlete's page
* (the licence photo). Asked for sparingly and cached in the database.
* with their letter, the referees), a match page (the referees, published before the match), a club's full register
* (`getCipClubeEpoca`: every associate with licence and photo) and an athlete's page (the licence photo). Asked for
* sparingly and cached in the database. Shared shape with ehf-stats / livereport (`WsFpa.clubAssociates`).
*/
export class FpaProvider {
static readonly AGENDA = "https://ws.fpa.pt/index.php/getAgendaJogosFAP/";
@@ -421,11 +422,155 @@ export class FpaProvider {
return parseFpaMatchPage(await this.html(`${FpaProvider.PORTAL}/jogo/${encodeURIComponent(gameId)}/`));
}
/**
* Someone registered with the federation, by licence number (CIPA, as printed on match reports and the portal):
* name, licence photo and every registration (season, as what, where). The portal's page gives the federation's
* internal id, which the registrations are kept under (it is not the licence number). Null when unknown.
*/
async member(licence: string): Promise<FpaMember | null> {
if (!/^\d{1,9}$/.test(licence)) return null;
const page = parseFpaMemberPage(await this.html(`${FpaProvider.PORTAL}/associado/${encodeURIComponent(licence)}/`));
if (!page) return null;
let registrations: FpaRegistration[] = [];
if (page.internalId) {
const rows = await get(this.fetcher, `${FpaProvider.WS}/getCipaInscricoes/${encodeURIComponent(page.internalId)}`, { accept: "application/json" }, "json");
if (Array.isArray(rows)) registrations = (rows as Record<string, unknown>[]).map(fpaRegistration).filter((r): r is FpaRegistration => !!r);
}
return { ...page, licence, registrations };
}
/** An athlete's licence photo (by licence number), if the federation has one. */
async athletePhoto(cipa: string): Promise<string | null> {
const html = await this.html(`${FpaProvider.PORTAL}/associado/${encodeURIComponent(cipa)}/`);
return /https:\/\/si\.fpa\.pt\/blob\/obj_anexo\/FOTO_CIPA\/\d+_\d+\.(?:jpe?g|png)/i.exec(html)?.[0] ?? null;
}
/**
* Everyone registered at a club for a season (athletes, coaches, officials, referees), with licence number and
* licence photo when the federation has one. This is the club register — not only the people named on a match
* sheet. Season ids are the portal's (`373` = 2025/26); see `fpaEpochFor`.
*/
async clubAssociates(clubId: string, seasonId: string): Promise<FpaClubAssociate[]> {
if (!/^\d+$/.test(clubId) || !/^\d+$/.test(seasonId)) return [];
const path = ["getCipClubeEpoca", clubId, seasonId].map(encodeURIComponent).join("/");
const rows = await get(this.fetcher, `${FpaProvider.WS}/${path}`, { accept: "application/json" }, "json");
await this.pause();
if (!Array.isArray(rows)) return [];
const out: FpaClubAssociate[] = [];
const seen = new Set<string>();
for (const raw of rows as Record<string, unknown>[]) {
const a = fpaClubAssociate(raw);
if (!a || seen.has(a.licence)) continue;
seen.add(a.licence);
out.push(a);
}
return out;
}
}
/** Someone on a club's FPA register for a season (from `getCipClubeEpoca`). */
export interface FpaClubAssociate {
licence: string;
/** Federation internal id (portal history); not the printed CIPA. */
internalId: string | null;
name: string;
photo: string | null;
kind: "athlete" | "coach" | "official" | "referee" | "other";
}
/** Handball seasons start in August; portal epoch ids advance one per year (2025/26 = 373). */
export function fpaEpochFor(date: Date = new Date()): string {
const year = date.getUTCFullYear();
const start = date.getUTCMonth() >= 7 ? year : year - 1;
return String(start - 1652);
}
function fpaClubAssociate(r: Record<string, unknown>): FpaClubAssociate | null {
const licence = String(r.CIP_NUMERO ?? "").trim().replace(/\.0+$/, "");
const name = cellText(String(r.CIP_NOME ?? ""));
if (!/^\d{1,9}$/.test(licence) || !name) return null;
const photo = str(r.URL_FOTO);
const kind: FpaClubAssociate["kind"] =
String(r.ATLETA ?? "").toUpperCase() === "S"
? "athlete"
: String(r.TECNICO ?? "").toUpperCase() === "S"
? "coach"
: String(r.OFICIAL ?? "").toUpperCase() === "S"
? "official"
: String(r.ARBITRO ?? "").toUpperCase() === "S"
? "referee"
: "other";
return {
licence,
internalId: str(r.ID_CIPA),
name,
photo: photo && /^https:\/\/si\.fpa\.pt\//i.test(photo) ? photo : null,
kind,
};
}
/** A registration of a member for one season: athlete, coach, official, table official or referee. */
export interface FpaRegistration {
season: string;
kind: "athlete" | "coach" | "official" | "table" | "referee" | "other";
/** "Atleta", "Treinador", "Delegado técnico", "Árbitro regional"... */
role: string;
/** The club or team ("AA AVANCA", "Sel.Nac.M"); null for referees. */
club: string | null;
clubName: string | null;
/** The age level for athletes ("Juvenis F"). */
level: string | null;
association: string | null;
}
export interface FpaMember {
licence: string;
internalId: string | null;
name: string;
photo: string | null;
/** "Árbitro, Oficial, Técnico, Atleta", as the portal says. */
registeredAs: string | null;
registrations: FpaRegistration[];
}
const FPA_KINDS: Record<string, FpaRegistration["kind"]> = { AT01: "athlete", TEC: "coach", OFI: "official", OMS: "table", ARB: "referee" };
function fpaRegistration(r: Record<string, unknown>): FpaRegistration | null {
const season = str(r.EPO_DESCRICAO);
if (!season) return null;
const code = str(r.GCI_TIP_INSCRICAO_TI013) ?? "";
const kind = FPA_KINDS[code] ?? (code.startsWith("AT") ? "athlete" : "other");
const detail = str(r.FOF_ABREV) ?? str(r.CJU_ABREV);
const role =
kind === "athlete" ? "Atleta" : kind === "coach" ? "Treinador" : kind === "table" ? "Oficial de mesa" : kind === "referee" ? (detail ?? "Árbitro") : (detail ? detail.charAt(0) + detail.slice(1).toLowerCase() : "Oficial");
return { season, kind, role: fpaAccents(role), club: str(r.CLU_ABREV), clubName: str(r.CLU_NOME), level: str(r.ESC_DESCRICAO), association: str(r.ASS_ABREV) };
}
/** The federation's codes are written without accents ("Delegado tecnico", "Funcionario"). */
function fpaAccents(s: string): string {
const fix: Record<string, string> = { tecnico: "técnico", tecnica: "técnica", funcionario: "funcionário", medico: "médico", fisioterapeuta: "fisioterapeuta", seccionista: "seccionista", estagiario: "estagiário", arb: "Árb" };
return s.replace(/\p{L}+/gu, (w) => {
const f = fix[w.toLowerCase()];
if (!f) return w;
return w[0] === w[0]!.toUpperCase() ? f[0]!.toUpperCase() + f.slice(1) : f;
});
}
/** A member's page on the portal: name, photo, the internal id its history is under. Null for an unknown licence. */
export function parseFpaMemberPage(html: string): Omit<FpaMember, "licence" | "registrations"> | null {
const $ = cheerio.load(html);
const box = $(".association-detail");
const name = box.find("h3").first().text().replace(/\s+/g, " ").trim();
if (!box.length || !name) return null;
let registeredAs: string | null = null;
box.find("tr").each((_, tr) => {
const cells = $(tr).children("td");
if (/inscrito como/i.test(cells.first().text())) registeredAs = cells.eq(1).text().replace(/\s+/g, " ").trim() || null;
});
const photo = box.find("img").attr("src") ?? null;
// The history table's settings carry the internal id ("cipa":"203445"); the photo's file name ends with it too.
const internalId = /TABLE_CONTENT_\d+\s*=\s*\{[^;]*?"cipa"\s*:\s*"(\d+)"/.exec(html)?.[1] ?? /FOTO_CIPA\/\d+_(\d+)\./i.exec(photo ?? "")?.[1] ?? null;
return { name, photo: photo && /^https:\/\/si\.fpa\.pt\//.test(photo) ? photo : null, registeredAs, internalId };
}
export interface FpaBoletim {
+183
View File
@@ -14,7 +14,12 @@ import { tallyOf, tallySquadPhotos } from "./squadPhotos.js";
import {
type Fetch,
type FixtureData,
type FpaClubAssociate,
type FpaMember,
FpaProvider,
type FpaRegistration,
fpaEpochFor,
fpaShortName,
FpfProvider,
LIGA_COMPETITIONS,
type LigaClubCompetition,
@@ -60,6 +65,13 @@ const FPA_REPORTS_PER_REFRESH = 30;
const FPA_RETRY_MS = 3 * 86400_000;
/** Reports read before licence numbers were kept, read again per refresh until none are left. */
const FPA_REREADS_PER_REFRESH = 40;
/**
* Clubs whose full FPA register (every associate with a licence photo) is pulled per refresh — not only the people
* on match sheets. Covers coaches, officials, youth and anyone else the federation lists for the club.
*/
const FPA_ASSOCIATE_CLUBS_PER_REFRESH = 12;
/** Skip a club's register again until this long has passed (the list changes slowly). */
const FPA_ASSOCIATE_RETRY_MS = 7 * 86400_000;
/** The handball referees and table officials, kept as one "team" so their licence (and photo) is known by name. */
const FPA_REFEREES_TEAM = { externalId: "ARBITRAGEM", name: REFEREES };
/** Officials of the game who become people of an event (faces to name): on the pitch, and at the table. */
@@ -505,6 +517,7 @@ export class SportsService {
}
await this.fpaSquads(fixtures, now, result);
await this.fpaReferees(now, result);
await this.fpaAssociates(fixtures, now, result);
if (result.errors.length) log.warn({ errors: result.errors.slice(0, 10) }, "sports: fpa refresh had errors");
log.info({ ...result, errors: result.errors.length }, "sports: fpa refreshed");
return result;
@@ -513,6 +526,15 @@ export class SportsService {
private readonly fpaTried = new Map<string, number>();
/** Reports read again for licence numbers (once each: some list none). */
private readonly fpaReread = new Set<string>();
/** Last time a club's full associate register was pulled. */
private readonly fpaAssociateAt = new Map<string, number>();
/** Clears in-memory FPA retry clocks (tests after a DB reset; production keeps them for the process). */
resetFpaClocks(): void {
this.fpaTried.clear();
this.fpaReread.clear();
this.fpaAssociateAt.clear();
}
private fpaCompetition(f: FixtureData): Promise<SportsCompetition> {
return this.deps.db.sportsCompetition.upsert({
@@ -1176,6 +1198,9 @@ export class SportsService {
const { db, log } = this.deps;
let person = await db.person.findUnique({ where: { organizationId_sportsPlayerId: { organizationId: orgId, sportsPlayerId: p.id } } });
let created = false;
// Handball: someone added by their licence number is the same person on the match report.
if (!person && team.provider === "FPA" && p.externalId)
person = await db.person.findFirst({ where: { organizationId: orgId, licence: p.externalId, sportsPlayerId: null } });
if (!person) person = await this.personForIdentity(orgId, p);
if (!person) {
const byName = await db.person.findUnique({ where: { organizationId_name: { organizationId: orgId, name: p.name } } });
@@ -1219,6 +1244,147 @@ export class SportsService {
if (photo && !person.referenceKey) headshots.push({ personId: person.id, url: photo });
}
/**
* A person from their handball federation licence (CIPA): the name, club and role of their latest registration,
* and (with biometrics on) the licence photo as the reference, so they are recognised in event photos too (a
* coach, a delegate, a former player), not only where a match report names them. The same licence is always the
* same person: one already added, or seen on a match report, is brought up to date instead.
*/
async personFromFpaLicence(orgId: string, licence: string): Promise<{ person: { id: string; name: string; club: string | null }; member: FpaMember; created: boolean; reference: boolean }> {
const { db, log } = this.deps;
const member = await this.fpa.member(licence.trim());
if (!member) throw notFound("fpa_member_not_found");
const org = await db.organization.findUnique({ where: { id: orgId }, select: { biometricsEnabled: true } });
if (!org) throw notFound("organization_not_found");
const latest = fpaLatestRole(member);
const club = latest?.club ?? null;
let person = await db.person.findUnique({ where: { organizationId_licence: { organizationId: orgId, licence: member.licence } } });
if (!person) {
// Seen on a match report: the squad entry with this licence.
const players = await db.sportsPlayer.findMany({ where: { externalId: member.licence, team: { provider: "FPA" } }, select: { id: true } });
if (players.length) person = await db.person.findFirst({ where: { organizationId: orgId, sportsPlayerId: { in: players.map((p) => p.id) }, licence: null } });
}
let created = false;
if (!person) {
const short = fpaShortName(member.name);
const same = await db.person.findUnique({ where: { organizationId_name: { organizationId: orgId, name: short } } });
// A name taken by someone else: the full name, and if that is taken too (by another licence), the licence
// number — guaranteed free — tells the two apart for sure.
let name = !same ? short : member.name;
let other = same ? await db.person.findUnique({ where: { organizationId_name: { organizationId: orgId, name } } }) : null;
if (other && other.licence && other.licence !== member.licence) {
name = `${member.name} (${member.licence})`;
other = await db.person.findUnique({ where: { organizationId_name: { organizationId: orgId, name } } });
}
person = other ?? (await db.person.create({ data: { organizationId: orgId, name, club, licence: member.licence } }));
created = !other;
}
if (person.licence !== member.licence || (!person.club && club)) {
person = await db.person.update({ where: { id: person.id }, data: { licence: member.licence, ...(!person.club && club && { club }) } });
}
let reference = false;
if (org.biometricsEnabled && member.photo && !person.referenceKey && !person.recognitionOffAt) {
try {
reference = await this.saveHeadshot(orgId, person.id, member.photo);
} catch (err) {
log.warn({ err, licence: member.licence }, "sports: fpa licence photo failed");
}
}
return { person: { id: person.id, name: person.name, club: person.club }, member, created, reference };
}
/**
* Full FPA club registers into people (every associate the federation lists for the club this season, with
* licence photo). Match sheets alone miss coaches, officials, youth and anyone not on a boletim — this closes
* that gap for face search. Clubs come from the agenda; a few per refresh, then again after a week.
*/
private async fpaAssociates(agenda: FixtureData[], now: Date, result: RefreshResult): Promise<void> {
const { db, log } = this.deps;
const clubIds = [...new Set(agenda.flatMap((f) => [f.home.clubId, f.away.clubId]).filter((id): id is string => !!id && /^\d+$/.test(id)))];
const due = clubIds.filter((id) => {
const at = this.fpaAssociateAt.get(id);
return !at || now.getTime() - at >= FPA_ASSOCIATE_RETRY_MS;
});
if (!due.length) return;
const orgs = await db.organization.findMany({ where: { biometricsEnabled: true }, select: { id: true } });
if (!orgs.length) return;
const epoch = fpaEpochFor(now);
let clubs = 0;
for (const clubId of due) {
if (clubs >= FPA_ASSOCIATE_CLUBS_PER_REFRESH) break;
clubs++;
this.fpaAssociateAt.set(clubId, now.getTime());
let associates: FpaClubAssociate[];
try {
associates = await this.fpa.clubAssociates(clubId, epoch);
} catch (err) {
result.errors.push(`fpa associates ${clubId}: ${(err as Error).message}`);
continue;
}
if (!associates.length) continue;
for (const org of orgs) {
for (const a of associates) {
try {
const done = await this.personFromFpaAssociate(org.id, a);
if (done.created) result.players++;
} catch (err) {
log.warn({ err, licence: a.licence, org: org.id }, "sports: fpa associate failed");
}
}
}
log.info({ clubId, associates: associates.length, orgs: orgs.length }, "sports: fpa club register");
}
}
/**
* Someone from a club's FPA register row (licence + name + photo already known — no second portal hit).
* Same person as `personFromFpaLicence` when the licence matches.
*/
async personFromFpaAssociate(
orgId: string,
a: FpaClubAssociate,
clubName: string | null = null,
): Promise<{ person: { id: string; name: string; club: string | null }; created: boolean; reference: boolean }> {
const { db, log } = this.deps;
const org = await db.organization.findUnique({ where: { id: orgId }, select: { biometricsEnabled: true } });
if (!org) throw notFound("organization_not_found");
let person = await db.person.findUnique({ where: { organizationId_licence: { organizationId: orgId, licence: a.licence } } });
if (!person) {
const players = await db.sportsPlayer.findMany({ where: { externalId: a.licence, team: { provider: "FPA" } }, select: { id: true } });
if (players.length) person = await db.person.findFirst({ where: { organizationId: orgId, sportsPlayerId: { in: players.map((p) => p.id) }, licence: null } });
}
let created = false;
if (!person) {
const short = fpaShortName(a.name);
const same = await db.person.findUnique({ where: { organizationId_name: { organizationId: orgId, name: short } } });
// A name taken by someone else: the full name, and if that is taken too (by another licence), the licence
// number — guaranteed free — tells the two apart for sure.
let name = !same ? short : a.name;
let other = same ? await db.person.findUnique({ where: { organizationId_name: { organizationId: orgId, name } } }) : null;
if (other && other.licence && other.licence !== a.licence) {
name = `${a.name} (${a.licence})`;
other = await db.person.findUnique({ where: { organizationId_name: { organizationId: orgId, name } } });
}
person = other ?? (await db.person.create({ data: { organizationId: orgId, name, club: clubName, licence: a.licence } }));
created = !other;
}
if (person.licence !== a.licence || (!person.club && clubName)) {
person = await db.person.update({
where: { id: person.id },
data: { licence: a.licence, ...(!person.club && clubName ? { club: clubName } : {}) },
});
}
let reference = false;
if (org.biometricsEnabled && a.photo && !person.referenceKey && !person.recognitionOffAt) {
try {
reference = await this.saveHeadshot(orgId, person.id, a.photo);
} catch (err) {
log.warn({ err, licence: a.licence }, "sports: fpa associate photo failed");
}
}
return { person: { id: person.id, name: person.name, club: person.club }, created, reference };
}
/** The person already created for this human at another club or in another season. */
private async personForIdentity(orgId: string, p: SportsPlayer) {
const match: ({ externalId: string } | { birthDate: string; fullName: string })[] = [];
@@ -1483,3 +1649,20 @@ export class SportsWorker {
if (!drained) this.opts.log.warn({}, "sports: stop timed out with work still running");
}
}
/** The role a member is best known by now: the latest season's, a player or coach before an official. */
export function fpaLatestRole(member: FpaMember): { season: string; role: string; club: string | null } | null {
const order: FpaRegistration["kind"][] = ["athlete", "coach", "official", "table", "referee", "other"];
const regs = [...member.registrations].sort((a, b) => b.season.localeCompare(a.season) || order.indexOf(a.kind) - order.indexOf(b.kind) || Number(a.club === "F.A.P.") - Number(b.club === "F.A.P."));
const r = regs[0];
if (!r) return null;
return { season: r.season, role: r.role, club: r.clubName ? fpaClubName(r.clubName) : r.club };
}
/** "Estarreja Andebol Clube" as is; "Selecções Nacionais Masculinas" → "Seleção Nacional Masculina"; capitals fixed. */
export function fpaClubName(name: string): string {
const sel = /^selec[cç][oõ]es nacionais (masculinas|femininas)/i.exec(name);
if (sel) return `Seleção Nacional ${sel[1]!.toLowerCase().startsWith("m") ? "Masculina" : "Feminina"}`;
if (/^federa[cç]ao andebol portugal$/i.test(name)) return "Federação de Andebol de Portugal";
return name === name.toUpperCase() ? name.toLowerCase().replace(/(^|\s)\p{L}/gu, (m) => m.toUpperCase()) : name;
}
+121 -3
View File
@@ -10,6 +10,7 @@ import { canonicalTeam, describeFolder, directorySides, exhibitionName, galleryR
import { CloudClient, parseMultistatus } from "../src/archive/nextcloud.js";
import { ArchiveService, localDirs } from "../src/archive/service.js";
import { FaceService } from "../src/faces/service.js";
import { normalize } from "../src/faces/math.js";
import type { FaceAnalysis, FaceEngine } from "../src/faces/process.js";
import { execFileSync } from "node:child_process";
import { SecretBox } from "../src/delivery/secrets.js";
@@ -18,6 +19,24 @@ import { MemoryBroadcaster } from "../src/realtime.js";
import { LocalStorage, UrlSigner } from "../src/storage/storage.js";
import { bearer, createTestApp, login, resetDb, seedUser, type TestContext } from "./helpers.js";
/** Face for archive search-by-photo tests: a fixed direction plus optional noise. */
function faceVec(seed: number, noise = 0): number[] {
const rand = (k: number) => {
const x = Math.sin(k * 127.1 + 311.7) * 43758.5453;
return (x - Math.floor(x)) * 2 - 1;
};
return normalize(Array.from({ length: 64 }, (_, i) => rand(seed * 1000 + i) + (noise ? rand(noise * 7919 + i) * 0.15 : 0)));
}
class FindEngine implements FaceEngine {
readonly model = "auraface-v1";
next: FaceAnalysis = { width: 800, height: 1000, faces: [] };
async analyse(): Promise<FaceAnalysis> {
return this.next;
}
async close(): Promise<void> {}
}
const KEY = Buffer.alloc(32, 7).toString("base64");
const quiet = { info: () => {}, warn: () => {} };
@@ -553,12 +572,24 @@ describe("archive from a Nextcloud", () => {
let orgId: string;
let ownerId: string;
let worker: ArchiveService;
const findEngine = new FindEngine();
const fetchProxy: typeof fetch = (input, init) => cloud.fetch(input, init);
// The cloud, and the handball federation's portal for a licence lookup.
const fetchProxy: typeof fetch = (input, init) => {
const u = new URL(typeof input === "string" ? input : input instanceof URL ? input.href : input.url);
if (u.host === "portal.fpa.pt")
return Promise.resolve(
u.pathname === "/associado/198159/"
? new Response('<div class="association-detail"><h3>Maria Ema Bastos Silva</h3><img src="https://si.fpa.pt/blob/obj_anexo/FOTO_CIPA/1_203445.JPG"></div><script>var TABLE_CONTENT_1 = {"cipa":"203445"};</script>', { headers: { "content-type": "text/html" } })
: new Response("<html></html>", { headers: { "content-type": "text/html" } }),
);
if (u.host === "ws.fpa.pt") return Promise.resolve(Response.json([{ EPO_DESCRICAO: "2024/25", GCI_TIP_INSCRICAO_TI013: "TEC", CLU_ABREV: "ESTARREJA AC", CLU_NOME: "Estarreja Andebol Clube" }]));
return cloud.fetch(input, init);
};
beforeAll(async () => {
storageRoot = await mkdtemp(path.join(tmpdir(), "pr-archive-test-"));
ctx = await createTestApp({ DELIVERY_SECRET_KEY: KEY, STORAGE_ROOT: storageRoot }, undefined, fetchProxy);
ctx = await createTestApp({ DELIVERY_SECRET_KEY: KEY, STORAGE_ROOT: storageRoot }, undefined, fetchProxy, undefined, findEngine);
});
afterAll(async () => {
await ctx.app.close();
@@ -1120,6 +1151,17 @@ describe("archive from a Nextcloud", () => {
const scoped = res.json() as { gallery: { id: string; title: string } | null; counts: Record<string, number> };
expect(scoped.gallery?.id).toBe(gid);
expect(scoped.counts.suggested).toBe(2);
// Handball archives: a licence number nobody has yet is looked up at the federation, and the person added.
await ctx.db.cloudSource.update({ where: { id: source.id }, data: { look: "fpa" } });
res = await ctx.app.inject({ method: "GET", url: `/v1/archive/${source.id}/people/search?q=198159`, headers: as(editor) });
expect(res.json()).toMatchObject({ people: [], fpa: { licence: "198159", name: "Maria Ema Bastos Silva", club: "Estarreja Andebol Clube", role: "Treinador · 2024/25" } });
res = await ctx.app.inject({ method: "POST", url: `/v1/archive/${source.id}/people/from-licence`, headers: as(reader), payload: { licence: "198159" } });
expect(res.statusCode).toBe(403);
res = await ctx.app.inject({ method: "POST", url: `/v1/archive/${source.id}/people/from-licence`, headers: as(editor), payload: { licence: "198159" } });
expect(res.json()).toMatchObject({ created: true, person: { name: "Maria Silva", club: "Estarreja Andebol Clube", licence: "198159" } });
res = await ctx.app.inject({ method: "GET", url: `/v1/archive/${source.id}/people/search?q=198159`, headers: as(editor) });
expect(res.json().fpa).toBeUndefined();
expect(res.json().people).toMatchObject([{ name: "Maria Silva", licence: "198159" }]);
// "Juntar nomes" is for those who edit everything.
res = await ctx.app.inject({ method: "POST", url: `/v1/archive/${source.id}/clubs/merge`, headers: as(editor), payload: { into: "Sporting CP", names: ["Sporting"] } });
expect(res.statusCode).toBe(403);
@@ -1341,11 +1383,87 @@ describe("archive from a Nextcloud", () => {
expect(photos.every((f) => f.photo?.eventId === fixed.eventId)).toBe(true);
});
it("lets cloud editors search the archive by a photo when the option is on", async () => {
await ctx.db.organization.update({ where: { id: orgId }, data: { biometricsEnabled: true, biometricsLegalBasis: "teste" } });
const source = await connect();
cloud.authorised = true;
await ctx.app.inject({ method: "GET", url: `/v1/cloud-sources/${source.id}`, headers: bearer(token) });
await worker.scan(source.id);
for (const id of await worker.claim(10)) await worker.index(id);
const photo = await ctx.db.photo.findFirstOrThrow({ where: { originalName: "PS_0001.jpg" } });
const martim = await ctx.db.person.create({
data: { organizationId: orgId, name: "Martim Costa", club: "Sporting CP", number: "21", centroid: faceVec(1), model: "auraface-v1" },
});
const group = await ctx.db.faceGroup.create({
data: { organizationId: orgId, eventId: photo.eventId!, centroid: faceVec(1, 2), model: "auraface-v1", size: 1, personId: martim.id },
});
await ctx.db.face.create({
data: {
organizationId: orgId,
photoId: photo.id,
groupId: group.id,
x0: 0.4,
y0: 0.2,
x1: 0.5,
y1: 0.35,
score: 0.9,
sharpness: 120,
embedding: faceVec(1, 3),
model: "auraface-v1",
},
});
const po01 = cloud.idOf("/FPA/Fotos/2025_2026/Competições Nacionais/PO01");
cloud.viewers.set("abc", { password: "abc-pass", shared: [po01], edit: [po01] });
cloud.viewers.set("leitor", { password: "l-pass", shared: [po01] });
const signIn = async (who: string) => {
cloud.loginAs = who;
cloud.authorised = false;
const { state } = (await ctx.app.inject({ method: "POST", url: `/v1/archive/${source.id}/login` })).json() as { state: string };
cloud.authorised = true;
return ((await ctx.app.inject({ method: "POST", url: "/v1/archive/login/poll", payload: { state } })).json() as { token: string }).token;
};
const as = (t: string) => ({ authorization: `Archive ${t}` });
const editor = await signIn("abc");
const reader = await signIn("leitor");
expect((await ctx.app.inject({ method: "GET", url: `/v1/archive/${source.id}/me`, headers: as(editor) })).json()).toMatchObject({ canFind: true, canReview: true });
expect((await ctx.app.inject({ method: "GET", url: `/v1/archive/${source.id}/me`, headers: as(reader) })).json()).toMatchObject({ canFind: false });
const probe = await sharp({ create: { width: 800, height: 1000, channels: 3, background: "#777" } }).jpeg().toBuffer();
const multipart = (data: Buffer) => {
const boundary = "----pr-find";
const head = Buffer.from(`--${boundary}\r\nContent-Disposition: form-data; name="file"; filename="retrato.jpg"\r\nContent-Type: image/jpeg\r\n\r\n`);
return { payload: Buffer.concat([head, data, Buffer.from(`\r\n--${boundary}--\r\n`)]), type: `multipart/form-data; boundary=${boundary}` };
};
findEngine.next = {
width: 800,
height: 1000,
faces: [{ x0: 0.3, y0: 0.2, x1: 0.7, y1: 0.6, score: 0.95, sharpness: 300, landmarks: [], embedding: faceVec(1) }],
};
const mp = multipart(probe);
let res = await ctx.app.inject({ method: "POST", url: `/v1/archive/${source.id}/find`, headers: { ...as(editor), "content-type": mp.type }, payload: mp.payload });
expect(res.statusCode).toBe(200);
const body = res.json() as { people: { name: string }[]; photos: { id: string }[]; total: number };
expect(body.people[0]?.name).toBe("Martim Costa");
expect(body.photos.map((p) => p.id)).toContain(photo.id);
res = await ctx.app.inject({ method: "POST", url: `/v1/archive/${source.id}/find`, headers: { ...as(reader), "content-type": mp.type }, payload: mp.payload });
expect(res.statusCode).toBe(403);
await ctx.app.inject({ method: "PATCH", url: `/v1/cloud-sources/${source.id}`, headers: bearer(token), payload: { photoFindEnabled: false } });
res = await ctx.app.inject({ method: "POST", url: `/v1/archive/${source.id}/find`, headers: { ...as(editor), "content-type": mp.type }, payload: mp.payload });
expect(res.statusCode).toBe(409);
expect(res.json()).toMatchObject({ error: "find_unavailable" });
expect((await ctx.app.inject({ method: "GET", url: `/v1/archive/${source.id}/me`, headers: as(editor) })).json()).toMatchObject({ canFind: false });
});
it("gives the archive's site its owner's look, which can be changed", async () => {
const source = await connect();
cloud.authorised = true;
let res = await ctx.app.inject({ method: "GET", url: `/v1/cloud-sources/${source.id}`, headers: bearer(token) });
expect(res.json()).toMatchObject({ look: "fpa" });
expect(res.json()).toMatchObject({ look: "fpa", photoFindEnabled: true });
expect((await ctx.app.inject({ method: "GET", url: `/v1/archive/${source.id}` })).json()).toMatchObject({ look: "fpa", name: "Cloud FPA" });
res = await ctx.app.inject({ method: "PATCH", url: `/v1/cloud-sources/${source.id}`, headers: bearer(token), payload: { look: "liga" } });
expect(res.json()).toMatchObject({ look: "liga" });
+11 -1
View File
@@ -272,7 +272,14 @@ describe("autopilot", () => {
const fap = "22222222-2222-4222-8222-222222222222";
await ctx.db.event.update({
where: { id: eventId },
data: { startsAt: start, sport: "andebol", createdById: userId, autopilot: { enabled: true, picksPerBurst: 2, selection: "best", bestCount: 16, deliverTargetId: record, restTargetId: fap } },
data: {
startsAt: start,
ingestFrom: new Date(start.getTime() - 2 * 60 * 60 * 1000),
ingestUntil: new Date(start.getTime() + 4 * 60 * 60 * 1000),
sport: "andebol",
createdById: userId,
autopilot: { enabled: true, picksPerBurst: 2, selection: "best", bestCount: 16, deliverTargetId: record, restTargetId: fap },
},
});
const sent: { targetId: string; photoIds: string[] }[] = [];
const deliveries = { enqueue: async (r: { targetId: string; photoIds: string[] }) => void sent.push({ targetId: r.targetId, photoIds: [...r.photoIds] }) };
@@ -282,6 +289,8 @@ describe("autopilot", () => {
const a2 = await shot(orgId, userId, eventId, 60_100, 600);
const b1 = await shot(orgId, userId, eventId, 120_000, 300);
const b2 = await shot(orgId, userId, eventId, 120_100, 200);
// Taken before this event's window, still filed here: not this client's folder.
const later = await shot(orgId, userId, eventId, -3 * 60 * 60 * 1000, 950);
for (let ids = await service.claim(10); ids.length; ids = await service.claim(10)) for (const id of ids) await service.process(id);
await service.decideBursts(new Date(start.getTime() + 7 * 60_000));
const to = (target: string) => sent.filter((x) => x.targetId === target).flatMap((x) => x.photoIds);
@@ -289,6 +298,7 @@ describe("autopilot", () => {
expect(to(record)).toEqual([a2]);
expect(to(fap).sort()).toEqual([a1, b1, b2].sort());
expect(to(record).filter((id) => to(fap).includes(id))).toEqual([]);
expect([...to(record), ...to(fap)]).not.toContain(later);
// Decided once: nothing is sent again.
await service.decideBursts(new Date(start.getTime() + 8 * 60_000));
expect(to(record)).toEqual([a2]);
+6
View File
@@ -571,6 +571,12 @@ describe("delivery", () => {
expect(zz.uploads.get(resent.remotePath!.split("/")[1]!)!.meta.filename).toBe(zz.uploads.get(itemA.remotePath!.split("/")[1]!)!.meta.filename);
expect(await delivery.queueEdited()).toBe(0);
// A reject that bypassed the library PATCH (flag flipped in the DB) is still taken back on the next sweep.
await ctx.db.photo.update({ where: { id: b }, data: { flag: "REJECT" } });
expect(await delivery.queueOrphanRetracts()).toBe(1);
expect(await ctx.db.deliveryItem.findFirstOrThrow({ where: { photoId: b } })).toMatchObject({ status: "QUEUED", retract: true });
expect(await delivery.queueOrphanRetracts()).toBe(0);
// A wrong password stops at once, with the desk's message.
await ctx.app.inject({ method: "PATCH", url: `/v1/orgs/${orgId}/delivery-targets/${targetId}`, headers: bearer(token), payload: { password: "errada" } });
const failed = await ctx.app.inject({ method: "POST", url: `/v1/orgs/${orgId}/delivery-targets/${targetId}/test`, headers: bearer(token) });
+59 -1
View File
@@ -1,5 +1,6 @@
import Fastify from "fastify";
import { describe, expect, it } from "vitest";
import { DesktopReleases, newer } from "../src/desktop/updates.js";
import { DesktopReleases, newer, registerDesktopRoutes, signedVersion } from "../src/desktop/updates.js";
const API = "https://git.example/api/v1/repos/o/r";
@@ -27,6 +28,51 @@ describe("desktop updates", () => {
expect(newer("1.0.0", "1.0.0-beta.2")).toBe(true);
});
it("reads the version Tauri embeds in a signature trusted comment", () => {
const sig = Buffer.from("trusted comment: timestamp:1\tfile:PhotoReport.app.tar.gz\tversion:0.3.24\n").toString("base64");
expect(signedVersion(sig)).toBe("0.3.24");
expect(signedVersion("dW50cnVzdGVkIGNvbW1lbnQ6IHNpZw==")).toBeNull();
});
it("skips a release whose manifest version disagrees with the signature (re-tagged build)", async () => {
const badSig = Buffer.from("trusted comment: timestamp:1\tfile:PhotoReport.app.tar.gz\tversion:0.3.24\n").toString("base64");
const goodSig = Buffer.from("trusted comment: timestamp:2\tfile:PhotoReport.app.tar.gz\tversion:0.3.25\n").toString("base64");
const releases = [
{
id: 20,
tag_name: "desktop-v0.3.25",
draft: false,
prerelease: false,
body: "",
published_at: null,
assets: [asset(1, "update-darwin-universal.json"), asset(2, "PhotoReport.app.tar.gz"), asset(3, "PhotoReport_0.3.24_universal.dmg")],
},
{
id: 19,
tag_name: "desktop-v0.3.24",
draft: false,
prerelease: false,
body: "ok",
published_at: null,
assets: [asset(10, "update-darwin-universal.json"), asset(11, "PhotoReport.app.tar.gz"), asset(12, "PhotoReport_0.3.24_universal.dmg")],
},
];
const files: Record<string, unknown> = {
// First download is the bad 0.3.25 manifest (same filename across releases; fake fetch keys by basename).
"update-darwin-universal.json": { version: "0.3.25", file: "PhotoReport.app.tar.gz", signature: badSig },
"PhotoReport.app.tar.gz": "bytes",
};
const r = new DesktopReleases({ api: API, token: "t" }, fakeGitea(releases, files).impl);
// Bad newest release is skipped; nothing older matches 0.3.25 either with this stub, so null — then swap to good.
expect(await r.updateFor("darwin", "aarch64", "0.3.24")).toBeNull();
files["update-darwin-universal.json"] = { version: "0.3.25", file: "PhotoReport.app.tar.gz", signature: goodSig };
const r2 = new DesktopReleases({ api: API, token: "t" }, fakeGitea(releases, files).impl);
expect(await r2.updateFor("darwin", "aarch64", "0.3.24")).toMatchObject({
version: "0.3.25",
installer: "/v1/desktop/download/20/PhotoReport_0.3.24_universal.dmg",
});
});
it("answers with the newest desktop release for the platform, through the API, and nothing when up to date", async () => {
const releases = [
{ id: 7, tag_name: "desktop-v0.3.0", draft: false, prerelease: false, body: "Catálogo local", published_at: "2026-10-13T09:00:00Z", assets: [asset(1, "update-darwin-universal.json"), asset(2, "PhotoReport_universal.app.tar.gz"), asset(4, "PhotoReport_0.3.0_universal.dmg")] },
@@ -70,4 +116,16 @@ describe("desktop updates", () => {
expect(await r.updateFor("darwin", "aarch64", "0.3.2")).toMatchObject({ version: "0.3.4", url: "/v1/desktop/download/11/PhotoReport.app.tar.gz" });
expect(await r.file(11, "PhotoReport.app.tar.gz")).not.toBeNull();
});
it("answers 503 instead of crashing the route when Gitea is unreachable (BIT-31961)", async () => {
const releases = new DesktopReleases({ api: API, token: "t" }, async () => {
throw new TypeError("fetch failed");
});
const app = Fastify({ logger: false });
await registerDesktopRoutes(app, { releases, publicApiUrl: "https://app.example" });
const res = await app.inject({ method: "GET", url: "/v1/desktop/download/7/PhotoReport_universal.app.tar.gz" });
expect(res.statusCode).toBe(503);
expect(res.json()).toEqual({ error: "download_unavailable" });
});
});
+16 -2
View File
@@ -3,6 +3,7 @@ import { hashPassword } from "../src/auth/passwords.js";
import { buildApp } from "../src/app.js";
import { loadConfig, type Config } from "../src/config.js";
import { createDb, type Db } from "../src/db.js";
import type { FaceEngine } from "../src/faces/process.js";
import type { Role } from "../src/generated/prisma/client.js";
import type { Broadcaster } from "../src/realtime.js";
import { assertTestDatabase } from "./guard.js";
@@ -13,7 +14,13 @@ export interface TestContext {
config: Config;
}
export async function createTestApp(overrides: Record<string, string> = {}, realtime?: Broadcaster, fetchImpl?: typeof fetch, engineOnline?: () => boolean): Promise<TestContext> {
export async function createTestApp(
overrides: Record<string, string> = {},
realtime?: Broadcaster,
fetchImpl?: typeof fetch,
engineOnline?: () => boolean,
faceEngine?: FaceEngine,
): Promise<TestContext> {
const config = loadConfig({
NODE_ENV: "test",
DATABASE_URL: assertTestDatabase(process.env.DATABASE_URL_TEST),
@@ -23,7 +30,14 @@ export async function createTestApp(overrides: Record<string, string> = {}, real
...overrides,
});
const db = createDb(config.DATABASE_URL);
const app = await buildApp({ config, db, ...(realtime && { realtime }), ...(fetchImpl && { fetchImpl }), ...(engineOnline && { engineOnline }) });
const app = await buildApp({
config,
db,
...(realtime && { realtime }),
...(fetchImpl && { fetchImpl }),
...(engineOnline && { engineOnline }),
...(faceEngine && { faceEngine }),
});
return { app, db, config };
}
+45
View File
@@ -364,6 +364,51 @@ describe("library", () => {
expect((none.json() as { total: number }).total).toBe(0);
});
it("takes a file back from the old event's folder when the photo moves", async () => {
const { orgId, admin, event } = await setup();
const { photoId } = (await service.ingestFile(await drop("foto.r1", "a.jpg", await jpeg()))) as { photoId: string };
await ctx.db.photo.update({ where: { id: photoId }, data: { eventId: event.id } });
const other = await ctx.app.inject({
method: "POST",
url: `/v1/orgs/${orgId}/events`,
headers: bearer(admin),
payload: { home: "Chegada da seleção", startsAt: "2026-09-24T09:00:00Z" },
});
expect(other.statusCode).toBe(201);
const otherId = (other.json() as { id: string }).id;
const target = await ctx.db.deliveryTarget.create({
data: { organizationId: orgId, name: "FPA", kind: "NEXTCLOUD", baseUrl: "https://cloud.photoreport.pt", username: "fpa", secretEnc: "sealed", folderTemplate: "/{event}/", fileNameTemplate: "{n}.jpg" },
});
const item = await ctx.db.deliveryItem.create({
data: { organizationId: orgId, targetId: target.id, photoId, eventId: event.id, sequence: 1, status: "DONE", remotePath: "/20260923 - VSC x AAAS/1.jpg" },
});
const moved = await ctx.app.inject({ method: "PATCH", url: `/v1/orgs/${orgId}/photos`, headers: bearer(admin), payload: { ids: [photoId], patch: { eventId: otherId } } });
expect(moved.statusCode).toBe(200);
expect(await ctx.db.deliveryItem.findUnique({ where: { id: item.id } })).toMatchObject({ status: "QUEUED", retract: true });
expect((await ctx.db.photo.findUnique({ where: { id: photoId } }))?.eventId).toBe(otherId);
});
it("takes a delivered file back when the photo is rejected or un-picked", async () => {
const { orgId, admin, event } = await setup();
const a = (await service.ingestFile(await drop("foto.r1", "a.jpg", await jpeg({ color: "#111111" })))) as { photoId: string };
const b = (await service.ingestFile(await drop("foto.r1", "b.jpg", await jpeg({ color: "#222222" })))) as { photoId: string };
await ctx.db.photo.updateMany({ where: { id: { in: [a.photoId, b.photoId] } }, data: { eventId: event.id, flag: "PICK" } });
const target = await ctx.db.deliveryTarget.create({
data: { organizationId: orgId, name: "FPA", kind: "NEXTCLOUD", baseUrl: "https://cloud.photoreport.pt", username: "fpa", secretEnc: "sealed", folderTemplate: "/{event}/", fileNameTemplate: "{n}.jpg" },
});
const [itemA, itemB] = await Promise.all(
[a.photoId, b.photoId].map((photoId, i) =>
ctx.db.deliveryItem.create({
data: { organizationId: orgId, targetId: target.id, photoId, eventId: event.id, sequence: i + 1, status: "DONE", remotePath: `/${i + 1}.jpg` },
}),
),
);
expect((await ctx.app.inject({ method: "PATCH", url: `/v1/orgs/${orgId}/photos`, headers: bearer(admin), payload: { ids: [a.photoId], patch: { flag: "REJECT" } } })).statusCode).toBe(200);
expect(await ctx.db.deliveryItem.findUnique({ where: { id: itemA.id } })).toMatchObject({ status: "QUEUED", retract: true });
expect((await ctx.app.inject({ method: "PATCH", url: `/v1/orgs/${orgId}/photos`, headers: bearer(admin), payload: { ids: [b.photoId], patch: { flag: "NONE" } } })).statusCode).toBe(200);
expect(await ctx.db.deliveryItem.findUnique({ where: { id: itemB.id } })).toMatchObject({ status: "QUEUED", retract: true });
});
it("previews the IPTC a delivery will write, with codes and identified players", async () => {
const { orgId, admin } = await setup();
const saved = await ctx.app.inject({ method: "PUT", url: `/v1/orgs/${orgId}/code-list`, headers: bearer(admin), payload: { content: "v7\tMiguel Silva (VSC)\nbad\n" } });
+73 -1
View File
@@ -5,7 +5,7 @@ import { CodeGeneratorSettings } from "@photoreport/contracts";
import sharp from "sharp";
import { afterAll, beforeAll, beforeEach, describe, expect, it } from "vitest";
import { BLOCK_START, buildCodeLines, mergeGenerated, teamPrefix, toTsv } from "../src/sports/codegen.js";
import { type Fetch, fpaProva, fpaShortName, fpfDate, lisbonTime, parseFpaBoletim, parseFpaClubTerms, parseFpaMatchPage, parseFpaReferees, parseFpfLineups, seasonOf } from "../src/sports/providers.js";
import { type Fetch, fpaEpochFor, fpaProva, fpaShortName, fpfDate, lisbonTime, parseFpaBoletim, parseFpaClubTerms, parseFpaMatchPage, parseFpaReferees, parseFpfLineups, seasonOf } from "../src/sports/providers.js";
import { SportsService } from "../src/sports/service.js";
import { LocalStorage } from "../src/storage/storage.js";
import { bearer, createTestApp, login, resetDb, seedUser, type TestContext } from "./helpers.js";
@@ -56,6 +56,8 @@ describe("federation data", () => {
expect(lisbonTime("2026-12-01").timeKnown).toBe(false);
expect(seasonOf(new Date("2026-10-13"))).toBe("20262027");
expect(seasonOf(new Date("2027-03-01"))).toBe("20262027");
expect(fpaEpochFor(new Date("2026-10-27T12:00:00Z"))).toBe("374");
expect(fpaEpochFor(new Date("2026-03-01T12:00:00Z"))).toBe("373");
});
it("reads the FPA match report: numbers and licences, the officials' letters, the referees", () => {
@@ -243,6 +245,15 @@ const fakeSites = (state: { benfica: { shirtNumber: number; name: string; photos
"utf8",
),
);
if (state.handball && u.host === "portal.fpa.pt" && u.pathname === "/associado/198159/") return bytes(Buffer.from(MEMBER_PAGE, "utf8"));
if (state.handball && u.host === "ws.fpa.pt" && u.pathname === "/index.php/getCipaInscricoes/203445") return json(MEMBER_REGISTRATIONS);
// Full club register (every associate, not only the match sheet): Vitória club 140, season 374.
if (state.handball && u.host === "ws.fpa.pt" && u.pathname === "/index.php/getCipClubeEpoca/140/374")
return json([
{ CIP_NUMERO: "100001", CIP_NOME: "Rui Manuel Sousa Lopes", ID_CIPA: "370001", ATLETA: "S", TECNICO: null, OFICIAL: null, ARBITRO: null, URL_FOTO: "https://si.fpa.pt/blob/obj_anexo/FOTO_CIPA/1_370001.JPG" },
{ CIP_NUMERO: "250001", CIP_NOME: "Ana Filipa Mendes Costa", ID_CIPA: "370999", ATLETA: null, TECNICO: "S", OFICIAL: null, ARBITRO: null, URL_FOTO: "https://si.fpa.pt/blob/obj_anexo/FOTO_CIPA/2_370999.JPG" },
]);
if (state.handball && u.host === "ws.fpa.pt" && u.pathname.includes("getCipClubeEpoca")) return json([]);
const licence = /^\/associado\/(100001|185283)\/$/.exec(u.pathname)?.[1];
if (state.handball && u.host === "portal.fpa.pt" && licence)
return bytes(Buffer.from(`<html><body><img src="https://si.fpa.pt/blob/obj_anexo/FOTO_CIPA/555_${licence}.JPG"></body></html>`, "utf8"));
@@ -341,6 +352,7 @@ describe("sports data service", () => {
});
beforeEach(async () => {
await resetDb(ctx.db);
sports.resetFpaClocks();
state.handball = false;
state.benfica = [
{ shirtNumber: 14, name: "Vangelis Pavlidis", photos: "https://www.ligaportugal.pt/p/pavlidis.png" },
@@ -479,6 +491,55 @@ describe("sports data service", () => {
expect((await ctx.app.inject({ method: "POST", url: `/v1/orgs/${org!.id}/events`, headers: bearer(token), payload: { home: "a", away: "b", startsAt: fixture.startsAt, homeTeamId: org!.id } })).statusCode).toBe(400);
});
it("FPA: a person from their licence number (name, latest role, licence photo), the same one on match reports", async () => {
state.handball = true;
const { org } = await seedUser(ctx.db, "[email protected]", { org: "fpa", role: "OWNER" });
await ctx.db.organization.update({ where: { id: org!.id }, data: { biometricsEnabled: true } });
const member = await sports.fpa.member("198159");
expect(member).toMatchObject({ name: "Maria Ema Bastos Silva", internalId: "203445", photo: "https://si.fpa.pt/blob/obj_anexo/FOTO_CIPA/636722_203445.JPG" });
expect(member!.registrations.map((r) => [r.season, r.kind, r.club])).toEqual([
["2010/11", "athlete", "ADA CANELAS"],
["2024/25", "coach", "ESTARREJA AC"],
["2025/26", "official", "Sel.Nac.M"],
]);
expect(await sports.fpa.member("99999999")).toBeNull();
const first = await sports.personFromFpaLicence(org!.id, "198159");
expect(first).toMatchObject({ created: true, reference: true, person: { name: "Maria Silva", club: "Seleção Nacional Masculina" } });
const again = await sports.personFromFpaLicence(org!.id, "198159");
expect(again).toMatchObject({ created: false, person: { id: first.person.id } });
expect((await ctx.db.person.findUniqueOrThrow({ where: { id: first.person.id } })).licence).toBe("198159");
});
it("FPA: the whole club register (getCipClubeEpoca) becomes people with licence photos, not only match-sheet names", async () => {
state.handball = true;
const { org } = await seedUser(ctx.db, "[email protected]", { org: "fpa-reg", role: "OWNER" });
await ctx.db.organization.update({ where: { id: org!.id }, data: { biometricsEnabled: true } });
const list = await sports.fpa.clubAssociates("140", "374");
expect(list).toEqual([
{ licence: "100001", internalId: "370001", name: "Rui Manuel Sousa Lopes", photo: "https://si.fpa.pt/blob/obj_anexo/FOTO_CIPA/1_370001.JPG", kind: "athlete" },
{ licence: "250001", internalId: "370999", name: "Ana Filipa Mendes Costa", photo: "https://si.fpa.pt/blob/obj_anexo/FOTO_CIPA/2_370999.JPG", kind: "coach" },
]);
const r = await sports.refreshFpa(now);
expect(r.errors).toEqual([]);
const coach = await ctx.db.person.findUnique({ where: { organizationId_licence: { organizationId: org!.id, licence: "250001" } } });
expect(coach).toMatchObject({ name: "Ana Costa", licence: "250001" });
expect(coach!.referenceKey).toBeTruthy();
});
it("FPA: two associates with the exact same name get told apart by licence, instead of a person_name_taken error", async () => {
const { org } = await seedUser(ctx.db, "[email protected]", { org: "fpa-homonimos", role: "OWNER" });
const first = await sports.personFromFpaAssociate(org!.id, { licence: "900001", internalId: null, name: "Maria Silva", photo: null, kind: "athlete" });
expect(first).toMatchObject({ created: true, person: { name: "Maria Silva" } });
const second = await sports.personFromFpaAssociate(org!.id, { licence: "900002", internalId: null, name: "Maria Silva", photo: null, kind: "athlete" });
expect(second).toMatchObject({ created: true, person: { name: "Maria Silva (900002)" } });
expect(second.person.id).not.toBe(first.person.id);
const people = await ctx.db.person.findMany({ where: { organizationId: org!.id }, orderBy: { licence: "asc" } });
expect(people.map((p) => [p.name, p.licence])).toEqual([
["Maria Silva", "900001"],
["Maria Silva (900002)", "900002"],
]);
});
it("keeps sports data to members and FPF links to admins", async () => {
const { user } = await seedUser(ctx.db, "[email protected]", { org: "abola", role: "PHOTOGRAPHER" });
const token = (await login(ctx.app, user.email)).body.accessToken;
@@ -528,7 +589,9 @@ describe("sports data service", () => {
expect(created.statusCode).toBe(201);
expect((await ctx.app.inject({ method: "POST", url: `/v1/events/${created.json().id}/squads/sync`, headers: bearer(token) })).statusCode).toBe(200);
const people = await ctx.db.person.findMany({ where: { organizationId: org!.id }, orderBy: { name: "asc" } });
// Ana Costa comes from the club register (getCipClubeEpoca), not the match sheet — coaches and the rest of the club.
expect(people.map((p) => [p.name, p.club, p.number, !!p.referenceKey])).toEqual([
["Ana Costa", null, null, true],
["Bruno Costa", "Arbitragem", null, false],
["Carlos Mesa", "Arbitragem", null, false],
["Duarte Sá", "Arbitragem", null, true],
@@ -628,3 +691,12 @@ describe("sports data service", () => {
]);
});
});
const MEMBER_PAGE = `<html><body><div class="association-detail"><div class="association-detail__image"><img src="https://si.fpa.pt/blob/obj_anexo/FOTO_CIPA/636722_203445.JPG"></div>
<div class="association-detail__content"><h3>Maria Ema Bastos Silva</h3><table><tr><td>CIPA</td><td>198159</td></tr><tr><td>Inscrito como</td><td>Oficial, Técnico, Atleta</td></tr></table></div></div>
<script>var TABLE_CONTENT_1 = {"title":"Hist\\u00f3rico","tabs":[],"cipa":"203445"};</script></body></html>`;
const MEMBER_REGISTRATIONS = [
{ EPO_DESCRICAO: "2010/11", GCI_TIP_INSCRICAO_TI013: "AT01", CLU_ABREV: "ADA CANELAS", CLU_NOME: "Associacao Desportiva Arsenal Canelas", ESC_DESCRICAO: "Iniciados F" },
{ EPO_DESCRICAO: "2024/25", GCI_TIP_INSCRICAO_TI013: "TEC", CLU_ABREV: "ESTARREJA AC", CLU_NOME: "Estarreja Andebol Clube" },
{ EPO_DESCRICAO: "2025/26", GCI_TIP_INSCRICAO_TI013: "OFI", CLU_ABREV: "Sel.Nac.M", CLU_NOME: "Selecções Nacionais Masculinas", FOF_ABREV: "DELEGADO TECNICO" },
];
+168
View File
@@ -0,0 +1,168 @@
import type { PhotoSummary } from "@photoreport/contracts";
import { memo, useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
import { useCachedImage } from "../offline/cache.js";
import { isDesktop } from "../platform.js";
import { filmLayout, filmScrollTo, filmWindow } from "./film-layout.js";
import { filmSourceKind, type FilmSource } from "./local-thumb.js";
interface FilmMods {
shiftKey: boolean;
metaKey: boolean;
ctrlKey: boolean;
}
interface FilmstripProps {
photos: PhotoSummary[];
currentId: string | null;
srcFor: (photo: PhotoSummary) => string;
onOpen: (id: string) => void;
/** Shift and command clicks (copy settings onto a range). Plain clicks still call this, then navigation is the caller's. */
onActivate?: (id: string, mods: FilmMods) => void;
selected?: ReadonlySet<string>;
/**
* Desktop only: a small JPEG of an unedited photo from the original on this computer. Null means this
* computer does not have it, and the cell uses the server thumbnail.
*/
localSrc?: (sha256: string) => Promise<string | null>;
}
/**
* The develop filmstrip. Only cells near the viewport mount an image. On the desktop app an unedited photo
* that lives on this computer is read from disk; every other photo uses the server thumbnail.
*/
export function Filmstrip({ photos, currentId, srcFor, onOpen, onActivate, selected, localSrc }: FilmstripProps) {
const scroller = useRef<HTMLDivElement>(null);
const followed = useRef<string | null>(null);
const layout = useMemo(() => filmLayout(photos), [photos]);
const [range, setRange] = useState({ start: 0, end: 0 });
const publish = useCallback(
(scrollLeft: number, viewWidth: number) => {
const next = filmWindow(layout, scrollLeft, viewWidth);
setRange((prev) => (prev.start === next.start && prev.end === next.end ? prev : next));
},
[layout],
);
useLayoutEffect(() => {
const el = scroller.current;
if (!el) return;
if (currentId && currentId !== followed.current) {
const index = photos.findIndex((p) => p.id === currentId);
if (index >= 0) {
followed.current = currentId;
const next = filmScrollTo(layout, index, el.scrollLeft, el.clientWidth);
if (next != null) el.scrollLeft = next;
}
}
publish(el.scrollLeft, el.clientWidth);
}, [currentId, layout, photos, publish]);
useEffect(() => {
const el = scroller.current;
if (!el || typeof ResizeObserver === "undefined") return;
const ro = new ResizeObserver(() => publish(el.scrollLeft, el.clientWidth));
ro.observe(el);
return () => ro.disconnect();
}, [publish]);
const { start, end } = range;
return (
<div
ref={scroller}
role="region"
aria-label="Fotos do evento"
className="h-[92px] shrink-0 overflow-x-auto border-t border-line bg-chrome p-1.5"
onScroll={(e) => publish(e.currentTarget.scrollLeft, e.currentTarget.clientWidth)}
>
<div className="relative h-full" style={{ width: layout.total }}>
{photos.slice(start, end).map((p, i) => {
const index = start + i;
return (
<div key={p.id} className="absolute top-0 h-full" style={{ left: layout.offsets[index], width: layout.widths[index] }}>
<FilmCell
photo={p}
src={srcFor(p)}
current={p.id === currentId}
pressed={selected?.has(p.id) ?? false}
onOpen={onOpen}
{...(onActivate ? { onActivate } : {})}
{...(localSrc ? { localSrc } : {})}
/>
</div>
);
})}
</div>
</div>
);
}
const FilmCell = memo(function FilmCell({
photo,
src,
current,
pressed,
onOpen,
onActivate,
localSrc,
}: {
photo: PhotoSummary;
src: string;
current: boolean;
pressed: boolean;
onOpen: (id: string) => void;
onActivate?: (id: string, mods: FilmMods) => void;
localSrc?: (sha256: string) => Promise<string | null>;
}) {
const kind: FilmSource = filmSourceKind(src, photo.developSeq, localSrc != null);
const [disk, setDisk] = useState<string | null>(null);
const [diskSettled, setDiskSettled] = useState(kind !== "disk");
useEffect(() => {
if (kind !== "disk" || !localSrc) {
setDisk(null);
setDiskSettled(true);
return;
}
let alive = true;
setDisk(null);
setDiskSettled(false);
void localSrc(photo.sha256).then((url) => {
if (!alive) return;
setDisk(url);
setDiskSettled(true);
});
return () => {
alive = false;
};
}, [kind, localSrc, photo.sha256]);
// The server thumbnail is fetched only once we know the disk does not have this photo.
const askServer = kind === "server" || (kind === "disk" && diskSettled && !disk);
const network = useCachedImage(askServer ? src : null, isDesktop());
const shown = kind === "blob" ? src : (disk ?? network);
return (
<button
type="button"
aria-current={current ? "true" : undefined}
aria-pressed={pressed ? true : undefined}
title={photo.name}
onClick={(e) => {
if (onActivate) onActivate(photo.id, { shiftKey: e.shiftKey, metaKey: e.metaKey, ctrlKey: e.ctrlKey });
else onOpen(photo.id);
}}
className={`relative h-full w-full border ${pressed || current ? "border-[#cfcfcf]" : "border-transparent opacity-70 hover:opacity-100"} ${current ? "ring-1 ring-white" : ""} ${photo.flag === "REJECT" ? "grayscale" : ""}`}
>
{shown ? (
<img src={shown} alt="" decoding="async" draggable={false} className="h-full w-full object-contain" />
) : (
<span className="block h-full w-full bg-[#262626]" />
)}
{photo.developSeq > 0 && <span className="absolute bottom-0.5 right-0.5 bg-black/70 px-1 font-mono text-[9px] text-white">±</span>}
{photo.flag !== "NONE" && (
<span className={`absolute left-0.5 top-0.5 px-1 text-[10px] ${photo.flag === "PICK" ? "bg-white text-black" : "bg-black/80 text-white"}`}>
{photo.flag === "PICK" ? "⚑" : "✕"}
</span>
)}
{photo.rating > 0 && <span className="absolute bottom-0.5 left-0.5 bg-black/70 px-1 text-[9px] text-white">{"★".repeat(photo.rating)}</span>}
</button>
);
});
+48 -3
View File
@@ -17,6 +17,48 @@ function renderWorker(): Worker | undefined {
}
let autoIds = 0;
let exportIds = 0;
/** Decodes one file into the render worker. A new key replaces whatever was open. */
export function openFrame(key: string, bytes: ArrayBuffer, maxEdge: number): Promise<void> {
const w = renderWorker();
if (!w) return Promise.reject(new Error("no worker"));
return new Promise((resolve, reject) => {
const onMessage = (e: MessageEvent<WorkerReply>) => {
const msg = e.data;
if (msg.type === "opened" && msg.key === key) {
w.removeEventListener("message", onMessage);
resolve();
return;
}
if (msg.type === "error" && msg.key === key && msg.ticket === undefined) {
w.removeEventListener("message", onMessage);
reject(new Error(msg.message));
}
};
w.addEventListener("message", onMessage);
w.postMessage({ type: "open", key, url: "", bytes, maxEdge } satisfies WorkerRequest, [bytes]);
});
}
/** One full-size render of the photo already open in the loupe. The loupe keeps its own frame. */
export function exportFrame(key: string, settings: string, maxW: number, maxH: number): Promise<{ width: number; height: number; pixels: Uint8ClampedArray }> {
const w = renderWorker();
if (!w) return Promise.reject(new Error("no worker"));
const id = ++exportIds;
return new Promise((resolve, reject) => {
const onMessage = (e: MessageEvent<WorkerReply>) => {
const msg = e.data;
if (msg.type !== "exported" && msg.type !== "exportError") return;
if (msg.id !== id) return;
w.removeEventListener("message", onMessage);
if (msg.type === "exported") resolve({ width: msg.width, height: msg.height, pixels: msg.pixels });
else reject(new Error(msg.message));
};
w.addEventListener("message", onMessage);
w.postMessage({ type: "export", id, key, settings, maxW, maxH } satisfies WorkerRequest);
});
}
/**
* Asks the render worker for automatic values computed from the open photo (tone, white balance, or the
* eyedropper at a point of the uncropped frame). Resolves with control id -> value, ready for `develop.set`.
@@ -59,6 +101,8 @@ interface ViewerProps {
onError?: (message: string) => void;
/** The original from this computer, when the desktop app has it (no download); null to use `sourceUrl`. */
localSource?: () => Promise<ArrayBuffer | null>;
/** Longest side to decode, when this is not the 1:1 view. The loupe still draws only what fits the screen. */
decodeEdge?: number;
/** 1:1 (Lightroom's Z): the photo at its own pixels, scrolled to look around, from the full-resolution original. */
actualPixels?: boolean;
/** Eyedropper on: a click reports where (0..1 in the shown frame). */
@@ -111,7 +155,7 @@ export function Viewer(props: ViewerProps) {
if (!w) return;
const onMessage = (e: MessageEvent<WorkerReply>) => {
const msg = e.data;
if (msg.type === "auto") return;
if (msg.type === "auto" || msg.type === "exported" || msg.type === "exportError") return;
if (msg.type === "opened") {
if (msg.key === photoKey) {
setOpened(msg.key);
@@ -144,14 +188,15 @@ export function Viewer(props: ViewerProps) {
void (async () => {
const bytes = await (callbacks.current.localSource?.() ?? Promise.resolve(null)).catch(() => null);
if (cancelled) return;
const msg: WorkerRequest = { type: "open", key: photoKey, url: sourceUrl, ...(bytes && { bytes }), ...(callbacks.current.actualPixels && { maxEdge: FULL_EDGE }) };
const edge = callbacks.current.actualPixels ? FULL_EDGE : callbacks.current.decodeEdge;
const msg: WorkerRequest = { type: "open", key: photoKey, url: sourceUrl, ...(bytes && { bytes }), ...(edge ? { maxEdge: edge } : {}) };
w.postMessage(msg, bytes ? [bytes] : []);
})();
return () => {
cancelled = true;
w.removeEventListener("message", onMessage);
};
}, [photoKey, sourceUrl, send]);
}, [photoKey, sourceUrl, send, props.decodeEdge]);
useEffect(() => {
if (opened !== photoKey || !size.w || !size.h) return;
+6 -2
View File
@@ -89,10 +89,14 @@ export type WorkerRequest =
| { type: "open"; key: string; url: string; bytes?: ArrayBuffer; maxEdge?: number }
| { type: "render"; ticket: number; key: string; settings: string; maxW: number; maxH: number; draft: boolean; applyCrop: boolean }
/** Auto values from the photo itself: tone (under `settings`), white balance, or the eyedropper at x, y. */
| { type: "auto"; id: number; key: string; kind: "tone" | "wb" | "pick" | "level"; settings?: string; x?: number; y?: number };
| { type: "auto"; id: number; key: string; kind: "tone" | "wb" | "pick" | "level"; settings?: string; x?: number; y?: number }
/** One full render of the open photo, for a JPEG saved from Revelar. Does not replace the loupe frame. */
| { type: "export"; id: number; key: string; settings: string; maxW: number; maxH: number };
export type WorkerReply =
| { type: "opened"; key: string; sourceWidth: number; sourceHeight: number }
| { type: "frame"; ticket: number; key: string; width: number; height: number; pixels: Uint8ClampedArray }
| { type: "error"; key: string; ticket?: number; message: string }
| { type: "auto"; id: number; values?: Record<string, number>; message?: string };
| { type: "auto"; id: number; values?: Record<string, number>; message?: string }
| { type: "exported"; id: number; width: number; height: number; pixels: Uint8ClampedArray }
| { type: "exportError"; id: number; message: string };
+94
View File
@@ -0,0 +1,94 @@
/**
* Filmstrip window. LightCraft draws every cell's slot but only asks for a thumbnail when the cell
* intersects the viewport plus four cell-widths on each side. Cells outside that stay empty, so a
* long folder does not queue a decode (or, here, a download) per photo.
*
* The buffer is four 3:2 frames, the usual camera picture, at the strip's cell height.
*/
/** Cell height: the 92px strip minus 6px of padding on each side. */
export const FILM_CELL_H = 80;
/** Space between cells, the same as the strip's old `gap-1`. */
export const FILM_GAP = 4;
/** Cells prepared past each edge of the viewport. */
export const FILM_BUFFER_CELLS = 4;
export interface FilmLayout {
widths: number[];
/** Left edge of each cell. */
offsets: number[];
total: number;
}
/** Width of one cell from the photo's pixel size. Missing size uses 3:2. */
export function filmCellWidth(width: number | null, height: number | null): number {
const w = width != null && width > 0 ? width : 3;
const h = height != null && height > 0 ? height : 2;
return Math.max(1, Math.round(FILM_CELL_H * (w / h)));
}
export function filmLayout(photos: readonly { width: number | null; height: number | null }[]): FilmLayout {
const widths = photos.map((p) => filmCellWidth(p.width, p.height));
const offsets: number[] = new Array(widths.length);
let x = 0;
for (let i = 0; i < widths.length; i++) {
offsets[i] = x;
x += widths[i]!;
if (i < widths.length - 1) x += FILM_GAP;
}
return { widths, offsets, total: x };
}
function bufferPx(): number {
return FILM_BUFFER_CELLS * filmCellWidth(3, 2);
}
/** Half-open index range `[start, end)` of cells to mount. */
export function filmWindow(layout: FilmLayout, scrollLeft: number, viewWidth: number): { start: number; end: number } {
const n = layout.widths.length;
if (n === 0) return { start: 0, end: 0 };
const pad = bufferPx();
const left = scrollLeft - pad;
const right = scrollLeft + Math.max(viewWidth, 0) + pad;
let start = n;
let lo = 0;
let hi = n - 1;
while (lo <= hi) {
const mid = (lo + hi) >> 1;
if (layout.offsets[mid]! + layout.widths[mid]! <= left) lo = mid + 1;
else {
start = mid;
hi = mid - 1;
}
}
if (start === n) return { start: n, end: n };
let end = n;
lo = start;
hi = n - 1;
while (lo <= hi) {
const mid = (lo + hi) >> 1;
if (layout.offsets[mid]! < right) lo = mid + 1;
else {
end = mid;
hi = mid - 1;
}
}
return { start, end };
}
/**
* Scroll offset that centres `index`, or null when that cell is already fully on screen.
* LightCraft leaves the strip where it is for a click on a visible thumbnail.
*/
export function filmScrollTo(layout: FilmLayout, index: number, scrollLeft: number, viewWidth: number): number | null {
if (index < 0 || index >= layout.widths.length) return null;
const left = layout.offsets[index]!;
const width = layout.widths[index]!;
const view = Math.max(viewWidth, 0);
if (left >= scrollLeft && left + width <= scrollLeft + view) return null;
const target = left - (view - width) / 2;
const max = Math.max(0, layout.total - view);
return Math.max(0, Math.min(target, max));
}
+105
View File
@@ -0,0 +1,105 @@
import type { PhotoSummary } from "@photoreport/contracts";
import { render, screen, waitFor } from "@testing-library/react";
import { describe, expect, it, vi } from "vitest";
import { Filmstrip } from "./Filmstrip.js";
import { filmCellWidth, filmLayout, filmScrollTo, filmWindow } from "./film-layout.js";
import { filmSourceKind } from "./local-thumb.js";
const frame = { width: 6000, height: 4000 };
describe("filmstrip window", () => {
it("sizes a cell from the photo, and falls back to 3:2", () => {
expect(filmCellWidth(6000, 4000)).toBe(120);
expect(filmCellWidth(4000, 6000)).toBe(53);
expect(filmCellWidth(null, null)).toBe(120);
});
it("loads the viewport plus four cells, not the rest of the folder", () => {
const layout = filmLayout(Array.from({ length: 200 }, () => frame));
expect(layout.offsets[1]).toBe(124);
expect(layout.total).toBe(200 * 120 + 199 * 4);
const atStart = filmWindow(layout, 0, 800);
expect(atStart.start).toBe(0);
expect(atStart.end).toBeLessThan(20);
const later = filmWindow(layout, 5000, 800);
expect(later.start).toBeGreaterThan(20);
expect(later.end).toBeLessThan(60);
expect(later.end - later.start).toBeLessThan(20);
});
it("centres a photo that is off screen and leaves a visible one alone", () => {
const layout = filmLayout(Array.from({ length: 40 }, () => frame));
expect(filmScrollTo(layout, 1, 0, 400)).toBeNull();
expect(filmScrollTo(layout, 20, 0, 400)).toBe(2340);
});
it("mounts images only for the visible window", () => {
const photos = Array.from({ length: 200 }, (_, i) => photo(i));
render(<Filmstrip photos={photos} currentId={null} srcFor={(p) => p.urls.thumb} onOpen={() => {}} />);
const strip = screen.getByRole("region", { name: "Fotos do evento" });
const images = strip.querySelectorAll("img");
expect(images.length).toBeGreaterThan(0);
expect(images.length).toBeLessThan(20);
});
it("reads an unedited local photo from disk and leaves the others to the server", async () => {
const localSrc = vi.fn(async (sha: string) => (sha === "on-disk" ? "blob:from-disk" : null));
const photos = [
photo(0, { sha256: "on-disk" }),
photo(1, { sha256: "edited", developSeq: 1 }),
photo(2, { sha256: "waiting", thumb: "blob:already" }),
photo(3, { sha256: "elsewhere" }),
];
render(<Filmstrip photos={photos} currentId={null} srcFor={(p) => p.urls.thumb} onOpen={() => {}} localSrc={localSrc} />);
await waitFor(() => expect(localSrc).toHaveBeenCalledWith("on-disk"));
expect(localSrc).toHaveBeenCalledWith("elsewhere");
expect(localSrc.mock.calls.map((c) => c[0])).not.toContain("edited");
expect(localSrc.mock.calls.map((c) => c[0])).not.toContain("waiting");
const strip = screen.getByRole("region", { name: "Fotos do evento" });
await waitFor(() => expect(strip.querySelector('img[src="blob:from-disk"]')).toBeTruthy());
expect(strip.querySelector('img[src="/t/1"]')).toBeTruthy();
expect(strip.querySelector('img[src="blob:already"]')).toBeTruthy();
await waitFor(() => expect(strip.querySelector('img[src="/t/3"]')).toBeTruthy());
});
});
describe("film source", () => {
it("uses the disk only for an unedited photo that is not already a local blob", () => {
expect(filmSourceKind("/t/1", 0, true)).toBe("disk");
expect(filmSourceKind("/t/1", 2, true)).toBe("server");
expect(filmSourceKind("blob:x", 0, true)).toBe("blob");
expect(filmSourceKind("/t/1", 0, false)).toBe("server");
});
});
function photo(i: number, over: Partial<PhotoSummary> & { thumb?: string } = {}): PhotoSummary {
const { thumb, ...rest } = over;
return {
id: `p${i}`,
eventId: "e",
originalName: `${i}.jpg`,
name: `${i}.jpg`,
sha256: "ab",
originalStored: true,
status: "READY",
width: 6000,
height: 4000,
capturedAt: null,
cameraModel: null,
lens: null,
focalLength: null,
aperture: null,
exposureTime: null,
iso: null,
rating: i === 3 ? 2 : 0,
flag: "NONE",
colorLabel: "NONE",
players: [],
uploader: null,
developSeq: 0,
urls: { thumb: thumb ?? `/t/${i}`, preview: `/p/${i}`, source: `/s/${i}` },
...rest,
};
}
+37
View File
@@ -0,0 +1,37 @@
import { kv } from "../offline/kv.js";
import { localFilmThumb } from "../platform.js";
/** Where a filmstrip cell's picture comes from. */
export type FilmSource = "blob" | "disk" | "server";
/**
* An unedited photo on the desktop app is read from this computer. A `blob:` URL is already local (not uploaded
* yet). Anything else — the browser, or a photo whose edit is only on the server — uses the server thumbnail.
*/
export function filmSourceKind(src: string, developSeq: number, fromDisk: boolean): FilmSource {
if (src.startsWith("blob:") || src.startsWith("data:")) return "blob";
if (fromDisk && developSeq === 0) return "disk";
return "server";
}
const pending = new Map<string, Promise<string | null>>();
/** The filmstrip JPEG for `sha256`, remembered for this session and on disk so a later open does not read it again. */
export function localFilmSrc(sha256: string): Promise<string | null> {
const hit = pending.get(sha256);
if (hit) return hit;
const job = loadLocalThumb(sha256);
pending.set(sha256, job);
return job;
}
async function loadLocalThumb(sha256: string): Promise<string | null> {
const key = `img:local:${sha256}@480`;
const kept = await kv.get<Blob>(key);
if (kept instanceof Blob) return URL.createObjectURL(kept);
const bytes = await localFilmThumb(sha256);
if (!bytes) return null;
const blob = new Blob([bytes], { type: "image/jpeg" });
void kv.set(key, blob);
return URL.createObjectURL(blob);
}
+12
View File
@@ -36,6 +36,18 @@ async function open(key: string, url: string, bytes?: ArrayBuffer, maxEdge = 204
self.onmessage = async (e: MessageEvent<WorkerRequest>) => {
const msg = e.data;
if (msg.type === "export") {
try {
const photo = current?.key === msg.key ? current.photo : await opening.get(msg.key);
if (!photo) throw new Error("photo not open");
photo.render(msg.settings, msg.maxW, msg.maxH, false, true);
const pixels = new Uint8ClampedArray(photo.pixels().buffer);
post({ type: "exported", id: msg.id, width: photo.width, height: photo.height, pixels }, [pixels.buffer]);
} catch (err) {
post({ type: "exportError", id: msg.id, message: err instanceof Error ? err.message : String(err) });
}
return;
}
try {
if (msg.type === "open") {
const photo = await open(msg.key, msg.url, msg.bytes, msg.maxEdge);
+83 -2
View File
@@ -46,6 +46,42 @@ export const t = {
},
moveToEvent: "Mover para evento",
movedToEvent: (n: number, name: string) => `${n} ${n === 1 ? "foto movida" : "fotos movidas"} para ${name}`,
removeFromEventAsk: (n: number, name?: string) => {
const where = name ? `«${name}»` : "deste evento";
return n === 1 ? `Remover esta foto de ${where}?` : `Remover ${n} fotos de ${where}?`;
},
removeFromEventHelp: "Ficam em Sem evento. Não são apagadas da biblioteca. O que já foi enviado sai desse destino.",
removedFromEvent: (n: number) => (n === 1 ? "1 foto retirada do evento" : `${n} fotos retiradas do evento`),
folderSheet: {
opening: "A abrir a pasta…",
close: "Fechar",
hint: "Folha de contacto desta pasta, neste computador. Não cria um evento nem envia fotografias. D abre o Revelar. Estrelas e marcas ficam só nesta sessão.",
develop: "Revelar",
developTitle: "Abre esta fotografia no Revelar, neste computador. Não envia o ficheiro.",
mergeTitle: "Funde as exposições desta pasta num DNG ao lado delas. As originais ficam. Não envia fotografias.",
alsoJpeg: "e o JPEG editado",
alsoJpegTitle: "No mesmo clique funde, grava o DNG, o JPEG revelado e o XMP com esses ajustes. Desmarca para gravar só o DNG.",
workingJpeg: (n: number, total: number) => `A revelar e a gravar o JPEG ${n} de ${total}…`,
merged: (n: number) => (n === 1 ? "1 DNG ficou nesta pasta." : `${n} DNG ficaram nesta pasta.`),
mergedBoth: (n: number) => (n === 1 ? "1 DNG e o JPEG editado ficaram nesta pasta." : `${n} DNG e os JPEG editados ficaram nesta pasta.`),
mergedDownload: (n: number) => (n === 1 ? "O DNG ficou nesta pasta. O JPEG foi descarregado." : "Os DNG ficaram nesta pasta. Os JPEG foram descarregados."),
empty: "Esta pasta não tem fotografias.",
failed: "Não foi possível abrir esta pasta.",
count: (n: number) => (n === 1 ? "1 foto" : `${n} fotos`),
},
folderDevelop: {
back: "Pasta",
preset: "Interior",
presetHelp: "Luz de dia, sombras abertas e janelas contidas. O XMP ao lado do DNG guarda estes ajustes para os mudares aqui.",
dressing: "A acertar brancos, luz e cor…",
save: "Guardar JPEG",
saving: "A gravar o JPEG…",
savedBeside: (name: string) => `${name} ficou nesta pasta.`,
savedDownload: (name: string) => `${name} foi descarregado.`,
saveFailed: "Não gravei o JPEG.",
openFailed: "Não abri esta fotografia no Revelar.",
adjustFailed: "Não apliquei este acerto.",
},
newEvent: "Novo evento",
noEvents: "Sem eventos. Cria o primeiro.",
noPhotos: "Sem fotografias neste filtro.",
@@ -80,7 +116,7 @@ export const t = {
setUpDelivery: "Configurar envio",
noTargetsHelp: "Ainda não há destinos de envio (FTP da agência, pasta, etc.). Cria um em Entregar.",
deliveryBadge: { QUEUED: "A enviar", DONE: "Enviada", FAILED: "Envio falhou" },
shortcuts: "P escolher · X rejeitar · U limpar · 0–5 estrelas · 6–9 cor · I informação · E/Enter lupa · G/Esc grelha · D revelar · R recortar · W conta-gotas · Ctrl+Alt+2 revelar · Photo Mechanic: T marcar · Cmd+1–5 cor · Ctrl+1–5 estrelas (Windows: Ctrl cor, Alt estrelas)",
shortcuts: "P escolher · X rejeitar · U limpar · 0–5 estrelas · 6–9 cor · Delete tirar do evento · I informação · E/Enter lupa · G/Esc grelha · D revelar · R recortar · W conta-gotas · Ctrl+Alt+2 revelar · Photo Mechanic: T marcar · Cmd+1–5 cor · Ctrl+1–5 estrelas (Windows: Ctrl cor, Alt estrelas)",
selected: (n: number) => (n === 1 ? "1 selecionada" : `${n} selecionadas`),
ofTotal: (n: number, total: number) => `${n} de ${total}`,
players: "Jogadores",
@@ -98,7 +134,11 @@ export const t = {
stop: "Desligar",
help: "A câmara envia por FTP para este computador (mesma rede). Cada foto que chega sobe logo para o evento abaixo e o original passa para a pasta de trabalho do evento.",
camera: "Na câmara",
edit: "Configurar",
edit: "Ligações",
connections: "Máquinas",
connectionsHelp: "Uma ligação por corpo. No menu FTP da câmara escreves o servidor, a porta, o utilizador e a palavra-passe. O cabo USB não usa isto: liga sozinho.",
machine: "Máquina",
addMachine: "+ Outra máquina",
server: "Servidor",
port: "Porta",
user: "Utilizador",
@@ -130,6 +170,7 @@ export const t = {
noNetwork: "Sem rede local: liga o computador ao Wi-Fi ou ao cabo.",
target: "Evento",
noTarget: "Sem evento: as fotos vão para “Sem evento”. Abre um evento na lista e escolhe-o aqui.",
targetClosed: "Este evento já fechou. As fotos tiradas fora dele vão para o evento da hora em que foram feitas, e não para esta pasta.",
useOpen: (name: string) => `Usar o evento aberto: ${name}`,
received: (n: number) => (n === 1 ? "1 foto recebida" : `${n} fotos recebidas`),
sent: (n: number) => `${n} enviadas`,
@@ -149,6 +190,41 @@ export const t = {
},
outdated: "Esta versão da app de computador ainda não tem FTP local. Instala a versão nova (0.2 ou mais recente).",
},
usbCamera: {
button: "USB",
title: "Câmara por USB",
help: "Com a câmara ligada por cabo, vês o cartão e cada foto nova. Nada sobe sozinho: escolhes o que descarregar para o evento abaixo.",
none: "Nenhuma câmara ligada por cabo.",
tetherOn: "Cabo ligado",
tetherOff: "Cabo desligado",
turnOn: "Ligar cabo",
turnOff: "Desligar cabo",
opening: "A ligar à câmara…",
tethered: "Câmara pronta — escolhe o que descarregar",
busy: "A câmara está ocupada por outra app (o EOS Utility, por exemplo). Fecha-a: o cabo só pode estar com uma de cada vez. A tentar outra vez sozinho.",
idle: "Cabo desligado",
listing: "A ler o cartão…",
rawKept: "O RAW fica na pasta de trabalho, ao lado do JPEG.",
outdated: "Esta versão da app de computador ainda não lê a câmara por USB. Instala a versão nova.",
received: (n: number) => (n === 1 ? "1 foto recebida" : `${n} fotos recebidas`),
sent: (n: number) => `${n} enviadas`,
failed: (n: number) => (n === 1 ? "1 falhou" : `${n} falharam`),
clockOk: "Relógio acertado com este computador.",
clockAhead: (n: number) => `A câmara estava ${n} s adiantada. O relógio ficou igual ao deste computador.`,
clockBehind: (n: number) => `A câmara estava ${n} s atrasada. O relógio ficou igual ao deste computador.`,
clockUnsupported: "Esta câmara não deixa acertar o relógio pelo cabo.",
clockSync: "Acertar relógio outra vez",
card: "Cartão",
files: (n: number) => (n === 1 ? "1 ficheiro" : `${n} ficheiros`),
newShot: "nova",
imported: "já puxada",
selectNew: "Seleccionar novas",
selectAll: "Todas",
selectNone: "Nenhuma",
refresh: "Actualizar lista",
download: (n: number) => (n === 1 ? "Descarregar 1" : `Descarregar ${n}`),
emptyCard: "O cartão ainda não tem fotos listadas.",
},
squad: {
title: "Pessoas",
help: "Quem pode ser identificado nas fotos, por clube. Os plantéis das competições que segues entram sozinhos; aqui juntas outras pessoas e as fotos oficiais (com a foto, a pessoa é sugerida logo no primeiro jogo).",
@@ -282,6 +358,9 @@ export const t = {
missing: "Falta o ficheiro original de alguma exposição.",
engine: "O motor ainda não grava o DNG. Quando a cópia do cartão acabar, atualiza a página.",
failed: "Não fundi. Tenta outra vez.",
raw: "Não consegui ler estes RAW para os fundir.",
write: "Não consegui gravar o DNG nesta pasta.",
failedDetail: (reason: string) => `Não fundi. ${reason}`,
},
},
card: {
@@ -591,6 +670,8 @@ export const t = {
pause: "Pausar",
look: "Aspeto do site",
looks: { none: "PhotoReport", liga: "Liga Portugal", fpa: "Federação de Andebol" } as Record<string, string>,
photoFind: "Procura por foto",
photoFindHelp: "Quem edita pastas na cloud (como a Federação) pode carregar uma foto e procurar essa cara no arquivo. A foto de pesquisa não fica guardada. Requer reconhecimento de caras ligado.",
hostname: "Endereço próprio",
hostnamePlaceholder: "arquivo.ligaportugal.pt",
hostnameHelp: "Opcional. Aponta esse endereço (DNS, CNAME) para o mesmo servidor do arquivo: o arquivo abre na raiz e o certificado é pedido sozinho.",
+330
View File
@@ -0,0 +1,330 @@
import type { Module } from "@photoreport/contracts";
import { useEffect, useRef, useState } from "react";
import { engineAuto, exportFrame, Viewer } from "../develop/Viewer.js";
import { loadEngine, type EngineModule } from "../develop/engine.js";
import { DevelopPanels } from "../develop/Panels.js";
import type { Crop } from "../develop/session.js";
import { t } from "../i18n.js";
import { jpegFromRgba } from "./finishMergedJpeg.js";
import { folderRead, saveDevelopedJpeg, saveDevelopedXmp } from "./folderDrop.js";
import type { FolderFile } from "./folderDrop.js";
import { developedJpegName, developedXmpName, developXmp, dirOf, FOLDER_DEVELOP_EDGE, interiorCommand, interiorPartial, partialFromSettings, partialFromXmp } from "./interiorPreset.js";
const MODULES: readonly Module[] = ["basic", "detail"];
const FULL: Crop = { rect: { x0: 0, y0: 0, x1: 1, y1: 1 }, angle: 0, aspect: null };
const isTyping = (target: EventTarget | null) =>
target instanceof HTMLElement && (target.isContentEditable || ["INPUT", "TEXTAREA", "SELECT"].includes(target.tagName));
function setCommand(values: Record<string, number>): string {
return JSON.stringify({ command: "develop.set", params: { values } });
}
/** Temperature and tint only take effect once the white balance is no longer As Shot. */
function applyValues(mod: EngineModule, settings: string, values: Record<string, number>): string {
let next = mod.apply(settings, setCommand(values));
if ("wb.temp" in values || "wb.tint" in values) {
next = mod.apply(next, JSON.stringify({ command: "develop.merge", params: { partial: { wb: { mode: "custom", scale: "kelvin" } } } }));
}
return next;
}
/**
* Revelar for one file from a folder dropped on this computer. Settings stay in this window.
* Opening the photo applies the interior look (neutral whites, recovered windows, colour). Nothing is uploaded.
*/
export function FolderDevelop(props: {
files: readonly FolderFile[];
path: string;
onPath: (path: string) => void;
onClose: () => void;
}) {
const { files, path, onPath, onClose } = props;
const file = files.find((item) => item.path === path) ?? null;
const engineRef = useRef<EngineModule | null>(null);
const pathRef = useRef(path);
pathRef.current = path;
const remembered = useRef(new Map<string, string>());
const dressing = useRef<string | null>(null);
const [engine, setEngine] = useState<EngineModule | null>(null);
const [missing, setMissing] = useState(false);
const [settings, setSettings] = useState<string | null>(null);
const [opened, setOpened] = useState(false);
const [before, setBefore] = useState(false);
const [picking, setPicking] = useState(false);
const [dragging, setDragging] = useState(false);
const [saving, setSaving] = useState(false);
const [note, setNote] = useState<string | null>(null);
const strip = useRef<HTMLDivElement>(null);
useEffect(() => {
let dead = false;
loadEngine().then(
(mod) => {
if (dead) return;
engineRef.current = mod;
setEngine(mod);
},
() => {
if (!dead) setMissing(true);
},
);
return () => {
dead = true;
};
}, []);
useEffect(() => {
if (!engine) return;
setSettings(remembered.current.get(path) ?? engine.defaultSettings());
setOpened(false);
setBefore(false);
setPicking(false);
}, [engine, path]);
useEffect(() => {
strip.current?.querySelector("[data-current='true']")?.scrollIntoView({ inline: "center", block: "nearest" });
}, [path]);
const applyInterior = async (forPath: string, fromSidecar: boolean) => {
const mod = engineRef.current;
if (!mod || dressing.current === forPath) return;
dressing.current = forPath;
setNote(t.folderDevelop.dressing);
try {
let next = mod.defaultSettings();
let loaded = false;
if (fromSidecar) {
const slash = Math.max(forPath.lastIndexOf("/"), forPath.lastIndexOf("\\"));
const fileName = slash >= 0 ? forPath.slice(slash + 1) : forPath;
const xmpPath = `${dirOf(forPath)}/${developedXmpName(fileName)}`;
try {
const bytes = await folderRead(xmpPath);
const partial = partialFromXmp(new TextDecoder().decode(bytes));
if (partial) {
next = mod.apply(next, interiorCommand(partial));
loaded = true;
}
} catch {
// No sidecar yet: the interior finish below is the first edit.
}
}
if (!loaded) {
let exposure: number | undefined;
try {
const tone = await engineAuto(forPath, "tone");
exposure = tone["light.exposure"];
} catch {
// The finish still opens the room when the photo has nothing to measure.
}
next = mod.apply(mod.defaultSettings(), interiorCommand(interiorPartial(exposure)));
}
if (pathRef.current !== forPath) return;
remembered.current.set(forPath, next);
setSettings(next);
setNote(null);
} catch {
if (pathRef.current !== forPath) return;
const next = mod.apply(mod.defaultSettings(), interiorCommand(interiorPartial(undefined)));
remembered.current.set(forPath, next);
setSettings(next);
setNote(null);
} finally {
if (dressing.current === forPath) dressing.current = null;
}
};
const index = files.findIndex((item) => item.path === path);
const go = (delta: number) => {
const next = files[index + delta];
if (next) onPath(next.path);
};
useEffect(() => {
const onKey = (e: KeyboardEvent) => {
if (isTyping(e.target)) return;
e.stopPropagation();
if (e.key === "Escape") {
e.preventDefault();
if (picking) setPicking(false);
else onClose();
return;
}
if (e.metaKey || e.ctrlKey || e.altKey) return;
if (e.key === "ArrowRight") {
e.preventDefault();
go(1);
} else if (e.key === "ArrowLeft") {
e.preventDefault();
go(-1);
} else if (e.key === "\\") setBefore((value) => !value);
else if (e.key.toLowerCase() === "w") setPicking((value) => !value);
};
window.addEventListener("keydown", onKey, true);
return () => window.removeEventListener("keydown", onKey, true);
}, [go, onClose, picking]);
const setValue = (id: string, value: number) => {
const mod = engineRef.current;
if (!mod || !settings) return;
setDragging(true);
const next = applyValues(mod, settings, { [id]: value });
remembered.current.set(path, next);
setSettings(next);
};
const save = async () => {
const mod = engineRef.current;
if (!mod || !settings || !file || saving) return;
setSaving(true);
setNote(t.folderDevelop.saving);
try {
const frame = await exportFrame(path, settings, FOLDER_DEVELOP_EDGE, FOLDER_DEVELOP_EDGE);
const blob = await jpegFromRgba(frame.pixels, frame.width, frame.height);
const bytes = new Uint8Array(await blob.arrayBuffer());
const name = developedJpegName(file.name);
const dir = dirOf(file.path);
const where = await saveDevelopedJpeg(dir, name, bytes);
const partial = partialFromSettings(settings);
if (partial) await saveDevelopedXmp(dir, developedXmpName(file.name), new TextEncoder().encode(developXmp(partial)));
setNote(where === "beside" ? t.folderDevelop.savedBeside(name) : t.folderDevelop.savedDownload(name));
} catch {
setNote(t.folderDevelop.saveFailed);
} finally {
setSaving(false);
}
};
if (!file) return null;
const shown = settings && before && engine ? engine.defaultSettings() : settings;
return (
<div className="flex min-h-0 flex-1 flex-col">
<div className="flex flex-wrap items-center gap-2 border-b border-line bg-raised px-3 py-1.5 text-[12px]">
<button type="button" onClick={onClose} className="h-6 border border-black bg-cell px-2.5 text-[12px] text-ink hover:bg-cell-on">
{t.folderDevelop.back}
</button>
<span className="min-w-0 flex-1 truncate text-ink" title={file.path}>
{file.name}
</span>
<button
type="button"
title={t.folderDevelop.presetHelp}
disabled={!opened || !engine || saving}
onClick={() => void applyInterior(path, false)}
className="h-6 border border-black bg-cell px-2.5 text-[12px] text-ink hover:bg-cell-on disabled:opacity-40"
>
{t.folderDevelop.preset}
</button>
<button
type="button"
disabled={!opened || !settings || saving}
onClick={() => void save()}
className="h-6 border border-black bg-accent px-2.5 text-[12px] text-white disabled:opacity-40"
>
{t.folderDevelop.save}
</button>
{note && (
<span role="status" className="max-w-sm truncate text-[12px] text-muted" title={note}>
{note}
</span>
)}
</div>
{missing ? (
<p className="p-8 text-center text-[13px] text-faint">{t.dev.engineMissing}</p>
) : (
<div className="flex min-h-0 flex-1">
<div className="min-w-0 flex-1 bg-black">
{engine && shown ? (
<Viewer
photoKey={path}
sourceUrl=""
settings={shown}
dragging={dragging}
cropping={false}
crop={FULL}
decodeEdge={FOLDER_DEVELOP_EDGE}
localSource={() => folderRead(path).catch(() => null)}
picking={picking}
onSourceSize={() => {
setOpened(true);
if (!remembered.current.has(path)) void applyInterior(path, true);
}}
onPick={(u, v) => {
setPicking(false);
void (async () => {
const mod = engineRef.current;
if (!mod || !settings) return;
try {
const values = await engineAuto(path, "pick", { x: u, y: v });
const next = applyValues(mod, settings, values);
remembered.current.set(path, next);
setSettings(next);
} catch {
setNote(t.folderDevelop.adjustFailed);
}
})();
}}
onError={() => setNote(t.folderDevelop.openFailed)}
/>
) : (
<p className="p-8 text-center font-mono text-[12px] text-faint">{t.dev.loading}</p>
)}
</div>
<aside className="w-80 shrink-0 overflow-y-auto border-l border-line bg-panel">
<DevelopPanels
modules={MODULES}
value={(id) => (engine && settings ? engine.value(settings, id) : Number.NaN)}
disabled={!opened || !engine}
onChange={setValue}
onEnd={() => setDragging(false)}
onSet={(values) => {
const mod = engineRef.current;
if (!mod || !settings) return;
const next = applyValues(mod, settings, values);
remembered.current.set(path, next);
setSettings(next);
}}
picking={picking}
onAuto={(kind) => {
if (kind === "pick") {
setPicking((value) => !value);
return;
}
void (async () => {
const mod = engineRef.current;
if (!mod || !settings) return;
try {
const values = await engineAuto(path, kind, kind === "tone" ? { settings } : {});
const next = applyValues(mod, settings, values);
remembered.current.set(path, next);
setSettings(next);
} catch {
setNote(t.folderDevelop.adjustFailed);
}
})();
}}
/>
<div className="px-3 py-2 text-[11px] text-faint">{t.folderDevelop.presetHelp}</div>
</aside>
</div>
)}
<div ref={strip} className="flex h-10 shrink-0 items-center gap-1 overflow-x-auto border-t border-line bg-chrome px-2">
{files.map((item) => (
<button
key={item.path}
type="button"
data-current={item.path === path ? "true" : "false"}
onClick={() => onPath(item.path)}
className={`h-6 max-w-40 shrink-0 truncate border px-2 font-mono text-[10px] ${
item.path === path ? "border-white/70 bg-cell-on text-ink" : "border-transparent text-muted hover:text-ink"
}`}
>
{item.name}
</button>
))}
</div>
</div>
);
}
+466
View File
@@ -0,0 +1,466 @@
import type { ColorLabel, PhotoFlag, PhotoPatch } from "@photoreport/contracts";
import { useEffect, useRef, useState, type CSSProperties } from "react";
import { t } from "../i18n.js";
import { prefs } from "../platform.js";
import { LABEL_COLOR } from "./Grid.js";
import { FOLDER_CELL_H, FOLDER_CELL_W, FOLDER_GAP, folderCols, folderWindow } from "./folder-layout.js";
import type { FolderListing } from "./folderDrop.js";
import { mergeFailureText } from "./folderMerge.js";
import { MergeError } from "./mergeExposures.js";
import { isMac, patchForKey, pmPatchForKey } from "./store.js";
interface Mark {
flag: PhotoFlag;
rating: number;
colorLabel: ColorLabel;
}
const EMPTY: Mark = { flag: "NONE", rating: 0, colorLabel: "NONE" };
const thumbs = new Map<string, string>();
const inflight = new Map<string, Promise<string | null>>();
function thumbUrl(path: string, edge: number, load: (path: string, edge: number) => Promise<ArrayBuffer | null>): Promise<string | null> {
const key = `${edge}:${path}`;
const hit = thumbs.get(key);
if (hit) return Promise.resolve(hit);
const pending = inflight.get(key);
if (pending) return pending;
const job = load(path, edge)
.then((buf) => {
inflight.delete(key);
if (!buf) return null;
const url = URL.createObjectURL(new Blob([buf], { type: "image/jpeg" }));
thumbs.set(key, url);
if (thumbs.size > 400) {
const oldest = thumbs.keys().next().value;
if (oldest) {
const gone = thumbs.get(oldest);
thumbs.delete(oldest);
if (gone) URL.revokeObjectURL(gone);
}
}
return url;
})
.catch(() => {
inflight.delete(key);
return null;
});
inflight.set(key, job);
return job;
}
function applyMark(mark: Mark, patch: PhotoPatch): Mark {
const next = { ...mark };
if (patch.flag) next.flag = patch.flag;
if (patch.rating !== undefined) next.rating = patch.rating;
if (patch.colorLabel) next.colorLabel = patch.colorLabel;
return next;
}
const isTyping = (target: EventTarget | null) =>
target instanceof HTMLElement && (target.isContentEditable || ["INPUT", "TEXTAREA", "SELECT"].includes(target.tagName));
/**
* Photo Mechanic's contact sheet for one folder on this computer: thumbnails, names, and culling for this
* session. Nothing is uploaded and no event is created. Stars and flags are not written back to the files.
*/
export function FolderSheet(props: {
folder: FolderListing;
onClose: () => void;
thumb: (path: string, edge: number) => Promise<ArrayBuffer | null>;
/**
* Merges the photos on this sheet and returns how many DNG files were written beside them.
* Absent in a view that cannot edit. The library's own merge stays on the event underneath.
*/
merge?: (input: {
files: FolderListing["files"];
selectedIds: readonly string[];
jpeg: boolean;
onStatus: (stack: number, total: number, phase?: "merge" | "jpeg") => void;
}) => Promise<{ made: number; jpeg: "beside" | "download" | "none" }>;
/** Opens the focused file in Revelar. Absent where the sheet cannot edit. */
onDevelop?: (path: string) => void;
}) {
const { folder, onClose, thumb, merge, onDevelop } = props;
const files = folder.files;
const scroller = useRef<HTMLDivElement>(null);
const [width, setWidth] = useState(800);
const [height, setHeight] = useState(600);
const [scrollTop, setScrollTop] = useState(0);
const [focus, setFocus] = useState<string | null>(files[0]?.path ?? null);
const [anchor, setAnchor] = useState<string | null>(files[0]?.path ?? null);
const [selected, setSelected] = useState<ReadonlySet<string>>(() => new Set(files[0] ? [files[0].path] : []));
const [marks, setMarks] = useState<ReadonlyMap<string, Mark>>(() => new Map());
const [loupe, setLoupe] = useState(false);
const [mergeStatus, setMergeStatus] = useState<string | null>(null);
const [mergeFailed, setMergeFailed] = useState(false);
const [merging, setMerging] = useState(false);
const [alsoJpeg, setAlsoJpeg] = useState(() => prefs.get("folder.alsoJpeg") !== "0");
const mergePending = useRef(false);
const runMerge = () => {
if (!merge || mergePending.current) return;
const withJpeg = alsoJpeg;
mergePending.current = true;
setMerging(true);
setMergeFailed(false);
setMergeStatus(t.merge.reading);
void merge({
files,
selectedIds: [...selected],
jpeg: withJpeg,
onStatus: (stack, total, phase) => setMergeStatus(phase === "jpeg" ? t.folderSheet.workingJpeg(stack, total) : t.merge.working(stack, total)),
}).then(
(result) => setMergeStatus(result.jpeg === "beside" ? t.folderSheet.mergedBoth(result.made) : result.jpeg === "download" ? t.folderSheet.mergedDownload(result.made) : t.folderSheet.merged(result.made)),
(err: unknown) => {
const code = err instanceof MergeError ? err.code : "failed";
const detail = err instanceof MergeError ? err.detail : undefined;
setMergeStatus(mergeFailureText(code, detail));
setMergeFailed(true);
},
).finally(() => {
mergePending.current = false;
setMerging(false);
});
};
useEffect(() => {
const el = scroller.current;
if (!el) return;
const measure = () => {
if (el.clientWidth > 0) setWidth(el.clientWidth);
if (el.clientHeight > 0) setHeight(el.clientHeight);
};
measure();
if (typeof ResizeObserver === "undefined") return;
const observer = new ResizeObserver(measure);
observer.observe(el);
return () => observer.disconnect();
}, [loupe]);
const cols = folderCols(width);
const rowH = FOLDER_CELL_H + FOLDER_GAP;
const rows = Math.max(1, Math.ceil(files.length / cols));
const windowed = folderWindow(files.length, cols, scrollTop, height);
useEffect(() => {
const el = scroller.current;
if (!el || !focus) return;
const index = files.findIndex((file) => file.path === focus);
if (index < 0) return;
const top = Math.floor(index / cols) * rowH;
const bottom = top + rowH;
if (top < el.scrollTop) el.scrollTop = top;
else if (bottom > el.scrollTop + el.clientHeight && el.clientHeight > 0) el.scrollTop = bottom - el.clientHeight;
}, [focus, cols, files, rowH]);
useEffect(() => {
const onKey = (e: KeyboardEvent) => {
if (isTyping(e.target)) return;
// The library is still mounted under this sheet; its keys must not cull that event.
e.stopPropagation();
const paths = files.map((file) => file.path);
const at = focus ? paths.indexOf(focus) : -1;
const current = focus ? (marks.get(focus) ?? EMPTY) : EMPTY;
const move = (delta: number, extend: boolean) => {
e.preventDefault();
if (!paths.length) return;
const next = paths[Math.max(0, Math.min(paths.length - 1, at < 0 ? 0 : at + delta))]!;
setFocus(next);
if (extend && anchor) {
const from = paths.indexOf(anchor);
const to = paths.indexOf(next);
const [lo, hi] = from < to ? [from, to] : [to, from];
setSelected(new Set(paths.slice(lo, hi + 1)));
} else {
setSelected(new Set([next]));
setAnchor(next);
}
};
if (e.key === "Escape") {
e.preventDefault();
e.stopPropagation();
if (loupe) setLoupe(false);
else onClose();
return;
}
if (e.key === "Delete" || e.key === "Backspace") {
e.preventDefault();
e.stopPropagation();
return;
}
const pm = pmPatchForKey(e, isMac(), current.flag);
const plain = !e.metaKey && !e.ctrlKey && !e.altKey ? patchForKey(e.key) : undefined;
const change = pm ?? plain;
if (change && selected.size) {
e.preventDefault();
e.stopPropagation();
setMarks((prev) => {
const next = new Map(prev);
const ids = [...selected];
const clearing = change.colorLabel && change.colorLabel !== "NONE" && ids.every((id) => (prev.get(id) ?? EMPTY).colorLabel === change.colorLabel);
for (const id of ids) {
const mark = applyMark(prev.get(id) ?? EMPTY, clearing ? { ...change, colorLabel: "NONE" } : change);
next.set(id, mark);
}
return next;
});
if (loupe && change.flag) move(1, false);
return;
}
if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === "a") {
e.preventDefault();
setSelected(new Set(paths));
return;
}
if (e.metaKey || e.ctrlKey || e.altKey) return;
if (e.key === "ArrowRight") return move(1, e.shiftKey);
if (e.key === "ArrowLeft") return move(-1, e.shiftKey);
if (e.key === "ArrowDown") return move(loupe ? 1 : cols, e.shiftKey);
if (e.key === "ArrowUp") return move(loupe ? -1 : -cols, e.shiftKey);
if ((e.key === "Enter" || e.key.toLowerCase() === "e") && focus) {
e.preventDefault();
setLoupe(true);
return;
}
if (e.key.toLowerCase() === "d" && focus && onDevelop) {
e.preventDefault();
onDevelop(focus);
return;
}
if (e.key.toLowerCase() === "g") setLoupe(false);
};
window.addEventListener("keydown", onKey, true);
return () => window.removeEventListener("keydown", onKey, true);
}, [anchor, cols, files, focus, loupe, marks, onClose, onDevelop, selected]);
const pick = (path: string, e: React.MouseEvent) => {
const paths = files.map((file) => file.path);
if (e.shiftKey && anchor) {
const from = paths.indexOf(anchor);
const to = paths.indexOf(path);
if (from >= 0 && to >= 0) {
const [lo, hi] = from < to ? [from, to] : [to, from];
setSelected(new Set(paths.slice(lo, hi + 1)));
setFocus(path);
return;
}
}
if (e.metaKey || e.ctrlKey) {
const next = new Set(selected);
if (next.has(path)) next.delete(path);
else next.add(path);
setSelected(next);
setFocus(path);
setAnchor(path);
return;
}
setSelected(new Set([path]));
setFocus(path);
setAnchor(path);
};
const focusFile = files.find((file) => file.path === focus) ?? null;
const focusMark = focus ? (marks.get(focus) ?? EMPTY) : EMPTY;
return (
<div className="flex min-h-0 flex-1 flex-col">
<div className="flex flex-wrap items-center gap-3 border-b border-line bg-raised px-3 py-1.5 text-[12px]">
<span className="truncate text-ink" title={folder.path}>
{folder.name}
</span>
<span className="font-mono text-[11px] text-faint">{t.folderSheet.count(files.length)}</span>
<span className="hidden text-[11px] text-faint sm:inline">{t.folderSheet.hint}</span>
{onDevelop && focus && (
<button
type="button"
title={t.folderSheet.developTitle}
onClick={() => onDevelop(focus)}
className="h-6 border border-black bg-cell px-2.5 text-[12px] text-ink hover:bg-cell-on"
>
{t.folderSheet.develop}
</button>
)}
{merge && files.length > 0 && (
<span className="inline-flex items-center gap-2">
<button
type="button"
title={t.folderSheet.mergeTitle}
disabled={merging}
onClick={runMerge}
className="h-6 border border-black bg-cell px-2.5 text-[12px] text-ink hover:bg-cell-on disabled:opacity-40"
>
{t.merge.button}
</button>
<label title={t.folderSheet.alsoJpegTitle} className="inline-flex items-center gap-1.5 text-[12px] text-ink">
<input
type="checkbox"
checked={alsoJpeg}
disabled={merging}
onChange={(e) => {
setAlsoJpeg(e.target.checked);
prefs.set("folder.alsoJpeg", e.target.checked ? "1" : "0");
}}
/>
{t.folderSheet.alsoJpeg}
</label>
{mergeStatus && (
<span role="status" title={mergeStatus} className={`max-w-xl text-[12px] ${mergeFailed ? "text-danger" : "text-muted"}`}>
{mergeStatus}
</span>
)}
</span>
)}
<button type="button" onClick={onClose} className="ml-auto h-6 border border-black bg-cell px-2.5 text-[12px] text-ink hover:bg-cell-on">
{t.folderSheet.close}
</button>
</div>
{loupe && focusFile ? (
<SheetLoupe file={focusFile} mark={focusMark} index={files.findIndex((file) => file.path === focusFile.path)} total={files.length} thumb={thumb} onClose={() => setLoupe(false)} />
) : files.length === 0 ? (
<p className="p-8 text-center text-[13px] text-faint">{t.folderSheet.empty}</p>
) : (
<div
ref={scroller}
className="min-h-0 flex-1 overflow-y-auto"
onScroll={(e) => setScrollTop(e.currentTarget.scrollTop)}
>
<div className="relative" style={{ height: rows * rowH }}>
{files.slice(windowed.from, windowed.to).map((file, offset) => {
const index = windowed.from + offset;
const mark = marks.get(file.path) ?? EMPTY;
return (
<SheetCell
key={file.path}
file={file}
index={index}
mark={mark}
selected={selected.has(file.path)}
focused={focus === file.path}
style={{
position: "absolute",
left: (index % cols) * (FOLDER_CELL_W + FOLDER_GAP),
top: Math.floor(index / cols) * rowH,
width: FOLDER_CELL_W,
height: FOLDER_CELL_H,
}}
thumb={thumb}
onPick={pick}
onOpen={(path) => {
setFocus(path);
setSelected(new Set([path]));
setAnchor(path);
setLoupe(true);
}}
/>
);
})}
</div>
</div>
)}
</div>
);
}
function SheetCell(props: {
file: { path: string; name: string };
index: number;
mark: Mark;
selected: boolean;
focused: boolean;
style: CSSProperties;
thumb: (path: string, edge: number) => Promise<ArrayBuffer | null>;
onPick: (path: string, e: React.MouseEvent) => void;
onOpen: (path: string) => void;
}) {
const { file, mark } = props;
const [src, setSrc] = useState<string | null>(null);
const [failed, setFailed] = useState(false);
useEffect(() => {
let dead = false;
setFailed(false);
void thumbUrl(file.path, 480, props.thumb).then((url) => {
if (!dead) setSrc(url);
});
return () => {
dead = true;
};
}, [file.path, props.thumb]);
const label = LABEL_COLOR[mark.colorLabel];
const flagText = mark.flag === "PICK" ? ", escolhida" : mark.flag === "REJECT" ? ", rejeitada" : "";
const stars = mark.rating ? `, ${mark.rating} estrelas` : "";
return (
<button
type="button"
style={props.style}
data-photo-id={file.path}
aria-pressed={props.selected}
aria-label={`${file.name}${flagText}${stars}`}
onClick={(e) => props.onPick(file.path, e)}
onDoubleClick={() => props.onOpen(file.path)}
className={`flex flex-col border px-1.5 pb-1 pt-1 ${
props.selected ? "border-[#9a9a9a] bg-cell-on" : "border-[#151516] bg-cell hover:bg-[#444445]"
} ${props.focused ? "outline outline-1 outline-offset-[-3px] outline-white/60" : ""} ${mark.flag === "REJECT" ? "opacity-40" : ""}`}
>
<span className="flex min-h-0 w-full flex-1 items-center justify-center">
{failed ? (
<span className="font-mono text-[10px] uppercase text-faint">erro</span>
) : src ? (
<img src={src} alt="" draggable={false} onError={() => setFailed(true)} className="max-h-full max-w-full object-contain" />
) : (
<span className="font-mono text-[10px] uppercase text-faint">…</span>
)}
</span>
<span className="flex w-full items-center justify-between text-[11px]">
<span aria-hidden="true" className={`w-3 ${mark.flag === "REJECT" ? "text-danger" : "text-ink"}`}>
{mark.flag === "PICK" ? "⚑" : mark.flag === "REJECT" ? "✕" : ""}
</span>
<span aria-hidden="true" className="tracking-[1px] text-[#cfcfcf]">
{"★".repeat(mark.rating)}
</span>
<span aria-hidden="true" className="h-2.5 w-2.5 rounded-[2px]" style={{ background: label ?? "transparent" }} />
</span>
<span className="w-full truncate text-center font-mono text-[10px] text-muted" title={file.name}>
{props.index + 1} {file.name}
</span>
</button>
);
}
function SheetLoupe(props: {
file: { path: string; name: string };
mark: Mark;
index: number;
total: number;
thumb: (path: string, edge: number) => Promise<ArrayBuffer | null>;
onClose: () => void;
}) {
const [src, setSrc] = useState<string | null>(null);
useEffect(() => {
let dead = false;
setSrc(null);
void thumbUrl(props.file.path, 1440, props.thumb).then((url) => {
if (!dead) setSrc(url);
});
return () => {
dead = true;
};
}, [props.file.path, props.thumb]);
return (
<div className="flex min-h-0 flex-1 flex-col bg-black">
<div className="flex items-center gap-3 px-3 py-1 text-[12px] text-muted">
<span className="truncate text-ink">{props.file.name}</span>
<span className="font-mono text-[11px] text-faint">
{props.index + 1} / {props.total}
</span>
<button type="button" onClick={props.onClose} className="ml-auto text-[12px] text-faint underline">
{t.folderSheet.close}
</button>
</div>
<div className="flex min-h-0 flex-1 items-center justify-center p-3">
{src ? <img src={src} alt="" className="max-h-full max-w-full object-contain" /> : <span className="font-mono text-[12px] text-faint">…</span>}
</div>
</div>
);
}
+39 -4
View File
@@ -9,6 +9,13 @@ import { localPhotos } from "../offline/local.js";
// the target has no organization, so a bare client is enough.
vi.mock("../auth.js", () => ({ useAuth: () => ({ api: {} }) }));
const autopilot = vi.hoisted(() => ({
run: (_args: unknown): Promise<void> => Promise.resolve(),
}));
vi.mock("../offline/autopilot.js", () => ({
planLocalAutopilot: (args: unknown) => autopilot.run(args),
}));
const status = (running: boolean): FtpStatus => ({
running,
settings: { port: 2121, users: [{ name: "1dx", password: "1dx" }], ingest: "~/Desktop/ingest", workFolder: "~/Desktop/{year}/{date} - {event}", autoStart: false, uploadOriginals: false },
@@ -17,22 +24,26 @@ const status = (running: boolean): FtpStatus => ({
error: null,
});
function fakeShell(files: IncomingFile[]) {
function fakeShell(files: IncomingFile[], originals = false) {
let running = false;
const calls: string[] = [];
const sent: unknown[] = [];
const asStatus = (runningNow: boolean): FtpStatus => ({
...status(runningNow),
settings: { ...status(runningNow).settings, uploadOriginals: originals },
});
const invoke = vi.fn(async (cmd: string, args?: Record<string, unknown>) => {
calls.push(cmd);
switch (cmd) {
case "ftp_status":
return status(running);
return asStatus(running);
case "ftp_start":
running = true;
return status(true);
return asStatus(true);
case "ftp_take":
return files.splice(0);
case "ftp_read":
return new TextEncoder().encode(`bytes of ${String(args?.path)}`).buffer;
return [...new TextEncoder().encode(`bytes of ${String(args?.path)}`)];
case "ftp_preview":
// Over the JSON bridge (page loaded from the server) binary answers arrive as arrays of numbers.
return [...new TextEncoder().encode(`preview of ${String(args?.path)}`)];
@@ -80,6 +91,30 @@ describe("local FTP feed", () => {
for (const photo of localPhotos.list()) localPhotos.remove(photo.id);
});
it("sends the original while detection is still running", async () => {
let release: (() => void) | undefined;
autopilot.run = () =>
new Promise((resolve) => {
release = resolve;
});
const shell = fakeShell([{ path: "/x/FTP/C.JPG", name: "C.JPG", size: 10, modifiedMs: 3 }], true);
const added: { name: string; kind: string }[] = [];
const add = (files: Iterable<File>, _eventId?: string, onSettled?: (f: File, s: UploadStatus) => void, original?: { sha256: string } | "original") => {
for (const f of files) {
added.push({ name: f.name, kind: original === "original" ? "original" : "preview" });
onSettled?.(f, "done");
}
};
const { result } = renderHook(() => useLocalFtp(add, true, shell.invoke));
await waitFor(() => expect(result.current.status).not.toBeNull());
act(() => result.current.setTarget({ id: "ev1", title: "ABC x Benfica", home: "ABC", away: "Benfica", startsAt: "2026-10-12T18:00:00Z" } as EventSummary));
await act(() => result.current.start());
await waitFor(() => expect(added).toEqual([{ name: "C.JPG", kind: "original" }]));
release?.();
autopilot.run = () => Promise.resolve();
for (const photo of localPhotos.list()) localPhotos.remove(photo.id);
});
it("does nothing outside the desktop app", async () => {
const shell = fakeShell([]);
renderHook(() => useLocalFtp(() => {}, false, shell.invoke));
+56 -25
View File
@@ -3,7 +3,7 @@ import type { EventSummary } from "@photoreport/sdk";
import { useAuth } from "../auth.js";
import { planLocalAutopilot } from "../offline/autopilot.js";
import { cache } from "../offline/cache.js";
import { exifDateTime, lisbonInstant, localPhoto, localPhotos, routeLocally } from "../offline/local.js";
import { eventForArrival, exifDateTime, lisbonInstant, localPhoto, localPhotos } from "../offline/local.js";
import { localId, offlineQueue } from "../offline/queue.js";
import { useCallback, useEffect, useRef, useState } from "react";
import { t } from "../i18n.js";
@@ -15,7 +15,7 @@ import type { DesktopOrigin, PreviewOf, UploadStatus } from "./uploads.js";
export interface FtpSettings {
port: number;
/** `enabled` missing (older desktop app): on. */
users: { name: string; password: string; enabled?: boolean }[];
users: { name: string; password: string; enabled?: boolean; label?: string }[];
ingest: string;
workFolder: string;
autoStart: boolean;
@@ -60,6 +60,12 @@ const IN_FLIGHT = 6;
* token expires, and the server answers 401. Two leaves room for the upload to leave.
*/
const IN_FLIGHT_ORIGINALS = 2;
/**
* Originals on the wire at once. One waits out each detection and each server reply, so a full card sits in
* ingest while the link is idle. This matches the upload queue. The slot stays held until that file has left,
* so the queue cannot pull the whole folder into memory.
*/
const ORIGINAL_UPLOADS = 4;
const POLL_MS = 1000;
/** The shell put the file back on the queue because the camera has not finished sending it. */
@@ -103,9 +109,11 @@ export function useLocalFtp(add: Add, enabled: boolean, invoke: Invoke = tauriIn
const [checkState, setCheckState] = useState<null | "busy" | "done" | "unsupported">(null);
const backlog = useRef<IncomingFile[]>([]);
const inFlight = useRef(0);
/** One full original at a time. Several at once freeze the window, and the preview must not wait for that. */
/** Originals being read or uploaded. The preview is already on screen and does not wait for these. */
const reading = useRef(0);
const readQueue = useRef<(() => void)[]>([]);
/** Local detection, one photo at a time, off the upload path. */
const autopilotChain = useRef(Promise.resolve());
const targetRef = useRef(target);
targetRef.current = target;
const originalsRef = useRef(false);
@@ -119,7 +127,7 @@ export function useLocalFtp(add: Add, enabled: boolean, invoke: Invoke = tauriIn
const pump = useCallback(() => {
const takeOriginal = () => {
if (reading.current < 1) {
if (reading.current < ORIGINAL_UPLOADS) {
reading.current++;
return Promise.resolve();
}
@@ -143,12 +151,13 @@ export function useLocalFtp(add: Add, enabled: boolean, invoke: Invoke = tauriIn
const [preview, info] = await Promise.all([invoke<unknown>("ftp_preview", { path: f.path }).then(asArrayBuffer), invoke<PreviewOf>("ftp_info", { path: f.path })]);
// In the library at once (with or without a network), from the preview made here; the server's copy
// takes its place when the upload is done.
const capturedAt = lisbonInstant(exifDateTime(preview));
const cached = orgId ? await cache.events(orgId) : null;
const events = cached?.events ?? [];
// A pin kept from a game already put away is not in the open list: follow the capture time instead.
const pinned = to && (!cached || events.some((e) => e.id === to.id && !e.archivedAt)) ? to : null;
const eventId = pinned?.id ?? routeLocally(events, capturedAt);
const capturedAt = lisbonInstant(exifDateTime(preview));
// A pin on a game already put away, or left over from the previous match, does not take the next photos.
const pinnedId = to && (!cached || events.some((e) => e.id === to.id && !e.archivedAt)) ? to.id : null;
const eventId = eventForArrival(pinnedId, events, capturedAt);
const filed = events.find((e) => e.id === eventId);
if (!localPhotos.bySha(info.sha256)) {
let url = "";
try {
@@ -166,11 +175,20 @@ export function useLocalFtp(add: Add, enabled: boolean, invoke: Invoke = tauriIn
slot = false;
pump();
// A full original from the camera still counts as FTP (the event's autopilot edits it), not a hand upload.
const routed = pinned ? undefined : events.find((e) => e.id === eventId);
const settle = (_file: File, result: UploadStatus, photo?: PhotoSummary) => {
if (result === "done" || result === "duplicate") {
setCounts((c) => ({ ...c, sent: c.sent + 1 }));
invoke("ftp_sent", { path: f.path, event: pinned?.title ?? (routed ? eventLabel(routed) : ""), date: pinned?.date ?? (routed ? routed.startsAt.slice(0, 10) : "") }).catch(() => {});
let sentEvent = "";
let sentDate = "";
if (filed) {
sentEvent = eventLabel(filed);
sentDate = filed.startsAt.slice(0, 10);
} else if (to && eventId === to.id) {
// The pin is not in the cached list (no capture time, or this computer has not seen the event).
sentEvent = to.title;
sentDate = to.date;
}
invoke("ftp_sent", { path: f.path, event: sentEvent, date: sentDate }).catch(() => {});
// Changes made to it meanwhile now go to the server's copy.
if (photo && orgId) {
offlineQueue(orgId).uploaded(info.sha256, photo.id);
@@ -184,13 +202,19 @@ export function useLocalFtp(add: Add, enabled: boolean, invoke: Invoke = tauriIn
}
};
const event = events.find((e) => e.id === eventId);
await planLocalAutopilot({ api, orgId, event, sha256: info.sha256, preview, width: info.width, height: info.height }).catch(() => {});
// The cloud must not wait for detection. One at a time, or a full card freezes the window.
const plan = autopilotChain.current.then(() =>
planLocalAutopilot({ api, orgId, event, sha256: info.sha256, preview, width: info.width, height: info.height }).catch(() => {}),
);
autopilotChain.current = plan.then(
() => undefined,
() => undefined,
);
if (!full) {
const file = new File([preview], f.name, { type: "image/jpeg", lastModified: f.modifiedMs });
add([file], eventId ?? undefined, (_file, result, photo) => settle(_file, result, photo), info);
return;
}
// One original at a time, and only when it is this file's turn to go up. Several at once freeze the window.
await takeOriginal();
let held = true;
const drop = () => {
@@ -358,21 +382,25 @@ function SettingsForm({ ftp, initial, onDone }: { ftp: LocalFtpState; initial: F
<input className={field} type="number" min={1024} max={65535} value={s.port} onChange={(e) => setS({ ...s, port: Number(e.target.value) })} />
</label>
<div>
<span className="text-[11px] uppercase tracking-wide text-faint">{L.logins}</span>
<span className="text-[11px] uppercase tracking-wide text-faint">{L.connections}</span>
<p className="mb-1 text-[11px] text-faint">{L.connectionsHelp}</p>
{s.users.map((u, i) => (
<div key={i} className="mt-1 flex items-center gap-1">
<input type="checkbox" aria-label={`${L.loginOn}: ${u.name || L.user}`} title={L.loginOn} checked={u.enabled !== false} onChange={(e) => setUser(i, { enabled: e.target.checked })} />
<input className={field} aria-label={L.user} placeholder={L.user} value={u.name} onChange={(e) => setUser(i, { name: e.target.value })} autoComplete="off" />
<input className={field} aria-label={L.password} placeholder={L.password} value={u.password} onChange={(e) => setUser(i, { password: e.target.value })} autoComplete="off" />
{s.users.length > 1 && (
<button type="button" aria-label={L.removeLogin} onClick={() => setS({ ...s, users: s.users.filter((_, j) => j !== i) })} className="px-1 text-faint hover:text-ink">
×
</button>
)}
<div key={i} className="mb-2 border border-line bg-[#161617] p-2">
<input className={field} aria-label={L.machine} placeholder={L.machine} value={u.label ?? ""} onChange={(e) => setUser(i, { label: e.target.value })} autoComplete="off" />
<div className="mt-1 flex items-center gap-1">
<input type="checkbox" aria-label={`${L.loginOn}: ${u.name || L.user}`} title={L.loginOn} checked={u.enabled !== false} onChange={(e) => setUser(i, { enabled: e.target.checked })} />
<input className={field} aria-label={L.user} placeholder={L.user} value={u.name} onChange={(e) => setUser(i, { name: e.target.value })} autoComplete="off" />
<input className={field} aria-label={L.password} placeholder={L.password} value={u.password} onChange={(e) => setUser(i, { password: e.target.value })} autoComplete="off" />
{s.users.length > 1 && (
<button type="button" aria-label={L.removeLogin} onClick={() => setS({ ...s, users: s.users.filter((_, j) => j !== i) })} className="px-1 text-faint hover:text-ink">
×
</button>
)}
</div>
</div>
))}
<button type="button" onClick={() => setS({ ...s, users: [...s.users, { name: "", password: "", enabled: true }] })} className="mt-1 text-accent underline">
{L.addLogin}
<button type="button" onClick={() => setS({ ...s, users: [...s.users, { name: "", password: "", enabled: true, label: "" }] })} className="text-accent underline">
{L.addMachine}
</button>
</div>
<label className="block">
@@ -444,6 +472,7 @@ export function LocalFtpButton({ ftp, events, openEventId }: { ftp: LocalFtpStat
<div className="mb-3">
<div className="mb-1 text-[11px] uppercase tracking-wide text-faint">{L.target}</div>
<div className="text-ink">{target ? `${target.date} · ${target.title}` : L.noTarget}</div>
{target && events.some((e) => e.id === target.id && Date.parse(e.ingestUntil) < Date.now()) && <p className="mt-1 text-[#f0a35a]">{L.targetClosed}</p>}
{openEvent && openEvent.id !== target?.id && (
<button onClick={() => ftp.setTarget(openEvent)} className="mt-1 text-left text-accent underline">
{L.useOpen(eventLabel(openEvent))}
@@ -467,8 +496,10 @@ export function LocalFtpButton({ ftp, events, openEventId }: { ftp: LocalFtpStat
<dd className="select-all text-ink">{status.settings.port}</dd>
{status.settings.users.map((u) => (
<div key={u.name} className="contents">
<dt className="text-faint">{L.user}</dt>
<dt className="text-faint">{u.label || L.machine}</dt>
<dd className={`select-all ${u.enabled === false ? "text-faint line-through" : "text-ink"}`}>
<span className="font-sans">{u.label || u.name}</span>
<span className="text-faint"> · </span>
{u.name} <span className="text-faint">/</span> {u.password}
{u.enabled === false && <span className="ml-1 font-sans no-underline">({L.loginOff})</span>}
</dd>
+65
View File
@@ -0,0 +1,65 @@
import { useEffect, useState } from "react";
import { t } from "../i18n.js";
/** Lightroom's question before a photo leaves the collection it is open in. */
export function RemoveFromEventDialog(props: {
count: number;
name?: string;
onCancel: () => void;
onConfirm: () => Promise<void>;
}) {
const [busy, setBusy] = useState(false);
const [failed, setFailed] = useState(false);
useEffect(() => {
const onKey = (e: KeyboardEvent) => {
if (e.key === "Escape") {
e.preventDefault();
e.stopPropagation();
props.onCancel();
}
};
window.addEventListener("keydown", onKey, true);
return () => window.removeEventListener("keydown", onKey, true);
}, [props.onCancel]);
return (
<div className="fixed inset-0 z-50 flex items-center justify-center bg-black/60 p-4" role="presentation" onMouseDown={props.onCancel}>
<div
role="dialog"
aria-modal="true"
aria-labelledby="remove-event-title"
className="w-full max-w-md border border-line bg-panel p-4 shadow-xl"
onMouseDown={(e) => e.stopPropagation()}
>
<p id="remove-event-title" className="text-[14px] text-ink">
{t.removeFromEventAsk(props.count, props.name)}
</p>
<p className="mt-1 text-[12px] text-muted">{t.removeFromEventHelp}</p>
{failed && (
<p role="alert" className="mt-2 text-[12px] text-danger">
{t.unexpectedError}
</p>
)}
<div className="mt-4 flex justify-end gap-2">
<button type="button" disabled={busy} onClick={props.onCancel} className="h-8 border border-black bg-cell px-3 text-[13px] text-ink hover:bg-cell-on disabled:opacity-40">
{t.cancel}
</button>
<button
type="button"
disabled={busy}
onClick={() => {
setBusy(true);
setFailed(false);
void props.onConfirm().catch(() => {
setBusy(false);
setFailed(true);
});
}}
className="h-8 border border-black bg-accent px-3 text-[13px] text-white hover:brightness-110 disabled:opacity-40"
>
{t.remove}
</button>
</div>
</div>
</div>
);
}
+86
View File
@@ -0,0 +1,86 @@
import { render, renderHook, screen, waitFor } from "@testing-library/react";
import type { EventSummary } from "@photoreport/sdk";
import { describe, expect, it, vi } from "vitest";
import type { Invoke } from "./LocalFtp.js";
import type { UploadStatus } from "./uploads.js";
import { UsbCameraButton, type UsbStatus, useUsbCamera, withSidecars } from "./UsbCamera.js";
const camera: UsbStatus = {
supported: true,
tether: true,
devices: [{ id: "abc", name: "Canon Digital Camera", vendorId: 1193, productId: 13075, state: "tethered", error: null, catalogReady: true }],
files: [
{ name: "IMG_0001.JPG", size: 10, isNew: true, imported: false },
{ name: "IMG_0001.CR3", size: 20, isNew: true, imported: false },
{ name: "IMG_0002.JPG", size: 10, isNew: false, imported: false },
],
};
function shell(files: { path: string; name: string; size: number; modifiedMs: number }[]) {
const sent: unknown[] = [];
const invoke = vi.fn(async (cmd: string, args?: Record<string, unknown>) => {
if (cmd === "camera_status") return camera;
if (cmd === "camera_take") return files.splice(0);
if (cmd === "ftp_preview") return [...new TextEncoder().encode(`preview of ${String(args?.path)}`)];
if (cmd === "ftp_info") return { sha256: "sha", size: 5_000_000, width: 6000, height: 4000 };
if (cmd === "ftp_sent") {
sent.push(args);
return null;
}
return null;
}) as unknown as Invoke;
return { invoke, sent };
}
const event = { id: "ev1", title: "", home: "Portugal", away: "Suíça", startsAt: "2026-11-04T19:00:00Z" } as EventSummary;
const usbStub = {
status: camera,
outdated: false,
counts: { received: 0, sent: 0, failed: 0 },
setTether: vi.fn(),
syncClock: vi.fn(),
importFiles: vi.fn(),
refresh: vi.fn(),
};
describe("usb tether", () => {
it("pulls only files the shell already downloaded (chosen on the camera panel)", async () => {
const { invoke, sent } = shell([{ path: "/ingest/.usb/IMG_0001.JPG", name: "IMG_0001.JPG", size: 10, modifiedMs: 1 }]);
const added: { name: string; eventId: string | undefined }[] = [];
const add = (files: Iterable<File>, eventId?: string, onSettled?: (f: File, s: UploadStatus) => void) => {
for (const f of files) {
added.push({ name: f.name, eventId });
onSettled?.(f, "done");
}
};
renderHook(() => useUsbCamera(add, true, { id: "ev1", title: "Portugal x Suíça", date: "2026-11-04" }, invoke));
await waitFor(() => expect(added).toEqual([{ name: "IMG_0001.JPG", eventId: "ev1" }]));
await waitFor(() => expect(sent).toEqual([{ path: "/ingest/.usb/IMG_0001.JPG", event: "Portugal x Suíça", date: "2026-11-04" }]));
});
it("uses the open event when a camera is plugged in and none is chosen", async () => {
const setTarget = vi.fn();
render(<UsbCameraButton usb={usbStub} target={null} setTarget={setTarget} openEvent={event} />);
await waitFor(() => expect(setTarget).toHaveBeenCalledWith(event));
expect(screen.getByRole("button", { name: /USB/ })).toBeTruthy();
});
it("leaves a chosen event alone", () => {
const setTarget = vi.fn();
render(
<UsbCameraButton
usb={usbStub}
target={{ id: "other", title: "ABC x Benfica", date: "2026-10-12" }}
setTarget={setTarget}
openEvent={event}
/>,
);
expect(setTarget).not.toHaveBeenCalled();
});
it("adds the RAW sidecar when a JPEG is selected for download", () => {
expect(withSidecars(["IMG_0001.JPG"], camera.files).sort()).toEqual(["IMG_0001.CR3", "IMG_0001.JPG"]);
expect(withSidecars(["IMG_0002.JPG"], camera.files)).toEqual(["IMG_0002.JPG"]);
});
});
+366
View File
@@ -0,0 +1,366 @@
import type { EventSummary } from "@photoreport/sdk";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { t } from "../i18n.js";
import { asArrayBuffer } from "../platform.js";
import { type FtpTarget, type IncomingFile, type Invoke, eventLabel } from "./LocalFtp.js";
import type { PreviewOf, UploadStatus } from "./uploads.js";
/** What the desktop shell reports for a PTP body on the USB cable (`camera.rs`). */
export interface UsbCamera {
id: string;
name: string;
vendorId: number;
productId: number;
/** opening: session starting; tethered: ready to pick files; busy: another app holds the cable; idle: off. */
state: "opening" | "tethered" | "busy" | "idle";
error: string | null;
/** synced: clock set to this Mac; unsupported: the body refuses; null: not tried yet. */
clock?: "synced" | "unsupported" | null;
/** Seconds the camera was ahead of the Mac before the sync. */
clockOffset?: number | null;
/** True once the card listing is available. */
catalogReady?: boolean;
}
export interface UsbFile {
name: string;
size: number;
createdMs?: number | null;
isNew?: boolean;
imported?: boolean;
}
export interface UsbStatus {
supported: boolean;
tether: boolean;
devices: UsbCamera[];
files: UsbFile[];
}
const tauriInvoke: Invoke = async (cmd, args) => (await import("@tauri-apps/api/core")).invoke(cmd, args);
const IN_FLIGHT = 6;
const POLL_MS = 1000;
type Add = (files: Iterable<File>, eventId?: string, onSettled?: (file: File, status: UploadStatus) => void, original?: PreviewOf) => void;
/**
* USB camera: the shell lists the card (and each new shot). Chosen files are downloaded into the
* ingest folder; this hook then uploads them to the target event like local FTP.
*/
export function useUsbCamera(add: Add, enabled: boolean, target: FtpTarget | null, invoke: Invoke = tauriInvoke) {
const [status, setStatus] = useState<UsbStatus | null>(null);
const [outdated, setOutdated] = useState(false);
const [counts, setCounts] = useState({ received: 0, sent: 0, failed: 0 });
const backlog = useRef<IncomingFile[]>([]);
const inFlight = useRef(0);
const targetRef = useRef(target);
targetRef.current = target;
const pump = useCallback(() => {
while (inFlight.current < IN_FLIGHT && backlog.current.length) {
const f = backlog.current.shift()!;
const to = targetRef.current;
inFlight.current++;
void (async () => {
try {
const [bytes, original] = await Promise.all([
invoke<unknown>("ftp_preview", { path: f.path }).then(asArrayBuffer),
invoke<PreviewOf>("ftp_info", { path: f.path }),
]);
const file = new File([bytes], f.name, { type: "image/jpeg", lastModified: f.modifiedMs });
add([file], to?.id, (_file, result) => {
inFlight.current--;
if (result === "done" || result === "duplicate") {
setCounts((c) => ({ ...c, sent: c.sent + 1 }));
invoke("ftp_sent", { path: f.path, event: to?.title ?? "", date: to?.date ?? "" }).catch(() => {});
} else {
setCounts((c) => ({ ...c, failed: c.failed + 1 }));
}
pump();
}, original);
} catch {
inFlight.current--;
setCounts((c) => ({ ...c, failed: c.failed + 1 }));
pump();
}
})();
}
}, [add, invoke]);
useEffect(() => {
if (!enabled) return;
let alive = true;
const tick = async () => {
try {
const s = await invoke<UsbStatus>("camera_status");
if (!alive) return;
setStatus(s);
if (!s.supported || !s.tether) return;
const files = await invoke<IncomingFile[]>("camera_take");
if (!alive || !files.length) return;
const to = targetRef.current;
const photos = files.filter((f) => /\.jpe?g$/i.test(f.name));
for (const raw of files) {
if (/\.jpe?g$/i.test(raw.name)) continue;
void invoke("ftp_sent", { path: raw.path, event: to?.title ?? "", date: to?.date ?? "" }).catch(() => {});
}
if (!photos.length) return;
backlog.current.push(...photos);
setCounts((c) => ({ ...c, received: c.received + photos.length }));
pump();
} catch {
if (alive) setOutdated(true);
}
};
void tick();
const timer = setInterval(() => void tick(), POLL_MS);
return () => {
alive = false;
clearInterval(timer);
};
}, [enabled, invoke, pump]);
const syncClock = useCallback(async () => {
try {
setStatus(await invoke<UsbStatus>("camera_sync"));
} catch {
setOutdated(true);
}
}, [invoke]);
const setTether = useCallback(
async (on: boolean) => {
try {
setStatus(await invoke<UsbStatus>("camera_tether", { enabled: on }));
} catch {
setOutdated(true);
}
},
[invoke],
);
const importFiles = useCallback(
async (names: string[]) => {
if (!names.length) return;
try {
setStatus(await invoke<UsbStatus>("camera_import", { names }));
} catch {
setOutdated(true);
}
},
[invoke],
);
const refresh = useCallback(async () => {
try {
setStatus(await invoke<UsbStatus>("camera_refresh"));
} catch {
setOutdated(true);
}
}, [invoke]);
return { status, outdated, counts, setTether, syncClock, importFiles, refresh };
}
export type UsbCameraState = ReturnType<typeof useUsbCamera>;
const live = (d: UsbCamera) => d.state === "tethered" || d.state === "opening" || d.state === "busy";
function stemOf(name: string) {
return name.replace(/\.[^.]+$/, "").toLowerCase();
}
/** JPEG names plus any RAW that shares the same stem (Canon CR3 beside the JPG, etc.). */
export function withSidecars(selected: Iterable<string>, files: UsbFile[]): string[] {
const want = new Set([...selected].map(stemOf));
return files.filter((f) => want.has(stemOf(f.name))).map((f) => f.name);
}
/** Button + panel in the Library toolbar. Hidden where the shell has no USB cameras (Windows, Linux). */
export function UsbCameraButton({
usb,
target,
setTarget,
openEvent,
}: {
usb: UsbCameraState;
target: FtpTarget | null;
setTarget: (e: EventSummary | null) => void;
openEvent: EventSummary | undefined;
}) {
const [open, setOpen] = useState(false);
const [picked, setPicked] = useState<Set<string>>(() => new Set());
const { status, counts } = usb;
const L = t.usbCamera;
const devices = status?.devices ?? [];
const files = status?.files ?? [];
const connected = devices.filter(live);
const on = connected.some((d) => d.state === "tethered" || d.state === "opening");
const catalogReady = devices.some((d) => d.catalogReady);
const jpegs = useMemo(() => files.filter((f) => /\.jpe?g$/i.test(f.name)), [files]);
useEffect(() => {
if (connected.length && !target && openEvent) setTarget(openEvent);
}, [connected.length, target, openEvent, setTarget]);
// Drop selections that left the catalog (unplug / refresh).
useEffect(() => {
const names = new Set(files.map((f) => f.name));
setPicked((prev) => {
let changed = false;
const next = new Set<string>();
for (const n of prev) {
if (names.has(n)) next.add(n);
else changed = true;
}
return changed ? next : prev;
});
}, [files]);
if (status && !status.supported && !usb.outdated) return null;
const toggle = (name: string) => {
setPicked((prev) => {
const next = new Set(prev);
if (next.has(name)) next.delete(name);
else next.add(name);
return next;
});
};
const download = () => {
const names = withSidecars(picked, files);
void usb.importFiles(names);
};
return (
<div className="relative">
<button
onClick={() => setOpen((o) => !o)}
aria-expanded={open}
className="flex h-6 items-center gap-1.5 border border-black bg-cell px-2.5 text-[12px] text-ink hover:bg-cell-on"
>
<span className={`inline-block h-1.5 w-1.5 rounded-full ${on ? "bg-[#4cc38a]" : connected.some((d) => d.state === "busy") ? "bg-[#f0a35a]" : "bg-faint"}`} />
{L.button}
{connected.length > 0 && <span className="max-w-40 truncate font-mono text-[11px] text-muted">{connected[0]?.name}</span>}
{jpegs.length > 0 && <span className="font-mono text-[11px] text-muted">{jpegs.length}</span>}
</button>
{open && (
<div className="absolute left-0 top-7 z-30 w-[420px] border border-black bg-panel p-3 text-[12px] shadow-xl" role="dialog" aria-label={L.title}>
<div className="mb-2 flex items-center justify-between">
<span className="font-semibold uppercase tracking-wide text-ink">{L.title}</span>
<span className={on ? "text-[#4cc38a]" : "text-faint"}>{status?.tether ? L.tetherOn : L.tetherOff}</span>
</div>
{usb.outdated && <p className="text-[#f0a35a]">{L.outdated}</p>}
{!usb.outdated && (
<>
<p className="mb-3 text-faint">{L.help}</p>
<div className="mb-3">
<div className="mb-1 text-[11px] uppercase tracking-wide text-faint">{t.localFtp.target}</div>
<div className="text-ink">{target ? `${target.date} · ${target.title}` : t.localFtp.noTarget}</div>
{openEvent && openEvent.id !== target?.id && (
<button onClick={() => setTarget(openEvent)} className="mt-1 text-left text-accent underline">
{t.localFtp.useOpen(eventLabel(openEvent))}
</button>
)}
</div>
{devices.length === 0 && <p className="text-faint">{L.none}</p>}
{devices.map((d) => (
<div key={d.id} className="mb-2 border border-line bg-[#161617] p-2">
<div className="font-mono text-ink">{d.name}</div>
<div className={d.state === "busy" ? "text-[#f0a35a]" : "text-muted"}>
{d.state === "opening" && L.opening}
{d.state === "tethered" && (d.catalogReady ? L.tethered : L.listing)}
{d.state === "idle" && L.idle}
{d.state === "busy" && L.busy}
</div>
{d.error && d.state === "busy" && <div className="mt-1 font-mono text-[11px] text-faint">{d.error}</div>}
{d.clock === "unsupported" && <div className="mt-1 text-[#f0a35a]">{L.clockUnsupported}</div>}
{d.clock === "synced" && (
<div className="mt-1 text-[#4cc38a]">
{d.clockOffset == null || Math.abs(d.clockOffset) < 2
? L.clockOk
: d.clockOffset > 0
? L.clockAhead(Math.round(d.clockOffset))
: L.clockBehind(Math.round(Math.abs(d.clockOffset)))}
</div>
)}
</div>
))}
{on && (
<div className="mb-3 border border-line bg-[#161617] p-2">
<div className="mb-2 flex items-center justify-between gap-2">
<span className="text-[11px] uppercase tracking-wide text-faint">
{L.card}
{jpegs.length > 0 && <span className="ml-2 font-mono normal-case text-muted">{L.files(jpegs.length)}</span>}
</span>
<div className="flex flex-wrap gap-2">
<button type="button" className="text-accent underline" onClick={() => setPicked(new Set(jpegs.filter((f) => f.isNew && !f.imported).map((f) => f.name)))}>
{L.selectNew}
</button>
<button type="button" className="text-accent underline" onClick={() => setPicked(new Set(jpegs.filter((f) => !f.imported).map((f) => f.name)))}>
{L.selectAll}
</button>
<button type="button" className="text-accent underline" onClick={() => setPicked(new Set())}>
{L.selectNone}
</button>
<button type="button" className="text-accent underline" onClick={() => void usb.refresh()}>
{L.refresh}
</button>
</div>
</div>
{!catalogReady && <p className="text-faint">{L.listing}</p>}
{catalogReady && jpegs.length === 0 && <p className="text-faint">{L.emptyCard}</p>}
{jpegs.length > 0 && (
<ul className="max-h-48 overflow-auto border border-line">
{jpegs.map((f) => {
const checked = picked.has(f.name);
return (
<li key={f.name} className="flex items-center gap-2 border-b border-line px-2 py-1 last:border-b-0 hover:bg-cell">
<input type="checkbox" checked={checked} disabled={!!f.imported} onChange={() => toggle(f.name)} className="accent-accent" />
<button type="button" className="min-w-0 flex-1 truncate text-left font-mono text-ink disabled:text-faint" disabled={!!f.imported} onClick={() => toggle(f.name)}>
{f.name}
</button>
{f.isNew && !f.imported && <span className="text-[10px] uppercase text-[#4cc38a]">{L.newShot}</span>}
{f.imported && <span className="text-[10px] uppercase text-faint">{L.imported}</span>}
</li>
);
})}
</ul>
)}
{picked.size > 0 && (
<button type="button" onClick={download} className="mt-2 h-7 w-full border border-black bg-cell px-3 text-ink hover:bg-cell-on">
{L.download(picked.size)}
</button>
)}
</div>
)}
{counts.received > 0 && (
<div className="mb-3 font-mono text-[11px] text-muted">
{L.received(counts.received)} · {L.sent(counts.sent)}
{counts.failed > 0 && <span className="text-[#f0a35a]"> · {L.failed(counts.failed)}</span>}
</div>
)}
<p className="mb-3 text-[11px] text-faint">{L.rawKept}</p>
{status && (
<div className="flex gap-2">
<button onClick={() => void usb.setTether(!status.tether)} className="h-7 border border-black bg-cell px-3 text-ink hover:bg-cell-on">
{status.tether ? L.turnOff : L.turnOn}
</button>
{on && (
<button onClick={() => void usb.syncClock()} className="h-7 border border-black bg-cell px-3 text-ink hover:bg-cell-on">
{L.clockSync}
</button>
)}
</div>
)}
</>
)}
</div>
)}
</div>
);
}
+48
View File
@@ -0,0 +1,48 @@
import { engineAuto, exportFrame, openFrame } from "../develop/Viewer.js";
import { loadEngine } from "../develop/engine.js";
import { folderRead, saveDevelopedJpeg, saveDevelopedXmp } from "./folderDrop.js";
import { developedJpegName, developedXmpName, developXmp, dirOf, FOLDER_DEVELOP_EDGE, interiorCommand, interiorPartial } from "./interiorPreset.js";
/** JPEG bytes of one rendered frame. The pixels are already the developed image. */
export async function jpegFromRgba(pixels: Uint8ClampedArray, width: number, height: number): Promise<Blob> {
const canvas = document.createElement("canvas");
canvas.width = width;
canvas.height = height;
const ctx = canvas.getContext("2d");
if (!ctx) throw new Error("canvas");
const rgba = new Uint8ClampedArray(pixels.byteLength);
rgba.set(pixels);
ctx.putImageData(new ImageData(rgba, width, height), 0, 0);
const blob = await new Promise<Blob | null>((resolve) => canvas.toBlob(resolve, "image/jpeg", 0.92));
if (!blob) throw new Error("jpeg");
return blob;
}
/**
* The merged DNG, revealed for an interior (neutral whites, held windows, colour) and written beside it.
* `download` means this shell cannot write into the folder yet, so the file went to Downloads.
*/
export async function finishMergedJpeg(dngPath: string): Promise<"beside" | "download"> {
const engine = await loadEngine();
const bytes = await folderRead(dngPath);
const key = `${dngPath}#${Date.now()}`;
await openFrame(key, bytes.slice(0), FOLDER_DEVELOP_EDGE);
let exposure: number | undefined;
try {
const tone = await engineAuto(key, "tone");
exposure = tone["light.exposure"];
} catch {
// The finish still opens the room when the photo has nothing to measure.
}
const partial = interiorPartial(exposure);
const settings = engine.apply(engine.defaultSettings(), interiorCommand(partial));
const frame = await exportFrame(key, settings, FOLDER_DEVELOP_EDGE, FOLDER_DEVELOP_EDGE);
const blob = await jpegFromRgba(frame.pixels, frame.width, frame.height);
const jpeg = new Uint8Array(await blob.arrayBuffer());
const slash = Math.max(dngPath.lastIndexOf("/"), dngPath.lastIndexOf("\\"));
const fileName = slash >= 0 ? dngPath.slice(slash + 1) : dngPath;
const dir = dirOf(dngPath);
const where = await saveDevelopedJpeg(dir, developedJpegName(fileName), jpeg);
await saveDevelopedXmp(dir, developedXmpName(fileName), new TextEncoder().encode(developXmp(partial)));
return where;
}
+22
View File
@@ -0,0 +1,22 @@
/** A contact-sheet cell: the picture, then the file name under it. */
export const FOLDER_CELL_W = 176;
export const FOLDER_CELL_H = 198;
export const FOLDER_GAP = 4;
const BUFFER_ROWS = 2;
const ROW_H = FOLDER_CELL_H + FOLDER_GAP;
export function folderCols(width: number): number {
if (width <= 0) return 1;
return Math.max(1, Math.floor((width + FOLDER_GAP) / (FOLDER_CELL_W + FOLDER_GAP)));
}
/** Indexes of the cells to mount: the rows on screen, plus two above and below. */
export function folderWindow(count: number, cols: number, scrollTop: number, viewHeight: number): { from: number; to: number } {
if (count <= 0 || cols <= 0) return { from: 0, to: 0 };
const rows = Math.ceil(count / cols);
const height = viewHeight > 0 ? viewHeight : ROW_H * 3;
const start = Math.max(0, Math.floor(scrollTop / ROW_H) - BUFFER_ROWS);
const end = Math.min(rows, Math.ceil((scrollTop + height) / ROW_H) + BUFFER_ROWS);
return { from: start * cols, to: Math.min(count, end * cols) };
}
+51
View File
@@ -0,0 +1,51 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { beginDropWait, htmlDropIsFolder, nativePaths, resetDropGate, saveDevelopedJpeg } from "./folderDrop.js";
describe("folder drop", () => {
beforeEach(() => resetDropGate());
afterEach(() => {
resetDropGate();
vi.useRealTimers();
});
it("opens a dropped folder and does not treat it as an upload", async () => {
const opened: string[] = [];
const wait = beginDropWait();
nativePaths(["/tmp/job"], async () => "/tmp/job", (path) => opened.push(path));
await expect(wait).resolves.toBe("folder");
expect(opened).toEqual(["/tmp/job"]);
});
it("leaves loose files to the upload", async () => {
const opened: string[] = [];
const wait = beginDropWait();
nativePaths(["/tmp/a.jpg"], async () => null, (path) => opened.push(path));
await expect(wait).resolves.toBe("files");
expect(opened).toEqual([]);
});
it("treats a drop as files when the shell never answers", async () => {
vi.useFakeTimers();
const wait = beginDropWait();
await vi.advanceTimersByTimeAsync(500);
await expect(wait).resolves.toBe("files");
});
it("writes a developed jpeg beside the photo", async () => {
const writes: string[] = [];
const where = await saveDevelopedJpeg("/job", "a.jpg", new Uint8Array([1, 2]), async (dir, name) => {
writes.push(`${dir}/${name}`);
});
expect(where).toBe("beside");
expect(writes).toEqual(["/job/a.jpg"]);
await expect(saveDevelopedJpeg("/job", "a.jpg", new Uint8Array([1]), async () => {
throw new Error("permission denied");
})).rejects.toThrow(/permission/);
});
it("sees a directory item as a folder", () => {
expect(htmlDropIsFolder([{ webkitGetAsEntry: () => ({ isDirectory: true }) }])).toBe(true);
expect(htmlDropIsFolder([{ webkitGetAsEntry: () => ({ isDirectory: false }) }])).toBe(false);
expect(htmlDropIsFolder([{}])).toBe(false);
});
});
+211
View File
@@ -0,0 +1,211 @@
import { asArrayBuffer, desktopInvoke, isDesktop, type Invoke } from "../platform.js";
export interface FolderFile {
path: string;
name: string;
}
export interface FolderListing {
path: string;
name: string;
files: FolderFile[];
}
type Kind = "folder" | "files";
interface Gate {
promise: Promise<Kind>;
resolve: (kind: Kind) => void;
timer: ReturnType<typeof setTimeout>;
settled: boolean;
}
let gate: Gate | null = null;
let nativeSeen = false;
const WAIT_MS = 500;
function finish(kind: Kind): void {
if (!gate || gate.settled) return;
gate.settled = true;
clearTimeout(gate.timer);
const resolve = gate.resolve;
gate = null;
nativeSeen = false;
resolve(kind);
}
function takeGate(): Gate {
if (gate && !gate.settled) return gate;
let resolve: (kind: Kind) => void = () => {};
const promise = new Promise<Kind>((r) => {
resolve = r;
});
const next: Gate = {
promise,
resolve,
settled: false,
timer: setTimeout(() => {
if (!nativeSeen) finish("files");
}, WAIT_MS),
};
gate = next;
return next;
}
/** The HTML drop waits on this. A folder reported by the shell resolves "folder" and must not be uploaded. */
export function beginDropWait(): Promise<Kind> {
return takeGate().promise;
}
/**
* Paths from the desktop shell. `isFolder` is the first directory among them. Opening happens after the HTML
* drop has been told not to upload.
*/
export function nativePaths(
paths: string[],
isFolder: (paths: string[]) => Promise<string | null>,
open: (path: string) => void,
): void {
nativeSeen = true;
const current = takeGate();
clearTimeout(current.timer);
void isFolder(paths)
.then((folder) => {
if (folder) {
finish("folder");
open(folder);
} else {
finish("files");
}
})
.catch(() => finish("files"));
}
/** Clears a wait left behind by a test. */
export function resetDropGate(): void {
if (gate) {
gate.settled = true;
clearTimeout(gate.timer);
gate = null;
}
nativeSeen = false;
}
export function htmlDropIsFolder(items: Iterable<{ webkitGetAsEntry?: () => { isDirectory: boolean } | null }>): boolean {
for (const item of items) {
const entry = item.webkitGetAsEntry?.();
if (entry?.isDirectory) return true;
}
return false;
}
export function folderDropPath(paths: string[], invoke: Invoke = desktopInvoke): Promise<string | null> {
return invoke<string | null>("folder_drop", { paths });
}
export async function openFolder(path: string, invoke: Invoke = desktopInvoke): Promise<FolderListing> {
try {
return await invoke<FolderListing>("folder_open", { path });
} catch (err) {
// The shell records the drop and then tells the page. If the page asks before that record is in, ask once more.
const message = err instanceof Error ? err.message : String(err);
if (!message.includes("not_allowed")) throw err;
await new Promise((resolve) => setTimeout(resolve, 0));
return invoke<FolderListing>("folder_open", { path });
}
}
/** Capture metadata of one photo on the open sheet, read in the desktop process. */
export function folderMeta(path: string, invoke: Invoke = desktopInvoke): Promise<string> {
return invoke<string>("folder_meta", { path });
}
/**
* Merges these photos in the desktop process and writes the DNG beside the middle one.
* The raws never cross into the page: a folder of CR3 does not fit in the browser engine.
*/
export function mergeFolderDng(paths: readonly string[], maxEdge: number, invoke: Invoke = desktopInvoke): Promise<string> {
return invoke<string>("folder_merge_dng", { paths, maxEdge });
}
/** The original of one photo on the open sheet, so Revelar can decode it here. */
export async function folderRead(path: string, invoke: Invoke = desktopInvoke): Promise<ArrayBuffer> {
return asArrayBuffer(await invoke<unknown>("folder_read", { path }));
}
/** The file is the raw body. `dir` and `name` ride in headers, the same way a merged DNG is written. */
async function writeJpegInShell(dir: string, name: string, bytes: Uint8Array): Promise<void> {
const { invoke } = await import("@tauri-apps/api/core");
await invoke<string>("folder_save_jpeg", bytes, {
headers: { dir: encodeURIComponent(dir), name: encodeURIComponent(name) },
});
}
async function writeXmpInShell(dir: string, name: string, bytes: Uint8Array): Promise<void> {
const { invoke } = await import("@tauri-apps/api/core");
await invoke<string>("folder_save_xmp", bytes, {
headers: { dir: encodeURIComponent(dir), name: encodeURIComponent(name) },
});
}
/** Writes the edit sidecar beside the DNG. A shell without the command leaves the JPEG as the only file. */
export async function saveDevelopedXmp(dir: string, name: string, bytes: Uint8Array, write?: (dir: string, name: string, bytes: Uint8Array) => Promise<void>): Promise<"beside" | "missing"> {
if (!dir) return "missing";
if (!write && !isDesktop()) return "missing";
try {
await (write ?? writeXmpInShell)(dir, name, bytes);
return "beside";
} catch (err) {
const message = err instanceof Error ? err.message : String(err);
if (!write && /not found|unknown command/i.test(message)) return "missing";
throw err;
}
}
function downloadJpeg(name: string, bytes: Uint8Array): void {
const copy = new Uint8Array(bytes.byteLength);
copy.set(bytes);
const blob = new Blob([copy], { type: "image/jpeg" });
const url = URL.createObjectURL(blob);
const link = document.createElement("a");
link.href = url;
link.download = name;
link.click();
setTimeout(() => URL.revokeObjectURL(url), 1500);
}
/**
* Writes a developed JPEG into the opened folder. A shell from before this command downloads the file instead.
* `write` replaces the shell call in tests.
*/
export async function saveDevelopedJpeg(
dir: string,
name: string,
bytes: Uint8Array,
write?: (dir: string, name: string, bytes: Uint8Array) => Promise<void>,
): Promise<"beside" | "download"> {
if (!dir) throw new Error("not_a_folder");
if (write || isDesktop()) {
try {
await (write ?? writeJpegInShell)(dir, name, bytes);
return "beside";
} catch (err) {
const message = err instanceof Error ? err.message : String(err);
const missing = !write && /not found|unknown command/i.test(message);
if (!missing) throw err;
}
}
downloadJpeg(name, bytes);
return "download";
}
export async function folderThumb(path: string, edge: number, invoke?: Invoke): Promise<ArrayBuffer | null> {
if (!invoke && !isDesktop()) return null;
try {
const call = invoke ?? desktopInvoke;
return asArrayBuffer(await call<unknown>("folder_thumb", { path, edge }));
} catch {
return null;
}
}
+123
View File
@@ -0,0 +1,123 @@
import { describe, expect, it } from "vitest";
import { mergeFailureText, mergeFolderExposures, mergeFolderNative } from "./folderMerge.js";
import { MergeError } from "./mergeExposures.js";
const at = (ms: number) => new Date(Date.parse("2026-10-21T10:00:00.000Z") + ms).toISOString();
function tags(bias: number, ms: number, exposureTime = 1 / 125): string {
return JSON.stringify({
capturedAt: at(ms),
cameraModel: "EOS R5",
focalLength: 16,
aperture: 8,
iso: 100,
width: 4000,
height: 3000,
exposureBias: bias,
exposureTime,
});
}
function files() {
return [
{ path: "/job/sala/dark.cr3", name: "dark.cr3" },
{ path: "/job/sala/mid.cr3", name: "mid.cr3" },
{ path: "/job/sala/bright.cr3", name: "bright.cr3" },
{ path: "/job/sala/mid-fundido.dng", name: "mid-fundido.dng" },
];
}
const meta = new Map([
["/job/sala/dark.cr3", tags(-2, 0)],
["/job/sala/mid.cr3", tags(0, 200)],
["/job/sala/bright.cr3", tags(2, 400)],
]);
describe("merge a contact sheet", () => {
it("writes one DNG beside the bracket when only the focused photo is selected", async () => {
const saved: { dir: string; name: string; bytes: Uint8Array }[] = [];
const made = await mergeFolderExposures({
files: files(),
selectedIds: ["/job/sala/dark.cr3"],
readFile: async (path) => new TextEncoder().encode(path),
readMeta: (bytes) => meta.get(new TextDecoder().decode(bytes)) ?? "{}",
mergeDng: () => new Uint8Array([1, 2, 3]),
saveDng: async (dir, name, bytes) => {
saved.push({ dir, name, bytes });
},
});
expect(made).toBe(1);
expect(saved).toEqual([{ dir: "/job/sala", name: "mid-fundido.dng", bytes: new Uint8Array([1, 2, 3]) }]);
});
it("merges the photos the user selected even when they are not a detected bracket", async () => {
const saved: string[] = [];
const made = await mergeFolderExposures({
files: files(),
selectedIds: ["/job/sala/dark.cr3", "/job/sala/mid.cr3"],
readFile: async (path) => new TextEncoder().encode(path),
readMeta: () => tags(0, 0, 1 / 125),
mergeDng: (frames) => new Uint8Array([frames.length]),
saveDng: async (_dir, name) => {
saved.push(name);
},
});
expect(made).toBe(1);
expect(saved).toEqual(["dark-fundido.dng"]);
});
it("says there is no set when a single photo is not part of a bracket", async () => {
const run = mergeFolderExposures({
files: [{ path: "/job/a.cr3", name: "a.cr3" }, { path: "/job/b.cr3", name: "b.cr3" }],
selectedIds: ["/job/a.cr3"],
readFile: async (path) => new TextEncoder().encode(path),
readMeta: () => tags(0, 0),
mergeDng: () => new Uint8Array([1]),
saveDng: async () => {},
});
await expect(run).rejects.toBeInstanceOf(MergeError);
await expect(run).rejects.toMatchObject({ code: "none" });
});
});
describe("merge a contact sheet on this computer", () => {
const pair = [
{ path: "/job/dark.cr3", name: "dark.cr3" },
{ path: "/job/mid.cr3", name: "mid.cr3" },
];
it("asks the desktop to merge the stack and keeps its reason when that fails", async () => {
const stacks: string[][] = [];
const run = mergeFolderNative({
files: pair,
selectedIds: pair.map((file) => file.path),
metaOf: async () => tags(0, 0),
mergePaths: async (paths) => {
stacks.push([...paths]);
throw new Error("cannot read the photo: cr3");
},
});
await expect(run).rejects.toMatchObject({ code: "failed", detail: "cannot read the photo: cr3" });
expect(stacks).toEqual([["/job/dark.cr3", "/job/mid.cr3"]]);
expect(mergeFailureText("failed", "cannot read the photo: cr3")).toBe("Não consegui ler estes RAW para os fundir.");
});
it("reveals each merged file when a jpeg was asked for", async () => {
const finished: string[] = [];
const phases: string[] = [];
const result = await mergeFolderNative({
files: pair,
selectedIds: pair.map((file) => file.path),
metaOf: async () => tags(0, 0),
onStatus: (stack, total, phase) => phases.push(`${phase ?? "merge"} ${stack}/${total}`),
mergePaths: async () => "/job/mid-fundido.dng",
finishJpeg: async (path) => {
finished.push(path);
return "beside";
},
});
expect(result).toEqual({ made: 1, jpeg: "beside" });
expect(finished).toEqual(["/job/mid-fundido.dng"]);
expect(phases).toEqual(["merge 1/1", "jpeg 1/1"]);
});
});
+222
View File
@@ -0,0 +1,222 @@
import { loadEngine, type EngineModule } from "../develop/engine.js";
import { t } from "../i18n.js";
import { frameFromCapture } from "../realestate/readFrame.js";
import { MergeError } from "./mergeExposures.js";
import { MERGE_EDGE, isMergedName, stacksOfFrames } from "./mergeStacks.js";
export interface FolderExposure {
path: string;
name: string;
}
function parentDir(path: string): string {
const slash = Math.max(path.lastIndexOf("/"), path.lastIndexOf("\\"));
if (slash <= 0) throw new MergeError("failed");
return path.slice(0, slash);
}
function stemOf(name: string): string {
const dot = name.lastIndexOf(".");
return dot > 0 ? name.slice(0, dot) : name;
}
/**
* Merges the contact sheet on this computer. A selection of two or more is that set; otherwise every
* bracket in the folder. The DNG is written beside the middle frame. Nothing is uploaded.
* Metadata is read first and the bytes dropped, then each stack is read again to merge: a folder of
* raws must not all sit in memory at once.
*/
export async function mergeFolderExposures(opts: {
files: readonly FolderExposure[];
selectedIds: readonly string[];
readFile: (path: string) => Promise<Uint8Array>;
readMeta: (bytes: Uint8Array) => string | Promise<string>;
mergeDng: (files: Uint8Array[]) => Uint8Array;
saveDng: (dir: string, name: string, bytes: Uint8Array) => Promise<void>;
onStatus?: (stack: number, total: number) => void;
}): Promise<number> {
const candidates = opts.files.filter((file) => !isMergedName(file.name));
const selected = new Set(opts.selectedIds);
const chosen = selected.size >= 2;
const pool = chosen ? candidates.filter((file) => selected.has(file.path)) : candidates;
if (pool.length < 2) throw new MergeError("none");
const frames = [];
for (const file of pool) {
const bytes = await readOrMissing(opts.readFile, file.path);
frames.push(await frameOfFile(file, bytes, opts.readMeta));
}
const stacks = stacksOfFrames(frames, opts.selectedIds);
if (stacks.length === 0) throw new MergeError("none");
const byPath = new Map(pool.map((file) => [file.path, file]));
let made = 0;
for (let index = 0; index < stacks.length; index++) {
opts.onStatus?.(index + 1, stacks.length);
const members = (stacks[index] ?? []).map((id) => byPath.get(id)).filter((file): file is FolderExposure => !!file);
if (members.length < 2) throw new MergeError("none");
const files: Uint8Array[] = [];
for (const member of members) files.push(await readOrMissing(opts.readFile, member.path));
const dng = mergedOrFailed(opts.mergeDng, files);
const mid = members[Math.floor((members.length - 1) / 2)]!;
try {
await opts.saveDng(parentDir(mid.path), `${stemOf(mid.name)}-fundido.dng`, dng);
} catch (err) {
if (err instanceof MergeError) throw err;
throw new MergeError("failed");
}
made += 1;
}
return made;
}
async function readOrMissing(readFile: (path: string) => Promise<Uint8Array>, path: string): Promise<Uint8Array> {
try {
const bytes = await readFile(path);
if (bytes.byteLength === 0) throw new MergeError("missing");
return bytes;
} catch (err) {
if (err instanceof MergeError) throw err;
throw new MergeError("missing");
}
}
async function frameOfFile(
file: FolderExposure,
bytes: Uint8Array,
readMeta: (bytes: Uint8Array) => string | Promise<string>,
) {
try {
const tags = JSON.parse(await readMeta(bytes)) as Record<string, unknown>;
return frameFromCapture(file.path, file.name, tags);
} catch {
return { id: file.path, fileName: file.name };
}
}
function mergedOrFailed(mergeDng: (files: Uint8Array[]) => Uint8Array, files: Uint8Array[]): Uint8Array {
try {
const dng = mergeDng(files);
if (dng.byteLength === 0) throw new MergeError("failed");
return dng;
} catch (err) {
if (err instanceof MergeError) throw err;
throw new MergeError("failed");
}
}
/**
* Merges the contact sheet in the desktop process. Metadata and the DNG stay there: sending every
* raw into the browser engine is what made a folder of CR3 fail with no reason.
*/
export async function mergeFolderNative(opts: {
files: readonly FolderExposure[];
selectedIds: readonly string[];
metaOf: (path: string) => Promise<string>;
/** Merges one stack and returns the DNG path written beside the middle frame. */
mergePaths: (paths: readonly string[]) => Promise<string>;
/** When set, each DNG is also revealed and saved as a JPEG before the next stack. */
finishJpeg?: (dngPath: string) => Promise<"beside" | "download">;
onStatus?: (stack: number, total: number, phase?: "merge" | "jpeg") => void;
}): Promise<{ made: number; jpeg: "beside" | "download" | "none" }> {
const candidates = opts.files.filter((file) => !isMergedName(file.name));
const selected = new Set(opts.selectedIds);
const chosen = selected.size >= 2;
const pool = chosen ? candidates.filter((file) => selected.has(file.path)) : candidates;
if (pool.length < 2) throw new MergeError("none");
const frames = [];
for (const file of pool) {
try {
const tags = JSON.parse(await opts.metaOf(file.path)) as Record<string, unknown>;
frames.push(frameFromCapture(file.path, file.name, tags));
} catch (err) {
if (err instanceof MergeError) throw err;
frames.push({ id: file.path, fileName: file.name });
}
}
const stacks = stacksOfFrames(frames, opts.selectedIds);
if (stacks.length === 0) throw new MergeError("none");
let made = 0;
let jpeg: "beside" | "download" | "none" = opts.finishJpeg ? "beside" : "none";
for (let index = 0; index < stacks.length; index++) {
const ids = stacks[index] ?? [];
if (ids.length < 2) throw new MergeError("none");
opts.onStatus?.(index + 1, stacks.length, "merge");
let dngPath = "";
try {
dngPath = await opts.mergePaths(ids);
} catch (err) {
if (err instanceof MergeError) throw err;
const detail = err instanceof Error ? err.message : String(err);
throw new MergeError("failed", detail);
}
if (opts.finishJpeg) {
opts.onStatus?.(index + 1, stacks.length, "jpeg");
try {
const where = await opts.finishJpeg(dngPath);
if (where === "download") jpeg = "download";
} catch (err) {
if (err instanceof MergeError) throw err;
const detail = err instanceof Error ? err.message : String(err);
throw new MergeError("failed", detail);
}
}
made += 1;
}
return { made, jpeg };
}
/** The sentence under the button. An unknown failure keeps the desktop's reason, so the next try is not a guess. */
export function mergeFailureText(code: MergeError["code"], detail?: string): string {
if (code !== "failed" || !detail) return t.merge.errors[code];
const lower = detail.toLowerCase();
if (lower.includes("permission") || lower.includes("read-only") || lower.includes("operation not permitted")) {
return t.merge.errors.write;
}
if (lower.includes("cannot read the photo") || lower.includes("cannot be reduced")) {
return t.merge.errors.raw;
}
return t.merge.errors.failedDetail(detail);
}
/** The desktop merge: capture metadata and the linear DNG come from the develop engine. */
export async function mergeFolderOnDisk(opts: {
files: readonly FolderExposure[];
selectedIds: readonly string[];
readFile: (path: string) => Promise<Uint8Array>;
saveDng: (dir: string, name: string, bytes: Uint8Array) => Promise<void>;
onStatus?: (stack: number, total: number) => void;
}): Promise<number> {
let engine: EngineModule;
try {
engine = await loadEngine();
} catch {
throw new MergeError("engine");
}
return mergeFolderExposures({
...opts,
readMeta: (bytes) => engine.readCaptureMeta(bytes),
mergeDng: (files) => dngOf(engine, files),
});
}
function dngOf(engine: EngineModule, files: Uint8Array[]): Uint8Array {
const job = new engine.BracketJob();
try {
for (const file of files) job.push(file);
if (!job.mergeDng) throw new MergeError("engine");
const dng = job.mergeDng(MERGE_EDGE);
const copy = new Uint8Array(dng.byteLength);
copy.set(dng);
return copy;
} catch (err) {
if (err instanceof MergeError) throw err;
throw new MergeError("failed");
} finally {
job.free();
}
}
+99
View File
@@ -0,0 +1,99 @@
import { render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { describe, expect, it, vi } from "vitest";
import { folderCols, folderWindow } from "./folder-layout.js";
import { FolderSheet } from "./FolderSheet.js";
describe("contact sheet window", () => {
it("mounts the rows on screen, not the whole folder", () => {
expect(folderCols(800)).toBe(4);
const first = folderWindow(200, 4, 0, 600);
expect(first.from).toBe(0);
expect(first.to).toBeLessThan(30);
const later = folderWindow(200, 4, 4000, 600);
expect(later.from).toBeGreaterThan(40);
expect(later.to - later.from).toBeLessThan(40);
});
});
describe("contact sheet", () => {
const thumb = vi.fn(async () => null);
it("shows the folder's file names and culls the focused one", async () => {
const user = userEvent.setup();
const onClose = vi.fn();
render(
<FolderSheet
folder={{ path: "/job", name: "Chegada", files: [{ path: "/job/a.jpg", name: "a.jpg" }, { path: "/job/b.jpg", name: "b.jpg" }] }}
onClose={onClose}
thumb={thumb}
/>,
);
expect(screen.getByText("Chegada").textContent).toBe("Chegada");
expect(screen.getByRole("button", { name: "a.jpg" }).textContent).toContain("a.jpg");
await user.keyboard("p");
expect(screen.getByRole("button", { name: "a.jpg, escolhida" }).getAttribute("aria-label")).toBe("a.jpg, escolhida");
await user.click(screen.getByRole("button", { name: "Fechar" }));
expect(onClose).toHaveBeenCalledOnce();
});
it("merges the photos on the sheet", async () => {
const user = userEvent.setup();
const merge = vi.fn(
async (_input: {
files: { path: string; name: string }[];
selectedIds: readonly string[];
jpeg: boolean;
onStatus: (stack: number, total: number, phase?: "merge" | "jpeg") => void;
}) => ({ made: 1, jpeg: "none" as const }),
);
render(
<FolderSheet
folder={{
path: "/job",
name: "Sala",
files: [
{ path: "/job/a.jpg", name: "a.jpg" },
{ path: "/job/b.jpg", name: "b.jpg" },
{ path: "/job/c.jpg", name: "c.jpg" },
],
}}
onClose={() => {}}
thumb={thumb}
merge={merge}
/>,
);
await user.click(screen.getByRole("button", { name: "Fundir exposições" }));
expect(merge).toHaveBeenCalledOnce();
const input = merge.mock.calls[0]![0];
expect(input.files.map((file) => file.name)).toEqual(["a.jpg", "b.jpg", "c.jpg"]);
expect(input.selectedIds).toEqual(["/job/a.jpg"]);
expect(input.jpeg).toBe(true);
expect((await screen.findByRole("status")).textContent).toBe("1 DNG ficou nesta pasta.");
});
it("opens the focused photo in develop", async () => {
const user = userEvent.setup();
const onDevelop = vi.fn();
render(
<FolderSheet
folder={{ path: "/job", name: "Sala", files: [{ path: "/job/a.jpg", name: "a.jpg" }, { path: "/job/b.jpg", name: "b.jpg" }] }}
onClose={() => {}}
thumb={thumb}
onDevelop={onDevelop}
/>,
);
await user.click(screen.getByRole("button", { name: "Revelar" }));
expect(onDevelop).toHaveBeenCalledWith("/job/a.jpg");
onDevelop.mockClear();
await user.keyboard("d");
expect(onDevelop).toHaveBeenCalledWith("/job/a.jpg");
});
it("does not mount a thumbnail button for every file", () => {
const files = Array.from({ length: 200 }, (_, i) => ({ path: `/job/${i}.jpg`, name: `${i}.jpg` }));
render(<FolderSheet folder={{ path: "/job", name: "job", files }} onClose={() => {}} thumb={thumb} />);
expect(screen.getByRole("button", { name: "0.jpg" }).textContent).toContain("0.jpg");
expect(screen.queryByRole("button", { name: "199.jpg" })).toBeNull();
});
});
+9 -2
View File
@@ -7,8 +7,14 @@ import { useLocalFtp } from "./LocalFtp.js";
import { useLibraryLive } from "./realtime.js";
import { useUploadQueue } from "./uploads.js";
import { useOfflineSync } from "../offline/sync.js";
import { useUsbCamera } from "./UsbCamera.js";
type Ingest = { uploads: ReturnType<typeof useUploadQueue>; localFtp: ReturnType<typeof useLocalFtp>; desktop: boolean };
type Ingest = {
uploads: ReturnType<typeof useUploadQueue>;
localFtp: ReturnType<typeof useLocalFtp>;
usb: ReturnType<typeof useUsbCamera>;
desktop: boolean;
};
const IngestContext = createContext<Ingest | null>(null);
@@ -29,9 +35,10 @@ function IngestState({ api, orgId, children }: { api: ReturnType<typeof useAuth>
const desktop = isDesktop();
const uploads = useUploadQueue(api, orgId);
const localFtp = useLocalFtp(uploads.add, desktop && !!orgId, undefined, orgId);
const usb = useUsbCamera(uploads.add, desktop && !!orgId, localFtp.target);
useOfflineSync(api, orgId);
return (
<IngestContext.Provider value={{ uploads, localFtp, desktop }}>
<IngestContext.Provider value={{ uploads, localFtp, usb, desktop }}>
{desktop && !!orgId && <OriginalResponder api={api} add={uploads.add} />}
{desktop && !!orgId && <FailedRepair api={api} orgId={orgId} add={uploads.add} />}
{children}
@@ -0,0 +1,66 @@
import { describe, expect, it } from "vitest";
import { developedJpegName, developedXmpName, developXmp, dirOf, interiorPartial, partialFromSettings, partialFromXmp } from "./interiorPreset.js";
describe("interior finish", () => {
it("opens the room from the photo's exposure and holds the windows", () => {
const next = interiorPartial(0.31);
expect(next.wb.mode).toBe("daylight");
expect(next.wb.temp).toBe(5500);
expect(next.wb.tint).toBe(10);
expect(next.light.exposure).toBe(0.71);
expect(next.light.contrast).toBe(12);
expect(next.light.highlights).toBe(-100);
expect(next.light.shadows).toBe(100);
expect(next.light.whites).toBe(-15);
expect(next.detail.sharpen_amount).toBe(40);
expect(next.detail.nr_color).toBe(25);
});
it("does not let a bright or dark measurement throw the exposure away", () => {
expect(interiorPartial(2).light.exposure).toBe(1.15);
expect(interiorPartial(-2).light.exposure).toBe(0.35);
expect(interiorPartial(undefined).light.exposure).toBe(0.7);
});
});
describe("develop sidecar", () => {
it("writes the edit and reads the same sliders back", () => {
const partial = interiorPartial(0.31);
const back = partialFromXmp(developXmp(partial));
expect(back).toEqual(partial);
});
it("reads a sidecar another editor saved", () => {
const xml = `<rdf:Description crs:WhiteBalance="Custom" crs:Temperature="5200" crs:Tint="+4" crs:Exposure2012="+0.40" crs:Shadows2012="+80" crs:Highlights2012="-60"/>`;
const back = partialFromXmp(xml);
expect(back?.wb.mode).toBe("custom");
expect(back?.wb.temp).toBe(5200);
expect(back?.light.exposure).toBe(0.4);
expect(back?.light.shadows).toBe(80);
expect(back?.light.highlights).toBe(-60);
});
it("takes the edit off the settings document", () => {
const partial = partialFromSettings(
JSON.stringify({
wb: { mode: "daylight", temp: 5500, tint: 10 },
light: { exposure: 0.71, contrast: 12, highlights: -100, shadows: 90, whites: -15, blacks: 4 },
color: { vibrance: 12, saturation: 0 },
effects: { clarity: 8, dehaze: 6 },
detail: { sharpen_amount: 40, nr_color: 25 },
}),
);
expect(partial?.light.shadows).toBe(90);
expect(partial?.wb.mode).toBe("daylight");
});
});
describe("developed jpeg name", () => {
it("uses the file's own stem beside it", () => {
expect(developedJpegName("PSR10172-fundido.dng")).toBe("PSR10172-fundido.jpg");
expect(developedXmpName("PSR10172-fundido.dng")).toBe("PSR10172-fundido.xmp");
expect(developedJpegName("PSR10172.CR3")).toBe("PSR10172.jpg");
expect(developedJpegName("sala")).toBe("sala.jpg");
expect(dirOf("/Users/cyclop/Desktop/RAW/PSR10172-fundido.dng")).toBe("/Users/cyclop/Desktop/RAW");
});
});
+239
View File
@@ -0,0 +1,239 @@
/** Longest side decoded for a folder photo in Revelar, and for the JPEG saved from it. */
export const FOLDER_DEVELOP_EDGE = 4096;
/**
* Daylight interior. Auto contrast (a high fixed value) was crushing the shadows it had just
* lifted, and a grey-world white balance on wood stayed warmer than the daylight the camera used.
* Exposure still follows the photo, a little brighter, and is kept inside a range that opens the
* room without throwing the windows away. The other sliders are the finish, not a nudge.
*/
export type InteriorPartial = {
wb: { mode: string; temp: number; tint: number; scale: "kelvin" };
light: { exposure: number; contrast: number; highlights: number; shadows: number; whites: number; blacks: number };
color: { vibrance: number; saturation: number };
effects: { clarity: number; dehaze: number };
detail: { sharpen_amount: number; nr_color: number };
};
const FINISH = {
contrast: 12,
highlights: -100,
shadows: 100,
whites: -15,
blacks: 4,
vibrance: 12,
saturation: 0,
clarity: 8,
dehaze: 6,
sharpen: 40,
nrColor: 25,
temp: 5500,
tint: 10,
} as const;
export function interiorPartial(autoExposure: number | undefined): InteriorPartial {
const base = Number.isFinite(autoExposure) ? (autoExposure as number) : 0.3;
const exposure = Math.round(Math.min(1.15, Math.max(0.35, base + 0.4)) * 100) / 100;
return {
wb: { mode: "daylight", temp: FINISH.temp, tint: FINISH.tint, scale: "kelvin" },
light: {
exposure,
contrast: FINISH.contrast,
highlights: FINISH.highlights,
shadows: FINISH.shadows,
whites: FINISH.whites,
blacks: FINISH.blacks,
},
color: { vibrance: FINISH.vibrance, saturation: FINISH.saturation },
effects: { clarity: FINISH.clarity, dehaze: FINISH.dehaze },
detail: { sharpen_amount: FINISH.sharpen, nr_color: FINISH.nrColor },
};
}
/** One develop.merge of the interior finish, including the daylight white balance. */
export function interiorCommand(partial: InteriorPartial): string {
return JSON.stringify({ command: "develop.merge", params: { partial } });
}
/** JPEG written beside the file being developed: `PSR10172-fundido.dng` becomes `PSR10172-fundido.jpg`. */
export function developedJpegName(fileName: string): string {
const slash = Math.max(fileName.lastIndexOf("/"), fileName.lastIndexOf("\\"));
const base = slash >= 0 ? fileName.slice(slash + 1) : fileName;
const dot = base.lastIndexOf(".");
const stem = dot > 0 ? base.slice(0, dot) : base;
return `${stem || "foto"}.jpg`;
}
/** Sidecar with the same stem, so the edit can be opened and changed again. */
export function developedXmpName(fileName: string): string {
return developedJpegName(fileName).replace(/\.jpg$/i, ".xmp");
}
export function dirOf(path: string): string {
const slash = Math.max(path.lastIndexOf("/"), path.lastIndexOf("\\"));
if (slash <= 0) return "";
return path.slice(0, slash);
}
type SettingsDoc = {
wb?: { mode?: string; temp?: number; tint?: number };
light?: Partial<InteriorPartial["light"]>;
color?: Partial<InteriorPartial["color"]>;
effects?: Partial<InteriorPartial["effects"]>;
detail?: { sharpen_amount?: number; nr_color?: number };
};
/** The edit currently on the photo, in the shape a sidecar stores. */
export function partialFromSettings(settings: string): InteriorPartial | null {
let doc: SettingsDoc;
try {
doc = JSON.parse(settings) as SettingsDoc;
} catch {
return null;
}
if (!doc || typeof doc !== "object") return null;
const fallback = interiorPartial(0.3);
const num = (value: number | undefined, instead: number) => (typeof value === "number" && Number.isFinite(value) ? value : instead);
const mode = typeof doc.wb?.mode === "string" && doc.wb.mode ? doc.wb.mode : fallback.wb.mode;
return {
wb: {
mode,
temp: num(doc.wb?.temp, fallback.wb.temp),
tint: num(doc.wb?.tint, fallback.wb.tint),
scale: "kelvin",
},
light: {
exposure: num(doc.light?.exposure, fallback.light.exposure),
contrast: num(doc.light?.contrast, fallback.light.contrast),
highlights: num(doc.light?.highlights, fallback.light.highlights),
shadows: num(doc.light?.shadows, fallback.light.shadows),
whites: num(doc.light?.whites, fallback.light.whites),
blacks: num(doc.light?.blacks, fallback.light.blacks),
},
color: {
vibrance: num(doc.color?.vibrance, fallback.color.vibrance),
saturation: num(doc.color?.saturation, fallback.color.saturation),
},
effects: {
clarity: num(doc.effects?.clarity, fallback.effects.clarity),
dehaze: num(doc.effects?.dehaze, fallback.effects.dehaze),
},
detail: {
sharpen_amount: num(doc.detail?.sharpen_amount, fallback.detail.sharpen_amount),
nr_color: num(doc.detail?.nr_color, fallback.detail.nr_color),
},
};
}
const WB_LABEL: Record<string, string> = {
asShot: "As Shot",
auto: "Auto",
daylight: "Daylight",
cloudy: "Cloudy",
shade: "Shade",
tungsten: "Tungsten",
fluorescent: "Fluorescent",
flash: "Flash",
custom: "Custom",
};
function crsNumber(value: number, digits: number): string {
const text = digits === 0 ? String(Math.round(value)) : value.toFixed(digits);
return value > 0 ? `+${text}` : text;
}
function xmlAttr(value: string): string {
return value.replace(/&/g, "&amp;").replace(/"/g, "&quot;").replace(/</g, "&lt;");
}
/**
* Sidecar in the camera-raw vocabulary: temperature, tint and the same sliders, so the edit can be
* read back here and by another raw editor that understands those names.
*/
export function developXmp(partial: InteriorPartial): string {
const wb = WB_LABEL[partial.wb.mode] ?? "Custom";
const attrs = [
`crs:Version="15.4"`,
`crs:ProcessVersion="11.0"`,
`crs:WhiteBalance="${xmlAttr(wb)}"`,
`crs:Temperature="${crsNumber(partial.wb.temp, 0)}"`,
`crs:Tint="${crsNumber(partial.wb.tint, 0)}"`,
`crs:Exposure2012="${crsNumber(partial.light.exposure, 2)}"`,
`crs:Contrast2012="${crsNumber(partial.light.contrast, 0)}"`,
`crs:Highlights2012="${crsNumber(partial.light.highlights, 0)}"`,
`crs:Shadows2012="${crsNumber(partial.light.shadows, 0)}"`,
`crs:Whites2012="${crsNumber(partial.light.whites, 0)}"`,
`crs:Blacks2012="${crsNumber(partial.light.blacks, 0)}"`,
`crs:Clarity2012="${crsNumber(partial.effects.clarity, 0)}"`,
`crs:Dehaze="${crsNumber(partial.effects.dehaze, 0)}"`,
`crs:Vibrance="${crsNumber(partial.color.vibrance, 0)}"`,
`crs:Saturation="${crsNumber(partial.color.saturation, 0)}"`,
`crs:Sharpness="${crsNumber(partial.detail.sharpen_amount, 0)}"`,
`crs:ColorNoiseReduction="${crsNumber(partial.detail.nr_color, 0)}"`,
].join(" ");
return `<?xml version="1.0" encoding="UTF-8"?>\n<x:xmpmeta xmlns:x="adobe:ns:meta/">\n <rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">\n <rdf:Description rdf:about="" xmlns:crs="http://ns.adobe.com/camera-raw-settings/1.0/" ${attrs}/>\n </rdf:RDF>\n</x:xmpmeta>\n`;
}
function crsAttr(xml: string, name: string): string | undefined {
const match = new RegExp(`crs:${name}="([^"]*)"`).exec(xml);
return match?.[1];
}
function crsFloat(xml: string, name: string): number | undefined {
const text = crsAttr(xml, name);
if (text === undefined) return undefined;
const value = Number(text);
return Number.isFinite(value) ? value : undefined;
}
const WB_MODE: Record<string, string> = {
"as shot": "asShot",
auto: "auto",
daylight: "daylight",
cloudy: "cloudy",
shade: "shade",
tungsten: "tungsten",
fluorescent: "fluorescent",
flash: "flash",
custom: "custom",
};
/** The edit stored in a sidecar. Null when the packet has none of the sliders. */
export function partialFromXmp(xml: string): InteriorPartial | null {
const exposure = crsFloat(xml, "Exposure2012");
const shadows = crsFloat(xml, "Shadows2012");
const highlights = crsFloat(xml, "Highlights2012");
const temp = crsFloat(xml, "Temperature");
if (exposure === undefined && shadows === undefined && highlights === undefined && temp === undefined) return null;
const fallback = interiorPartial(exposure);
const label = (crsAttr(xml, "WhiteBalance") ?? "").toLowerCase().replace(/\s+/g, " ");
const mode = WB_MODE[label] ?? (temp === undefined ? fallback.wb.mode : "custom");
return {
wb: {
mode,
temp: temp ?? fallback.wb.temp,
tint: crsFloat(xml, "Tint") ?? fallback.wb.tint,
scale: "kelvin",
},
light: {
exposure: exposure ?? fallback.light.exposure,
contrast: crsFloat(xml, "Contrast2012") ?? fallback.light.contrast,
highlights: highlights ?? fallback.light.highlights,
shadows: shadows ?? fallback.light.shadows,
whites: crsFloat(xml, "Whites2012") ?? fallback.light.whites,
blacks: crsFloat(xml, "Blacks2012") ?? fallback.light.blacks,
},
color: {
vibrance: crsFloat(xml, "Vibrance") ?? fallback.color.vibrance,
saturation: crsFloat(xml, "Saturation") ?? fallback.color.saturation,
},
effects: {
clarity: crsFloat(xml, "Clarity2012") ?? fallback.effects.clarity,
dehaze: crsFloat(xml, "Dehaze") ?? fallback.effects.dehaze,
},
detail: {
sharpen_amount: crsFloat(xml, "Sharpness") ?? fallback.detail.sharpen_amount,
nr_color: crsFloat(xml, "ColorNoiseReduction") ?? fallback.detail.nr_color,
},
};
}
+5 -2
View File
@@ -5,8 +5,11 @@ import { localOriginal } from "../platform.js";
import { MERGE_EDGE, stacksToMerge } from "./mergeStacks.js";
export class MergeError extends Error {
constructor(readonly code: "none" | "missing" | "engine" | "failed") {
super(code);
constructor(
readonly code: "none" | "missing" | "engine" | "failed",
readonly detail?: string,
) {
super(detail ? `${code}: ${detail}` : code);
}
}
+25 -17
View File
@@ -4,12 +4,14 @@ import { groupBrackets, type BracketFrame } from "@photoreport/metadata";
/** The engine's long-side cap for a merge. The DNG is this photo, not the full sensor. */
export const MERGE_EDGE = 4096;
/** A DNG this merge already wrote is not another exposure. */
export function isMergedName(name: string): boolean {
const lower = name.toLowerCase();
return lower.endsWith(".dng") || lower.includes("-fundido");
}
function isMergedFile(photo: PhotoSummary): boolean {
const names = [photo.originalName, photo.name];
return names.some((name) => {
const lower = name.toLowerCase();
return lower.endsWith(".dng") || lower.includes("-fundido");
});
return isMergedName(photo.originalName) || isMergedName(photo.name);
}
export function frameOf(photo: PhotoSummary): BracketFrame {
@@ -27,25 +29,31 @@ export function frameOf(photo: PhotoSummary): BracketFrame {
};
}
function byCapture(a: PhotoSummary, b: PhotoSummary): number {
function byFrame(a: BracketFrame, b: BracketFrame): number {
const time = (a.capturedAt ?? "").localeCompare(b.capturedAt ?? "");
if (time !== 0) return time;
return (a.originalName || a.name).localeCompare(b.originalName || b.name, undefined, { numeric: true, sensitivity: "base" });
return (a.fileName ?? a.id).localeCompare(b.fileName ?? b.id, undefined, { numeric: true, sensitivity: "base" });
}
/**
* Stacks to merge. A selection of two or more is that set (detected into angles when they are brackets,
* otherwise one stack in capture order). With nothing selected, every bracket in the folder is a stack.
* A DNG already produced here is not an exposure.
* otherwise one stack in capture order). With fewer than two selected, every bracket in the folder is a stack.
*/
export function stacksOfFrames(frames: readonly BracketFrame[], selectedIds: readonly string[]): string[][] {
const selected = new Set(selectedIds);
const chosen = selected.size >= 2;
const pool = chosen ? frames.filter((frame) => selected.has(frame.id)) : [...frames];
if (pool.length < 2) return [];
const grouped = groupBrackets(pool);
if (grouped.stacks.length > 0) return grouped.stacks.map((stack) => stack.frameIds);
if (!chosen) return [];
return [[...pool].sort(byFrame).map((frame) => frame.id)];
}
/**
* Stacks in a library collection. A DNG already produced here is not an exposure.
*/
export function stacksToMerge(photos: readonly PhotoSummary[], selectedIds: readonly string[]): string[][] {
const ready = photos.filter((photo) => photo.status === "READY" && !isMergedFile(photo));
const selected = new Set(selectedIds);
const chosen = selected.size >= 2;
const pool = chosen ? ready.filter((photo) => selected.has(photo.id)) : ready;
if (pool.length < 2) return [];
const grouped = groupBrackets(pool.map(frameOf));
if (grouped.stacks.length > 0) return grouped.stacks.map((stack) => stack.frameIds);
if (!chosen) return [];
return [[...pool].sort(byCapture).map((photo) => photo.id)];
return stacksOfFrames(ready.map(frameOf), selectedIds);
}
+35
View File
@@ -0,0 +1,35 @@
import { render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { describe, expect, it, vi } from "vitest";
import { RemoveFromEventDialog } from "./RemoveFromEvent.js";
import { isEventScope, isRemoveKey } from "./remove.js";
describe("remove from the open event", () => {
it("is Delete or Backspace, and only while an event is open", () => {
expect(isRemoveKey({ key: "Delete", metaKey: false, ctrlKey: false, altKey: false })).toBe(true);
expect(isRemoveKey({ key: "Backspace", metaKey: false, ctrlKey: false, altKey: false })).toBe(true);
expect(isRemoveKey({ key: "Delete", metaKey: true, ctrlKey: false, altKey: false })).toBe(false);
expect(isRemoveKey({ key: "x", metaKey: false, ctrlKey: false, altKey: false })).toBe(false);
expect(isEventScope("6d8c2c3e-1b2a-4c5d-9e8f-0a1b2c3d4e5f")).toBe(true);
expect(isEventScope("inbox")).toBe(false);
expect(isEventScope("search:ana")).toBe(false);
expect(isEventScope("face:")).toBe(false);
expect(isEventScope(null)).toBe(false);
});
it("asks before removing, and says so when it fails", async () => {
const user = userEvent.setup();
const onConfirm = vi.fn(async () => {
throw new Error("no");
});
const onCancel = vi.fn();
render(<RemoveFromEventDialog count={2} name="Jogo" onCancel={onCancel} onConfirm={onConfirm} />);
expect(screen.getByRole("dialog").textContent).toContain("Remover 2 fotos de «Jogo»?");
expect(screen.getByText("Ficam em Sem evento. Não são apagadas da biblioteca. O que já foi enviado sai desse destino.").textContent).toContain("Sem evento");
await user.click(screen.getByRole("button", { name: "Remover" }));
expect(onConfirm).toHaveBeenCalledOnce();
expect((await screen.findByRole("alert")).textContent).toContain("Algo correu mal");
await user.keyboard("{Escape}");
expect(onCancel).toHaveBeenCalled();
});
});
+21
View File
@@ -0,0 +1,21 @@
import type { ApiClient } from "@photoreport/sdk";
import { localPhotos } from "../offline/local.js";
import { patchPhotos } from "../offline/sync.js";
/** An open event, not the inbox and not a search or a face lookup. */
export function isEventScope(scope: string | null | undefined): scope is string {
return !!scope && scope !== "inbox" && !scope.startsWith("search:") && !scope.startsWith("face:");
}
/** Delete and Backspace, the keys Lightroom and Photo Mechanic use to take a photo out of what is open. */
export function isRemoveKey(e: { key: string; metaKey: boolean; ctrlKey: boolean; altKey: boolean }): boolean {
return (e.key === "Delete" || e.key === "Backspace") && !e.metaKey && !e.ctrlKey && !e.altKey;
}
/** Takes the photos out of their event. They stay in the library, under Sem evento. Local-only photos move there too. */
export async function removeFromEvent(api: ApiClient, orgId: string, ids: string[]): Promise<void> {
const local = ids.filter((id) => id.startsWith("local:"));
const server = ids.filter((id) => !id.startsWith("local:"));
for (const id of local) localPhotos.patch(id, { eventId: null });
if (server.length) await patchPhotos(api, orgId, server, { eventId: null });
}
+16
View File
@@ -86,6 +86,22 @@ describe("library store", () => {
expect(s.photos[0]!.delivery).toBe("DONE");
});
it("takes a removed photo out of the event and lands on the next one", () => {
const next = libraryReducer(loaded, { type: "patch", ids: ["a"], patch: { eventId: null } });
expect(next.photos.map((p) => p.id)).toEqual(["c"]);
expect(next.focus).toBe("c");
expect([...next.selected]).toEqual(["c"]);
const last = libraryReducer(loaded, { type: "select", id: "c", mode: "single", visible: ["a", "c"] });
const back = libraryReducer(last, { type: "patch", ids: ["c"], patch: { eventId: null } });
expect(back.photos.map((p) => p.id)).toEqual(["a"]);
expect(back.focus).toBe("a");
const none = libraryReducer(loaded, { type: "patch", ids: ["a", "c"], patch: { eventId: null } });
expect(none.photos).toEqual([]);
expect(none.focus).toBeNull();
});
it("comes back to the active photo from another module, once its page arrives, unless you pick one first", () => {
let s = libraryReducer(initialLibrary, { type: "load", scope: "e1", focus: "c" });
s = libraryReducer(s, { type: "loaded", scope: "e1", photos: [photo("a", "1"), photo("b", "2")], done: false });
+30 -3
View File
@@ -67,6 +67,29 @@ function withFreshFileUrls(current: PhotoSummary, incoming: PhotoSummary | undef
return { ...next, urls: incoming.urls };
}
/** Photos that left this event: the selection moves to the next one that stayed, as a contact sheet does. */
function afterLeave(state: LibraryState, photos: PhotoSummary[]): LibraryState {
const stay = new Set(photos.map((p) => p.id));
const selected = new Set([...state.selected].filter((id) => stay.has(id)));
let focus = state.focus;
if (focus && !stay.has(focus)) {
const at = state.photos.findIndex((p) => p.id === focus);
const later = state.photos.slice(at + 1).find((p) => stay.has(p.id));
let earlier: PhotoSummary | undefined;
for (let i = at - 1; i >= 0; i--) {
const photo = state.photos[i];
if (photo && stay.has(photo.id)) {
earlier = photo;
break;
}
}
focus = later?.id ?? earlier?.id ?? null;
}
if (focus && selected.size === 0) selected.add(focus);
const anchor = state.anchor && stay.has(state.anchor) ? state.anchor : focus;
return { ...state, photos, selected, focus, anchor };
}
/** The server's copy replaces a local photo: what was done to it here stays (it is being sent too). */
function replaceLocal(state: LibraryState, local: PhotoSummary, server: PhotoSummary): LibraryState {
const keep: Partial<PhotoSummary> = {
@@ -131,9 +154,13 @@ export function libraryReducer(state: LibraryState, action: LibraryAction): Libr
}
case "patch": {
const ids = new Set(action.ids);
let photos = state.photos.map((p) => (ids.has(p.id) ? applyPatch(p, action.patch) : p));
// Moved to another event: it leaves this view.
if (action.patch.eventId !== undefined) photos = photos.filter((p) => inScope(state.scope, p));
const photos = state.photos.map((p) => (ids.has(p.id) ? applyPatch(p, action.patch) : p));
// Moved to another event, or taken out of this one: it leaves this view, and the selection follows.
if (action.patch.eventId !== undefined) {
const staying = photos.filter((p) => inScope(state.scope, p));
if (staying.length !== photos.length) return afterLeave(state, staying);
return { ...state, photos: staying };
}
return { ...state, photos };
}
case "local": {
+17 -1
View File
@@ -73,8 +73,10 @@ export function lisbonInstant(exif: string | null): string | null {
return new Date(guess - (asLisbon - guess)).toISOString();
}
type RoutedEvent = Pick<EventSummary, "id" | "ingestFrom" | "ingestUntil" | "archivedAt" | "startsAt">;
/** The event a photo taken at `at` belongs to, as the server would route it (offline guess; the server decides). */
export function routeLocally(events: Pick<EventSummary, "id" | "ingestFrom" | "ingestUntil" | "archivedAt" | "startsAt">[], at: string | null): string | null {
export function routeLocally(events: RoutedEvent[], at: string | null): string | null {
if (!at) return null;
const t = Date.parse(at);
const open = events.filter((e) => !e.archivedAt && Date.parse(e.ingestFrom) <= t && t <= Date.parse(e.ingestUntil));
@@ -82,6 +84,20 @@ export function routeLocally(events: Pick<EventSummary, "id" | "ingestFrom" | "i
return open[0]?.id ?? null;
}
/**
* Where a local-FTP photo goes. The event the photographer pinned receives it only while the capture falls in that
* event's window. Outside it (the pin left over from yesterday's match), the photo goes to the event of the time
* it was taken. A pin whose window isn't in the list, or a photo with no capture time, keeps the pin.
*/
export function eventForArrival(pinnedId: string | null, events: RoutedEvent[], at: string | null): string | null {
if (!pinnedId) return routeLocally(events, at);
const pinned = events.find((e) => e.id === pinnedId);
if (!pinned || !at) return pinnedId;
const t = Date.parse(at);
if (Date.parse(pinned.ingestFrom) <= t && t <= Date.parse(pinned.ingestUntil)) return pinnedId;
return routeLocally(events, at);
}
export function localPhoto(p: { sha256: string; name: string; width: number; height: number; capturedAt: string | null; eventId: string | null; url: string }): PhotoSummary {
return {
id: localId(p.sha256),
+6 -1
View File
@@ -2,7 +2,7 @@ import type { PhotoSummary } from "@photoreport/contracts";
import { ApiError, type ApiClient } from "@photoreport/sdk";
import { beforeEach, describe, expect, it, vi } from "vitest";
import { initialLibrary, libraryReducer } from "../library/store.js";
import { exifDateTime, lisbonInstant, localPhoto, routeLocally } from "./local.js";
import { eventForArrival, exifDateTime, lisbonInstant, localPhoto, routeLocally } from "./local.js";
import { isNetworkError, localId, OfflineQueue } from "./queue.js";
function memoryStore() {
@@ -120,6 +120,11 @@ describe("photos arriving on this computer", () => {
];
expect(routeLocally(events, at)).toBe("braga");
expect(routeLocally(events, "2026-09-03T15:00:00Z")).toBeNull();
// Yesterday's pin only holds photos taken inside it. The next morning goes to that morning's event.
expect(eventForArrival("braga", events, at)).toBe("braga");
expect(eventForArrival("braga", events, "2026-10-10T15:30:00Z")).toBe("other");
expect(eventForArrival("braga", events, null)).toBe("braga");
expect(eventForArrival("missing", events, "2026-10-10T15:30:00Z")).toBe("missing");
});
it("show in the library at once and give way to the server's copy, keeping what was done to them", () => {
+12
View File
@@ -223,6 +223,18 @@ function SourceCard({ api, source, isAdmin, active, onSelect, onChange, onRemove
</select>
</label>
)}
{isAdmin && (
<label className="flex w-full flex-wrap items-center gap-2">
<input
type="checkbox"
checked={!!source.photoFindEnabled}
disabled={busy}
onChange={(e) => void run(() => api.updateCloudSource(source.id, { photoFindEnabled: e.target.checked }))}
/>
<span className="text-[12px] text-ink">{A.photoFind}</span>
<span className="w-full text-faint">{A.photoFindHelp}</span>
</label>
)}
{isAdmin && (
<form
className="flex w-full flex-wrap items-center gap-2"
+72 -50
View File
@@ -4,6 +4,8 @@ import { useCallback, useEffect, useMemo, useRef, useState, useSyncExternalStore
import { useLocation, useNavigate, useParams } from "react-router";
import { useAuth } from "../auth.js";
import { HelpLink } from "../components/HelpLink.js";
import { Filmstrip } from "../develop/Filmstrip.js";
import { localFilmSrc } from "../develop/local-thumb.js";
import { type EngineModule, loadEngine } from "../develop/engine.js";
import { DevelopPanels, Section, Slider } from "../develop/Panels.js";
import { type Crop, cropOf, DevelopSession, localOutbox } from "../develop/session.js";
@@ -19,6 +21,8 @@ import { MergeButton } from "../library/MergeButton.js";
import { localPhotos } from "../offline/local.js";
import { isNetworkError, offlineQueue } from "../offline/queue.js";
import { patchPhotos, useOfflineSync } from "../offline/sync.js";
import { RemoveFromEventDialog } from "../library/RemoveFromEvent.js";
import { isRemoveKey, removeFromEvent } from "../library/remove.js";
import { ALL_PHOTOS, applyPatch, isMac, type LibraryFilter, matchesFilter, patchForKey, pmPatchForKey } from "../library/store.js";
import { t } from "../i18n.js";
import { useLibraryLive } from "../library/realtime.js";
@@ -101,7 +105,6 @@ export function DevelopPage() {
const [targets, setTargets] = useState<DeliveryTarget[]>([]);
const [sourceSize, setSourceSize] = useState<{ w: number; h: number } | null>(null);
const [note, setNote] = useState<string | null>(null);
const strip = useRef<HTMLDivElement>(null);
const modules = me?.preferences.editorModules ?? DEFAULT_MODULES;
useEffect(() => {
@@ -115,6 +118,8 @@ export function DevelopPage() {
// The event (or inbox) the library has open, all of it (page by page), as the library shows it.
const scope = orgId ? (prefs.get(`scope:${orgId}`) ?? null) : null;
const [all, setAll] = useState<PhotoSummary[] | null>(null);
const gone = useRef(new Set<string>());
const stillHere = (list: PhotoSummary[]) => (gone.current.size ? list.filter((p) => !gone.current.has(p.id)) : list);
useEffect(() => {
if (!orgId) return;
let alive = true;
@@ -122,21 +127,24 @@ export function DevelopPage() {
const kept = scope ? await cache.photos(orgId, scope) : undefined;
if (!alive) return;
// The filmstrip (including photos still only on this computer) before the network answers.
setAll(kept ?? []);
setAll(stillHere(kept ?? []));
const got: PhotoSummary[] = [];
try {
for (let offset = 0; ; offset += PAGE) {
const page = await api.listPhotos(orgId, { ...(scope && { event: scope }), offset, limit: PAGE });
got.push(...page.photos);
if (!alive) return;
setAll([...got]);
setAll(stillHere(got));
if (offset + page.photos.length >= page.total || page.photos.length === 0) break;
}
if (scope) void cache.setPhotos(orgId, scope, got);
if (!alive) return;
const listed = stillHere(got);
setAll(listed);
if (scope) void cache.setPhotos(orgId, scope, listed);
} catch (err) {
// No network: the folder as last seen on this computer.
const kept = isNetworkError(err) && scope ? await cache.photos(orgId, scope) : undefined;
if (alive) setAll((a) => (a && a.length ? a : (kept ?? [])));
const fallback = isNetworkError(err) && scope ? (kept ?? (await cache.photos(orgId, scope))) : undefined;
if (alive) setAll((a) => (a && a.length ? stillHere(a) : stillHere(fallback ?? [])));
}
})();
return () => {
@@ -191,6 +199,7 @@ export function DevelopPage() {
}, [orgId, scope, current?.id]); // eslint-disable-line react-hooks/exhaustive-deps
const canEdit = !!current && !!role && (hasRole(role, "INGESTER") || current.uploader?.id === me?.user.id || current.id.startsWith("local:"));
const [removeOpen, setRemoveOpen] = useState(false);
useEffect(() => {
if (!current || typeof engine !== "object") return;
@@ -269,10 +278,6 @@ export function DevelopPage() {
[photos, index, navigate],
);
useEffect(() => {
strip.current?.querySelector('[aria-current="true"]')?.scrollIntoView({ block: "nearest", inline: "nearest" });
}, [current?.id]);
useEffect(() => {
const onKey = (e: KeyboardEvent) => {
if (isTyping(e.target)) return;
@@ -329,6 +334,10 @@ export function DevelopPage() {
else if (!mod && !e.altKey && !e.shiftKey && e.key.toLowerCase() === "e") navigate("/", { state: { focus: current?.id, loupe: true } });
else if (!mod && e.shiftKey && e.key.toLowerCase() === "a" && canEdit) void autoAllRef.current();
else if (!mod && !e.shiftKey && e.key.toLowerCase() === "i" && canCull && current) setInfo(true);
else if (!cropKeys.current.active && isRemoveKey(e) && canCull && current?.eventId) {
e.preventDefault();
setRemoveOpen(true);
}
else if (!mod && !e.altKey && patchForKey(e.key)) {
e.preventDefault();
flagCurrent(patchForKey(e.key)!);
@@ -805,48 +814,61 @@ export function DevelopPage() {
<FilterBar compact filter={filter} onChange={changeFilter} />
<HelpLink section="filtro" label={t.help.filtro.title} />
</div>
<div ref={strip} className="flex h-[92px] shrink-0 gap-1 overflow-x-auto border-t border-line bg-chrome p-1.5" aria-label="Fotos do evento">
{photos.map((p) => (
<button
key={p.id}
aria-current={p.id === current?.id}
aria-pressed={selected.has(p.id)}
onClick={(e) => {
const ids = photos.map((item) => item.id);
if (e.shiftKey && current) {
const a = ids.indexOf(current.id);
const b = ids.indexOf(p.id);
const [lo, hi] = a < b ? [a, b] : [b, a];
setSelected(new Set(ids.slice(Math.max(0, lo), hi + 1)));
navigate(`/develop/${p.id}`);
return;
}
if (e.metaKey || e.ctrlKey) {
setSelected((prev) => {
const next = new Set(prev);
if (next.has(p.id) && next.size > 1) next.delete(p.id);
else next.add(p.id);
return next;
});
return;
}
setSelected(new Set([p.id]));
navigate(`/develop/${p.id}`);
}}
className={`relative h-full shrink-0 border ${selected.has(p.id) ? "border-[#cfcfcf]" : "border-transparent opacity-70 hover:opacity-100"} ${p.id === current?.id ? "ring-1 ring-white" : ""} ${p.flag === "REJECT" ? "grayscale" : ""}`}
title={p.name}
>
<img src={api.absolute(p.urls.thumb)} alt="" loading="lazy" className="h-full w-auto" draggable={false} />
{p.developSeq > 0 && <span className="absolute bottom-0.5 right-0.5 bg-black/70 px-1 font-mono text-[9px] text-white">±</span>}
{p.flag !== "NONE" && (
<span className={`absolute left-0.5 top-0.5 px-1 text-[10px] ${p.flag === "PICK" ? "bg-white text-black" : "bg-black/80 text-white"}`}>{p.flag === "PICK" ? "⚑" : "✕"}</span>
)}
{p.rating > 0 && <span className="absolute bottom-0.5 left-0.5 bg-black/70 px-1 text-[9px] text-white">{"★".repeat(p.rating)}</span>}
</button>
))}
</div>
<Filmstrip
photos={photos}
currentId={current?.id ?? null}
selected={selected}
srcFor={(p) => api.absolute(p.urls.thumb)}
onOpen={(id) => navigate(`/develop/${id}`)}
onActivate={(id, mods) => {
const ids = photos.map((item) => item.id);
if (mods.shiftKey && current) {
const a = ids.indexOf(current.id);
const b = ids.indexOf(id);
const [lo, hi] = a < b ? [a, b] : [b, a];
setSelected(new Set(ids.slice(Math.max(0, lo), hi + 1)));
navigate(`/develop/${id}`);
return;
}
if (mods.metaKey || mods.ctrlKey) {
setSelected((prev) => {
const next = new Set(prev);
if (next.has(id) && next.size > 1) next.delete(id);
else next.add(id);
return next;
});
return;
}
setSelected(new Set([id]));
navigate(`/develop/${id}`);
}}
{...(isDesktop() ? { localSrc: localFilmSrc } : {})}
/>
<div className="border-t border-line bg-raised px-3 py-1 text-[11px] text-faint">{cropping ? t.dev.cropShortcuts : t.dev.shortcuts}</div>
{info && current && <IptcInfo api={api} orgId={orgId} photos={[current]} sequence={photos} targets={targets} canDeliver={!!role && hasRole(role, "INGESTER")} onClose={() => setInfo(false)} />}
{removeOpen && current?.eventId && (
<RemoveFromEventDialog
count={1}
onCancel={() => setRemoveOpen(false)}
onConfirm={async () => {
const id = current.id;
await removeFromEvent(api, orgId, [id]);
gone.current.add(id);
setAll((list) => (list ? list.filter((p) => p.id !== id) : list));
setPhotos((list) => list.filter((p) => p.id !== id));
if (scope) {
void cache.photos(orgId, scope).then((list) => {
if (list) void cache.setPhotos(orgId, scope, list.filter((p) => p.id !== id));
});
}
const rest = photos.filter((p) => p.id !== id);
const next = rest[index] ?? rest[index - 1];
setRemoveOpen(false);
if (next) navigate(`/develop/${next.id}`);
else navigate("/");
}}
/>
)}
</div>
);
}
+150 -11
View File
@@ -12,17 +12,26 @@ import { EventSettingsButton } from "../library/EventSettings.js";
import { useFolderScan } from "../library/folderScan.js";
import { FacesView } from "../library/FacesView.js";
import { LookupBanner } from "../library/PhotoLookup.js";
import { FolderDevelop } from "../library/FolderDevelop.js";
import { FolderSheet } from "../library/FolderSheet.js";
import { beginDropWait, folderDropPath, folderMeta, htmlDropIsFolder, mergeFolderDng, nativePaths, openFolder, folderThumb, type FolderListing } from "../library/folderDrop.js";
import { finishMergedJpeg } from "../library/finishMergedJpeg.js";
import { mergeFolderNative } from "../library/folderMerge.js";
import { MERGE_EDGE } from "../library/mergeStacks.js";
import { Grid, Loupe, type LoupeFace } from "../library/Grid.js";
import { InfoPanel } from "../library/InfoPanel.js";
import { IptcInfo } from "../library/IptcInfo.js";
import { useLibraryLive } from "../library/realtime.js";
import { useIngest } from "../library/ingest.js";
import { LocalFtpButton } from "../library/LocalFtp.js";
import { UsbCameraButton } from "../library/UsbCamera.js";
import { CardIngestButton, CardOverallStatus } from "../library/CardIngest.js";
import { MergeButton } from "../library/MergeButton.js";
import { AutopilotButton } from "../library/Autopilot.js";
import { SquadsButton } from "../library/Squads.js";
import { type PlayerPick, photoIdsOf, samePicks } from "../library/squadFilter.js";
import { RemoveFromEventDialog } from "../library/RemoveFromEvent.js";
import { isEventScope, isRemoveKey, removeFromEvent } from "../library/remove.js";
import { initialLibrary, isMac, type LibraryFilter, libraryReducer, matchesFilter, patchForKey, pmPatchForKey } from "../library/store.js";
import { cache, warmImages, type CachedEvents } from "../offline/cache.js";
import { localPhotos } from "../offline/local.js";
@@ -261,9 +270,51 @@ export function LibraryPage() {
dispatch({ type: "local", photos: localPhotos.list() });
}, [localVersion]);
const waitingChanges = useQueueSize(orgId);
const { uploads, localFtp, desktop } = useIngest();
const { uploads, localFtp, usb, desktop } = useIngest();
const fileInput = useRef<HTMLInputElement>(null);
const [dragging, setDragging] = useState(false);
const [sheet, setSheet] = useState<FolderListing | null>(null);
const [developPath, setDevelopPath] = useState<string | null>(null);
const [openingFolder, setOpeningFolder] = useState(false);
const [removeOpen, setRemoveOpen] = useState(false);
useEffect(() => {
if (!isDesktop()) return;
let dead = false;
let unlisten = () => {};
void import("@tauri-apps/api/webview").then(({ getCurrentWebview }) =>
getCurrentWebview().onDragDropEvent((event) => {
if (event.payload.type === "enter") setDragging(true);
else if (event.payload.type === "leave") setDragging(false);
else if (event.payload.type === "drop") {
setDragging(false);
nativePaths(event.payload.paths, folderDropPath, (path) => {
setOpeningFolder(true);
setLoupe(false);
void openFolder(path).then(
(listing) => {
if (dead) return;
setOpeningFolder(false);
setDevelopPath(null);
setSheet(listing);
},
() => {
if (dead) return;
setOpeningFolder(false);
setError(t.folderSheet.failed);
},
);
});
}
}),
).then((stop) => {
if (dead) stop();
else unlisten = stop;
});
return () => {
dead = true;
unlisten();
};
}, []);
const uploadInto = state.scope && state.scope !== "inbox" && !state.scope.startsWith("search:") && !state.scope.startsWith("face:") ? state.scope : undefined;
const openEvent = events.find((e) => e.id === uploadInto) ?? archivedEvents?.find((e) => e.id === uploadInto);
useEffect(() => {
@@ -313,6 +364,7 @@ export function LibraryPage() {
useEffect(() => {
const onKey = (e: KeyboardEvent) => {
if (sheet) return;
// Lightroom's module keys: Ctrl/Cmd+Alt+2 (or +Up, back to the other module) opens Develop on this photo.
if (!isTyping(e.target) && (e.metaKey || e.ctrlKey) && e.altKey && (e.code === "Digit2" || e.key === "ArrowUp") && focus) {
e.preventDefault();
@@ -320,6 +372,11 @@ export function LibraryPage() {
}
// Photo Mechanic's keys (Cmd+1-5 colour, Ctrl+1-5 stars, T tag), next to Lightroom's.
const pm = isTyping(e.target) ? undefined : pmPatchForKey(e, isMac(), focus?.flag);
if (!isTyping(e.target) && isRemoveKey(e) && canCull && isEventScope(state.scope) && selection.length) {
e.preventDefault();
setRemoveOpen(true);
return;
}
if (pm && selection.length) {
e.preventDefault();
const change = { ...pm };
@@ -365,7 +422,7 @@ export function LibraryPage() {
};
window.addEventListener("keydown", onKey);
return () => window.removeEventListener("keydown", onKey);
}, [visibleIds, selection, focus, loupe, patch, navigate, canCull]);
}, [visibleIds, selection, focus, loupe, patch, navigate, canCull, sheet, state.scope]);
// The photo you are on is the active one for every module (Develop opens on it).
useEffect(() => {
@@ -422,7 +479,10 @@ export function LibraryPage() {
scope={state.scope}
canCreate={canCreate}
canSeeInbox={canCull}
onOpen={(scope) => void open(scope)}
onOpen={(scope) => {
setSheet(null);
void open(scope);
}}
onCreate={() => setCreating(true)}
onLookup={(file) => void runLookup(file)}
archived={archivedEvents}
@@ -470,6 +530,7 @@ export function LibraryPage() {
{t.cardScan.button}
</button>
)}
{desktop && <UsbCameraButton usb={usb} target={localFtp.target} setTarget={localFtp.setTarget} openEvent={openEvent} />}
{desktop && <LocalFtpButton ftp={localFtp} events={events} openEventId={uploadInto} />}
{desktop && <CardIngestButton />}
{openEvent && (
@@ -496,7 +557,7 @@ export function LibraryPage() {
{canCull && openEvent && (
<AutopilotButton api={api} event={openEvent} targets={targets} canEdit={canCreate} onSaved={(e) => setEvents((list) => list.map((x) => (x.id === e.id ? e : x)))} />
)}
{canCull && selection.length > 0 && (
{canCull && !sheet && selection.length > 0 && (
<select
aria-label={t.shop.addToGallery}
className="h-6 border border-black bg-cell px-1.5 text-[12px] text-ink"
@@ -524,20 +585,20 @@ export function LibraryPage() {
))}
</select>
)}
{canCull && state.scope && !state.scope.startsWith("search:") && !state.scope.startsWith("face:") && (
{canCull && !sheet && state.scope && !state.scope.startsWith("search:") && !state.scope.startsWith("face:") && (
<MergeButton api={api} orgId={orgId} eventId={state.scope === "inbox" ? null : state.scope} photos={state.photos} selectedIds={[...state.selected]} />
)}
{canCull && (
<SendButton
api={api}
orgId={orgId}
selection={selection}
selection={sheet ? [] : selection}
targets={targets}
eventId={openEvent?.id ?? null}
onQueued={(items) => items.forEach((item) => dispatch({ type: "message", message: { type: "delivery.updated", item } }))}
/>
)}
{canCull && selection.length > 0 && !state.scope?.startsWith("search:") && !state.scope?.startsWith("face:") && (
{canCull && !sheet && selection.length > 0 && !state.scope?.startsWith("search:") && !state.scope?.startsWith("face:") && (
<select
aria-label={t.moveToEvent}
className="h-6 border border-black bg-cell px-1.5 text-[12px] text-ink"
@@ -566,8 +627,13 @@ export function LibraryPage() {
))}
</select>
)}
{canCull && !sheet && isEventScope(state.scope) && selection.length > 0 && (
<button type="button" onClick={() => setRemoveOpen(true)} className="h-6 border border-black bg-cell px-2.5 text-[12px] text-ink hover:bg-cell-on">
{t.remove}
</button>
)}
{info && <span className="text-[11px] text-ok">{info}</span>}
{canCull && focus && selection.length > 1 && (
{canCull && !sheet && focus && selection.length > 1 && (
<SyncSettingsButton
count={selection.filter((p) => p.id !== focus.id).length}
onApply={async ({ controls, crop }) => {
@@ -609,7 +675,7 @@ export function LibraryPage() {
</div>
<div
className={`min-h-0 flex-1 overflow-y-auto ${dragging ? "outline outline-2 -outline-offset-4 outline-accent" : ""}`}
className={`min-h-0 flex-1 ${sheet ? "flex flex-col overflow-hidden" : "overflow-y-auto"} ${dragging ? "outline outline-2 -outline-offset-4 outline-accent" : ""}`}
onDragOver={(e) => {
if (!e.dataTransfer.types.includes("Files")) return;
e.preventDefault();
@@ -619,7 +685,15 @@ export function LibraryPage() {
onDrop={(e) => {
e.preventDefault();
setDragging(false);
uploads.add(e.dataTransfer.files, uploadInto);
const files = e.dataTransfer.files;
if (htmlDropIsFolder(e.dataTransfer.items)) return;
if (!isDesktop()) {
uploads.add(files, uploadInto);
return;
}
void beginDropWait().then((kind) => {
if (kind === "files") uploads.add(files, uploadInto);
});
}}
>
{error && (
@@ -640,7 +714,48 @@ export function LibraryPage() {
onClose={() => void open(lookup.from ?? "inbox")}
/>
)}
{view === "faces" && state.scope && state.scope !== "inbox" && !state.scope.startsWith("search:") && !state.scope.startsWith("face:") ? (
{sheet && developPath && sheet.files.some((file) => file.path === developPath) ? (
<FolderDevelop files={sheet.files} path={developPath} onPath={setDevelopPath} onClose={() => setDevelopPath(null)} />
) : sheet ? (
<FolderSheet
folder={sheet}
onClose={() => {
setDevelopPath(null);
setSheet(null);
}}
onDevelop={setDevelopPath}
thumb={folderThumb}
{...(canCull
? {
merge: async (input: {
files: FolderListing["files"];
selectedIds: readonly string[];
jpeg: boolean;
onStatus: (stack: number, total: number, phase?: "merge" | "jpeg") => void;
}) => {
const result = await mergeFolderNative({
files: input.files,
selectedIds: input.selectedIds,
onStatus: input.onStatus,
metaOf: folderMeta,
mergePaths: (paths) => mergeFolderDng(paths, MERGE_EDGE),
...(input.jpeg ? { finishJpeg: finishMergedJpeg } : {}),
});
const folderPath = sheet.path;
try {
const listing = await openFolder(folderPath);
setSheet((current) => (current?.path === folderPath ? listing : current));
} catch {
// The DNG is already beside the frames. Reopening the folder shows it.
}
return result;
},
}
: {})}
/>
) : openingFolder ? (
<p className="p-8 text-center text-[13px] text-faint">{t.folderSheet.opening}</p>
) : view === "faces" && state.scope && state.scope !== "inbox" && !state.scope.startsWith("search:") && !state.scope.startsWith("face:") ? (
<FacesView api={api} orgId={orgId} eventId={state.scope} canAnalyse={canCreate} refreshKey={facesTick} />
) : loupe && focus ? (
<Loupe photo={focus} src={api.absolute(focus.urls.preview)} fallback={api.absolute(focus.urls.thumb)} index={visibleIds.indexOf(focus.id)} total={visibleIds.length} faces={loupeFaces} />
@@ -690,6 +805,30 @@ export function LibraryPage() {
onPlayers={(ids, players) => patch(ids, { players })}
/>
{removeOpen && isEventScope(state.scope) && (
<RemoveFromEventDialog
count={selection.length}
{...(openEvent ? { name: openEvent.title } : {})}
onCancel={() => setRemoveOpen(false)}
onConfirm={async () => {
const ids = selection.map((p) => p.id);
const scope = state.scope;
await removeFromEvent(api, orgId, ids);
dispatch({ type: "patch", ids, patch: { eventId: null } });
if (isEventScope(scope)) {
const serverIds = new Set(ids.filter((id) => !id.startsWith("local:")));
setEvents((list) => list.map((event) => (event.id === scope ? { ...event, photoCount: Math.max(0, event.photoCount - serverIds.size) } : event)));
setInboxCount((n) => n + serverIds.size);
void cache.photos(orgId, scope).then((list) => {
if (list) void cache.setPhotos(orgId, scope, list.filter((p) => !serverIds.has(p.id)));
});
}
setInfo(t.removedFromEvent(ids.length));
setTimeout(() => setInfo(null), 4000);
setRemoveOpen(false);
}}
/>
)}
{iptcOpen && <IptcInfo api={api} orgId={orgId} photos={selection} sequence={visible} targets={targets} canDeliver={canCull} onClose={() => setIptcOpen(false)} />}
{creating && (
<EventForm
+12
View File
@@ -40,6 +40,18 @@ describe("localOriginal", () => {
});
});
describe("localFilmThumb", () => {
it("returns the desktop thumbnail, or null when this computer does not have the file", async () => {
const { localFilmThumb } = await import("./platform.js");
const bytes = new Uint8Array([0xff, 0xd8]).buffer;
const has = (async (cmd: string, args?: Record<string, unknown>) =>
cmd === "local_film_thumb" && args?.sha256 === "abc" ? bytes : Promise.reject("not_found")) as never;
expect(await localFilmThumb("abc", has)).toBe(bytes);
expect(await localFilmThumb("other", has)).toBeNull();
expect(await localFilmThumb("abc")).toBeNull();
});
});
describe("asArrayBuffer", () => {
it("accepts what the desktop bridge sends: ArrayBuffer, typed arrays or arrays of numbers", async () => {
const { asArrayBuffer } = await import("./platform.js");
+14
View File
@@ -125,3 +125,17 @@ export async function localOriginal(sha256: string, invokeImpl?: Invoke): Promis
return null;
}
}
/**
* A small JPEG of this photo from the original on this computer, for the filmstrip. Null in the browser, or when
* this computer does not have the file (the strip then uses the server thumbnail).
*/
export async function localFilmThumb(sha256: string, invokeImpl?: Invoke): Promise<ArrayBuffer | null> {
if (!invokeImpl && !isDesktop()) return null;
try {
const invoke: Invoke = invokeImpl ?? desktopInvoke;
return asArrayBuffer(await invoke<unknown>("local_film_thumb", { sha256 }));
} catch {
return null;
}
}
+2
View File
@@ -12,6 +12,8 @@ What the shell adds today:
- Refresh token in the OS keychain (macOS Keychain, Windows Credential Manager, Linux Secret Service).
Without a keychain the session stays in memory and ends when the app closes.
- Local FTP server for cameras (`src/ftp.rs`, Library → **FTP local**). See below.
- USB tether (`src/camera.rs` + `camera_mac.m`, Library → **USB**): a PTP body on the cable sends new shots
to the open event and syncs its clock to this Mac. EOS Utility must not hold the cable.
- Local catalogue (`src/catalog.rs`, Preferências → **Catálogo local**). See below.
- Works without network: when the server can't be reached at start-up, the window opens the copy of the web app
bundled in the installer (photo engine included), so the catalogue, local FTP and editing originals on disk go on;
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@photoreport/desktop",
"version": "0.3.21",
"version": "0.3.26",
"private": true,
"type": "module",
"scripts": {
+4 -3
View File
@@ -1,6 +1,6 @@
[package]
name = "photoreport-desktop"
version = "0.3.21"
version = "0.3.26"
edition = "2024"
publish = false
description = "PhotoReport desktop: the web app in a native shell, with keychain sign-in and (later) local FTP and the native engine."
@@ -11,6 +11,7 @@ crate-type = ["staticlib", "cdylib", "rlib"]
[build-dependencies]
tauri-build = { version = "2", features = [] }
cc = "1"
[dependencies]
tauri = { version = "2", features = [] }
@@ -30,9 +31,9 @@ serde_json = "1"
sha2 = "0.10"
libc = "0.2"
image = { version = "0.25", default-features = false, features = ["jpeg"] }
# Capture time and filmstrip thumbnails. The embedded-preview feature reads the camera JPEG; the browser build leaves it off.
photoreport-engine = { path = "../../../engine/core", features = ["embedded-preview", "photo-merge"] }
photoreport-faces = { path = "../../../workers/faces" }
# Capture time (EXIF / IPTC / XMP, including CR3) comes from the engine's LightCraft reader.
photoreport-engine = { path = "../../../engine/core" }
tauri-plugin-dialog = "2"
tauri-plugin-updater = "2"
# New versions of the interface (see src/ui.rs). Already built for the updater: same versions, no new crates.
+30 -2
View File
@@ -1,6 +1,18 @@
fn main() {
// The keychain and local FTP commands get ACL permissions, so the web app loaded from the server (a remote origin) can be
// granted them explicitly in capabilities/default.json.
let target = std::env::var("CARGO_CFG_TARGET_OS").unwrap_or_default();
if target == "macos" {
// ImageCaptureCore: PTP cameras (they never mount as a volume).
cc::Build::new()
.file("src/camera_mac.m")
.flag("-fobjc-arc")
.compile("camera_mac");
println!("cargo:rustc-link-lib=framework=Foundation");
println!("cargo:rustc-link-lib=framework=ImageCaptureCore");
println!("cargo:rustc-link-lib=framework=IOKit");
println!("cargo:rerun-if-changed=src/camera_mac.m");
}
// The keychain, local FTP and USB camera commands get ACL permissions, so the web app loaded from the server
// (a remote origin) can be granted them explicitly in capabilities/default.json.
tauri_build::try_build(tauri_build::Attributes::new().app_manifest(
tauri_build::AppManifest::new().commands(&[
"refresh_token_get",
@@ -18,6 +30,16 @@ fn main() {
"ftp_save_settings",
"local_original",
"local_original_changed",
"local_film_thumb",
"folder_drop",
"folder_open",
"folder_thumb",
"folder_read",
"folder_meta",
"folder_merge_dng",
"folder_save_dng",
"folder_save_jpeg",
"folder_save_xmp",
"ftp_preview",
"ftp_info",
"catalog_folders",
@@ -45,6 +67,12 @@ fn main() {
"delivery_folder_pick",
"delivery_write",
"import_upload_profiles",
"camera_status",
"camera_take",
"camera_tether",
"camera_sync",
"camera_import",
"camera_refresh",
]),
))
.expect("failed to run tauri-build");
@@ -33,6 +33,16 @@
"allow-ftp-save-settings",
"allow-local-original",
"allow-local-original-changed",
"allow-local-film-thumb",
"allow-folder-drop",
"allow-folder-open",
"allow-folder-thumb",
"allow-folder-read",
"allow-folder-meta",
"allow-folder-merge-dng",
"allow-folder-save-dng",
"allow-folder-save-jpeg",
"allow-folder-save-xmp",
"allow-ftp-preview",
"allow-ftp-info",
"allow-catalog-folders",
@@ -59,7 +69,13 @@
"allow-delivery-folders",
"allow-delivery-folder-pick",
"allow-delivery-write",
"allow-import-upload-profiles"
"allow-import-upload-profiles",
"allow-camera-status",
"allow-camera-take",
"allow-camera-tether",
"allow-camera-sync",
"allow-camera-import",
"allow-camera-refresh"
],
"remote": {
"urls": [
@@ -0,0 +1,11 @@
# Automatically generated - DO NOT EDIT!
[[permission]]
identifier = "allow-camera-import"
description = "Enables the camera_import command without any pre-configured scope."
commands.allow = ["camera_import"]
[[permission]]
identifier = "deny-camera-import"
description = "Denies the camera_import command without any pre-configured scope."
commands.deny = ["camera_import"]
@@ -0,0 +1,11 @@
# Automatically generated - DO NOT EDIT!
[[permission]]
identifier = "allow-camera-refresh"
description = "Enables the camera_refresh command without any pre-configured scope."
commands.allow = ["camera_refresh"]
[[permission]]
identifier = "deny-camera-refresh"
description = "Denies the camera_refresh command without any pre-configured scope."
commands.deny = ["camera_refresh"]
@@ -0,0 +1,11 @@
# Automatically generated - DO NOT EDIT!
[[permission]]
identifier = "allow-camera-status"
description = "Enables the camera_status command without any pre-configured scope."
commands.allow = ["camera_status"]
[[permission]]
identifier = "deny-camera-status"
description = "Denies the camera_status command without any pre-configured scope."
commands.deny = ["camera_status"]
@@ -0,0 +1,11 @@
# Automatically generated - DO NOT EDIT!
[[permission]]
identifier = "allow-camera-sync"
description = "Enables the camera_sync command without any pre-configured scope."
commands.allow = ["camera_sync"]
[[permission]]
identifier = "deny-camera-sync"
description = "Denies the camera_sync command without any pre-configured scope."
commands.deny = ["camera_sync"]
@@ -0,0 +1,11 @@
# Automatically generated - DO NOT EDIT!
[[permission]]
identifier = "allow-camera-take"
description = "Enables the camera_take command without any pre-configured scope."
commands.allow = ["camera_take"]
[[permission]]
identifier = "deny-camera-take"
description = "Denies the camera_take command without any pre-configured scope."
commands.deny = ["camera_take"]
@@ -0,0 +1,11 @@
# Automatically generated - DO NOT EDIT!
[[permission]]
identifier = "allow-camera-tether"
description = "Enables the camera_tether command without any pre-configured scope."
commands.allow = ["camera_tether"]
[[permission]]
identifier = "deny-camera-tether"
description = "Denies the camera_tether command without any pre-configured scope."
commands.deny = ["camera_tether"]
@@ -0,0 +1,11 @@
# Automatically generated - DO NOT EDIT!
[[permission]]
identifier = "allow-folder-drop"
description = "Enables the folder_drop command without any pre-configured scope."
commands.allow = ["folder_drop"]
[[permission]]
identifier = "deny-folder-drop"
description = "Denies the folder_drop command without any pre-configured scope."
commands.deny = ["folder_drop"]
@@ -0,0 +1,11 @@
# Automatically generated - DO NOT EDIT!
[[permission]]
identifier = "allow-folder-merge-dng"
description = "Enables the folder_merge_dng command without any pre-configured scope."
commands.allow = ["folder_merge_dng"]
[[permission]]
identifier = "deny-folder-merge-dng"
description = "Denies the folder_merge_dng command without any pre-configured scope."
commands.deny = ["folder_merge_dng"]
@@ -0,0 +1,11 @@
# Automatically generated - DO NOT EDIT!
[[permission]]
identifier = "allow-folder-meta"
description = "Enables the folder_meta command without any pre-configured scope."
commands.allow = ["folder_meta"]
[[permission]]
identifier = "deny-folder-meta"
description = "Denies the folder_meta command without any pre-configured scope."
commands.deny = ["folder_meta"]
@@ -0,0 +1,11 @@
# Automatically generated - DO NOT EDIT!
[[permission]]
identifier = "allow-folder-open"
description = "Enables the folder_open command without any pre-configured scope."
commands.allow = ["folder_open"]
[[permission]]
identifier = "deny-folder-open"
description = "Denies the folder_open command without any pre-configured scope."
commands.deny = ["folder_open"]
@@ -0,0 +1,11 @@
# Automatically generated - DO NOT EDIT!
[[permission]]
identifier = "allow-folder-read"
description = "Enables the folder_read command without any pre-configured scope."
commands.allow = ["folder_read"]
[[permission]]
identifier = "deny-folder-read"
description = "Denies the folder_read command without any pre-configured scope."
commands.deny = ["folder_read"]
@@ -0,0 +1,11 @@
# Automatically generated - DO NOT EDIT!
[[permission]]
identifier = "allow-folder-save-dng"
description = "Enables the folder_save_dng command without any pre-configured scope."
commands.allow = ["folder_save_dng"]
[[permission]]
identifier = "deny-folder-save-dng"
description = "Denies the folder_save_dng command without any pre-configured scope."
commands.deny = ["folder_save_dng"]
@@ -0,0 +1,11 @@
# Automatically generated - DO NOT EDIT!
[[permission]]
identifier = "allow-folder-save-jpeg"
description = "Enables the folder_save_jpeg command without any pre-configured scope."
commands.allow = ["folder_save_jpeg"]
[[permission]]
identifier = "deny-folder-save-jpeg"
description = "Denies the folder_save_jpeg command without any pre-configured scope."
commands.deny = ["folder_save_jpeg"]
@@ -0,0 +1,11 @@
# Automatically generated - DO NOT EDIT!
[[permission]]
identifier = "allow-folder-save-xmp"
description = "Enables the folder_save_xmp command without any pre-configured scope."
commands.allow = ["folder_save_xmp"]
[[permission]]
identifier = "deny-folder-save-xmp"
description = "Denies the folder_save_xmp command without any pre-configured scope."
commands.deny = ["folder_save_xmp"]
@@ -0,0 +1,11 @@
# Automatically generated - DO NOT EDIT!
[[permission]]
identifier = "allow-folder-thumb"
description = "Enables the folder_thumb command without any pre-configured scope."
commands.allow = ["folder_thumb"]
[[permission]]
identifier = "deny-folder-thumb"
description = "Denies the folder_thumb command without any pre-configured scope."
commands.deny = ["folder_thumb"]
@@ -0,0 +1,11 @@
# Automatically generated - DO NOT EDIT!
[[permission]]
identifier = "allow-local-film-thumb"
description = "Enables the local_film_thumb command without any pre-configured scope."
commands.allow = ["local_film_thumb"]
[[permission]]
identifier = "deny-local-film-thumb"
description = "Denies the local_film_thumb command without any pre-configured scope."
commands.deny = ["local_film_thumb"]
+737
View File
@@ -0,0 +1,737 @@
//! A folder dropped on the window, shown as a contact sheet.
//!
//! The page only learns the path because the operating system delivered it to this window. `folder_open` refuses
//! any other path, and a file is only read inside a folder that was opened that way. Nothing is uploaded.
//! Writes stay inside an opened folder: a merged `-fundido.dng`, or a JPEG exported from Revelar.
use std::collections::HashSet;
use std::path::{Path, PathBuf};
use std::sync::Mutex;
use serde::Serialize;
use crate::catalog::{is_photo, photos_under};
use crate::local::read_film_thumb;
#[derive(Default)]
pub struct OpenFolders {
/// Canonical paths of folders the user actually dropped on the window.
dropped: Mutex<HashSet<PathBuf>>,
/// Folders opened as a contact sheet this session. Thumbnails stay inside these.
open: Mutex<Vec<PathBuf>>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct FolderListing {
pub path: String,
pub name: String,
pub files: Vec<FolderFile>,
}
#[derive(Debug, Serialize)]
pub struct FolderFile {
pub path: String,
pub name: String,
}
impl OpenFolders {
/// Remember folders from a drop on this window. Files in the same drop are ignored.
pub fn note(&self, paths: &[PathBuf]) {
let mut dropped = self.dropped.lock().unwrap();
for path in paths {
if !path.is_dir() {
continue;
}
if let Ok(canon) = path.canonicalize() {
dropped.insert(canon);
}
}
}
/// The dropped folder, canonical, or an error when it was not dropped here or is not a folder.
pub fn open(&self, path: &Path) -> Result<PathBuf, String> {
let canon = path.canonicalize().map_err(|e| e.to_string())?;
if !canon.is_dir() {
return Err("not_a_folder".to_string());
}
if !self.dropped.lock().unwrap().contains(&canon) {
return Err("not_allowed".to_string());
}
let mut open = self.open.lock().unwrap();
if !open.iter().any(|root| root == &canon) {
open.push(canon.clone());
}
Ok(canon)
}
/// A photo inside an opened folder. A symlink that leaves the folder is refused.
pub fn allow_file(&self, path: &Path) -> Result<PathBuf, String> {
let canon = path.canonicalize().map_err(|_| "not_found".to_string())?;
if !canon.is_file() {
return Err("not_found".to_string());
}
if !is_photo(&canon) {
return Err("not_a_photo".to_string());
}
let open = self.open.lock().unwrap();
if !open.iter().any(|root| canon.starts_with(root)) {
return Err("not_allowed".to_string());
}
Ok(canon)
}
/// Where a merged DNG may be written: a single `-fundido.dng` name, inside an opened folder, never through a
/// symlink that leaves it. Replacing an earlier merge of the same name is allowed.
pub fn allow_save_dng(&self, dir: &Path, name: &str, len: usize) -> Result<PathBuf, String> {
if len == 0 || len > MAX_DNG_BYTES {
return Err("bad_file".to_string());
}
if !is_fundido_dng(name) {
return Err("not_a_merge".to_string());
}
let dir = dir.canonicalize().map_err(|e| e.to_string())?;
if !dir.is_dir() {
return Err("not_a_folder".to_string());
}
let open = self.open.lock().unwrap();
if !open.iter().any(|root| dir.starts_with(root)) {
return Err("not_allowed".to_string());
}
let dest = dir.join(name);
match std::fs::symlink_metadata(&dest) {
Ok(meta) if meta.file_type().is_symlink() || !meta.is_file() => {
return Err("not_allowed".to_string());
}
_ => {}
}
Ok(dest)
}
/// Where a developed JPEG may be written: one `.jpg` name, inside an opened folder, never through a symlink
/// that leaves it. Replacing an earlier export of the same name is allowed.
pub fn allow_save_jpeg(&self, dir: &Path, name: &str, len: usize) -> Result<PathBuf, String> {
if len == 0 || len > MAX_JPEG_BYTES {
return Err("bad_file".to_string());
}
if !is_jpeg_export(name) {
return Err("not_a_jpeg".to_string());
}
let dir = dir.canonicalize().map_err(|e| e.to_string())?;
if !dir.is_dir() {
return Err("not_a_folder".to_string());
}
let open = self.open.lock().unwrap();
if !open.iter().any(|root| dir.starts_with(root)) {
return Err("not_allowed".to_string());
}
let dest = dir.join(name);
match std::fs::symlink_metadata(&dest) {
Ok(meta) if meta.file_type().is_symlink() || !meta.is_file() => {
return Err("not_allowed".to_string());
}
_ => {}
}
Ok(dest)
}
/// An edit sidecar next to a photo in an opened folder. Same folder rules as the JPEG.
pub fn allow_save_xmp(&self, dir: &Path, name: &str, len: usize) -> Result<PathBuf, String> {
if len == 0 || len > MAX_XMP_BYTES {
return Err("bad_file".to_string());
}
if !is_xmp_sidecar(name) {
return Err("not_an_xmp".to_string());
}
let dir = dir.canonicalize().map_err(|e| e.to_string())?;
if !dir.is_dir() {
return Err("not_a_folder".to_string());
}
let open = self.open.lock().unwrap();
if !open.iter().any(|root| dir.starts_with(root)) {
return Err("not_allowed".to_string());
}
let dest = dir.join(name);
match std::fs::symlink_metadata(&dest) {
Ok(meta) if meta.file_type().is_symlink() || !meta.is_file() => {
return Err("not_allowed".to_string());
}
_ => {}
}
Ok(dest)
}
/// An existing sidecar in an opened folder, so Revelar can load the edit.
pub fn allow_xmp(&self, path: &Path) -> Result<PathBuf, String> {
let canon = path.canonicalize().map_err(|_| "not_found".to_string())?;
if !canon.is_file() {
return Err("not_found".to_string());
}
let name = canon.file_name().and_then(|n| n.to_str()).unwrap_or("");
if !is_xmp_sidecar(name) {
return Err("not_an_xmp".to_string());
}
let open = self.open.lock().unwrap();
if !open.iter().any(|root| canon.starts_with(root)) {
return Err("not_allowed".to_string());
}
Ok(canon)
}
}
/// A merged DNG is tens of megabytes. Anything larger is not this merge.
const MAX_DNG_BYTES: usize = 512 * 1024 * 1024;
fn is_fundido_dng(name: &str) -> bool {
if name.contains('/') || name.contains('\\') || name.contains('\0') || name.starts_with('.') {
return false;
}
let lower = name.to_ascii_lowercase();
lower.ends_with(".dng") && lower.contains("-fundido")
}
fn is_jpeg_export(name: &str) -> bool {
if name.contains('/') || name.contains('\\') || name.contains('\0') || name.starts_with('.') {
return false;
}
let lower = name.to_ascii_lowercase();
lower.ends_with(".jpg") || lower.ends_with(".jpeg")
}
fn is_xmp_sidecar(name: &str) -> bool {
if name.contains('/') || name.contains('\\') || name.contains('\0') || name.starts_with('.') {
return false;
}
name.to_ascii_lowercase().ends_with(".xmp")
}
/// A developed JPEG from Revelar. Larger than this is not a still from this editor.
const MAX_JPEG_BYTES: usize = 80 * 1024 * 1024;
/// An edit sidecar is a short XML packet. Anything larger is not one of these.
const MAX_XMP_BYTES: usize = 1024 * 1024;
fn percent_decode(value: &str) -> String {
let bytes = value.as_bytes();
let mut out = Vec::with_capacity(bytes.len());
let mut i = 0;
while i < bytes.len() {
if bytes[i] == b'%'
&& i + 2 < bytes.len()
&& let Ok(v) = u8::from_str_radix(&value[i + 1..i + 3], 16)
{
out.push(v);
i += 3;
continue;
}
out.push(bytes[i]);
i += 1;
}
String::from_utf8_lossy(&out).into_owned()
}
fn sort_names(paths: &mut [PathBuf]) {
paths.sort_by(|a, b| {
let an = a.file_name().map(|n| n.to_string_lossy().to_lowercase());
let bn = b.file_name().map(|n| n.to_string_lossy().to_lowercase());
an.cmp(&bn).then(a.cmp(b))
});
}
fn is_listed_file(entry: &std::fs::DirEntry) -> bool {
let Ok(kind) = entry.file_type() else {
return false;
};
// `file_type` does not follow symlinks, so a link out of the folder is not a photo of this sheet.
if !kind.is_file() {
return false;
}
let name = entry.file_name();
let name = name.to_string_lossy();
!name.starts_with('.') && !name.starts_with("._") && is_photo(&entry.path())
}
/// Photos of the folder itself. A card or a job folder that only holds subfolders lists the photos inside
/// those, the same folders a contact sheet is opened on when the top level has nothing to show.
pub fn contact_files(root: &Path) -> Vec<PathBuf> {
let mut direct = Vec::new();
if let Ok(entries) = std::fs::read_dir(root) {
for entry in entries.flatten() {
if is_listed_file(&entry) {
direct.push(entry.path());
}
}
}
if !direct.is_empty() {
sort_names(&mut direct);
return direct;
}
let mut nested = photos_under(root);
sort_names(&mut nested);
nested
}
fn listing(root: PathBuf) -> FolderListing {
let name = root
.file_name()
.map(|n| n.to_string_lossy().into_owned())
.unwrap_or_else(|| root.to_string_lossy().into_owned());
let files = contact_files(&root)
.into_iter()
.map(|path| {
let file_name = path
.file_name()
.map(|n| n.to_string_lossy().into_owned())
.unwrap_or_default();
FolderFile {
path: path.to_string_lossy().into_owned(),
name: file_name,
}
})
.collect();
FolderListing {
path: root.to_string_lossy().into_owned(),
name,
files,
}
}
/// The first dropped path that is a folder, so the page can open it instead of uploading the files inside.
#[tauri::command]
pub fn folder_drop(paths: Vec<String>) -> Option<String> {
paths
.into_iter()
.map(PathBuf::from)
.find(|path| path.is_dir())
.map(|path| path.to_string_lossy().into_owned())
}
/// The contact sheet of a folder the user dropped on this window.
#[tauri::command]
pub fn folder_open(
folders: tauri::State<'_, OpenFolders>,
path: String,
) -> Result<FolderListing, String> {
let root = folders.open(Path::new(&path))?;
Ok(listing(root))
}
/// A JPEG of one photo on the open sheet. `edge` is the long side (the grid asks for 480, the loupe for more).
#[tauri::command]
pub async fn folder_thumb(
folders: tauri::State<'_, OpenFolders>,
path: String,
edge: u32,
) -> Result<tauri::ipc::Response, String> {
let file = folders.allow_file(Path::new(&path))?;
let edge = edge.clamp(32, 1600);
let jpeg = read_film_thumb(file, edge).await?;
Ok(tauri::ipc::Response::new(jpeg))
}
/// The original of one photo on the open sheet, so a merge can read the exposures.
#[tauri::command]
pub async fn folder_read(
folders: tauri::State<'_, OpenFolders>,
path: String,
) -> Result<tauri::ipc::Response, String> {
let file = if path.to_ascii_lowercase().ends_with(".xmp") {
folders.allow_xmp(Path::new(&path))?
} else {
folders.allow_file(Path::new(&path))?
};
let bytes = tokio::fs::read(&file).await.map_err(|e| e.to_string())?;
if path.to_ascii_lowercase().ends_with(".xmp") && bytes.len() > MAX_XMP_BYTES {
return Err("bad_file".to_string());
}
Ok(tauri::ipc::Response::new(bytes))
}
/// Capture metadata of one photo on the open sheet. The bytes stay in this process.
#[tauri::command]
pub async fn folder_meta(
folders: tauri::State<'_, OpenFolders>,
path: String,
) -> Result<String, String> {
let file = folders.allow_file(Path::new(&path))?;
tokio::task::spawn_blocking(move || {
let bytes = std::fs::read(&file).map_err(|e| e.to_string())?;
Ok(photoreport_engine::capture::read_capture(&bytes).to_string())
})
.await
.map_err(|e| e.to_string())?
}
/// The files of one stack, in merge order, and where the DNG is written (beside the middle frame).
pub fn merge_plan(
folders: &OpenFolders,
paths: &[String],
) -> Result<(Vec<PathBuf>, PathBuf), String> {
if paths.len() < 2 {
return Err("none".to_string());
}
let mut files = Vec::with_capacity(paths.len());
for path in paths {
files.push(folders.allow_file(Path::new(path))?);
}
let mid = &files[(files.len() - 1) / 2];
let dir = mid.parent().ok_or_else(|| "failed".to_string())?;
let stem = mid
.file_stem()
.and_then(|s| s.to_str())
.ok_or_else(|| "failed".to_string())?;
let dest = folders.allow_save_dng(dir, &format!("{stem}-fundido.dng"), 1)?;
Ok((files, dest))
}
fn merge_files_to(files: &[PathBuf], dest: &Path, max_edge: u32) -> Result<(), String> {
let mut bufs = Vec::with_capacity(files.len());
for file in files {
bufs.push(std::fs::read(file).map_err(|e| e.to_string())?);
}
let refs: Vec<&[u8]> = bufs.iter().map(Vec::as_slice).collect();
let dng =
photoreport_engine::merge::merge_linear_dng(&refs, max_edge).map_err(|e| e.to_string())?;
if dng.is_empty() || dng.len() > MAX_DNG_BYTES {
return Err("bad_file".to_string());
}
std::fs::write(dest, dng).map_err(|e| e.to_string())
}
/// Merges one stack and writes the DNG beside the middle frame. The raws are not sent to the page.
#[tauri::command]
pub async fn folder_merge_dng(
folders: tauri::State<'_, OpenFolders>,
paths: Vec<String>,
max_edge: u32,
) -> Result<String, String> {
let (files, dest) = merge_plan(&folders, &paths)?;
tokio::task::spawn_blocking(move || {
merge_files_to(&files, &dest, max_edge)?;
Ok(dest.to_string_lossy().into_owned())
})
.await
.map_err(|e| e.to_string())?
}
/// Writes one merged DNG into an opened folder. The bytes are the request body; `dir` and `name` are
/// percent-encoded headers, so the DNG is not sent as a JSON array.
#[tauri::command]
pub async fn folder_save_dng(
request: tauri::ipc::Request<'_>,
folders: tauri::State<'_, OpenFolders>,
) -> Result<String, String> {
let header = |name: &str| {
request
.headers()
.get(name)
.and_then(|v| v.to_str().ok())
.map(percent_decode)
.ok_or_else(|| format!("missing {name}"))
};
let dir = header("dir")?;
let name = header("name")?;
let tauri::ipc::InvokeBody::Raw(data) = request.body() else {
return Err("expected the file as the body".to_string());
};
// Copy before the write: the request does not live across the await.
let bytes = data.to_vec();
let path = folders.allow_save_dng(Path::new(&dir), &name, bytes.len())?;
tokio::fs::write(&path, &bytes)
.await
.map_err(|e| e.to_string())?;
Ok(path.to_string_lossy().into_owned())
}
/// Writes one developed JPEG into an opened folder. The bytes are the request body; `dir` and `name` are
/// percent-encoded headers.
#[tauri::command]
pub async fn folder_save_jpeg(
request: tauri::ipc::Request<'_>,
folders: tauri::State<'_, OpenFolders>,
) -> Result<String, String> {
let header = |name: &str| {
request
.headers()
.get(name)
.and_then(|v| v.to_str().ok())
.map(percent_decode)
.ok_or_else(|| format!("missing {name}"))
};
let dir = header("dir")?;
let name = header("name")?;
let tauri::ipc::InvokeBody::Raw(data) = request.body() else {
return Err("expected the file as the body".to_string());
};
let bytes = data.to_vec();
let path = folders.allow_save_jpeg(Path::new(&dir), &name, bytes.len())?;
tokio::fs::write(&path, &bytes)
.await
.map_err(|e| e.to_string())?;
Ok(path.to_string_lossy().into_owned())
}
/// Writes the edit sidecar beside the DNG. The bytes are the request body; `dir` and `name` are percent-encoded headers.
#[tauri::command]
pub async fn folder_save_xmp(
request: tauri::ipc::Request<'_>,
folders: tauri::State<'_, OpenFolders>,
) -> Result<String, String> {
let header = |name: &str| {
request
.headers()
.get(name)
.and_then(|v| v.to_str().ok())
.map(percent_decode)
.ok_or_else(|| format!("missing {name}"))
};
let dir = header("dir")?;
let name = header("name")?;
let tauri::ipc::InvokeBody::Raw(data) = request.body() else {
return Err("expected the file as the body".to_string());
};
let bytes = data.to_vec();
let path = folders.allow_save_xmp(Path::new(&dir), &name, bytes.len())?;
tokio::fs::write(&path, &bytes)
.await
.map_err(|e| e.to_string())?;
Ok(path.to_string_lossy().into_owned())
}
#[cfg(test)]
mod tests {
use super::*;
fn temp_dir(name: &str) -> PathBuf {
let dir = std::env::temp_dir().join(format!("pr-sheet-{name}-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
dir
}
#[test]
fn a_folder_lists_its_own_photos_and_an_empty_one_lists_what_is_inside() {
let root = temp_dir("flat");
std::fs::write(root.join("b.JPG"), b"b").unwrap();
std::fs::write(root.join("a.jpg"), b"a").unwrap();
std::fs::write(root.join("notes.txt"), b"no").unwrap();
std::fs::create_dir_all(root.join("sub")).unwrap();
std::fs::write(root.join("sub").join("nested.CR3"), b"raw").unwrap();
let names: Vec<_> = contact_files(&root)
.iter()
.map(|p| p.file_name().unwrap().to_string_lossy().into_owned())
.collect();
assert_eq!(names, vec!["a.jpg".to_string(), "b.JPG".to_string()]);
let card = temp_dir("card");
std::fs::create_dir_all(card.join("DCIM").join("100CANON")).unwrap();
std::fs::write(
card.join("DCIM").join("100CANON").join("IMG_0001.CR3"),
b"raw",
)
.unwrap();
let nested = contact_files(&card);
assert_eq!(nested.len(), 1);
assert_eq!(
nested[0].file_name().unwrap().to_string_lossy(),
"IMG_0001.CR3"
);
let _ = std::fs::remove_dir_all(&root);
let _ = std::fs::remove_dir_all(&card);
}
#[test]
fn only_a_dropped_folder_can_be_opened_and_only_its_photos_read() {
let root = temp_dir("open");
let photo = root.join("frame.jpg");
std::fs::write(&photo, b"jpeg").unwrap();
let other = temp_dir("other");
let outside = other.join("secret.jpg");
std::fs::write(&outside, b"jpeg").unwrap();
let folders = OpenFolders::default();
assert_eq!(folders.open(&root).unwrap_err(), "not_allowed");
folders.note(&[root.clone(), outside.clone()]);
let opened = folders.open(&root).unwrap();
assert_eq!(opened, root.canonicalize().unwrap());
assert!(folders.allow_file(&photo).is_ok());
assert_eq!(folders.allow_file(&outside).unwrap_err(), "not_allowed");
assert_eq!(
folders.allow_file(&root.join("missing.jpg")).unwrap_err(),
"not_found"
);
#[cfg(unix)]
{
let link = root.join("escape.jpg");
std::os::unix::fs::symlink(&outside, &link).unwrap();
assert!(contact_files(&root).iter().all(|p| p != &link));
assert_eq!(folders.allow_file(&link).unwrap_err(), "not_allowed");
}
let _ = std::fs::remove_dir_all(&root);
let _ = std::fs::remove_dir_all(&other);
}
#[test]
fn a_dropped_jpeg_becomes_a_contact_sheet_thumbnail() {
let root = temp_dir("thumb");
let photo = root.join("frame.jpg");
let rgb = image::RgbImage::from_fn(800, 200, |x, y| {
image::Rgb([(x % 256) as u8, (y % 256) as u8, 40])
});
let mut bytes = Vec::new();
image::codecs::jpeg::JpegEncoder::new_with_quality(&mut bytes, 80)
.encode_image(&rgb)
.unwrap();
std::fs::write(&photo, &bytes).unwrap();
let folders = OpenFolders::default();
folders.note(&[root.clone()]);
folders.open(&root).unwrap();
let file = folders.allow_file(&photo).unwrap();
let thumb =
photoreport_engine::film_thumb_sized(&std::fs::read(&file).unwrap(), 480).unwrap();
assert!(thumb.starts_with(&[0xFF, 0xD8]));
assert!(thumb.len() < bytes.len());
let _ = std::fs::remove_dir_all(&root);
}
#[test]
fn a_merge_is_only_a_fundido_dng_inside_the_open_folder() {
let root = temp_dir("save");
let nested = root.join("sala");
std::fs::create_dir_all(&nested).unwrap();
let other = temp_dir("save-other");
let folders = OpenFolders::default();
folders.note(&[root.clone()]);
folders.open(&root).unwrap();
let saved = folders
.allow_save_dng(&nested, "IMG_0002-fundido.dng", 4)
.unwrap();
assert_eq!(
saved,
nested.canonicalize().unwrap().join("IMG_0002-fundido.dng")
);
assert_eq!(
folders
.allow_save_dng(&other, "IMG_0002-fundido.dng", 4)
.unwrap_err(),
"not_allowed"
);
assert_eq!(
folders
.allow_save_dng(&nested, "../IMG_0002-fundido.dng", 4)
.unwrap_err(),
"not_a_merge"
);
assert_eq!(
folders
.allow_save_dng(&nested, "IMG_0002.dng", 4)
.unwrap_err(),
"not_a_merge"
);
assert_eq!(
folders
.allow_save_dng(&nested, "IMG_0002-fundido.dng", 0)
.unwrap_err(),
"bad_file"
);
#[cfg(unix)]
{
let link = nested.join("IMG_0002-fundido.dng");
let outside = other.join("secret.dng");
std::fs::write(&outside, b"x").unwrap();
std::os::unix::fs::symlink(&outside, &link).unwrap();
assert_eq!(
folders
.allow_save_dng(&nested, "IMG_0002-fundido.dng", 4)
.unwrap_err(),
"not_allowed"
);
}
let _ = std::fs::remove_dir_all(&root);
let _ = std::fs::remove_dir_all(&other);
}
#[test]
fn a_jpeg_export_stays_inside_the_open_folder() {
let root = temp_dir("jpeg");
let nested = root.join("sala");
std::fs::create_dir_all(&nested).unwrap();
let other = temp_dir("jpeg-other");
let folders = OpenFolders::default();
folders.note(&[root.clone()]);
folders.open(&root).unwrap();
let saved = folders.allow_save_jpeg(&nested, "IMG_0002.jpg", 4).unwrap();
assert_eq!(saved, nested.canonicalize().unwrap().join("IMG_0002.jpg"));
assert_eq!(
folders
.allow_save_jpeg(&other, "IMG_0002.jpg", 4)
.unwrap_err(),
"not_allowed"
);
assert_eq!(
folders
.allow_save_jpeg(&nested, "../IMG_0002.jpg", 4)
.unwrap_err(),
"not_a_jpeg"
);
assert_eq!(
folders
.allow_save_jpeg(&nested, "IMG_0002.dng", 4)
.unwrap_err(),
"not_a_jpeg"
);
assert_eq!(
folders
.allow_save_jpeg(&nested, "IMG_0002.jpg", 0)
.unwrap_err(),
"bad_file"
);
let xmp = folders.allow_save_xmp(&nested, "IMG_0002.xmp", 20).unwrap();
assert_eq!(xmp, nested.canonicalize().unwrap().join("IMG_0002.xmp"));
assert_eq!(
folders
.allow_save_xmp(&nested, "../IMG_0002.xmp", 20)
.unwrap_err(),
"not_an_xmp"
);
assert_eq!(
folders
.allow_save_xmp(&other, "IMG_0002.xmp", 20)
.unwrap_err(),
"not_allowed"
);
let _ = std::fs::remove_dir_all(&root);
let _ = std::fs::remove_dir_all(&other);
}
#[test]
fn a_stack_is_named_after_its_middle_frame() {
let root = temp_dir("plan");
let names = ["dark.jpg", "mid.jpg", "bright.jpg"];
for name in names {
std::fs::write(root.join(name), b"jpeg").unwrap();
}
let folders = OpenFolders::default();
folders.note(&[root.clone()]);
folders.open(&root).unwrap();
let paths: Vec<String> = names
.iter()
.map(|name| root.join(name).to_string_lossy().into_owned())
.collect();
let (files, dest) = merge_plan(&folders, &paths).unwrap();
assert_eq!(files.len(), 3);
assert_eq!(
dest.file_name().unwrap().to_string_lossy(),
"mid-fundido.dng"
);
assert_eq!(merge_plan(&folders, &paths[..1]).unwrap_err(), "none");
let _ = std::fs::remove_dir_all(&root);
}
}
+392
View File
@@ -0,0 +1,392 @@
//! USB tether (macOS). A Canon (or any PTP body) does not show up as a disk; ImageCaptureCore
//! (`camera_mac.m`) lists the card and each new shot. Nothing is copied until the photographer
//! picks files (`camera_import`). Chosen files land in `<ingest>/.usb` and the web app polls
//! `camera_take` to file them like a local-FTP photo. The dot folder is skipped by the FTP scan.
use std::path::Path;
use std::sync::{Mutex, OnceLock};
use serde::{Deserialize, Serialize};
use crate::ftp::{FtpState, IncomingFile};
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CameraDevice {
pub id: String,
pub name: String,
pub vendor_id: i32,
pub product_id: i32,
/// "opening", "tethered", "busy" (another app holds the PTP session) or "idle".
pub state: String,
pub error: Option<String>,
/// "synced" after the body clock is set to this Mac, "unsupported" when it refuses.
#[serde(default)]
pub clock: Option<String>,
/// Seconds the camera was ahead of the Mac before the sync. Positive means the camera was fast.
#[serde(default)]
pub clock_offset: Option<f64>,
/// True once the card listing is complete (and keeps updating as new shots appear).
#[serde(default)]
pub catalog_ready: bool,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CameraFile {
pub name: String,
pub size: u64,
#[serde(default)]
pub created_ms: Option<i64>,
/// True when the file appeared after this session opened (a tethered shot).
#[serde(default)]
pub is_new: bool,
/// Already pulled into the ingest folder in this session.
#[serde(default)]
pub imported: bool,
}
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CameraStatus {
/// False on systems without ImageCaptureCore (the button stays hidden).
pub supported: bool,
pub tether: bool,
pub devices: Vec<CameraDevice>,
pub files: Vec<CameraFile>,
}
#[derive(Debug, Deserialize)]
#[serde(tag = "kind")]
enum CameraEvent {
#[serde(rename = "devices")]
Devices { devices: Vec<CameraDevice> },
#[serde(rename = "catalog")]
Catalog {
#[serde(rename = "cameraId")]
#[allow(dead_code)]
camera_id: String,
files: Vec<CameraFile>,
},
#[serde(rename = "file")]
File { path: String, name: String, size: u64 },
}
struct Inner {
devices: Vec<CameraDevice>,
files: Vec<CameraFile>,
pending: Vec<IncomingFile>,
tether: bool,
dir: String,
}
pub struct CameraState {
inner: Mutex<Inner>,
}
impl Default for CameraState {
fn default() -> Self {
Self {
inner: Mutex::new(Inner {
devices: Vec::new(),
files: Vec::new(),
pending: Vec::new(),
tether: true,
dir: String::new(),
}),
}
}
}
fn queue() -> &'static Mutex<Vec<String>> {
static Q: OnceLock<Mutex<Vec<String>>> = OnceLock::new();
Q.get_or_init(|| Mutex::new(Vec::new()))
}
impl CameraState {
fn drain(&self) {
let pending = match queue().lock() {
Ok(mut q) => std::mem::take(&mut *q),
Err(_) => return,
};
let Ok(mut inner) = self.inner.lock() else {
return;
};
for line in pending {
apply_event(&mut inner, &line);
}
}
/// `<ingest>/.usb`, created if needed. Hidden so the FTP folder scan leaves these files alone.
pub fn sync_dir(&self, ingest: &Path) {
let dir = ingest.join(".usb");
let _ = std::fs::create_dir_all(&dir);
let text = dir.to_string_lossy().into_owned();
let changed = self
.inner
.lock()
.map(|mut i| {
let changed = i.dir != text;
i.dir = text.clone();
changed
})
.unwrap_or(false);
if changed {
set_download_dir(&text);
}
}
pub fn status(&self) -> CameraStatus {
self.drain();
let inner = self.inner.lock().ok();
CameraStatus {
supported: supported(),
tether: inner.as_ref().is_none_or(|i| i.tether),
devices: inner.as_ref().map(|i| i.devices.clone()).unwrap_or_default(),
files: inner.map(|i| i.files.clone()).unwrap_or_default(),
}
}
pub fn take(&self) -> Vec<IncomingFile> {
self.drain();
self.inner
.lock()
.map(|mut i| std::mem::take(&mut i.pending))
.unwrap_or_default()
}
pub fn set_tether(&self, on: bool) {
if let Ok(mut inner) = self.inner.lock() {
inner.tether = on;
if !on {
inner.files.clear();
}
}
set_tether_native(on);
}
pub fn import(&self, names: &[String]) {
if names.is_empty() {
return;
}
let Ok(json) = serde_json::to_string(names) else {
return;
};
import_native(&json);
}
}
fn apply_event(inner: &mut Inner, line: &str) {
let Ok(event) = serde_json::from_str::<CameraEvent>(line) else {
return;
};
match event {
CameraEvent::Devices { devices } => inner.devices = devices,
CameraEvent::Catalog { camera_id: _, files } => inner.files = files,
CameraEvent::File { path, name, size } => {
if size > 0 && (crate::ftp::is_jpeg_name(&name) || crate::ftp::is_raw_name(&name)) {
inner.pending.push(IncomingFile::at(path, name, size));
}
}
}
}
#[cfg(target_os = "macos")]
fn supported() -> bool {
true
}
#[cfg(not(target_os = "macos"))]
fn supported() -> bool {
false
}
#[cfg(target_os = "macos")]
unsafe extern "C" fn on_camera_json(json: *const std::ffi::c_char) {
use std::ffi::CStr;
if json.is_null() {
return;
}
let Ok(text) = unsafe { CStr::from_ptr(json) }.to_str() else {
return;
};
if let Ok(mut q) = queue().lock() {
q.push(text.to_string());
}
}
#[cfg(target_os = "macos")]
unsafe extern "C" {
fn pr_camera_start(cb: unsafe extern "C" fn(*const std::ffi::c_char));
fn pr_camera_set_dir(dir: *const std::ffi::c_char);
fn pr_camera_set_tether(on: i32);
fn pr_camera_sync();
fn pr_camera_import(names_json: *const std::ffi::c_char);
fn pr_camera_refresh_catalog();
}
#[cfg(target_os = "macos")]
fn set_download_dir(dir: &str) {
let Ok(c) = std::ffi::CString::new(dir) else {
return;
};
unsafe { pr_camera_set_dir(c.as_ptr()) }
}
#[cfg(not(target_os = "macos"))]
fn set_download_dir(_dir: &str) {}
#[cfg(target_os = "macos")]
fn set_tether_native(on: bool) {
unsafe { pr_camera_set_tether(i32::from(on)) }
}
#[cfg(not(target_os = "macos"))]
fn set_tether_native(_on: bool) {}
#[cfg(target_os = "macos")]
fn sync_native() {
unsafe { pr_camera_sync() }
}
#[cfg(not(target_os = "macos"))]
fn sync_native() {}
#[cfg(target_os = "macos")]
fn import_native(names_json: &str) {
let Ok(c) = std::ffi::CString::new(names_json) else {
return;
};
unsafe { pr_camera_import(c.as_ptr()) }
}
#[cfg(not(target_os = "macos"))]
fn import_native(_names_json: &str) {}
#[cfg(target_os = "macos")]
fn refresh_catalog_native() {
unsafe { pr_camera_refresh_catalog() }
}
#[cfg(not(target_os = "macos"))]
fn refresh_catalog_native() {}
/// Starts the browser once. Safe to call at launch; callbacks only enqueue a string.
pub fn start(ftp: &FtpState) {
#[cfg(target_os = "macos")]
{
static STARTED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
if STARTED.swap(true, std::sync::atomic::Ordering::SeqCst) {
return;
}
unsafe { pr_camera_start(on_camera_json) }
}
let dir = ftp.ingest_dir();
let _ = std::fs::create_dir_all(dir.join(".usb"));
set_download_dir(&dir.join(".usb").to_string_lossy());
}
#[tauri::command]
pub fn camera_status(cam: tauri::State<'_, CameraState>, ftp: tauri::State<'_, FtpState>) -> CameraStatus {
cam.sync_dir(&ftp.ingest_dir());
cam.status()
}
#[tauri::command]
pub fn camera_take(cam: tauri::State<'_, CameraState>) -> Vec<IncomingFile> {
cam.take()
}
#[tauri::command]
pub fn camera_tether(cam: tauri::State<'_, CameraState>, enabled: bool) -> CameraStatus {
cam.set_tether(enabled);
cam.status()
}
/// Sets the open camera's clock to this computer's clock.
#[tauri::command]
pub fn camera_sync(cam: tauri::State<'_, CameraState>) -> CameraStatus {
sync_native();
cam.status()
}
/// Downloads the named files from the open camera into the ingest folder (JPEG + RAW sidecars if listed).
#[tauri::command]
pub fn camera_import(cam: tauri::State<'_, CameraState>, names: Vec<String>) -> CameraStatus {
cam.import(&names);
cam.status()
}
/// Re-reads the card listing (after a big burst the list can lag).
#[tauri::command]
pub fn camera_refresh(cam: tauri::State<'_, CameraState>) -> CameraStatus {
refresh_catalog_native();
cam.status()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_chosen_shot_queues_the_jpeg_and_the_raw() {
let mut inner = Inner {
devices: Vec::new(),
files: Vec::new(),
pending: Vec::new(),
tether: true,
dir: String::new(),
};
apply_event(
&mut inner,
r#"{"kind":"devices","devices":[{"id":"abc","name":"Canon Digital Camera","vendorId":1193,"productId":13075,"state":"tethered","error":null,"catalogReady":true}]}"#,
);
apply_event(
&mut inner,
r#"{"kind":"catalog","cameraId":"abc","files":[{"name":"IMG_0001.JPG","size":10,"isNew":true,"imported":false},{"name":"IMG_0001.CR3","size":20,"isNew":true,"imported":false}]}"#,
);
apply_event(
&mut inner,
r#"{"kind":"file","path":"/ingest/.usb/IMG_0001.JPG","name":"IMG_0001.JPG","size":10}"#,
);
apply_event(
&mut inner,
r#"{"kind":"file","path":"/ingest/.usb/IMG_0001.CR3","name":"IMG_0001.CR3","size":20}"#,
);
assert_eq!(inner.devices.len(), 1);
assert!(inner.devices[0].catalog_ready);
assert_eq!(inner.files.len(), 2);
assert_eq!(inner.pending.len(), 2);
}
#[test]
fn an_unplugged_camera_clears_the_list() {
let mut inner = Inner {
devices: vec![CameraDevice {
id: "abc".into(),
name: "Canon".into(),
vendor_id: 1193,
product_id: 1,
state: "tethered".into(),
error: None,
clock: None,
clock_offset: None,
catalog_ready: true,
}],
files: vec![CameraFile {
name: "a.jpg".into(),
size: 1,
created_ms: None,
is_new: false,
imported: false,
}],
pending: Vec::new(),
tether: true,
dir: String::new(),
};
apply_event(&mut inner, r#"{"kind":"devices","devices":[]}"#);
apply_event(&mut inner, r#"{"kind":"catalog","cameraId":"abc","files":[]}"#);
assert!(inner.devices.is_empty());
assert!(inner.files.is_empty());
}
}
+568
View File
@@ -0,0 +1,568 @@
// USB still cameras speak PTP, so macOS never mounts them as a disk. Image Capture (and this file)
// talks to them through ImageCaptureCore: open a session, list what is on the card (and each new
// shot as it appears), and download only the files the photographer picks. Nothing is copied on its
// own — that is deliberate: a full card would flood the ingest folder.
// One process can hold the PTP session; if EOS Utility has it, opening fails and we try again.
#import <Foundation/Foundation.h>
#import <IOKit/IOKitLib.h>
#import <ImageCaptureCore/ImageCaptureCore.h>
typedef void (*pr_camera_cb)(const char *json);
static pr_camera_cb g_callback = NULL;
static NSString *g_dir = nil;
static BOOL g_tether = YES;
static void emit(NSDictionary *obj) {
if (!g_callback || !obj) return;
NSData *data = [NSJSONSerialization dataWithJSONObject:obj options:0 error:nil];
if (!data) return;
NSString *s = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
if (s) g_callback(s.UTF8String);
}
static BOOL is_still(ICCameraItem *item) {
if (![item isKindOfClass:[ICCameraFile class]]) return NO;
NSString *ext = item.name.pathExtension.lowercaseString ?: @"";
NSSet *exts = [NSSet setWithArray:@[
@"jpg", @"jpeg", @"cr2", @"cr3", @"nef", @"arw", @"raf", @"rw2", @"dng", @"orf", @"pef", @"srw", @"heic", @"hif"
]];
if ([exts containsObject:ext]) return YES;
NSString *uti = item.UTI.lowercaseString ?: @"";
if ([uti containsString:@"movie"] || [uti containsString:@"video"] || [uti containsString:@"audio"]) return NO;
return [uti containsString:@"image"] || [uti containsString:@"raw"];
}
@interface PRCam : NSObject
@property (retain) ICCameraDevice *device;
@property (copy) NSString *uuid;
@property (copy) NSString *name;
@property (assign) int vendor;
@property (assign) int product;
@property (copy) NSString *state; // opening | tethered | busy | idle
@property (copy) NSString *errorText;
@property (assign) BOOL catalogReady;
@property (assign) BOOL openRequested;
@property (retain) NSMutableSet<NSString *> *fetched;
@property (retain) NSMutableSet<NSString *> *seenAtConnect;
@property (retain) NSMutableDictionary<NSString *, ICCameraFile *> *filesByName;
/// synced | unsupported. Nil until the session is ready.
@property (copy) NSString *clock;
@property (assign) double clockOffset;
@property (assign) BOOL clockOffsetKnown;
@property (assign) BOOL clockDone;
@end
@implementation PRCam
@end
@interface PRCameraHub : NSObject <ICDeviceBrowserDelegate, ICCameraDeviceDelegate, ICCameraDeviceDownloadDelegate>
@property (retain) ICDeviceBrowser *browser;
@property (retain) NSMutableDictionary<NSString *, PRCam *> *cams;
@property (copy) NSString *dir;
@property (assign) BOOL tether;
@property (assign) BOOL retryScheduled;
@property (retain) NSArray<NSDictionary *> *locked;
@end
@implementation PRCameraHub
- (void)start {
self.cams = [NSMutableDictionary dictionary];
self.tether = g_tether;
self.dir = g_dir;
self.locked = @[];
self.browser = [ICDeviceBrowser new];
self.browser.delegate = self;
self.browser.browsedDeviceTypeMask = (ICDeviceTypeMask)(ICDeviceTypeMaskCamera | ICDeviceLocationTypeLocal);
[self.browser start];
// EOS Utility takes exclusive USB ownership, and then Image Capture lists nothing. Poll the
// registry so the camera still shows up as busy until that app lets go.
[NSTimer scheduledTimerWithTimeInterval:2 target:self selector:@selector(refreshLocked) userInfo:nil repeats:YES];
[self refreshLocked];
}
- (void)refreshLocked {
[self scanLocked];
[self publish];
}
- (void)scanLocked {
NSMutableArray *found = [NSMutableArray array];
io_iterator_t iter = 0;
kern_return_t kr = IOServiceGetMatchingServices(kIOMainPortDefault, IOServiceMatching("IOUSBHostDevice"), &iter);
if (kr != KERN_SUCCESS) {
self.locked = @[];
return;
}
io_object_t dev;
while ((dev = IOIteratorNext(iter))) {
NSString *name = CFBridgingRelease(IORegistryEntryCreateCFProperty(dev, CFSTR("USB Product Name"), kCFAllocatorDefault, 0));
NSNumber *vendor = CFBridgingRelease(IORegistryEntryCreateCFProperty(dev, CFSTR("idVendor"), kCFAllocatorDefault, 0));
NSNumber *product = CFBridgingRelease(IORegistryEntryCreateCFProperty(dev, CFSTR("idProduct"), kCFAllocatorDefault, 0));
NSString *owner = CFBridgingRelease(IORegistryEntryCreateCFProperty(dev, CFSTR("UsbExclusiveOwner"), kCFAllocatorDefault, 0));
BOOL camera = [name.lowercaseString containsString:@"camera"];
BOOL known = NO;
for (PRCam *cam in self.cams.allValues) {
if (cam.vendor == vendor.intValue && cam.product == product.intValue) known = YES;
}
if (camera && !known) {
NSString *who = owner;
NSRange comma = [who rangeOfString:@", "];
if (comma.location != NSNotFound) who = [who substringFromIndex:comma.location + 2];
[found addObject:@{
@"id": [NSString stringWithFormat:@"usb-%d-%d", vendor.intValue, product.intValue],
@"name": name ?: @"Câmara",
@"vendorId": vendor ?: @0,
@"productId": product ?: @0,
@"state": who.length ? @"busy" : @"opening",
@"error": who.length ? who : [NSNull null],
@"catalogReady": @NO,
}];
}
IOObjectRelease(dev);
}
IOObjectRelease(iter);
self.locked = found;
}
- (BOOL)accepts:(ICDevice *)device {
if (![device isKindOfClass:[ICCameraDevice class]]) return NO;
if (device.transportType && ![device.transportType isEqualToString:ICTransportTypeUSB]) return NO;
NSString *kind = device.productKind.lowercaseString ?: @"";
if ([kind isEqualToString:@"iphone"] || [kind isEqualToString:@"ipad"] || [kind isEqualToString:@"ipod"]) return NO;
return YES;
}
- (PRCam *)camFor:(ICDevice *)device {
NSString *uuid = device.UUIDString ?: device.name ?: @"camera";
PRCam *cam = self.cams[uuid];
if (!cam) {
cam = [PRCam new];
cam.uuid = uuid;
cam.fetched = [NSMutableSet set];
cam.seenAtConnect = [NSMutableSet set];
cam.filesByName = [NSMutableDictionary dictionary];
cam.clockDone = NO;
cam.openRequested = NO;
self.cams[uuid] = cam;
}
cam.device = (ICCameraDevice *)device;
cam.name = device.name ?: @"Câmara";
cam.vendor = device.usbVendorID;
cam.product = device.usbProductID;
return cam;
}
- (void)publish {
NSMutableArray *list = [NSMutableArray array];
for (NSString *key in self.cams) {
PRCam *cam = self.cams[key];
[list addObject:@{
@"id": cam.uuid ?: @"",
@"name": cam.name ?: @"Câmara",
@"vendorId": @(cam.vendor),
@"productId": @(cam.product),
@"state": cam.state ?: @"opening",
@"error": cam.errorText ?: [NSNull null],
@"clock": cam.clock ?: [NSNull null],
@"clockOffset": cam.clockOffsetKnown ? @(cam.clockOffset) : [NSNull null],
@"catalogReady": @(cam.catalogReady),
}];
}
if (self.locked) [list addObjectsFromArray:self.locked];
emit(@{@"kind": @"devices", @"devices": list});
}
- (void)publishCatalog:(PRCam *)cam {
NSMutableArray *files = [NSMutableArray array];
for (NSString *name in cam.filesByName) {
ICCameraFile *file = cam.filesByName[name];
BOOL isNew = ![cam.seenAtConnect containsObject:name];
NSDate *created = file.creationDate;
[files addObject:@{
@"name": name,
@"size": @(file.fileSize),
@"createdMs": created ? @((long long)(created.timeIntervalSince1970 * 1000.0)) : [NSNull null],
@"isNew": @(isNew),
@"imported": @([cam.fetched containsObject:name]),
}];
}
[files sortUsingComparator:^NSComparisonResult(NSDictionary *a, NSDictionary *b) {
NSNumber *ca = a[@"createdMs"];
NSNumber *cb = b[@"createdMs"];
if ([ca isKindOfClass:[NSNumber class]] && [cb isKindOfClass:[NSNumber class]] && ![ca isEqual:[NSNull null]] && ![cb isEqual:[NSNull null]]) {
NSComparisonResult byDate = [cb compare:ca];
if (byDate != NSOrderedSame) return byDate;
}
return [((NSString *)a[@"name"]) compare:b[@"name"]];
}];
emit(@{@"kind": @"catalog", @"cameraId": cam.uuid ?: @"", @"files": files});
}
- (void)indexItem:(ICCameraItem *)item cam:(PRCam *)cam {
if (!is_still(item) || !item.name) return;
cam.filesByName[item.name] = (ICCameraFile *)item;
}
- (void)rebuildCatalog:(PRCam *)cam {
[cam.filesByName removeAllObjects];
for (ICCameraItem *item in cam.device.mediaFiles) [self indexItem:item cam:cam];
[self publishCatalog:cam];
}
- (void)syncClock:(PRCam *)cam {
if (cam.clockDone || !cam.device.hasOpenSession) return;
if (cam.device.capabilities.count == 0) return;
cam.clockDone = YES;
if (![cam.device.capabilities containsObject:ICCameraDeviceCanSyncClock]) {
cam.clock = @"unsupported";
cam.clockOffsetKnown = NO;
[self publish];
return;
}
cam.clockOffset = cam.device.timeOffset;
cam.clockOffsetKnown = YES;
[cam.device requestSyncClock];
cam.clock = @"synced";
[self publish];
}
/// Apple: do not send requests until deviceDidBecomeReady. Opening earlier hangs some Canon bodies.
- (void)requestOpenIfReady:(PRCam *)cam {
if (!self.tether) {
cam.state = @"idle";
cam.errorText = nil;
[self publish];
return;
}
if (cam.device.hasOpenSession) {
cam.state = @"tethered";
cam.errorText = nil;
[self publish];
return;
}
if (cam.openRequested) return;
cam.openRequested = YES;
cam.state = @"opening";
cam.errorText = nil;
cam.device.delegate = self;
[cam.device requestOpenSession];
[self publish];
}
- (void)scheduleRetry {
if (self.retryScheduled || !self.tether) return;
self.retryScheduled = YES;
__weak PRCameraHub *weak = self;
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(4 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
PRCameraHub *hub = weak;
if (!hub) return;
hub.retryScheduled = NO;
if (!hub.tether) return;
for (NSString *key in hub.cams.allKeys) {
PRCam *cam = hub.cams[key];
if ([cam.state isEqualToString:@"busy"] || [cam.state isEqualToString:@"opening"]) {
cam.openRequested = NO;
[hub requestOpenIfReady:cam];
}
}
});
}
- (NSString *)uniqueName:(NSString *)original {
NSString *base = original.lastPathComponent ?: @"photo.JPG";
NSString *stem = base.stringByDeletingPathExtension;
NSString *ext = base.pathExtension;
NSString *candidate = base;
NSFileManager *fm = [NSFileManager defaultManager];
for (int n = 1; n < 1000; n++) {
if (![fm fileExistsAtPath:[self.dir stringByAppendingPathComponent:candidate]]) return candidate;
candidate = ext.length
? [NSString stringWithFormat:@"%@-%d.%@", stem, n, ext]
: [NSString stringWithFormat:@"%@-%d", stem, n];
}
return candidate;
}
- (void)download:(ICCameraFile *)file cam:(PRCam *)cam {
if (self.dir.length == 0 || !file.name) return;
if ([cam.fetched containsObject:file.name]) return;
NSFileManager *fm = [NSFileManager defaultManager];
[fm createDirectoryAtPath:self.dir withIntermediateDirectories:YES attributes:nil error:nil];
NSString *save = [self uniqueName:file.name];
NSURL *url = [NSURL fileURLWithPath:self.dir isDirectory:YES];
if (!url) return;
[cam.fetched addObject:file.name];
NSDictionary *options = @{
ICDownloadsDirectoryURL: url,
ICSaveAsFilename: save,
ICOverwrite: @NO,
ICDeleteAfterSuccessfulDownload: @NO,
};
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
[cam.device requestDownloadFile:file
options:options
downloadDelegate:self
didDownloadSelector:@selector(didDownloadFile:error:options:contextInfo:)
contextInfo:(void *)CFBridgingRetain(cam.uuid)];
#pragma clang diagnostic pop
}
- (void)importNames:(NSArray<NSString *> *)names {
if (self.dir.length == 0 || names.count == 0) return;
for (NSString *key in self.cams) {
PRCam *cam = self.cams[key];
if (!cam.device.hasOpenSession) continue;
for (NSString *name in names) {
ICCameraFile *file = cam.filesByName[name];
if (file) [self download:file cam:cam];
}
[self publishCatalog:cam];
}
}
#pragma mark ICDeviceBrowserDelegate
- (void)deviceBrowser:(ICDeviceBrowser *)browser didAddDevice:(ICDevice *)device moreComing:(BOOL)moreComing {
(void)browser;
(void)moreComing;
if (![self accepts:device]) return;
PRCam *cam = [self camFor:device];
cam.catalogReady = NO;
cam.openRequested = NO;
cam.device.delegate = self;
cam.state = self.tether ? @"opening" : @"idle";
[self publish];
// Session opens from deviceDidBecomeReady — not here.
}
- (void)deviceBrowser:(ICDeviceBrowser *)browser didRemoveDevice:(ICDevice *)device moreGoing:(BOOL)moreGoing {
(void)browser;
(void)moreGoing;
NSString *uuid = device.UUIDString ?: device.name;
if (uuid) [self.cams removeObjectForKey:uuid];
[self publish];
emit(@{@"kind": @"catalog", @"cameraId": uuid ?: @"", @"files": @[]});
}
#pragma mark ICDeviceDelegate
- (void)device:(ICDevice *)device didOpenSessionWithError:(NSError *)error {
PRCam *cam = [self camFor:device];
cam.openRequested = NO;
if (error) {
cam.state = @"busy";
cam.errorText = error.localizedDescription;
[self publish];
[self scheduleRetry];
return;
}
cam.state = @"tethered";
cam.errorText = nil;
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
[cam.device requestEnableTethering];
#pragma clang diagnostic pop
[self syncClock:cam];
[self publish];
}
- (void)device:(ICDevice *)device didCloseSessionWithError:(NSError *)error {
(void)error;
PRCam *cam = self.cams[device.UUIDString ?: @""];
if (!cam) return;
cam.openRequested = NO;
cam.catalogReady = NO;
if (self.tether) {
cam.state = @"busy";
[self scheduleRetry];
} else {
cam.state = @"idle";
}
[self publish];
}
- (void)didRemoveDevice:(ICDevice *)device {
[self deviceBrowser:self.browser didRemoveDevice:device moreGoing:NO];
}
- (void)deviceDidBecomeReady:(ICDevice *)device {
PRCam *cam = [self camFor:device];
[self requestOpenIfReady:cam];
[self syncClock:cam];
[self publish];
}
- (void)deviceDidBecomeReadyWithCompleteContentCatalog:(ICCameraDevice *)device {
PRCam *cam = [self camFor:device];
// Snapshot what was already on the card so the UI can mark later shots as "new".
[cam.seenAtConnect removeAllObjects];
for (ICCameraItem *item in cam.device.mediaFiles) {
if (item.name && is_still(item)) [cam.seenAtConnect addObject:item.name];
}
cam.catalogReady = YES;
if ([cam.state isEqualToString:@"opening"]) cam.state = @"tethered";
cam.errorText = nil;
[self rebuildCatalog:cam];
[self syncClock:cam];
[self publish];
}
- (void)cameraDevice:(ICCameraDevice *)camera didAddItems:(NSArray<ICCameraItem *> *)items {
PRCam *cam = [self camFor:camera];
// List only — never auto-download. The photographer picks what to pull.
for (ICCameraItem *item in items) [self indexItem:item cam:cam];
[self publishCatalog:cam];
}
- (void)cameraDevice:(ICCameraDevice *)camera didRemoveItems:(NSArray<ICCameraItem *> *)items {
PRCam *cam = [self camFor:camera];
for (ICCameraItem *item in items) {
if (item.name) [cam.filesByName removeObjectForKey:item.name];
}
[self publishCatalog:cam];
}
- (void)cameraDevice:(ICCameraDevice *)camera didReceiveThumbnail:(CGImageRef)thumbnail forItem:(ICCameraItem *)item error:(NSError *)error {
(void)camera;
(void)thumbnail;
(void)item;
(void)error;
}
- (void)cameraDevice:(ICCameraDevice *)camera didReceiveMetadata:(NSDictionary *)metadata forItem:(ICCameraItem *)item error:(NSError *)error {
(void)camera;
(void)metadata;
(void)item;
(void)error;
}
- (void)cameraDevice:(ICCameraDevice *)camera didRenameItems:(NSArray<ICCameraItem *> *)items {
(void)camera;
(void)items;
}
- (void)cameraDeviceDidChangeCapability:(ICCameraDevice *)camera {
(void)camera;
}
- (void)cameraDevice:(ICCameraDevice *)camera didReceivePTPEvent:(NSData *)eventData {
(void)camera;
(void)eventData;
}
- (void)cameraDeviceDidRemoveAccessRestriction:(ICDevice *)device {
(void)device;
}
- (void)cameraDeviceDidEnableAccessRestriction:(ICDevice *)device {
(void)device;
}
- (void)didDownloadFile:(ICCameraFile *)file error:(NSError *)error options:(NSDictionary *)options contextInfo:(void *)contextInfo {
NSString *camId = contextInfo ? CFBridgingRelease(contextInfo) : nil;
if (error || self.dir.length == 0) {
if (camId && file.name) {
PRCam *cam = self.cams[camId];
[cam.fetched removeObject:file.name];
[self publishCatalog:cam];
}
return;
}
NSString *saved = options[ICSavedFilename];
if (![saved isKindOfClass:[NSString class]] || saved.length == 0) saved = file.name;
if (saved.length == 0) return;
NSString *path = [self.dir stringByAppendingPathComponent:saved];
NSDictionary *attrs = [[NSFileManager defaultManager] attributesOfItemAtPath:path error:nil];
unsigned long long size = [attrs fileSize];
if (size == 0) return;
emit(@{@"kind": @"file", @"path": path, @"name": saved, @"size": @(size)});
if (camId) {
PRCam *cam = self.cams[camId];
if (cam) [self publishCatalog:cam];
}
}
@end
static PRCameraHub *g_hub = nil;
static void on_main(void (^block)(void)) {
if ([NSThread isMainThread]) block();
else dispatch_async(dispatch_get_main_queue(), block);
}
void pr_camera_start(pr_camera_cb cb) {
g_callback = cb;
on_main(^{
if (g_hub) return;
g_hub = [PRCameraHub new];
[g_hub start];
});
}
void pr_camera_set_dir(const char *dir) {
NSString *path = dir ? [NSString stringWithUTF8String:dir] : @"";
on_main(^{
g_dir = [path copy];
g_hub.dir = g_dir;
});
}
void pr_camera_sync(void) {
on_main(^{
if (!g_hub) return;
for (NSString *key in g_hub.cams.allKeys) {
PRCam *cam = g_hub.cams[key];
cam.clockDone = NO;
[g_hub syncClock:cam];
}
});
}
void pr_camera_set_tether(int on) {
on_main(^{
g_tether = on ? YES : NO;
if (!g_hub) return;
g_hub.tether = g_tether;
for (NSString *key in g_hub.cams.allKeys) {
PRCam *cam = g_hub.cams[key];
if (g_hub.tether) {
cam.openRequested = NO;
[g_hub requestOpenIfReady:cam];
} else if (cam.device.hasOpenSession) {
cam.state = @"idle";
[cam.device requestCloseSession];
} else {
cam.state = @"idle";
}
}
[g_hub publish];
});
}
void pr_camera_import(const char *names_json) {
if (!names_json) return;
NSString *text = [NSString stringWithUTF8String:names_json];
NSData *data = [text dataUsingEncoding:NSUTF8StringEncoding];
if (!data) return;
id parsed = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
if (![parsed isKindOfClass:[NSArray class]]) return;
NSArray *names = (NSArray *)parsed;
on_main(^{
[g_hub importNames:names];
});
}
void pr_camera_refresh_catalog(void) {
on_main(^{
if (!g_hub) return;
for (NSString *key in g_hub.cams.allKeys) {
PRCam *cam = g_hub.cams[key];
if (cam.catalogReady) [g_hub rebuildCatalog:cam];
}
});
}
+136 -28
View File
@@ -5,11 +5,11 @@
//! then deletes the original; on any mismatch or error it never deletes, so a card is never emptied of a file
//! that did not arrive whole. The last settings used are remembered (like Photo Mechanic's dialog).
use std::collections::HashMap;
use std::io::{Read, Write};
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex};
use std::collections::HashMap;
use chrono::{Datelike, Local, TimeZone};
use serde::{Deserialize, Serialize};
@@ -20,8 +20,8 @@ use crate::local::sha256_file;
/// RAW extensions we offload (lower-case, no dot).
const RAW_EXTS: &[&str] = &[
"cr2", "cr3", "crw", "nef", "nrw", "arw", "srf", "sr2", "raf", "orf", "rw2", "pef", "srw", "x3f", "3fr", "iiq",
"erf", "kdc", "mrw", "dng", "raw",
"cr2", "cr3", "crw", "nef", "nrw", "arw", "srf", "sr2", "raf", "orf", "rw2", "pef", "srw",
"x3f", "3fr", "iiq", "erf", "kdc", "mrw", "dng", "raw",
];
const JPEG_EXTS: &[&str] = &["jpg", "jpeg"];
const OTHER_IMAGE_EXTS: &[&str] = &["heic", "heif", "tif", "tiff", "png"];
@@ -29,7 +29,10 @@ const OTHER_IMAGE_EXTS: &[&str] = &["heic", "heif", "tif", "tiff", "png"];
const SIDECAR_EXTS: &[&str] = &["wav", "xmp"];
fn ext_of(path: &Path) -> String {
path.extension().and_then(|e| e.to_str()).unwrap_or("").to_ascii_lowercase()
path.extension()
.and_then(|e| e.to_str())
.unwrap_or("")
.to_ascii_lowercase()
}
fn is_raw(ext: &str) -> bool {
RAW_EXTS.contains(&ext)
@@ -44,7 +47,9 @@ fn is_image(ext: &str) -> bool {
/// `~/x` -> the home folder; anything else as given.
fn expand(p: &str) -> PathBuf {
if let Some(rest) = p.strip_prefix("~/") {
return dirs::home_dir().unwrap_or_else(std::env::temp_dir).join(rest);
return dirs::home_dir()
.unwrap_or_else(std::env::temp_dir)
.join(rest);
}
PathBuf::from(p)
}
@@ -128,14 +133,21 @@ impl CardState {
if let Some(dir) = file.parent() {
std::fs::create_dir_all(dir).map_err(|e| e.to_string())?;
}
std::fs::write(&file, serde_json::to_vec_pretty(&s).map_err(|e| e.to_string())?).map_err(|e| e.to_string())?;
std::fs::write(
&file,
serde_json::to_vec_pretty(&s).map_err(|e| e.to_string())?,
)
.map_err(|e| e.to_string())?;
*self.settings.lock().unwrap() = Some(s);
Ok(())
}
fn begin(&self, job_id: &str) -> Arc<AtomicBool> {
let flag = Arc::new(AtomicBool::new(false));
self.cancel.lock().unwrap().insert(job_id.to_string(), flag.clone());
self.cancel
.lock()
.unwrap()
.insert(job_id.to_string(), flag.clone());
flag
}
@@ -302,9 +314,13 @@ pub async fn card_scan(source: String, settings: Option<CardSettings>) -> Result
}
let mut files = Vec::new();
collect(&root, &mut files);
let mode = settings.as_ref().map(|s| s.raw_jpeg).unwrap_or(RawJpeg::Both);
let mode = settings
.as_ref()
.map(|s| s.raw_jpeg)
.unwrap_or(RawJpeg::Both);
let with_sidecars = settings.as_ref().map(|s| s.sidecars).unwrap_or(false);
let (mut raw, mut jpeg, mut other, mut bytes, mut sidecar_bytes) = (0usize, 0usize, 0usize, 0u64, 0u64);
let (mut raw, mut jpeg, mut other, mut bytes, mut sidecar_bytes) =
(0usize, 0usize, 0usize, 0u64, 0u64);
for f in &files {
let ext = ext_of(f);
if !wanted(&ext, mode) {
@@ -331,7 +347,14 @@ pub async fn card_scan(source: String, settings: Option<CardSettings>) -> Result
}
None => (None, None),
};
Ok(CardScan { raw, jpeg, other, bytes, free_bytes, fits })
Ok(CardScan {
raw,
jpeg,
other,
bytes,
free_bytes,
fits,
})
})
.await
.map_err(|e| e.to_string())?
@@ -428,7 +451,11 @@ fn report(app: Option<&AppHandle>, progress: &Progress) {
/// Bytes still free for a normal user on the volume that holds `path` (the nearest existing parent).
#[cfg(unix)]
fn volume_free(path: &Path) -> Option<u64> {
let mut cursor = if path.as_os_str().is_empty() { PathBuf::from(".") } else { path.to_path_buf() };
let mut cursor = if path.as_os_str().is_empty() {
PathBuf::from(".")
} else {
path.to_path_buf()
};
loop {
if cursor.exists() {
break;
@@ -494,17 +521,26 @@ fn plan_days(photos: &[PathBuf], settings: &CardSettings) -> Vec<DayPlan> {
let mut rows: Vec<(String, Planned)> = Vec::with_capacity(photos.len());
for src in photos {
let ext = ext_of(src);
let name = src.file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_default();
let name = src
.file_name()
.map(|n| n.to_string_lossy().to_string())
.unwrap_or_default();
let when = capture_day(src, &ext);
let key = day_key(&when);
let folder = render_folder(&settings.folder_template, &when, &ext);
let dir = base.join(folder.trim_start_matches('/'));
let photo_len = std::fs::metadata(src).map(|m| m.len()).unwrap_or(0);
let target = dir.join(&name);
let photo_write = if target.exists() && !settings.overwrite { 0 } else { photo_len };
let photo_write = if target.exists() && !settings.overwrite {
0
} else {
photo_len
};
let mut write_len = photo_write;
if settings.sidecars {
if let (Some(stem), Some(parent)) = (src.file_stem().and_then(|s| s.to_str()), src.parent()) {
if let (Some(stem), Some(parent)) =
(src.file_stem().and_then(|s| s.to_str()), src.parent())
{
for ext in SIDECAR_EXTS {
let side = parent.join(format!("{stem}.{ext}"));
if !side.is_file() {
@@ -518,13 +554,26 @@ fn plan_days(photos: &[PathBuf], settings: &CardSettings) -> Vec<DayPlan> {
}
}
}
rows.push((key, Planned { src: src.clone(), dir, name, photo_len, write_len }));
rows.push((
key,
Planned {
src: src.clone(),
dir,
name,
photo_len,
write_len,
},
));
}
rows.sort_by(|a, b| a.0.cmp(&b.0).then_with(|| a.1.src.cmp(&b.1.src)));
let mut days: Vec<DayPlan> = Vec::new();
for (key, item) in rows {
if days.last().map(|day| day.key.as_str()) != Some(key.as_str()) {
days.push(DayPlan { key, items: Vec::new(), write_len: 0 });
days.push(DayPlan {
key,
items: Vec::new(),
write_len: 0,
});
}
let day = days.last_mut().unwrap();
day.write_len += item.write_len;
@@ -562,17 +611,30 @@ fn room_for(settings: &CardSettings) -> Option<u64> {
/// usually finish later, not sooner. A second card is a second call, so the two readers work at once.
/// `room` limits how much may be written. Days are copied whole, oldest first; a day that does not fit is
/// not started, and neither is any day after it. A move deletes a day's sources only once that day is complete.
fn ingest_dir(app: Option<&AppHandle>, root: &Path, settings: &CardSettings, job_id: &str, cancel: &AtomicBool, room: Option<u64>) -> Result<CardResult, String> {
fn ingest_dir(
app: Option<&AppHandle>,
root: &Path,
settings: &CardSettings,
job_id: &str,
cancel: &AtomicBool,
room: Option<u64>,
) -> Result<CardResult, String> {
if !root.is_dir() {
return Err("not_a_folder".to_string());
}
let base = expand(&settings.destination);
let mut files = Vec::new();
collect(root, &mut files);
let photos: Vec<PathBuf> = files.into_iter().filter(|f| wanted(&ext_of(f), settings.raw_jpeg)).collect();
let photos: Vec<PathBuf> = files
.into_iter()
.filter(|f| wanted(&ext_of(f), settings.raw_jpeg))
.collect();
let (days, held) = days_that_fit(plan_days(&photos, settings), room);
let total: usize = days.iter().map(|day| day.items.len()).sum();
let bytes_total: u64 = days.iter().map(|day| day.items.iter().map(|item| item.photo_len).sum::<u64>()).sum();
let bytes_total: u64 = days
.iter()
.map(|day| day.items.iter().map(|item| item.photo_len).sum::<u64>())
.sum();
let mut bytes_done = 0u64;
let mut r = CardResult {
copied: 0,
@@ -585,7 +647,10 @@ fn ingest_dir(app: Option<&AppHandle>, root: &Path, settings: &CardSettings, job
held: held.clone(),
};
if let Some(day) = held.first() {
note(&mut r.notes, &format!("O dia {day} não cabe. Fica no cartão, tal como os dias a seguir."));
note(
&mut r.notes,
&format!("O dia {day} não cabe. Fica no cartão, tal como os dias a seguir."),
);
}
let mut index = 0usize;
for day in &days {
@@ -603,7 +668,17 @@ fn ingest_dir(app: Option<&AppHandle>, root: &Path, settings: &CardSettings, job
break;
}
index += 1;
report(app, &Progress { done: index, total, name: item.name.clone(), job_id: job_id.to_string(), bytes_done, bytes_total });
report(
app,
&Progress {
done: index,
total,
name: item.name.clone(),
job_id: job_id.to_string(),
bytes_done,
bytes_total,
},
);
if let Err(e) = std::fs::create_dir_all(&item.dir) {
r.failed += 1;
bytes_done += item.photo_len;
@@ -628,7 +703,10 @@ fn ingest_dir(app: Option<&AppHandle>, root: &Path, settings: &CardSettings, job
// Sidecars (same stem): best effort. A sidecar that fails is noted but does not fail the photo.
let mut sidecars_done: Vec<PathBuf> = Vec::new();
if settings.sidecars {
if let (Some(stem), Some(parent)) = (item.src.file_stem().and_then(|s| s.to_str()), item.src.parent()) {
if let (Some(stem), Some(parent)) = (
item.src.file_stem().and_then(|s| s.to_str()),
item.src.parent(),
) {
for ext in SIDECAR_EXTS {
let side = parent.join(format!("{stem}.{ext}"));
if !side.exists() {
@@ -666,7 +744,14 @@ fn ingest_dir(app: Option<&AppHandle>, root: &Path, settings: &CardSettings, job
let finished = r.copied + r.moved + r.skipped + r.failed;
report(
app,
&Progress { done: finished, total, name: String::new(), job_id: job_id.to_string(), bytes_done, bytes_total },
&Progress {
done: finished,
total,
name: String::new(),
job_id: job_id.to_string(),
bytes_done,
bytes_total,
},
);
Ok(r)
}
@@ -675,7 +760,13 @@ fn ingest_dir(app: Option<&AppHandle>, root: &Path, settings: &CardSettings, job
/// `card-progress` events as it goes. `job_id` lets several cards report progress without mixing, and lets
/// [`card_cancel`] stop one of them. Omitted, the job is named `default` (one card at a time).
#[tauri::command]
pub async fn card_ingest(app: AppHandle, source: String, settings: CardSettings, job_id: Option<String>, state: tauri::State<'_, CardState>) -> Result<CardResult, String> {
pub async fn card_ingest(
app: AppHandle,
source: String,
settings: CardSettings,
job_id: Option<String>,
state: tauri::State<'_, CardState>,
) -> Result<CardResult, String> {
let job_id = job_id.unwrap_or_else(|| "default".to_string());
let cancel = state.begin(&job_id);
let end_id = job_id.clone();
@@ -703,7 +794,10 @@ pub fn card_settings(state: tauri::State<'_, CardState>) -> CardSettings {
}
#[tauri::command]
pub fn card_save_settings(state: tauri::State<'_, CardState>, settings: CardSettings) -> Result<CardSettings, String> {
pub fn card_save_settings(
state: tauri::State<'_, CardState>,
settings: CardSettings,
) -> Result<CardSettings, String> {
state.save(settings.clone())?;
Ok(settings)
}
@@ -727,7 +821,8 @@ mod tests {
..CardSettings::default()
};
let stopped = ingest_dir(None, &src, &settings, "job", &AtomicBool::new(true), None).unwrap();
let stopped =
ingest_dir(None, &src, &settings, "job", &AtomicBool::new(true), None).unwrap();
assert!(stopped.stopped);
assert_eq!(stopped.copied, 0);
assert!(!dst.join("a.jpg").exists());
@@ -751,7 +846,12 @@ mod tests {
std::fs::write(&old, b"day-one").unwrap();
std::fs::write(&new, b"day-two-is-bigger").unwrap();
let past = std::time::SystemTime::now() - std::time::Duration::from_secs(5 * 24 * 3600);
std::fs::OpenOptions::new().write(true).open(&old).unwrap().set_modified(past).unwrap();
std::fs::OpenOptions::new()
.write(true)
.open(&old)
.unwrap()
.set_modified(past)
.unwrap();
let settings = CardSettings {
destination: dst.to_string_lossy().to_string(),
folder_template: String::new(),
@@ -760,7 +860,15 @@ mod tests {
..CardSettings::default()
};
let room = std::fs::metadata(&old).unwrap().len();
let done = ingest_dir(None, &src, &settings, "job", &AtomicBool::new(false), Some(room)).unwrap();
let done = ingest_dir(
None,
&src,
&settings,
"job",
&AtomicBool::new(false),
Some(room),
)
.unwrap();
assert_eq!(done.moved, 1);
assert_eq!(done.held.len(), 1);
assert!(dst.join("old.jpg").exists());
+1 -1
View File
@@ -77,7 +77,7 @@ fn now_secs() -> u64 {
.unwrap_or(0)
}
fn is_photo(path: &Path) -> bool {
pub(crate) fn is_photo(path: &Path) -> bool {
path.extension()
.and_then(|e| e.to_str())
.map(|e| EXTENSIONS.contains(&e.to_ascii_lowercase().as_str()))
+259 -50
View File
@@ -7,10 +7,10 @@
//! Results stay on disk (the face, and the name for this game) so opening the same folder again does not
//! read the photos a second time.
use std::io::Write;
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
use std::sync::{Arc, Mutex};
use std::io::Write;
use std::time::{Duration, Instant, UNIX_EPOCH};
use serde::{Deserialize, Serialize};
@@ -30,7 +30,9 @@ pub struct FaceScan {
impl Default for FaceScan {
fn default() -> Self {
Self { cancel: Arc::new(AtomicBool::new(false)) }
Self {
cancel: Arc::new(AtomicBool::new(false)),
}
}
}
@@ -100,7 +102,10 @@ struct Job {
}
fn cache_root() -> PathBuf {
dirs::cache_dir().unwrap_or_else(std::env::temp_dir).join("pt.photoreport.desktop").join("face-scan")
dirs::cache_dir()
.unwrap_or_else(std::env::temp_dir)
.join("pt.photoreport.desktop")
.join("face-scan")
}
fn models_dir() -> PathBuf {
@@ -112,9 +117,15 @@ fn file_key(root: &Path, path: &Path) -> String {
let meta = std::fs::metadata(path).ok();
let len = meta.as_ref().map(|m| m.len()).unwrap_or(0);
let modified = meta.and_then(|m| m.modified().ok()).unwrap_or(UNIX_EPOCH);
let secs = modified.duration_since(UNIX_EPOCH).map(|d| d.as_secs()).unwrap_or(0);
let secs = modified
.duration_since(UNIX_EPOCH)
.map(|d| d.as_secs())
.unwrap_or(0);
let raw = format!("{}\0{len}\0{secs}", rel.to_string_lossy());
Sha256::digest(raw.as_bytes()).iter().map(|b| format!("{b:02x}")).collect()
Sha256::digest(raw.as_bytes())
.iter()
.map(|b| format!("{b:02x}"))
.collect()
}
fn engine_file(key: &str) -> PathBuf {
@@ -126,7 +137,11 @@ fn thumb_file(key: &str) -> PathBuf {
}
fn named_file(org_id: &str, event_id: &str, key: &str) -> PathBuf {
cache_root().join("names").join(org_id).join(event_id).join(format!("{key}.json"))
cache_root()
.join("names")
.join(org_id)
.join(event_id)
.join(format!("{key}.json"))
}
fn read_json<T: for<'a> Deserialize<'a>>(path: &Path) -> Option<T> {
@@ -148,8 +163,14 @@ fn worth_naming(faces: &[FoundFace]) -> Vec<&FoundFace> {
const MIN_SIDE: f32 = 0.012;
const MIN_SHARP: f32 = 45.0;
const RELATIVE: f32 = 0.25;
let big: Vec<&FoundFace> = faces.iter().filter(|f| (f.x1 - f.x0).max(f.y1 - f.y0) >= MIN_SIDE).collect();
let sharpest = big.iter().filter_map(|f| f.sharpness).fold(0.0_f32, f32::max);
let big: Vec<&FoundFace> = faces
.iter()
.filter(|f| (f.x1 - f.x0).max(f.y1 - f.y0) >= MIN_SIDE)
.collect();
let sharpest = big
.iter()
.filter_map(|f| f.sharpness)
.fold(0.0_f32, f32::max);
big.into_iter()
.filter(|f| match f.sharpness {
None => true,
@@ -161,10 +182,19 @@ fn worth_naming(faces: &[FoundFace]) -> Vec<&FoundFace> {
fn to_scan(face: &FoundFace, with_embedding: bool) -> ScanFace {
ScanFace {
rect: Rect { x0: face.x0, y0: face.y0, x1: face.x1, y1: face.y1 },
rect: Rect {
x0: face.x0,
y0: face.y0,
x1: face.x1,
y1: face.y1,
},
number: None,
person: None,
embedding: if with_embedding { face.embedding.clone() } else { None },
embedding: if with_embedding {
face.embedding.clone()
} else {
None
},
}
}
@@ -179,26 +209,46 @@ fn b64(data: &[u8]) -> String {
let n = (b0 << 16) | (b1.unwrap_or(0) << 8) | b2.unwrap_or(0);
out.push(TABLE[((n >> 18) & 63) as usize] as char);
out.push(TABLE[((n >> 12) & 63) as usize] as char);
out.push(if b1.is_some() { TABLE[((n >> 6) & 63) as usize] as char } else { '=' });
out.push(if b2.is_some() { TABLE[(n & 63) as usize] as char } else { '=' });
out.push(if b1.is_some() {
TABLE[((n >> 6) & 63) as usize] as char
} else {
'='
});
out.push(if b2.is_some() {
TABLE[(n & 63) as usize] as char
} else {
'='
});
i += 3;
}
out
}
fn thumb_jpeg(path: &Path) -> Vec<u8> {
let Ok(reader) = image::ImageReader::open(path).and_then(|r| r.with_guessed_format()) else { return Vec::new() };
let Ok(img) = reader.decode() else { return Vec::new() };
let Ok(reader) = image::ImageReader::open(path).and_then(|r| r.with_guessed_format()) else {
return Vec::new();
};
let Ok(img) = reader.decode() else {
return Vec::new();
};
let small = img.thumbnail(480, 480);
let mut bytes = Vec::new();
if small.write_to(&mut std::io::Cursor::new(&mut bytes), image::ImageFormat::Jpeg).is_err() {
if small
.write_to(
&mut std::io::Cursor::new(&mut bytes),
image::ImageFormat::Jpeg,
)
.is_err()
{
return Vec::new();
}
bytes
}
fn jpeg_paths(dir: &Path, out: &mut Vec<PathBuf>) {
let Ok(entries) = std::fs::read_dir(dir) else { return };
let Ok(entries) = std::fs::read_dir(dir) else {
return;
};
for entry in entries.flatten() {
let path = entry.path();
let name = entry.file_name();
@@ -208,7 +258,9 @@ fn jpeg_paths(dir: &Path, out: &mut Vec<PathBuf>) {
}
if path.is_dir() {
jpeg_paths(&path, out);
} else if name.to_ascii_lowercase().ends_with(".jpg") || name.to_ascii_lowercase().ends_with(".jpeg") {
} else if name.to_ascii_lowercase().ends_with(".jpg")
|| name.to_ascii_lowercase().ends_with(".jpeg")
{
out.push(path);
}
}
@@ -226,7 +278,9 @@ fn memory_gb() -> f64 {
/// One engine per core, and only as many as memory can hold (each copy of the model is large).
/// `extra_gb` is RAM already taken by the accelerator, so the CPU copies leave room for it.
fn engine_cap(extra_gb: f64) -> usize {
let cpus = std::thread::available_parallelism().map(|n| n.get()).unwrap_or(2);
let cpus = std::thread::available_parallelism()
.map(|n| n.get())
.unwrap_or(2);
let spare = (memory_gb() - 2.0 - extra_gb).max(0.7);
let by_mem = (spare / 0.7).floor().max(1.0) as usize;
cpus.max(1).min(by_mem.max(1))
@@ -244,7 +298,14 @@ fn cpu_ticks() -> Option<(u64, u64)> {
}
let mut info = Load { ticks: [0; 4] };
let mut count = 4u32;
let rc = unsafe { host_statistics(mach_host_self(), 3, (&mut info as *mut Load).cast(), &mut count) };
let rc = unsafe {
host_statistics(
mach_host_self(),
3,
(&mut info as *mut Load).cast(),
&mut count,
)
};
if rc != 0 {
return None;
}
@@ -266,7 +327,11 @@ fn cpu_ticks() -> Option<(u64, u64)> {
idle = n;
}
}
if total == 0 { None } else { Some((idle, total)) }
if total == 0 {
None
} else {
Some((idle, total))
}
}
#[cfg(not(any(target_os = "macos", target_os = "linux")))]
@@ -279,7 +344,11 @@ fn cpu_used(prev: &mut Option<(u64, u64)>) -> Option<f64> {
let used = prev.and_then(|(idle, total)| {
let idle_d = now.0.saturating_sub(idle);
let total_d = now.1.saturating_sub(total);
if total_d == 0 { None } else { Some(1.0 - (idle_d as f64) / (total_d as f64)) }
if total_d == 0 {
None
} else {
Some(1.0 - (idle_d as f64) / (total_d as f64))
}
});
*prev = Some(now);
used
@@ -297,9 +366,23 @@ fn emit_prepare(app: &AppHandle, step: &'static str, done: u64, total: u64) {
let _ = app.emit("faces-prepare", Prepare { step, done, total });
}
fn emit_one(app: &AppHandle, done: &AtomicUsize, total: usize, path: &Path, cached: bool, needs_name: bool, error: bool, roster: Option<i32>, thumb: &[u8], faces: Vec<ScanFace>) {
fn emit_one(
app: &AppHandle,
done: &AtomicUsize,
total: usize,
path: &Path,
cached: bool,
needs_name: bool,
error: bool,
roster: Option<i32>,
thumb: &[u8],
faces: Vec<ScanFace>,
) {
let n = done.fetch_add(1, Ordering::Relaxed) + 1;
let name = path.file_name().map(|s| s.to_string_lossy().to_string()).unwrap_or_default();
let name = path
.file_name()
.map(|s| s.to_string_lossy().to_string())
.unwrap_or_default();
let _ = app.emit(
"faces-photo",
Progress {
@@ -311,13 +394,23 @@ fn emit_one(app: &AppHandle, done: &AtomicUsize, total: usize, path: &Path, cach
needs_name,
error,
roster,
thumb: if thumb.is_empty() { String::new() } else { b64(thumb) },
thumb: if thumb.is_empty() {
String::new()
} else {
b64(thumb)
},
faces,
},
);
}
async fn ensure_models(app: &AppHandle, cancel: &AtomicBool, api: &str, token: &str, org_id: &str) -> Result<PathBuf, String> {
async fn ensure_models(
app: &AppHandle,
cancel: &AtomicBool,
api: &str,
token: &str,
org_id: &str,
) -> Result<PathBuf, String> {
let dir = models_dir();
std::fs::create_dir_all(&dir).map_err(|e| e.to_string())?;
if MODEL_FILES.iter().all(|name| dir.join(name).is_file()) {
@@ -332,7 +425,10 @@ async fn ensure_models(app: &AppHandle, cancel: &AtomicBool, api: &str, token: &
if dest.is_file() {
continue;
}
let url = format!("{}/v1/orgs/{org_id}/faces/models/{name}", api.trim_end_matches('/'));
let url = format!(
"{}/v1/orgs/{org_id}/faces/models/{name}",
api.trim_end_matches('/')
);
download_model(app, cancel, &http, &url, &dest, token).await?;
}
Ok(dir)
@@ -340,8 +436,20 @@ async fn ensure_models(app: &AppHandle, cancel: &AtomicBool, api: &str, token: &
/// The recogniser is about 250 MB. Report bytes so the wait is not a frozen sentence.
/// The recogniser is about 250 MB. Report bytes so the wait is not a frozen sentence.
async fn download_model(app: &AppHandle, cancel: &AtomicBool, http: &reqwest::Client, url: &str, dest: &Path, token: &str) -> Result<(), String> {
let mut res = http.get(url).bearer_auth(token).send().await.map_err(|e| e.to_string())?;
async fn download_model(
app: &AppHandle,
cancel: &AtomicBool,
http: &reqwest::Client,
url: &str,
dest: &Path,
token: &str,
) -> Result<(), String> {
let mut res = http
.get(url)
.bearer_auth(token)
.send()
.await
.map_err(|e| e.to_string())?;
if !res.status().is_success() {
return Err(format!("models_{}", res.status().as_u16()));
}
@@ -370,7 +478,15 @@ async fn download_model(app: &AppHandle, cancel: &AtomicBool, http: &reqwest::Cl
Ok(())
}
fn run_jobs(dir: PathBuf, jobs: Arc<Mutex<Vec<Job>>>, cancel: Arc<AtomicBool>, app: AppHandle, done: Arc<AtomicUsize>, total: usize, accel: Option<Arc<Accel>>) {
fn run_jobs(
dir: PathBuf,
jobs: Arc<Mutex<Vec<Job>>>,
cancel: Arc<AtomicBool>,
app: AppHandle,
done: Arc<AtomicUsize>,
total: usize,
accel: Option<Arc<Accel>>,
) {
emit_prepare(&app, "load", 0, 0);
let engine = match Engine::load(&dir, "auraface", 0.6) {
Ok(engine) => engine,
@@ -386,27 +502,62 @@ fn run_jobs(dir: PathBuf, jobs: Arc<Mutex<Vec<Job>>>, cancel: Arc<AtomicBool>, a
let job = jobs.lock().ok().and_then(|mut q| q.pop());
let Some(job) = job else { return };
if let Some(cached) = read_json::<EngineCache>(&engine_file(&job.key)) {
let faces = worth_naming(&cached.faces).into_iter().map(|f| to_scan(f, true)).collect();
let faces = worth_naming(&cached.faces)
.into_iter()
.map(|f| to_scan(f, true))
.collect();
let thumb = std::fs::read(thumb_file(&job.key)).unwrap_or_default();
emit_one(&app, &done, total, &job.path, true, true, false, None, &thumb, faces);
emit_one(
&app, &done, total, &job.path, true, true, false, None, &thumb, faces,
);
continue;
}
match engine.analyse_with(&job.path, &mut |rgb| accel.as_ref().and_then(|device| device.embed(rgb).ok())) {
match engine.analyse_with(&job.path, &mut |rgb| {
accel.as_ref().and_then(|device| device.embed(rgb).ok())
}) {
Ok(read) => {
let _ = write_json(&engine_file(&job.key), &EngineCache { faces: read.faces.clone() });
let _ = write_json(
&engine_file(&job.key),
&EngineCache {
faces: read.faces.clone(),
},
);
let thumb = thumb_jpeg(&job.path);
if !thumb.is_empty() {
let _ = std::fs::write(thumb_file(&job.key), &thumb);
}
let faces = worth_naming(&read.faces).into_iter().map(|f| to_scan(f, true)).collect();
emit_one(&app, &done, total, &job.path, false, true, false, None, &thumb, faces);
let faces = worth_naming(&read.faces)
.into_iter()
.map(|f| to_scan(f, true))
.collect();
emit_one(
&app, &done, total, &job.path, false, true, false, None, &thumb, faces,
);
}
Err(_) => emit_one(&app, &done, total, &job.path, false, false, true, None, &[], Vec::new()),
Err(_) => emit_one(
&app,
&done,
total,
&job.path,
false,
false,
true,
None,
&[],
Vec::new(),
),
}
}
}
fn scan_folder(app: AppHandle, folder: String, org_id: String, event_id: String, models: PathBuf, cancel: Arc<AtomicBool>) -> Result<(), String> {
fn scan_folder(
app: AppHandle,
folder: String,
org_id: String,
event_id: String,
models: PathBuf,
cancel: Arc<AtomicBool>,
) -> Result<(), String> {
let root = PathBuf::from(&folder);
if !root.is_dir() {
return Err("not_a_folder".into());
@@ -421,7 +572,18 @@ fn scan_folder(app: AppHandle, folder: String, org_id: String, event_id: String,
let key = file_key(&root, &path);
if let Some(named) = read_json::<NamedCache>(&named_file(&org_id, &event_id, &key)) {
let thumb = std::fs::read(thumb_file(&key)).unwrap_or_default();
emit_one(&app, &done, total, &path, true, false, false, named.roster, &thumb, named.faces);
emit_one(
&app,
&done,
total,
&path,
true,
false,
false,
named.roster,
&thumb,
named.faces,
);
continue;
}
pending.push(Job { path, key });
@@ -448,9 +610,23 @@ fn scan_folder(app: AppHandle, folder: String, org_id: String, event_id: String,
break;
}
if alive == 0 && !handles.is_empty() && left > 0 {
let rest = jobs.lock().map(|mut q| std::mem::take(&mut *q)).unwrap_or_default();
let rest = jobs
.lock()
.map(|mut q| std::mem::take(&mut *q))
.unwrap_or_default();
for job in rest {
emit_one(&app, &done, total, &job.path, false, false, true, None, &[], Vec::new());
emit_one(
&app,
&done,
total,
&job.path,
false,
false,
true,
None,
&[],
Vec::new(),
);
}
break;
}
@@ -459,7 +635,11 @@ fn scan_folder(app: AppHandle, folder: String, org_id: String, event_id: String,
let used = cpu_used(&mut sample).unwrap_or(0.0);
let busy = handles.is_empty() || used < CPU_TARGET;
if busy {
let batch = if handles.is_empty() { 2.min(cap) } else { 2.min(cap - handles.len()) };
let batch = if handles.is_empty() {
2.min(cap)
} else {
2.min(cap - handles.len())
};
for _ in 0..batch {
let jobs = jobs.clone();
let cancel = cancel.clone();
@@ -467,7 +647,9 @@ fn scan_folder(app: AppHandle, folder: String, org_id: String, event_id: String,
let done = done.clone();
let dir = models.clone();
let accel = accel.clone();
handles.push(std::thread::spawn(move || run_jobs(dir, jobs, cancel, app, done, total, accel)));
handles.push(std::thread::spawn(move || {
run_jobs(dir, jobs, cancel, app, done, total, accel)
}));
}
}
}
@@ -493,7 +675,15 @@ pub fn faces_cancel(state: tauri::State<'_, FaceScan>) {
/// Reads every JPEG under `folder` on this computer. Emits `faces-photo` as each one finishes.
/// A photo already named for this game is not read again. The models are downloaded once.
#[tauri::command]
pub async fn faces_scan(app: AppHandle, state: tauri::State<'_, FaceScan>, folder: String, org_id: String, event_id: String, api: String, token: String) -> Result<(), String> {
pub async fn faces_scan(
app: AppHandle,
state: tauri::State<'_, FaceScan>,
folder: String,
org_id: String,
event_id: String,
api: String,
token: String,
) -> Result<(), String> {
state.cancel.store(false, Ordering::Relaxed);
let cancel = state.cancel.clone();
let models = match ensure_models(&app, &cancel, &api, &token, &org_id).await {
@@ -501,14 +691,23 @@ pub async fn faces_scan(app: AppHandle, state: tauri::State<'_, FaceScan>, folde
other => other?,
};
let cancel2 = cancel.clone();
tauri::async_runtime::spawn_blocking(move || scan_folder(app, folder, org_id, event_id, models, cancel2))
.await
.map_err(|e| e.to_string())?
tauri::async_runtime::spawn_blocking(move || {
scan_folder(app, folder, org_id, event_id, models, cancel2)
})
.await
.map_err(|e| e.to_string())?
}
/// Remembers the names for one photo of this game, so the next search of the same file skips the server too.
#[tauri::command]
pub fn faces_remember(folder: String, path: String, org_id: String, event_id: String, roster: Option<i32>, faces: Vec<ScanFace>) -> Result<(), String> {
pub fn faces_remember(
folder: String,
path: String,
org_id: String,
event_id: String,
roster: Option<i32>,
faces: Vec<ScanFace>,
) -> Result<(), String> {
let root = PathBuf::from(&folder);
let file = PathBuf::from(&path);
let key = file_key(&root, &file);
@@ -519,14 +718,20 @@ pub fn faces_remember(folder: String, path: String, org_id: String, event_id: St
face
})
.collect();
write_json(&named_file(&org_id, &event_id, &key), &NamedCache { roster, faces })
write_json(
&named_file(&org_id, &event_id, &key),
&NamedCache { roster, faces },
)
}
/// The original JPEG, for importing the photos the photographer picked. Only a JPEG, and only after a scan.
#[tauri::command]
pub fn faces_read(path: String) -> Result<tauri::ipc::Response, String> {
let file = PathBuf::from(&path);
let name = file.file_name().map(|s| s.to_string_lossy().to_ascii_lowercase()).unwrap_or_default();
let name = file
.file_name()
.map(|s| s.to_string_lossy().to_ascii_lowercase())
.unwrap_or_default();
if !name.ends_with(".jpg") && !name.ends_with(".jpeg") {
return Err("not_a_jpeg".into());
}
@@ -561,7 +766,11 @@ mod tests {
sharpness: Some(300.0),
embedding: Some(vec![1.0]),
};
let soft = FoundFace { sharpness: Some(10.0), embedding: Some(vec![1.0]), ..sharp.clone() };
let soft = FoundFace {
sharpness: Some(10.0),
embedding: Some(vec![1.0]),
..sharp.clone()
};
let faces = [sharp.clone(), soft];
let named = worth_naming(&faces);
assert_eq!(named.len(), 1);
+152 -2
View File
@@ -39,6 +39,9 @@ pub struct FtpUser {
/// Switched off: the login stays saved but the server refuses it (one per camera body, like other FTP servers).
#[serde(default = "enabled_by_default")]
pub enabled: bool,
/// What you call this body ("R3", "1DX"). Empty: the login name is the label.
#[serde(default)]
pub label: String,
}
fn enabled_by_default() -> bool {
@@ -69,6 +72,7 @@ impl Default for FtpSettings {
name: "photoreport".into(),
password: new_password(),
enabled: true,
label: String::new(),
}],
ingest: "~/Desktop/ingest".into(),
work_folder: "~/Desktop/{year}/{date} - {event}".into(),
@@ -116,6 +120,17 @@ pub struct IncomingFile {
modified_ms: u64,
}
impl IncomingFile {
pub(crate) fn at(path: String, name: String, size: u64) -> Self {
Self {
path,
name,
size,
modified_ms: now_ms(),
}
}
}
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct FtpStatus {
@@ -181,6 +196,52 @@ fn expand(p: &str) -> PathBuf {
}
}
const RAW_EXT: &[&str] = &[
"cr2", "cr3", "nef", "arw", "raf", "rw2", "dng", "orf", "pef", "srw", "heic", "hif",
];
/// RAW (and HEIC) files sitting next to a JPEG with the same stem.
fn raw_sidecars(jpeg: &Path) -> Vec<PathBuf> {
let Some(dir) = jpeg.parent() else {
return Vec::new();
};
let Some(stem) = jpeg.file_stem().and_then(|s| s.to_str()) else {
return Vec::new();
};
let Ok(entries) = std::fs::read_dir(dir) else {
return Vec::new();
};
let mut out = Vec::new();
for entry in entries.flatten() {
let path = entry.path();
if path == jpeg {
continue;
}
let same = path
.file_stem()
.and_then(|s| s.to_str())
.is_some_and(|s| s.eq_ignore_ascii_case(stem));
if same && is_raw(&path) {
out.push(path);
}
}
out
}
pub(crate) fn is_jpeg_name(name: &str) -> bool {
is_photo(Path::new(name))
}
pub(crate) fn is_raw_name(name: &str) -> bool {
is_raw(Path::new(name))
}
fn is_raw(path: &Path) -> bool {
path.extension()
.and_then(|e| e.to_str())
.is_some_and(|e| RAW_EXT.contains(&e.to_ascii_lowercase().as_str()))
}
fn is_photo(path: &Path) -> bool {
matches!(
path.extension()
@@ -457,7 +518,7 @@ impl FtpState {
Ok(())
}
fn ingest_dir(&self) -> PathBuf {
pub(crate) fn ingest_dir(&self) -> PathBuf {
expand(&self.settings().ingest)
}
@@ -477,6 +538,17 @@ impl FtpState {
}
}
/// JPEG or the RAW beside it, still inside the ingest tree. `ftp_read` stays JPEG-only.
fn inside_kept(&self, path: &str) -> Result<PathBuf, String> {
let root = self.ingest_dir().canonicalize().map_err(|e| e.to_string())?;
let p = Path::new(path).canonicalize().map_err(|_| "not_found".to_string())?;
if p.starts_with(&root) && (is_photo(&p) || is_raw(&p)) {
Ok(p)
} else {
Err("forbidden".into())
}
}
pub fn status(&self) -> FtpStatus {
let settings = self.settings();
let waiting = {
@@ -610,8 +682,17 @@ impl FtpState {
}
/// The server has the photo: move the original into the event's work folder (kept, never deleted).
/// A tethered RAW next to the JPEG (or a RAW-only shot) is filed the same way.
pub fn sent(&self, path: &str, event: &str, date: &str) -> Result<String, String> {
let p = self.finished_jpeg(path)?;
let file_name = Path::new(path)
.file_name()
.and_then(|s| s.to_str())
.unwrap_or("");
let p = if is_raw_name(file_name) {
self.inside_kept(path)?
} else {
self.finished_jpeg(path)?
};
let dir = work_folder(&self.settings().work_folder, event, date);
std::fs::create_dir_all(&dir).map_err(|e| e.to_string())?;
let name = p
@@ -629,7 +710,29 @@ impl FtpState {
target = dir.join(format!("{stem}-{n}{ext}"));
n += 1;
}
let sidecars = if is_photo(&p) {
raw_sidecars(&p)
} else {
Vec::new()
};
let paired = target
.file_stem()
.map(|s| s.to_string_lossy().into_owned())
.unwrap_or_else(|| stem.clone());
move_file(&p, &target).map_err(|e| e.to_string())?;
for raw in sidecars {
let raw_ext = raw
.extension()
.map(|e| e.to_string_lossy().into_owned())
.unwrap_or_default();
let mut raw_target = dir.join(format!("{paired}.{raw_ext}"));
let mut k = 1;
while raw_target.exists() {
raw_target = dir.join(format!("{paired}-{k}.{raw_ext}"));
k += 1;
}
let _ = move_file(&raw, &raw_target);
}
self.taken.lock().unwrap().remove(path);
Ok(target.to_string_lossy().into_owned())
}
@@ -951,6 +1054,47 @@ mod tests {
);
}
/// Tether saves the RAW next to the JPEG; filing the JPEG takes the RAW into the work folder.
#[test]
fn sent_keeps_the_raw_with_the_jpeg() {
let dir = std::env::temp_dir().join(format!("pr-raw-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
let ingest = dir.join("ingest").join(".usb");
std::fs::create_dir_all(&ingest).unwrap();
// Minimal JPEG with SOI/EOI so finished_jpeg accepts it.
std::fs::write(ingest.join("IMG_0001.JPG"), [0xFFu8, 0xD8, 0xFF, 0xD9]).unwrap();
std::fs::write(ingest.join("IMG_0001.CR3"), b"raw").unwrap();
let state = FtpState {
config_path: Some(dir.join("ftp.json")),
..Default::default()
};
state
.save(FtpSettings {
port: 2121,
users: vec![FtpUser {
name: "1dx".into(),
password: "1dx".into(),
enabled: true,
label: String::new(),
}],
ingest: dir.join("ingest").to_string_lossy().into_owned(),
work_folder: dir.join("work/{date} - {event}").to_string_lossy().into_owned(),
auto_start: false,
upload_originals: false,
})
.unwrap();
let jpeg = ingest.join("IMG_0001.JPG");
let moved = state
.sent(jpeg.to_str().unwrap(), "POR x SUI", "2026-11-04")
.unwrap();
let moved = PathBuf::from(&moved);
assert!(moved.is_file());
assert!(moved.with_extension("CR3").is_file());
assert!(!jpeg.exists());
assert!(!ingest.join("IMG_0001.CR3").exists());
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn settings_are_checked() {
let mut s = FtpSettings::default();
@@ -960,11 +1104,13 @@ mod tests {
name: "1dx".into(),
password: "1dx".into(),
enabled: true,
label: String::new(),
},
FtpUser {
name: "R3".into(),
password: "r3".into(),
enabled: false,
label: "R3".into(),
},
];
assert!(s.check().is_ok());
@@ -974,6 +1120,7 @@ mod tests {
// Settings saved by an older app have no "enabled": the login is on.
let old: FtpUser = serde_json::from_str(r#"{"name":"r1","password":"r1"}"#).unwrap();
assert!(old.enabled);
assert!(old.label.is_empty());
s.port = 21;
assert_eq!(s.check().unwrap_err(), "port_low");
s.port = 2121;
@@ -1007,11 +1154,13 @@ mod tests {
name: "1dx".into(),
password: "1dx".into(),
enabled: true,
label: String::new(),
},
FtpUser {
name: "R3".into(),
password: "r3".into(),
enabled: false,
label: "R3".into(),
},
],
ingest: dir.join("ingest").to_string_lossy().into_owned(),
@@ -1128,6 +1277,7 @@ mod tests {
name: "1dx".into(),
password: "1dx".into(),
enabled: true,
label: String::new(),
}],
ingest: dir.join("ingest").to_string_lossy().into_owned(),
work_folder: dir
+43 -7
View File
@@ -1,15 +1,18 @@
//! Native shell around apps/app. The web app calls these commands through `@tauri-apps/api` when it runs
//! inside the desktop app (see apps/app/src/platform.ts). The refresh token never touches disk in clear:
//! it lives in the OS keychain (macOS Keychain, Windows Credential Manager, Secret Service on Linux).
//! `ftp` runs the local FTP server cameras send photos to; `local` finds originals on disk for the editor; `catalog`
//! indexes the photographer's own folders for it; `deliver` saves deliveries to folders here and imports upload
//! destinations from Photo Mechanic and FileZilla; `updater` keeps the shell itself current.
//! `ftp` runs the local FTP server cameras send photos to; `camera` receives tethered shots from a body
//! plugged in by USB; `local` finds originals on disk for the editor; `catalog` indexes the photographer's
//! own folders for it; `deliver` saves deliveries to folders here and imports upload destinations from
//! Photo Mechanic and FileZilla; `updater` keeps the shell itself current.
mod accel;
mod browse;
mod camera;
mod card;
mod catalog;
mod faces;
mod deliver;
mod faces;
mod ftp;
mod local;
mod preview;
@@ -84,15 +87,18 @@ pub fn run() {
.plugin(tauri_plugin_dialog::init())
.plugin(tauri_plugin_updater::Builder::new().build())
.manage(ftp::FtpState::default())
.manage(camera::CameraState::default())
.manage(local::LocalIndex::default())
.manage(catalog::Catalog::default())
.manage(card::CardState::default())
.manage(faces::FaceScan::default())
.manage(browse::OpenFolders::default())
.manage(card::CardState::default())
.manage(faces::FaceScan::default())
.manage(deliver::Deliveries::default())
.manage(shared)
.setup(|app| {
use tauri::Manager;
ftp::auto_start(&app.state::<ftp::FtpState>());
camera::start(&app.state::<ftp::FtpState>());
// `tauri dev` serves the dev server: nothing to update.
if !cfg!(debug_assertions) {
ui::watch(app.handle().clone());
@@ -109,6 +115,20 @@ pub fn run() {
.build()?;
Ok(())
})
// The main window is the window's own webview, so a drop arrives as a window event. Noting it only on
// the webview event left the folder unrecorded, and opening it was refused.
.on_window_event(|window, event| {
use tauri::Manager;
if let tauri::WindowEvent::DragDrop(tauri::DragDropEvent::Drop { paths, .. }) = event {
window.state::<browse::OpenFolders>().note(paths);
}
})
.on_webview_event(|webview, event| {
use tauri::Manager;
if let tauri::WebviewEvent::DragDrop(tauri::DragDropEvent::Drop { paths, .. }) = event {
webview.state::<browse::OpenFolders>().note(paths);
}
})
.invoke_handler(tauri::generate_handler![
refresh_token_get,
refresh_token_set,
@@ -125,6 +145,16 @@ pub fn run() {
ftp::ftp_save_settings,
local::local_original,
local::local_original_changed,
local::local_film_thumb,
browse::folder_drop,
browse::folder_open,
browse::folder_thumb,
browse::folder_read,
browse::folder_meta,
browse::folder_merge_dng,
browse::folder_save_dng,
browse::folder_save_jpeg,
browse::folder_save_xmp,
ftp::ftp_preview,
ftp::ftp_info,
catalog::catalog_folders,
@@ -151,7 +181,13 @@ pub fn run() {
deliver::delivery_folders,
deliver::delivery_folder_pick,
deliver::delivery_write,
deliver::import_upload_profiles
deliver::import_upload_profiles,
camera::camera_status,
camera::camera_take,
camera::camera_tether,
camera::camera_sync,
camera::camera_import,
camera::camera_refresh
])
.run(context);
if let Err(err) = result {
+64
View File
@@ -124,6 +124,51 @@ pub async fn local_original(
Ok(tauri::ipc::Response::new(bytes))
}
/// How many filmstrip thumbnails are read at once. Each one may open a whole raw to reach the camera JPEG.
const FILM_SLOTS: usize = 2;
fn film_slots() -> &'static tokio::sync::Semaphore {
static SLOTS: std::sync::OnceLock<tokio::sync::Semaphore> = std::sync::OnceLock::new();
SLOTS.get_or_init(|| tokio::sync::Semaphore::new(FILM_SLOTS))
}
#[cfg(test)]
fn film_thumb_file(path: &Path) -> Result<Vec<u8>, String> {
let bytes = std::fs::read(path).map_err(|e| e.to_string())?;
photoreport_engine::film_thumb(&bytes).ok_or_else(|| "no_preview".to_string())
}
/// A small JPEG of a file on this computer. `edge` is the long side. The same two slots as the filmstrip, so a
/// contact sheet and the strip never decode more than two files at once.
pub(crate) async fn read_film_thumb(path: PathBuf, edge: u32) -> Result<Vec<u8>, String> {
let permit = film_slots().acquire().await.map_err(|e| e.to_string())?;
let (tx, rx) = tokio::sync::oneshot::channel();
std::thread::spawn(move || {
let result = (|| {
let bytes = std::fs::read(&path).map_err(|e| e.to_string())?;
photoreport_engine::film_thumb_sized(&bytes, edge)
.ok_or_else(|| "no_preview".to_string())
})();
let _ = tx.send(result);
});
let jpeg = rx.await.map_err(|e| e.to_string())??;
drop(permit);
Ok(jpeg)
}
/// A small JPEG of the original on this computer, for the filmstrip. `not_found` when this computer does not
/// have the file; `no_preview` when showing it would mean decoding a raw sensor. Does not re-hash the file:
/// the index already recorded it, and hashing every photo would read the folder twice.
#[tauri::command]
pub async fn local_film_thumb(
index: tauri::State<'_, LocalIndex>,
sha256: String,
) -> Result<tauri::ipc::Response, String> {
let path = index.find_changed(&sha256).ok_or("not_found")?;
let jpeg = read_film_thumb(path, photoreport_engine::thumb::FILM_EDGE).await?;
Ok(tauri::ipc::Response::new(jpeg))
}
#[cfg(test)]
mod tests {
use super::*;
@@ -158,4 +203,23 @@ mod tests {
assert_eq!(again.find_changed(&sha), Some(photo.clone()));
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn a_filed_jpeg_becomes_a_filmstrip_thumbnail() {
let dir = std::env::temp_dir().join(format!("pr-film-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let photo = dir.join("frame.jpg");
let rgb = image::RgbImage::from_fn(800, 200, |x, y| {
image::Rgb([(x % 256) as u8, (y % 256) as u8, 40])
});
let mut bytes = Vec::new();
image::codecs::jpeg::JpegEncoder::new_with_quality(&mut bytes, 80)
.encode_image(&rgb)
.unwrap();
std::fs::write(&photo, &bytes).unwrap();
let thumb = film_thumb_file(&photo).unwrap();
assert!(thumb.starts_with(&[0xFF, 0xD8]));
assert!(thumb.len() < bytes.len());
let _ = std::fs::remove_dir_all(&dir);
}
}
+10 -2
View File
@@ -108,11 +108,19 @@ pub fn exif_date(jpeg: &[u8]) -> Option<(i32, u32, u32)> {
let le = &tiff[..2] == b"II";
let u16_at = |o: usize| -> Option<u16> {
let b = tiff.get(o..o + 2)?;
Some(if le { u16::from_le_bytes([b[0], b[1]]) } else { u16::from_be_bytes([b[0], b[1]]) })
Some(if le {
u16::from_le_bytes([b[0], b[1]])
} else {
u16::from_be_bytes([b[0], b[1]])
})
};
let u32_at = |o: usize| -> Option<u32> {
let b = tiff.get(o..o + 4)?;
Some(if le { u32::from_le_bytes([b[0], b[1], b[2], b[3]]) } else { u32::from_be_bytes([b[0], b[1], b[2], b[3]]) })
Some(if le {
u32::from_le_bytes([b[0], b[1], b[2], b[3]])
} else {
u32::from_be_bytes([b[0], b[1], b[2], b[3]])
})
};
let ifd0 = u32_at(4)? as usize;
let count0 = u16_at(ifd0)? as usize;
+1 -1
View File
@@ -1,7 +1,7 @@
{
"$schema": "https://schema.tauri.app/config/2",
"productName": "PhotoReport",
"version": "0.3.21",
"version": "0.3.26",
"identifier": "pt.photoreport.desktop",
"build": {
"devUrl": "http://localhost:5173",
+45 -5
View File
@@ -4,6 +4,7 @@ import { useCallback, useEffect, useState } from "react";
import { useRouter } from "next/navigation";
import { cached, call, readStored, storageKey, writeStored, type Me } from "./api";
import { Browse, type Tab } from "./Browse";
import { FindByPhoto } from "./FindByPhoto";
import { Gallery } from "./Gallery";
import { Icon } from "./parts";
import fpaLogo from "./logos/fpa.png";
@@ -13,7 +14,7 @@ import { Review } from "./Review";
import type { ArchiveInfo } from "./page";
/** Where the viewer is: one of the lists, in a gallery, on a person's photos, or on "more of this face". */
export type View = { kind: "browse"; tab?: Tab; person?: string; gallery?: string } | { kind: "gallery"; id: string } | { kind: "person"; id: string } | { kind: "face"; id: string };
export type View = { kind: "browse"; tab?: Tab; person?: string; gallery?: string } | { kind: "gallery"; id: string } | { kind: "person"; id: string } | { kind: "face"; id: string } | { kind: "find" };
/** Each owner's template: its name and logo. Colours and type are in archive.css (`data-look`). */
const TEMPLATE: Record<"liga" | "fpa", { owner: string; logo: string }> = {
@@ -57,6 +58,12 @@ export function ArchiveView({ info, start }: { info: ArchiveInfo; start?: View }
cached<Me>(`/v1/archive/${info.id}/me`, token, setMe).catch(() => setMe(null));
}, [token, info.id, meTick]);
// Editors who can search by photo: start the face engine as soon as they are in, so the first search is quicker.
useEffect(() => {
if (!token || !me?.canFind) return;
void fetch(`/v1/archive/${info.id}/find/ready`, { headers: { authorization: `Archive ${token}` } }).catch(() => undefined);
}, [token, me?.canFind, info.id]);
/** Ends the session here and on the server (which revokes the app password kept on the cloud). */
const signOut = useCallback(() => {
const t = readStored(storageKey(info.id));
@@ -82,7 +89,9 @@ export function ArchiveView({ info, start }: { info: ArchiveInfo; start?: View }
? `${base}/g/${v.id}`
: v.kind === "person"
? `${base}/p/${v.id}`
: `${base}/f/${v.id}`;
: v.kind === "find"
? `${home}?t=procurar`
: `${base}/f/${v.id}`;
router.push(href);
window.scrollTo({ top: 0 });
},
@@ -100,7 +109,7 @@ export function ArchiveView({ info, start }: { info: ArchiveInfo; start?: View }
[view.kind, go, home],
);
const current: Tab | null = view.kind === "browse" ? tab : view.kind === "person" || view.kind === "face" ? "people" : "galleries";
const current: Tab | null = view.kind === "browse" ? tab : view.kind === "person" || view.kind === "face" ? "people" : view.kind === "find" ? null : "galleries";
const brand = (
<a className="arq-brand" href={home} onClick={(e) => (e.preventDefault(), openTab("galleries"))}>
@@ -161,12 +170,43 @@ export function ArchiveView({ info, start }: { info: ArchiveInfo; start?: View }
{t === "review" && !!me?.pending && <span className="arq-count">{me.pending}</span>}
</button>
))}
{me?.canFind && (
<button type="button" aria-current={view.kind === "find" ? "page" : undefined} onClick={() => go({ kind: "find" })}>
Procurar por foto
</button>
)}
</div>
</nav>
</header>
<main className="arq-main">
{view.kind === "gallery" ? (
{view.kind === "find" && me?.canFind && token ? (
<FindByPhoto
sourceId={info.id}
token={token}
me={me}
onClose={() => go({ kind: "browse" })}
onExpired={expired}
onPerson={(id) => go({ kind: "person", id })}
onGallery={(id) => go({ kind: "gallery", id })}
onFace={(id) => go({ kind: "face", id })}
/>
) : view.kind === "find" ? (
<div className="arq-wrap arq-body">
<div className="arq-lock">
<Icon name="lock" size={48} />
<h1 className="arq-disp" style={{ margin: 0 }}>
Só para quem pode editar
</h1>
<p className="arq-muted" style={{ maxWidth: 520, margin: 0 }}>
A procura por foto é para quem tem permissão de edição nas pastas destas fotos.
</p>
<button type="button" className="arq-btn" onClick={() => openTab("galleries")}>
Voltar às galerias
</button>
</div>
</div>
) : view.kind === "gallery" ? (
<Gallery id={view.id} sourceId={info.id} me={me} token={token} onBack={() => go({ kind: "browse" })} onExpired={expired} onFace={(id) => go({ kind: "face", id })} onPerson={(id) => go({ kind: "person", id })} onReview={(id) => go({ kind: "browse", tab: "review", gallery: id })} />
) : view.kind === "person" || view.kind === "face" ? (
<PhotosOf
@@ -220,7 +260,7 @@ export function ArchiveView({ info, start }: { info: ArchiveInfo; start?: View }
</div>
</div>
) : (
<Browse sourceId={info.id} token={token} tab={tab} onTab={openTab} onExpired={expired} onGallery={(id) => go({ kind: "gallery", id })} onPerson={(id) => go({ kind: "person", id })} canReview={!!me?.canReview} canManage={!!me?.canManagePeople} />
<Browse sourceId={info.id} token={token} tab={tab} onTab={openTab} onExpired={expired} onGallery={(id) => go({ kind: "gallery", id })} onPerson={(id) => go({ kind: "person", id })} canReview={!!me?.canReview} canManage={!!me?.canManagePeople} fpa={info.look === "fpa"} />
)}
</main>
+98 -1
View File
@@ -1,7 +1,7 @@
"use client";
import { Fragment, useCallback, useEffect, useMemo, useRef, useState } from "react";
import { cached, call, contents, fold, forget, initials, KIND_LABEL, prefetch, shortDay, Unauthorised, type Directory, type GalleryCard, type GalleryKind, type GallerySort, type PeopleList } from "./api";
import { addFromLicence, cached, call, contents, fold, forget, initials, KIND_LABEL, prefetch, shortDay, Unauthorised, type Directory, type FpaCard, type GalleryCard, type GalleryKind, type GallerySort, type PeopleList } from "./api";
import { eventLayout } from "./events";
import { Icon, Loading, PersonFace } from "./parts";
@@ -24,7 +24,10 @@ export function Browse({
onPerson,
canReview = false,
canManage = false,
fpa = false,
}: {
/** A handball archive: people can be added by their federation licence (for those who review). */
fpa?: boolean;
/** The viewer edits the whole archive: may join a club's names ("Juntar nomes"). */
canManage?: boolean;
/** The viewer edits on the cloud: sees the suggestions waiting for confirmation. */
@@ -144,6 +147,9 @@ export function Browse({
};
}, [tab, sourceId, token, guard, attempt, teamsTry, peopleTick, peopleSeason]);
// Another filter: back to the tournaments' tiles.
useEffect(() => setOpenGroup(null), [kind, season, sort, q, team, player]);
/** Joins (or parts) club names, then reads people and teams again. */
const joinClubs = (path: "merge" | "unmerge", body: unknown, done: string) => {
setJoinNote(null);
@@ -493,6 +499,7 @@ export function Browse({
<>
<div className="arq-people-head">
<h1 className="arq-disp arq-h1">Pessoas</h1>
{fpa && canReview && <LicenceAdd sourceId={sourceId} token={token} onPerson={onPerson} onExpired={onExpired} />}
{!!people?.seasons?.length && (
<label className="arq-filter">
<span>Época</span>
@@ -744,3 +751,93 @@ export function Browse({
</>
);
}
/**
* Adds someone by their handball federation licence (CIPA): who the federation says it is (name, photo, every
* registration), then the person, with the licence photo to be recognised by. For people events show who no match
* report names: coaches of other years, delegates, staff.
*/
function LicenceAdd({ sourceId, token, onPerson, onExpired }: { sourceId: string; token: string; onPerson: (id: string) => void; onExpired: () => void }) {
const [open, setOpen] = useState(false);
const [licence, setLicence] = useState("");
const [found, setFound] = useState<{ member: FpaCard; person: { id: string; name: string } | null } | null>(null);
const [state, setState] = useState<"idle" | "looking" | "adding" | "missing" | "failed">("idle");
const look = (e: React.FormEvent) => {
e.preventDefault();
const n = licence.trim();
if (!/^\d{3,9}$/.test(n)) return setState("missing");
setState("looking");
setFound(null);
call<{ member: FpaCard; person: { id: string; name: string } | null }>(`/v1/archive/${sourceId}/fpa/${n}`, token).then(
({ body }) => {
setFound(body);
setState("idle");
},
(err) => (err instanceof Unauthorised ? onExpired() : setState(String(err?.message) === "404" ? "missing" : "failed")),
);
};
const add = () => {
if (!found) return;
setState("adding");
addFromLicence(sourceId, token, found.member.licence).then(
(p) => onPerson(p.id),
(err) => (err instanceof Unauthorised ? onExpired() : setState("failed")),
);
};
if (!open)
return (
<button type="button" className="arq-btn ghost" onClick={() => setOpen(true)}>
Adicionar pela licença FPA
</button>
);
return (
<div className="arq-licence">
<form onSubmit={look} className="arq-licence-form">
<label>
<span className="arq-sr">Número de licença (CIPA)</span>
<input inputMode="numeric" value={licence} onChange={(e) => setLicence(e.target.value.replace(/\D/g, ""))} placeholder="Nº de licença (CIPA)" autoFocus />
</label>
<button type="submit" className="arq-btn" disabled={state === "looking"}>
{state === "looking" ? "A procurar…" : "Procurar"}
</button>
<button type="button" className="arq-link" onClick={() => (setOpen(false), setFound(null), setState("idle"))}>
Fechar
</button>
</form>
{state === "missing" && <p className="arq-muted">A federação não tem ninguém com esse número.</p>}
{state === "failed" && <p className="arq-muted">Não foi possível falar com a federação. Tenta outra vez.</p>}
{found && (
<div className="arq-licence-card">
<PersonFace p={{ reference: found.member.photo, face: null, name: found.member.name }} size={88} round={false} />
<div>
<strong>{found.member.name}</strong>
<small className="arq-muted">
Licença {found.member.licence}
{found.member.role ? ` · ${found.member.role}` : ""}
{found.member.club ? ` · ${found.member.club}` : ""}
</small>
{found.member.history.length > 0 && (
<ul>
{found.member.history.map((h) => (
<li key={h}>{h}</li>
))}
</ul>
)}
{found.person ? (
<button type="button" className="arq-btn" onClick={() => onPerson(found.person!.id)}>
Já está no arquivo: ver {found.person.name}
</button>
) : (
<button type="button" className="arq-btn accent" disabled={state === "adding"} onClick={add}>
{state === "adding" ? "A adicionar…" : "Adicionar ao arquivo"}
</button>
)}
<small className="arq-muted">A foto da licença passa a ser a referência para o reconhecimento facial.</small>
</div>
</div>
)}
</div>
);
}
@@ -0,0 +1,261 @@
"use client";
import { useEffect, useMemo, useState } from "react";
import { asJpeg } from "../../../lib/asJpeg";
import { SelfieCamera } from "../../../lib/SelfieCamera";
import { day, download, Forbidden, LEVEL, Unauthorised, type FindByPhotoResult, type Level, type Me, type PhotoFace } from "./api";
import { Lightbox } from "./Lightbox";
import { Icon } from "./parts";
/**
* Internal search for editors on the cloud: upload a photo of a person and find that face across the archive
* (folders they may see). The photo is not kept. Used by the news desk (FPA and similar).
*/
export function FindByPhoto({
sourceId,
token,
me,
onClose,
onExpired,
onPerson,
onGallery,
onFace,
}: {
sourceId: string;
token: string;
me: Me;
onClose: () => void;
onExpired: () => void;
onPerson: (id: string) => void;
onGallery: (id: string) => void;
onFace: (id: string) => void;
}) {
const [busy, setBusy] = useState(false);
const [error, setError] = useState<string | null>(null);
const [file, setFile] = useState<File | null>(null);
const [result, setResult] = useState<FindByPhotoResult | null>(null);
const [only, setOnly] = useState<Level | null>(null);
const [index, setIndex] = useState<number | null>(null);
const [camera, setCamera] = useState(false);
// Start the face engine while the editor is on this page, so the first upload does not wait on model load.
useEffect(() => {
void fetch(`/v1/archive/${sourceId}/find/ready`, { headers: { authorization: `Archive ${token}` } }).catch(() => undefined);
}, [sourceId, token]);
const search = async (next: File, face = 0) => {
setBusy(true);
setError(null);
setOnly(null);
setIndex(null);
try {
// Phones (esp. iPhone) often hand over HEIC; the API only reads JPEG/PNG/WebP. Decode here and send JPEG.
const jpeg = await asJpeg(next);
setFile(jpeg);
const form = new FormData();
form.append("file", jpeg, "foto.jpg");
const res = await fetch(`/v1/archive/${sourceId}/find${face ? `?face=${face}` : ""}`, {
method: "POST",
body: form,
headers: { authorization: `Archive ${token}` },
});
const body = (await res.json().catch(() => ({}))) as FindByPhotoResult & { error?: string };
if (!res.ok) {
if (res.status === 401) {
onExpired();
return;
}
if (res.status === 403) throw new Forbidden();
const msg: Record<string, string> = {
no_face: "Não encontrámos nenhuma cara nessa foto. Experimenta uma com a cara de frente e bem iluminada.",
not_an_image: "Esse ficheiro não é uma foto. Tira outra ou escolhe um JPEG da galeria.",
find_unavailable: "A procura por foto não está disponível neste arquivo.",
archive_edit_required: "Só quem edita pastas na cloud pode usar esta procura.",
engine_unavailable: "O reconhecimento de caras não está disponível de momento. Tenta daqui a pouco.",
rate_limited: "Muitas pesquisas seguidas. Tenta daqui a um minuto.",
};
setError(msg[body.error ?? ""] ?? "Não foi possível pesquisar agora.");
setResult(null);
return;
}
setResult(body);
} catch (err) {
if (err instanceof Unauthorised) onExpired();
else if (err instanceof Forbidden) setError("Só quem edita pastas na cloud pode usar esta procura.");
else if (err instanceof Error && err.message === "convert_failed")
setError("Não conseguimos ler essa foto. Tira outra com a câmara ou escolhe um JPEG da galeria.");
else setError("Não foi possível pesquisar agora. Confirma a rede e tenta outra vez.");
setResult(null);
} finally {
setBusy(false);
}
};
const counts = useMemo(() => {
const c: Record<Level, number> = { confirmed: 0, probable: 0, similar: 0 };
for (const p of result?.photos ?? []) if (p.level) c[p.level]++;
return c;
}, [result]);
const photos = useMemo(() => (result ? (only ? result.photos.filter((p) => p.level === only) : result.photos) : []), [result, only]);
const person = result?.identity ?? result?.people[0] ?? null;
const licence = person && "licence" in person ? (person.licence ?? null) : null;
const rememberFaces = (photoId: string, faces: PhotoFace[] | undefined) => {
setResult((cur) => (cur ? { ...cur, photos: cur.photos.map((p) => (p.id === photoId ? { ...p, faces } : p)) } : cur));
};
return (
<div className="arq-wrap arq-body">
<nav className="arq-crumbs" aria-label="Caminho">
<button type="button" onClick={onClose}>
<Icon name="back" size={16} />
Voltar
</button>
</nav>
<section style={{ display: "flex", flexDirection: "column", gap: 12, marginBottom: 20 }}>
<span className="arq-badge">Procura por foto</span>
<h1 className="arq-disp" style={{ margin: 0 }}>
Encontrar fotos de uma pessoa
</h1>
<p className="arq-muted" style={{ margin: 0, maxWidth: 560 }}>
Carrega uma fotografia com a cara bem visível (retrato, recorte de imprensa). Mostramos as fotos do arquivo em que essa pessoa aparece. A foto só serve para esta pesquisa: não fica guardada.
</p>
<div style={{ display: "flex", flexWrap: "wrap", gap: 10, alignItems: "center" }}>
<button type="button" className="arq-btn" disabled={busy} aria-busy={busy} onClick={() => setCamera(true)}>
{busy ? "A procurar…" : "Tirar foto"}
</button>
<label className="arq-link" style={{ cursor: busy ? "wait" : "pointer", position: "relative" }}>
{result ? "Outra da galeria" : "Escolher da galeria"}
<input
type="file"
accept="image/*,.heic,.heif"
style={{ position: "absolute", inset: 0, width: "100%", height: "100%", opacity: 0, cursor: "pointer" }}
disabled={busy}
onChange={(e) => {
const f = e.target.files?.[0];
if (f) void search(f);
e.target.value = "";
}}
/>
</label>
{result && result.faces.length > 1 && file && (
<button type="button" className="arq-link" disabled={busy} onClick={() => void search(file, (result.used + 1) % result.faces.length)}>
Há {result.faces.length} caras — usar a {((result.used + 1) % result.faces.length) + 1}.ª
</button>
)}
</div>
{error && (
<p role="alert" className="arq-muted" style={{ color: "#b00020", margin: 0 }}>
{error}
</p>
)}
</section>
{result && (
<>
<div style={{ display: "flex", flexWrap: "wrap", gap: 16, alignItems: "center", marginBottom: 12 }}>
{person && (
<p style={{ margin: 0 }}>
{result.via === "registry" ? "Ficha FPA: " : "Mais parecido: "}
<button type="button" className="arq-link" onClick={() => onPerson(person.id)}>
{person.name}
</button>
{person.club ? ` · ${person.club}` : ""}
{licence ? ` · CIPA ${licence}` : person.number ? ` · #${person.number}` : ""}
</p>
)}
<div className="arq-stats" style={{ marginLeft: "auto" }}>
<span>
<b>{result.total}</b>
<small>fotos</small>
</span>
{(Object.keys(LEVEL) as Level[]).map((l) =>
counts[l] ? (
<span key={l}>
<b>{counts[l]}</b>
<small>{LEVEL[l]}</small>
</span>
) : null,
)}
</div>
</div>
{result.total > 0 && (
<div className="arq-pills scroll" role="group" aria-label="Mostrar" style={{ marginBottom: 12 }}>
<button type="button" className="arq-pill" aria-pressed={only === null} onClick={() => setOnly(null)}>
Todas <span className="arq-n">{result.photos.length}</span>
</button>
{(Object.keys(LEVEL) as Level[])
.filter((l) => counts[l] > 0)
.map((l) => (
<button key={l} type="button" className="arq-pill" aria-pressed={only === l} onClick={() => setOnly(only === l ? null : l)}>
{LEVEL[l]} <span className="arq-n">{counts[l]}</span>
</button>
))}
</div>
)}
{!result.total ? (
<div className="arq-empty">Não encontrámos fotos desta cara nas pastas que podes ver.</div>
) : (
<div className="arq-grid">
{photos.map((p, i) => (
<button key={p.id} type="button" className="arq-tile" onClick={() => setIndex(i)} aria-label={p.gallery?.title ?? p.name}>
{/* eslint-disable-next-line @next/next/no-img-element */}
<img src={p.thumb} alt="" loading={i < 12 ? "eager" : "lazy"} decoding="async" />
{p.level && (
<span className={`arq-badge ${p.level === "confirmed" ? "ok" : p.level === "probable" ? "maybe" : "sim"}`}>
{LEVEL[p.level]}
{p.level === "similar" && p.score ? ` ${Math.round(p.score * 100)}%` : ""}
</span>
)}
<span className="arq-names">
<span>{[p.gallery?.title, p.gallery?.startsAt ? day.format(new Date(p.gallery.startsAt)) : null].filter(Boolean).join(" · ")}</span>
</span>
</button>
))}
</div>
)}
</>
)}
{camera && (
<SelfieCamera
onCancel={() => setCamera(false)}
onShot={(shot) => {
setCamera(false);
void search(shot);
}}
/>
)}
{index !== null && photos[index] && (
<Lightbox
photos={photos}
index={index}
onIndex={setIndex}
token={token}
onLoaded={rememberFaces}
onFace={onFace}
onPerson={onPerson}
review={me.canReview ? { sourceId, onDone: () => undefined } : undefined}
onDownload={(photoId) => void download(sourceId, token, { photoIds: [photoId] }).catch((err) => (err instanceof Unauthorised ? onExpired() : undefined))}
extra={(p) =>
p.gallery ? (
<>
<span className="arq-label">Galeria</span>
<span>
<button type="button" className="arq-link" onClick={() => onGallery(p.gallery!.id)}>
{p.gallery.title}
</button>
</span>
</>
) : null
}
/>
)}
</div>
);
}
Loaded 100 of 116 files, more files were not shown because too many files have changed in this diff. Show more