Compare commits

..
Author SHA1 Message Date
spark cb2b887a48 Add a Cloud W17 destination beside Cloud M19 for the women's under-17 games.
ci / rust (pull_request) Successful in 5m1s
ci / typescript (pull_request) Successful in 11m4s
It uses the organisation's existing FPA Nextcloud account and sends into Seleções Nacionais/W17, only when the photographer picks it.
2026-11-27 19:08:09 +00:00
spark 413983a057 Merge pull request 'List each under-17 EHF match once' (#314) from task/w17-fold-friendly into main
ci / rust (push) Successful in 4m7s
ci / typescript (push) Successful in 9m42s
2026-11-27 15:30:58 +00:00
spark 30b30ef122 Fold the under-17 friendly into the official EHF match so Portugal–Italy is listed once.
ci / rust (pull_request) Successful in 4m9s
ci / typescript (pull_request) Successful in 9m50s
The FPA camp and the EHF page were storing the same kick-off as two fixtures. An event already opened on the friendly stays on the one row.
2026-11-27 15:14:26 +00:00
spark 2fad6e96c3 Merge pull request 'Import the women's under-17 EHF EURO qualification' (#313) from task/w17-ehf-euro into main
ci / rust (push) Successful in 4m13s
ci / typescript (push) Successful in 9m47s
2026-11-27 14:33:30 +00:00
spark ae6e467103 Import the women's under-17 EHF EURO qualification so Portugal–Italy can be picked.
ci / rust (pull_request) Successful in 4m38s
ci / typescript (pull_request) Successful in 10m0s
The standing list was only the men's Euro Cup. Tonight's game is on the W17 page and never reached the event form.
2026-11-27 13:59:55 +00:00
spark 360dc5efb8 Sign in to ZeroZero again when publish returns 403
ci / rust (push) Successful in 5m52s
ci / typescript (push) Successful in 11m29s
A stale desk session answers 403. Sign in once more before accepting the refusal.
2026-11-26 22:33:59 +00:00
spark 92cecc7214 Merge pull request 'fix(delivery): idempotent retry when item leaves FAILED between render and click (BIT-33418)' (#312) from task/BIT-33418-retry-race-condition into main
ci / rust (push) Successful in 6m28s
ci / typescript (push) Successful in 11m55s
2026-11-26 22:31:41 +00:00
spark 0a845f8bc6 Sign in to ZeroZero again when publish returns 403.
ci / rust (pull_request) Successful in 6m44s
ci / typescript (pull_request) Successful in 12m48s
A stale desk session answers Insufficient permissions instead of 401. One fresh login is tried before that refusal is accepted.
2026-11-26 22:20:55 +00:00
paula-alves a9b7007d5d fix(delivery): idempotent retry when item leaves FAILED between render and click (BIT-33418)
ci / rust (pull_request) Successful in 7m10s
ci / typescript (pull_request) Successful in 12m3s
Race condition: between the desktop rendering a FAILED delivery row and the
user clicking "Repetir", the autopilot/queue worker can requeue, retry, or
retract the item. The retry endpoint's updateMany (where status=FAILED)
matched zero rows and threw notFound("failed_item_not_found") -> 404, and
the frontend promise had no .catch -> unhandledrejection -> error loop.

API: when the item no longer matches FAILED, fetch it; if it exists return
its current state (200, idempotent), only 404 when the row is gone.
Frontend: add a rejection handler that reloads the list so a stale FAILED
row refreshes instead of becoming an unhandled rejection.

Paperclip-BIT-33418
2026-11-26 22:19:13 +00:00
spark 56c115933c Do not fail a ZeroZero delivery when the account cannot publish.
ci / rust (pull_request) Successful in 4m10s
ci / typescript (pull_request) Successful in 11m13s
A photographer login may upload and still get 403 on photo-sync. The file is already on the desk, so that refusal is not a failed delivery.
2026-11-26 22:07:12 +00:00
spark 63b021cec8 Merge pull request 'Publish ZeroZero photos onto the public game after upload' (#310) from task/zerozero-publish-game into main
ci / rust (push) Successful in 4m23s
ci / typescript (push) Successful in 10m5s
2026-11-26 20:31:40 +00:00
spark 28f08bc5bc Publish ZeroZero photos onto the public game after upload.
ci / rust (pull_request) Successful in 4m15s
ci / typescript (pull_request) Successful in 10m36s
The desk keeps a file until photo-sync runs, so a delivery was done while the game stayed empty.
2026-11-26 20:11:48 +00:00
tiago-neves 7f44cba460 Merge pull request 'Desktop release builds open the local app and install their own updates (BIT-33402)' (#308) from task/BIT-33402-desktop-self-update into main
ci / rust (push) Successful in 4m10s
ci / typescript (push) Successful in 9m36s
desktop-release / build (deb,appimage, linux-x86_64, ubuntu-latest) (push) Failing after 11m15s
desktop-release / build (--target universal-apple-darwin, dmg,app, darwin-universal, macos) (push) Failing after 17m51s
desktop-release / build (, msi, windows-x86_64, windows) (push) Canceled after 0s
2026-11-26 15:25:05 +00:00
tiago-neves fcaa795b1d Merge branch 'main' into task/BIT-33402-desktop-self-update
ci / rust (pull_request) Successful in 11m45s
ci / typescript (pull_request) Successful in 15m6s
2026-11-26 15:09:48 +00:00
tiago-neves 6077a1062a Merge pull request 'fix(test): use date relative to now in ContextMenu event fixture (BIT-33405)' (#309) from task/BIT-33405-context-menu-date-flake into main
ci / rust (push) Successful in 11m52s
ci / typescript (push) Failing after 14m43s
2026-11-26 15:09:42 +00:00
spark e6b5f2e390 Let a Windows release, a Linux or Windows cable, and a future Developer ID join the desktop build.
ci / rust (pull_request) Successful in 11m45s
ci / typescript (pull_request) Failing after 14m55s
The installer job was waiting on a commented matrix row, USB stayed on Image Capture, face detection could not read the Windows CPU, and notarisation had nowhere to put an Apple account.
2026-11-26 15:09:36 +00:00
paula-alves 2a750ef916 fix(test): use date relative to now in ContextMenu event fixture (BIT-33405)
ci / rust (pull_request) Successful in 4m34s
ci / typescript (pull_request) Successful in 10m19s
The hardcoded startsAt 2026-11-21 fell outside EventsPanel RECENT_DAYS=4
window after 2026-11-25, collapsing the event under "Anteriores" and making
the test fail on every CI run. Derive startsAt, ingestFrom and ingestUntil
from Date.now() so the fixture stays inside the recent window regardless
of the run date.

Paperclip-Issue: BIT-33405
Paperclip-Agent: Bug Squasher (urlKey bug-squasher; id 4669adc7-6368-43ef-bf27-5a601a6b7b83)
2026-11-26 14:58:41 +00:00
spark 2a612a6f9a Keep a photo's arrival hash after it leaves the ingest folder.
ci / rust (pull_request) Successful in 4m9s
ci / typescript (pull_request) Failing after 9m40s
Filing rewrites the path, and a later caption change rewrites the hash. The index follows the filed file so the original can still be opened.
2026-11-26 14:45:06 +00:00
spark af63ea5673 Serve the installed interface from the app and let a release replace itself.
A production build was treated as development, so the window stayed on localhost:5173. Release builds now carry the updater key and install a newer signed shell on their own.
2026-11-26 14:45:06 +00:00
spark 452d84bff2 Merge pull request 'fix(shop): accept an order without a payment method (BIT-30361)' (#305) from task/BIT-30361-manual-payment into main
ci / rust (push) Successful in 4m24s
ci / typescript (push) Successful in 10m41s
2026-11-25 01:44:18 +00:00
paula-alves c75d4f81c3 Merge main so the autopilot suite sees a full-size frame.
ci / rust (pull_request) Successful in 7m6s
ci / typescript (pull_request) Successful in 12m43s
2026-11-25 01:31:06 +00:00
spark e731e48cb8 Merge pull request 'Define the full-frame size the autopilot tests record (BIT-33293)' (#307) from task/BIT-33293-autopilot-ci into main
ci / rust (push) Successful in 7m20s
ci / typescript (push) Successful in 12m53s
2026-11-25 01:30:42 +00:00
paula-alves 7372aff0ff Apply a learnt tighter crop when the body cut would take the feet.
ci / rust (pull_request) Successful in 4m10s
ci / typescript (pull_request) Successful in 10m47s
The recorded cut is refused so the player stays whole, and the scale is what still narrows the frame. The gallery tests get a longer budget now that each frame is actually planned.

Paperclip-Issue: BIT-33293
2026-11-25 01:19:33 +00:00
paula-alves d2b6f4383c Define the full-frame size the autopilot tests already record.
ci / rust (pull_request) Successful in 6m40s
ci / typescript (pull_request) Failing after 12m46s
The suite keeps a 600 px JPEG so it does not time out, and the planner reads 6000×4000. That clears the delivery floor, so focus still ranks a burst and a learnt crop stays tighter. Those names were used before they existed.

Paperclip-Issue: BIT-33293
2026-11-25 01:04:05 +00:00
David Santos c723b28c3a Autopilot tests: keep small files, record full-frame size (BIT-33293)
ci / rust (push) Successful in 7m0s
ci / typescript (push) Failing after 11m13s
Full-size JPEGs made the suite time out; the planner only reads photo.width/height.

Paperclip-Issue: BIT-33293
2026-11-25 01:01:45 +00:00
paula-alves cbd3f318d5 fix(shop): accept an order when no payment method is connected
ci / rust (pull_request) Successful in 4m18s
ci / typescript (pull_request) Failing after 8m42s
A buyer can still place the order. It stays unpaid until an admin records money collected out of band, and that admin is then responsible for delivering the work. No invoice goes out while invoicing is off.
2026-11-25 00:11:38 +00:00
spark ed9c382356 Merge pull request 'Keep Lightroom crops on the photograph aspect and send file edits back' (#304) from task/lightroom-roundtrip into main
ci / rust (push) Successful in 6m55s
ci / typescript (push) Failing after 10m8s
Keep a straightened crop on the photograph aspect and send Lightroom changes back.
2026-11-23 17:48:43 +00:00
spark 91bc9aefc7 Keep a straightened crop on the photograph's aspect and send Lightroom's changes back.
ci / rust (pull_request) Successful in 7m2s
ci / typescript (pull_request) Failing after 10m13s
Lightroom turns the stored corners around the crop centre, so writing the levelled rectangle made the crop Custom. The file now stores those corners, the original is found by its own hash, and edits already queued go out while the socket stays up.
2026-11-23 17:47:47 +00:00
spark 6ba556ba9f Merge pull request 'Write the newsroom metadata into the originals Lightroom imports' (#303) from task/lightroom-file-metadata into main
ci / rust (push) Successful in 7m8s
ci / typescript (push) Failing after 10m13s
2026-11-23 15:38:06 +00:00
spark f36da3408b Write the newsroom metadata into the originals Lightroom imports.
ci / rust (pull_request) Successful in 7m11s
ci / typescript (pull_request) Failing after 10m13s
The embed command was missing from the desktop permission list, so every write was refused. The write also looked up the preview hash, and a full mark history no longer fit in storage, so today's files stayed empty.
2026-11-23 15:37:31 +00:00
spark 0fa7c91366 Write Lightroom metadata onto the camera XMP description
ci / rust (push) Successful in 7m12s
ci / typescript (push) Failing after 9m57s
Stamp caption, title, keywords and creator on the camera XMP description Lightroom reads.
2026-11-23 14:40:26 +00:00
spark a9d89eae19 Write Lightroom metadata onto the camera XMP description.
ci / rust (pull_request) Successful in 7m16s
ci / typescript (pull_request) Failing after 10m23s
A metadata rescan reads the first description, and today's originals were never rewritten because earlier flushes waited behind the rest of the library.
2026-11-23 14:39:04 +00:00
spark 3db365452f Crop a clear person in reportage
ci / rust (push) Successful in 7m31s
ci / typescript (push) Failing after 10m29s
Crop a clear person in reportage instead of saying nobody was found.
2026-11-23 13:44:40 +00:00
spark 88cd74f5ff Crop a clear person in reportage instead of saying nobody was found.
ci / rust (pull_request) Successful in 7m40s
ci / typescript (pull_request) Failing after 10m47s
A single figure with empty floor — someone walking, a suitcase beside them — is the subject. The crop keeps the body and what they carry. A conversation, a distant figure, and a frame that is already full stay as shot.
2026-11-23 13:44:22 +00:00
spark 52fe4b67db Make disk XMP picks/edits reliable (BIT-33124)
ci / rust (push) Successful in 7m53s
ci / typescript (push) Failing after 11m28s
Make disk XMP picks and edits reliable on import (BIT-33124).
2026-11-23 13:14:30 +00:00
spark c922e21cc6 Make disk XMP picks and edits reliable on import (BIT-33124).
ci / rust (pull_request) Successful in 8m10s
ci / typescript (pull_request) Failing after 10m56s
Fix the API build (exactOptionalPropertyTypes), read JPEG sidecars, apply marks from the indexed original instead of the stripped preview, and re-reconcile watched files so Veneto-style imports keep picks and soft crops.
2026-11-23 13:14:09 +00:00
spark e77bbfcf53 Read disk XMP picks/edits into the library (BIT-33124)
ci / typescript (push) Failing after 2m8s
ci / rust (push) Successful in 8m28s
2026-11-23 12:59:41 +00:00
spark 5052fd5c92 Read pick, stars, colour and soft crop from disk XMP on import (BIT-33124).
ci / typescript (pull_request) Failing after 2m15s
ci / rust (pull_request) Successful in 8m29s
Local FTP and hand import used to ignore Lightroom/Photo Mechanic marks on
the original; server ingest only saw stars. Arrival and the desktop watcher
now apply xmpDM:pick, Rating, Label and crs:Crop into the library.
2026-11-23 12:59:24 +00:00
spark c9dc67b1eb Fix exactOptionalPropertyTypes for edgeClutter and rollAngle (BIT-32879).
ci / rust (push) Successful in 6m5s
ci / typescript (push) Failing after 9m55s
Unblocks API build so the main deploy can land the crop/learning changes.
2026-11-22 15:11:16 +00:00
spark 72bc65cf6e Tighten autopilot crop and burst framing (BIT-32879)
ci / typescript (push) Failing after 1m19s
ci / rust (push) Successful in 6m10s
2026-11-22 15:10:22 +00:00
88 changed files with 13032 additions and 335 deletions

No files matched your search

+51 -10
View File
@@ -1,8 +1,9 @@
name: desktop-release
# Tag `desktop-vX.Y.Z` builds the desktop installers and attaches them to a Gitea release.
# Linux builds on the standard runner. macOS (.dmg) builds on a Mac registered as a runner with the label "macos"
# (infra/desktop/macos-runner.sh, once); a release made while that Mac is off waits for it. Windows (.msi) needs a
# runner labelled "windows": register one, then uncomment its entry.
# (infra/desktop/macos-runner.sh, once); a release made while that Mac is off waits for it. Windows (.msi) builds
# on a runner labelled "windows" (Git bash, plus the WebView2 step). No Windows runner is registered yet, so a
# tag waits on that job until one is online. Notarisation runs only when the Apple secrets below are set.
#
# Self-updates (apps/desktop/src-tauri/src/updater.rs): with the secret TAURI_SIGNING_PRIVATE_KEY (and
# TAURI_SIGNING_PRIVATE_KEY_PASSWORD) and the variable TAURI_UPDATER_PUBKEY set (`tauri signer generate`), each job
@@ -14,6 +15,10 @@ on:
jobs:
build:
defaults:
run:
# Windows runners default to PowerShell. Git bash is what the rest of this job is written for.
shell: bash
strategy:
fail-fast: false
matrix:
@@ -25,9 +30,10 @@ jobs:
bundles: dmg,app
platform: darwin-universal
args: --target universal-apple-darwin
# - runner: windows
# bundles: msi
# platform: windows-x86_64
- runner: windows
bundles: msi
platform: windows-x86_64
args: ""
runs-on: ${{ matrix.runner }}
env:
VITE_API_URL: https://api.next.photoreport.pt
@@ -35,13 +41,23 @@ jobs:
PHOTOREPORT_UPDATER_PUBKEY: ${{ vars.TAURI_UPDATER_PUBKEY }}
TAURI_SIGNING_PRIVATE_KEY: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY }}
TAURI_SIGNING_PRIVATE_KEY_PASSWORD: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY_PASSWORD }}
# Empty until a Developer ID and an app-specific password (or an App Store Connect API key) are stored.
# Tauri notarises only when a full set is present; the install step drops blank values so a missing
# secret does not turn into a failed notarisation.
APPLE_SIGNING_IDENTITY: ${{ secrets.APPLE_SIGNING_IDENTITY }}
APPLE_ID: ${{ secrets.APPLE_ID }}
APPLE_PASSWORD: ${{ secrets.APPLE_PASSWORD }}
APPLE_TEAM_ID: ${{ secrets.APPLE_TEAM_ID }}
APPLE_API_ISSUER: ${{ secrets.APPLE_API_ISSUER }}
APPLE_API_KEY: ${{ secrets.APPLE_API_KEY }}
APPLE_API_KEY_PATH: ${{ secrets.APPLE_API_KEY_PATH }}
steps:
- uses: actions/checkout@v4
- name: System libraries (Linux)
if: runner.os == 'Linux'
run: |
sudo apt-get update
sudo apt-get install -y libwebkit2gtk-4.1-dev libayatana-appindicator3-dev librsvg2-dev libsecret-1-dev
sudo apt-get install -y libwebkit2gtk-4.1-dev libayatana-appindicator3-dev librsvg2-dev libsecret-1-dev libgphoto2-dev pkg-config
- uses: pnpm/action-setup@v4
- uses: actions/setup-node@v4
with:
@@ -68,6 +84,10 @@ jobs:
sleep 15
done
test "$ok" = 1
- name: WebView2 runtime (Windows)
if: runner.os == 'Windows'
shell: powershell
run: powershell -NoProfile -ExecutionPolicy Bypass -File infra/desktop/windows-webview2.ps1
- name: Both Mac processors (universal app)
if: runner.os == 'macOS'
run: rustup target add aarch64-apple-darwin x86_64-apple-darwin
@@ -82,11 +102,32 @@ jobs:
- name: Installers
shell: bash
run: |
# Blank Apple secrets must not look "set", or Tauri tries to notarise with an empty account.
for name in APPLE_SIGNING_IDENTITY APPLE_ID APPLE_PASSWORD APPLE_TEAM_ID APPLE_API_ISSUER APPLE_API_KEY APPLE_API_KEY_PATH; do
if [[ -z "${!name:-}" ]]; then
unset "$name"
fi
done
extra=()
# Signed updater artifacts only when the release key is there (a build without it still works).
# The bundler checks each signature against plugins.updater.pubkey, so the public key goes into the config too.
if [[ -n "$TAURI_SIGNING_PRIVATE_KEY" ]]; then
extra=(--config "$(node -e 'console.log(JSON.stringify({bundle:{createUpdaterArtifacts:true},plugins:{updater:{pubkey:process.env.PHOTOREPORT_UPDATER_PUBKEY}}}))')")
# Updater artifacts when the release key is there. A Developer ID also turns on the hardened
# runtime with the entitlements the bundled ONNX library needs, which is what notarisation requires.
config="$(node -e '
const bundle = {};
const plugins = {};
if (process.env.TAURI_SIGNING_PRIVATE_KEY) {
bundle.createUpdaterArtifacts = true;
plugins.updater = { pubkey: process.env.PHOTOREPORT_UPDATER_PUBKEY };
}
if (process.platform === "darwin" && process.env.APPLE_SIGNING_IDENTITY) {
bundle.macOS = { hardenedRuntime: true, entitlements: "entitlements.plist" };
}
const cfg = {};
if (Object.keys(bundle).length) cfg.bundle = bundle;
if (Object.keys(plugins).length) cfg.plugins = plugins;
if (Object.keys(cfg).length) process.stdout.write(JSON.stringify(cfg));
')"
if [[ -n "$config" ]]; then
extra=(--config "$config")
fi
pnpm --filter @photoreport/desktop exec tauri build --bundles ${{ matrix.bundles }} ${{ matrix.args }} "${extra[@]}"
- name: Update manifest
+11
View File
@@ -32,6 +32,17 @@ Read `docs/ARCHITECTURE.md` before any task. One task id per branch/PR (`task/BI
13. **Prefer Rust for local heavy work.** Detection, measure, level, develop and anything CPU-bound on the
desktop should live in `engine/` (native / WASM), not in ad-hoc TypeScript, when practical. TypeScript
orchestrates; Rust does the pixels and the scores. Safer, faster, one implementation with the workers.
14. **Start from the latest `origin/main`.** Paperclip, Claude Code and Cursor fetch and fast-forward this
checkout before editing. Do not leave the work only on an old branch or another folder. A pinned engine
revision is the LightCraft `rev` in the root `Cargo.toml`, not a stale checkout of this repo.
15. **The photograph's aspect is not a dial.** The autopilot and every automatic file write keep the original
aspect (`docs/photo-editing-rules.md`). A straightened crop is written as the corners Lightroom turns back
around the crop centre (`apps/app/src/desktop/lightroomCrop.ts`). Writing the levelled rectangle plus the
angle makes Lightroom show Custom. Do not invent another ratio to satisfy a framing rule.
16. **Lightroom round-trip is the file, not the catalog.** While the desktop app is open it reads crop, pick,
stars and colour back from the work-folder original and sends them to the server. Exposure and the other
develop sliders are written out and are not read back. A change that Lightroom has not written into the
file is invisible. Newsroom fields (caption, title, keywords, creator) go on the first `rdf:Description`.
## Porting from the old projects
+1 -1
View File
@@ -211,7 +211,7 @@ export class AutopilotService {
cropBias: style?.cropBias ?? null,
sport: photo.event?.sport ?? null,
lens: lensHintFromExif(photo.exif, photo.focalLength, photo.lens),
edgeClutter,
...(edgeClutter ? { edgeClutter } : {}),
settings,
});
const ops = planned.ops;
+56 -25
View File
@@ -14,12 +14,12 @@
* stays whole when that person stays in the crop. A crop that slices a ball is not a crop.
* - An open frame with a team in it stays open: the row is the subject, and the crop does not drop people out of it.
* - Cutting another sharp person in half is avoided; cutting blurred ones doesn't matter.
* - A generic event is reportage. The crop reads the shot the way a picture editor does, and trusts the
* framing: a long shot is the place, a full-length or a group whose bodies are whole stays as it was made,
* and a frame the camera already closed is only finished (mid-limb, a person already cut off at the edge
* left out). It is not zoomed to a sports fill. The space left around someone was left on purpose.
* A prime of 100mm or longer may step one notch closer on a single full-length, because it cannot zoom.
* A long shot and a group stay. That step stays centred on the photograph.
* - A generic event is reportage. One clear person is the subject, even with empty floor around them
* (someone walking, a suitcase beside them): the crop keeps the whole body and what they carry, and
* cuts that empty floor. It is not a sports fill. A conversation stays as framed. A distant figure
* (under about a fifth of the frame) is the place. A figure that already fills the frame stays.
* A frame the camera already closed is only finished (mid-limb). A person already cut off at the edge
* is left out.
* - "tight" is the agencies' handball look, and only with a ball in play: the subject fills the height, cut
* mid-shin or mid-thigh when the foot is already out. "full" keeps whole bodies when they fit.
*
@@ -60,6 +60,8 @@ export interface Detections {
height: number;
people: Detection[];
balls: Detection[];
/** Suitcase, handbag or backpack next to a person. Part of the subject, not scenery. */
carried?: Detection[];
}
export interface Composition {
@@ -344,19 +346,45 @@ function edgeAccident(p: Detection, tallest: number): boolean {
}
/**
* Reportage: the frame is the photograph. True when closing it would throw away a plan the camera finished.
* A person already cut off at the edge of a full-length is the exception: they are not the picture.
* A person shorter than this is scenery in a place, not who the photo is about.
* Taller than this, alone in the frame, they are the subject — a suitcase and empty floor do not hide them.
*/
function framedOnPurpose(inSubject: Detection[], others: Detection[]): boolean {
const CLEAR_PERSON = 0.22;
/**
* Reportage leaves the photograph when it is not one clear person with room around them.
* A conversation stays. A distant figure stays. A body that already fills the height stays.
* Someone the frame already cut off at the edge is not a reason to leave the rest.
*/
function leaveAsShot(inSubject: Detection[], others: Detection[]): boolean {
const intent = shotIntent(inSubject);
if (!intent) return false;
if (intent === "closed") return false;
if (intent === "scene") return true;
const tallest = Math.max(...inSubject.map(h));
for (const p of others) {
if (edgeAccident(p, tallest)) return false;
if (!intent || intent === "closed") return false;
const tallestPerson = inSubject.reduce((a, b) => (h(b) > h(a) ? b : a));
const tallest = h(tallestPerson);
if (others.some((p) => edgeAccident(p, tallest))) return false;
if (intent === "group") return true;
// Several people under half the frame: the place, or a wide shot. One person that size is the subject.
if (intent === "scene" && inSubject.length > 1) return true;
if (tallest < CLEAR_PERSON) return true;
if (tallestPerson.y0 <= 0.06 && tallestPerson.y1 >= 0.94) return true;
return false;
}
/** A bag or suitcase touching the person is part of the subject. One across the frame is not. */
function withCarried(box: Box, people: Detection[], carried: readonly Detection[] | undefined): Box {
if (!carried?.length) return box;
let out = box;
for (const item of carried) {
if (item.score < 0.35) continue;
let close = false;
for (const p of people) {
const gapX = Math.max(0, Math.max(p.x0, item.x0) - Math.min(p.x1, item.x1));
const gapY = Math.max(0, Math.max(p.y0, item.y0) - Math.min(p.y1, item.y1));
if (overlap(p, item) > 0 || (gapX < 0.12 && gapY < 0.15)) close = true;
}
if (close) out = union(out, item);
}
return true;
return out;
}
/**
@@ -562,14 +590,15 @@ export function compose(d: Detections, aspect: number | null = null, opts: Compo
const detected = reportage ? forReportage(d, faces) : d;
const found = findSubject(detected, opts.focus, { reportage, sport: opts.sport ?? null, faces });
if (!found) return null;
const { box: s, reason, people: inSubject, ball } = found;
const { reason, people: inSubject, ball } = found;
const s = withCarried(found.box, inSubject, d.carried);
const ratio = (aspect ?? d.width / d.height) * (d.height / d.width); // width/height in frame fractions
const tallest = Math.max(...inSubject.map(h));
const others = detected.people.filter((p) => p.score >= MIN_PERSON && !inSubject.includes(p));
// A long shot, a full-length, or a group the camera already finished. The margins are the picture.
// A long prime is the exception on one full-length: the lens could not zoom, so one step closer is allowed.
// A conversation, a distant figure, or a body that already fills the frame stays as shot.
// One clear person does not: empty floor and a suitcase are not "no subject".
const primeFigure = reportage && isLongPrime(opts.lens) && shotIntent(inSubject) === "figure";
if (reportage && framedOnPurpose(inSubject, others) && !primeFigure) return null;
if (reportage && leaveAsShot(inSubject, others)) return null;
// Zoom at the wide end: the photographer opened on purpose — do not reframe (level only later).
if (isWideZoomOpen(opts.lens)) return null;
const headroom = 0.04 * tallest;
@@ -620,9 +649,10 @@ export function compose(d: Detections, aspect: number | null = null, opts: Compo
if (cut) return finish(cut);
}
// Whole bodies, feet included. A little headroom gives way before a complete foot does.
const whole = frame(s, ratio, sole, headroom, tallest, others, inSubject, reason, minWidth, false, false, reportage, balls, primeFigure, lead, edgeClutter)
?? frame(s, ratio, sole, 0, tallest, others, inSubject, reason, minWidth, false, false, reportage, balls, primeFigure, lead, edgeClutter)
?? frame(s, ratio, s.y1, 0, tallest, others, inSubject, reason, minWidth, false, false, reportage, balls, primeFigure, lead, edgeClutter);
// One person: score a real crop (empty floor goes). Do not prefer the untouched frame.
const whole = frame(s, ratio, sole, headroom, tallest, others, inSubject, reason, minWidth, false, false, reportage, balls, primeFigure, lead, edgeClutter, false)
?? frame(s, ratio, sole, 0, tallest, others, inSubject, reason, minWidth, false, false, reportage, balls, primeFigure, lead, edgeClutter, false)
?? frame(s, ratio, s.y1, 0, tallest, others, inSubject, reason, minWidth, false, false, reportage, balls, primeFigure, lead, edgeClutter, false);
if (whole || feetIn) return finish(whole);
return finish(frame(s, ratio, s.y0 + MID_THIGH * tallest, headroom, tallest, others, inSubject, reason, minWidth, false, true, reportage, balls, false, lead, edgeClutter));
}
@@ -662,7 +692,7 @@ export function minCropWidth(width: number, height: number, minLongEdge = 2400):
return Math.min(1, Math.max(floor, minLongEdge / long) * (width >= height ? 1 : height / width));
}
function frame(s: Box, ratio: number, mustBottom: number, headroom: number, tallest: number, others: Detection[], inSubject: Detection[], reason: Composition["reason"], minWidth: number, tight = false, pinBottom = false, reportage = false, balls: readonly Box[] = [], closer = false, lead: -1 | 0 | 1 = 0, edgeClutter?: (rect: Box) => number): (Composition & { cost: number }) | null {
function frame(s: Box, ratio: number, mustBottom: number, headroom: number, tallest: number, others: Detection[], inSubject: Detection[], reason: Composition["reason"], minWidth: number, tight = false, pinBottom = false, reportage = false, balls: readonly Box[] = [], closer = false, lead: -1 | 0 | 1 = 0, edgeClutter?: (rect: Box) => number, holdFrame?: boolean): (Composition & { cost: number }) | null {
const mainSharp = Math.max(...inSubject.map(sharp));
const keep = requiredBox(s, inSubject);
let best: { rect: Box; cost: number } | null = null;
@@ -705,7 +735,8 @@ function frame(s: Box, ratio: number, mustBottom: number, headroom: number, tall
// A player the photographer left in the picture stays in it. Cutting them out, or through the body,
// is not a crop. Soft scenery may still go.
if (dropsPlayer(r, others, mainSharp, tallest)) continue;
const c = cost(r, s, others, ch, tallest, mainSharp, ratio, inSubject, tight, reportage, closer, lead, edgeClutter, minWidth) + jointCost(r, inSubject, others, mainSharp);
const stayWide = holdFrame ?? reportage;
const c = cost(r, s, others, ch, tallest, mainSharp, ratio, inSubject, tight, stayWide, closer, lead, edgeClutter, minWidth) + jointCost(r, inSubject, others, mainSharp);
if (!best || c < best.cost) best = { rect: r, cost: c };
}
}
+3 -2
View File
@@ -4,7 +4,7 @@ import * as ort from "onnxruntime-node";
import { modelsDir } from "../lib/models.js";
import sharp from "sharp";
import type { Detection, Detections } from "./compose.js";
import { BALL, PERSON, YOLOX_SIZE, decodeYolox, nmsKeep, sharpnessOf } from "./yolox.js";
import { BACKPACK, BALL, HANDBAG, PERSON, SUITCASE, YOLOX_SIZE, decodeYolox, nmsKeep, sharpnessOf } from "./yolox.js";
/**
* People and balls in a photo, with YOLOX-s (Apache-2.0, COCO classes; infra/faces/download-models.sh fetches it).
@@ -94,7 +94,8 @@ export class SubjectDetector {
const all = decodeYolox(raw, scale, width, height);
const people = nmsKeep(all.filter((d) => d.cls === PERSON));
await addSharpness(file, people);
return { width, height, people, balls: nmsKeep(all.filter((d) => d.cls === BALL)) };
const carried = nmsKeep(all.filter((d) => d.cls === BACKPACK || d.cls === HANDBAG || d.cls === SUITCASE));
return { width, height, people, balls: nmsKeep(all.filter((d) => d.cls === BALL)), carried };
}
}
+60 -6
View File
@@ -1,5 +1,6 @@
import { describe, expect, it } from "vitest";
import { keepPhotoAspect } from "./geometry.js";
import { frameScore } from "./compose.js";
import { cropTooHard, levelWithoutChopping, planFrame, type PlanSettings } from "./planFrame.js";
const settings: PlanSettings = {
@@ -55,12 +56,46 @@ describe("planFrame", () => {
expect(crop.params.aspect).toEqual([6000, 4000]);
});
it("does not close a reportage frame the camera left open, even when matches are cropped tight", () => {
it("on a full-size file ranks the sharper frame and keeps a learnt crop tighter", () => {
const person = { x0: 0.42, y0: 0.2, x1: 0.58, y1: 0.85, score: 0.9, sharpness: 1 };
const at = (focus: number) => ({
detections: { width: 600, height: 400, people: [{ ...person, focus }], balls: [] as [] },
width: 6000,
height: 4000,
reportage: false,
values: { "light.exposure": 0.2, "light.contrast": 10 },
angle: 1.5,
settings: { ...settings, toneStrength: 0.5, framing: "full" as const, minLongEdge: 2400 },
});
const soft = planFrame(at(100));
const sharp = planFrame(at(900));
expect(soft.composition).not.toBeNull();
expect(sharp.composition).not.toBeNull();
expect(frameScore(at(900).detections, sharp.composition)).toBeGreaterThan(frameScore(at(100).detections, soft.composition));
const widthOf = (planned: ReturnType<typeof planFrame>) => {
const crop = planned.ops.find((op) => op.command === "crop.set");
if (!crop || crop.command !== "crop.set") return 1;
return crop.params.rect.x1 - crop.params.rect.x0;
};
const plain = widthOf(planFrame(at(300)));
const learnt = widthOf(planFrame({ ...at(300), cropFactor: 0.84 }));
expect(learnt).toBeLessThan(plain);
// A uniform shrink is stored as a body cut. If that cut would take the feet, the scale still applies.
const fromCut = widthOf(planFrame({
...at(300),
cropFactor: 0.84,
cropBias: { dx: 0, dy: 0, scale: 0.84, dAngle: 0, cut: 0.935, head: 0.067, sides: 0 },
}));
expect(fromCut).toBeLessThan(plain);
});
it("crops one clear person in reportage and ignores a learnt sports cut", () => {
const person = { x0: 0.35, y0: 0.28, x1: 0.52, y1: 0.72 };
const planned = planFrame({
detections: {
width: 6000,
height: 4000,
people: [{ x0: 0.35, y0: 0.28, x1: 0.52, y1: 0.72, score: 0.9, sharpness: 1 }],
people: [{ ...person, score: 0.9, sharpness: 1 }],
balls: [],
},
width: 6000,
@@ -71,7 +106,17 @@ describe("planFrame", () => {
cropBias: { dx: 0, dy: 0, scale: 0.8, dAngle: 0, cut: 0.5, head: 0.02, sides: 0.1 },
settings,
});
expect(planned.ops.some((op) => op.command === "crop.set")).toBe(false);
const crop = planned.ops.find((op) => op.command === "crop.set");
expect(crop?.command).toBe("crop.set");
if (!crop || crop.command !== "crop.set") return;
const rect = crop.params.rect;
expect(rect.x0).toBeLessThanOrEqual(person.x0);
expect(rect.x1).toBeGreaterThanOrEqual(person.x1);
expect(rect.y0).toBeLessThanOrEqual(person.y0);
expect(rect.y1).toBeGreaterThan(person.y1);
expect(rect.x1 - rect.x0).toBeLessThan(0.92);
// The learnt match cut (half the body) must not land on this photograph.
expect(rect.y1).toBeGreaterThan(person.y0 + 0.7 * (person.y1 - person.y0));
});
it("does not apply a learnt cut that chops a player the crop had kept", () => {
@@ -98,12 +143,13 @@ describe("planFrame", () => {
expect(crop.params.rect.x1).toBeGreaterThanOrEqual(0.62);
});
it("does not close a reportage full-length the camera already composed", () => {
it("crops a reportage full-length that still has empty floor around the person", () => {
const person = { x0: 0.3, y0: 0.12, x1: 0.48, y1: 0.82 };
const planned = planFrame({
detections: {
width: 6000,
height: 4000,
people: [{ x0: 0.3, y0: 0.12, x1: 0.48, y1: 0.82, score: 0.9, sharpness: 1 }],
people: [{ ...person, score: 0.9, sharpness: 1 }],
balls: [],
},
width: 6000,
@@ -113,7 +159,15 @@ describe("planFrame", () => {
angle: 0,
settings,
});
expect(planned.ops.some((op) => op.command === "crop.set")).toBe(false);
const crop = planned.ops.find((op) => op.command === "crop.set");
expect(crop?.command).toBe("crop.set");
if (!crop || crop.command !== "crop.set") return;
const rect = crop.params.rect;
expect(rect.y0).toBeLessThanOrEqual(person.y0);
expect(rect.y1).toBeGreaterThan(person.y1);
expect(rect.x0).toBeLessThanOrEqual(person.x0);
expect(rect.x1).toBeGreaterThanOrEqual(person.x1);
expect(rect.x1 - rect.x0).toBeLessThan(0.92);
});
it("reduces the straighten angle when leveling would chop the subject's feet", () => {
+3 -1
View File
@@ -210,9 +210,11 @@ export function planFrame(input: {
}
if (bias && typeof bias.cut === "number") {
// The photographer's cut on the body (legs, head, arms), not a uniform shrink.
// It must not chop a player this photograph had kept whole.
// It must not chop a player this photograph had kept whole. When the cut would,
// the scale still applies: a tighter frame that keeps the player inside.
const placed = frameOnSubject(composition.rect, composition.subject, bias);
if (!chopsKeptPlayer(composition.rect, placed, composition.subject)) rect = placed;
else if (factor && factor !== 1) rect = factor < 1 ? tighter(composition.rect, composition.subject, factor) : biasCrop(composition.rect, composition.subject, { dx: bias.dx, dy: bias.dy, scale: factor });
if (bias.dx) {
const w = rect.x1 - rect.x0;
const x0 = Math.min(Math.max(0, rect.x0 + bias.dx), 1 - w);
+10 -2
View File
@@ -11,7 +11,7 @@ import { modelsDir } from "../lib/models.js";
import type { LocalStorage } from "../storage/storage.js";
import { readFocusPoint } from "../ingest/exif.js";
import { focusFromExifJson } from "../ingest/focus.js";
import { compose, isReportage } from "./compose.js";
import { compose, findSubject, isReportage } from "./compose.js";
import { lazyDetector } from "./detect.js";
const Params = z.object({ photoId: z.uuid() });
@@ -51,7 +51,15 @@ export async function registerCompositionRoutes(app: FastifyInstance, deps: { db
const original = photo.originalStored ? storage.resolve(photo.storageKey) : preview;
const focus = focusFromExifJson(photo.exif) ?? (existsSync(original) ? await readFocusPoint(original) : null);
const context = isReportage(photo.event) ? "reportage" : "sport";
return { crop: compose(detections, aspect ? aspect[0] / aspect[1] : null, { focus, context, faces: photo.faces, sport: photo.event?.sport ?? null }) };
const faces = photo.faces;
const sport = photo.event?.sport ?? null;
const crop = compose(detections, aspect ? aspect[0] / aspect[1] : null, { focus, context, faces, sport });
let found = crop != null;
if (!found) {
const subject = findSubject(detections, focus, { reportage: context === "reportage", sport, faces });
found = subject != null;
}
return { crop, found };
});
/** YOLOX-s, so the desktop can crop with the same detector. Not a face model: no biometrics gate. */
+7 -2
View File
@@ -1,10 +1,15 @@
import type { Detection } from "./compose.js";
/** YOLOX-s input. People are COCO class 0, the sports ball is class 32. */
/** YOLOX-s input. People are COCO class 0, the sports ball is class 32. Bags travel with the person. */
export const YOLOX_SIZE = 640;
export const PERSON = 0;
export const BACKPACK = 24;
export const HANDBAG = 26;
export const SUITCASE = 28;
export const BALL = 32;
const WANTED = [PERSON, BALL, BACKPACK, HANDBAG, SUITCASE];
export interface RawDet extends Detection {
cls: number;
}
@@ -23,7 +28,7 @@ export function decodeYolox(raw: Float32Array, scale: number, width: number, hei
const o = a * stride;
const obj = raw[o + 4]!;
if (obj < 0.1) continue;
for (const cls of [PERSON, BALL]) {
for (const cls of WANTED) {
const score = obj * raw[o + 5 + cls]!;
if (score < 0.25) continue;
const bx = (raw[o]! + x) * s;
+28 -6
View File
@@ -4,13 +4,19 @@ import type { Db } from "../db.js";
/** The destination photographers pick to send an under-19 national game to the FPA cloud. */
export const CLOUD_M19_TARGET = "Cloud M19";
/** The same kind of destination for the women's under-17 side. */
export const CLOUD_W17_TARGET = "Cloud W17";
/**
* One Nextcloud destination per organisation that already delivers club games to cloud.photoreport.pt.
* Same account and file name as that destination; the folder is Seleções Nacionais/M19.
* Same account and file name as that destination; the folder is under Seleções Nacionais.
* It does not send on arrival: the photographer chooses it for this game.
* Returns how many destinations were created.
*/
export async function ensureCloudM19Target(db: Db): Promise<number> {
async function ensureNationalCloudTarget(
db: Db,
target: { name: string; folder: string; fileName: string },
): Promise<number> {
const sources = await db.deliveryTarget.findMany({
where: {
kind: "NEXTCLOUD",
@@ -31,21 +37,21 @@ export async function ensureCloudM19Target(db: Db): Promise<number> {
if (seen.has(source.organizationId)) continue;
seen.add(source.organizationId);
const exists = await db.deliveryTarget.findUnique({
where: { organizationId_name: { organizationId: source.organizationId, name: CLOUD_M19_TARGET } },
where: { organizationId_name: { organizationId: source.organizationId, name: target.name } },
select: { id: true },
});
if (exists) continue;
await db.deliveryTarget.create({
data: {
organizationId: source.organizationId,
name: CLOUD_M19_TARGET,
name: target.name,
kind: source.kind,
baseUrl: source.baseUrl,
username: source.username,
secretEnc: source.secretEnc,
hostFingerprint: source.hostFingerprint,
folderTemplate: DESTINATION_EXAMPLES.fpaM19.folder,
fileNameTemplate: source.fileNameTemplate || DESTINATION_EXAMPLES.fpaM19.fileName,
folderTemplate: target.folder,
fileNameTemplate: source.fileNameTemplate || target.fileName,
longEdge: source.longEdge,
jpegQuality: source.jpegQuality,
sharpen: source.sharpen,
@@ -64,3 +70,19 @@ export async function ensureCloudM19Target(db: Db): Promise<number> {
}
return created;
}
export function ensureCloudM19Target(db: Db): Promise<number> {
return ensureNationalCloudTarget(db, {
name: CLOUD_M19_TARGET,
folder: DESTINATION_EXAMPLES.fpaM19.folder,
fileName: DESTINATION_EXAMPLES.fpaM19.fileName,
});
}
export function ensureCloudW17Target(db: Db): Promise<number> {
return ensureNationalCloudTarget(db, {
name: CLOUD_W17_TARGET,
folder: DESTINATION_EXAMPLES.fpaW17.folder,
fileName: DESTINATION_EXAMPLES.fpaW17.fileName,
});
}
+7 -2
View File
@@ -392,8 +392,13 @@ export async function registerDeliveryRoutes(
where: { id: itemId, organizationId: orgId, status: "FAILED" },
data: { status: "QUEUED", attempts: 0, nextAttemptAt: new Date(), lastError: null },
});
if (!result.count) throw notFound("failed_item_not_found");
return toItemSummary(await db.deliveryItem.findUniqueOrThrow({ where: { id: itemId } }));
if (result.count) return toItemSummary(await db.deliveryItem.findUniqueOrThrow({ where: { id: itemId } }));
// Race: the item was no longer FAILED between the render and the retry (autopilot/queue worker
// requeued, retried, or retracted it). The retry is idempotent — return the current state instead
// of a 404, so the desktop does not unhandledrejection into the error loop (BIT-33418).
const current = await db.deliveryItem.findUnique({ where: { id: itemId } });
if (!current) throw notFound("item_not_found");
return toItemSummary(current);
});
/** ZeroZero: the event's game on the photo desk (chosen, or found by teams and time). */
+1
View File
@@ -175,6 +175,7 @@ export class ZerozeroTransport implements Transport {
const account = await this.client.login();
const author = meta?.author?.trim() || account.name || "PhotoReport";
const imageId = await this.client.upload(gameId, fileName, data, author);
await this.client.publish(gameId, imageId);
return `${gameId}/${imageId}`;
});
}
+145
View File
@@ -1,6 +1,45 @@
import { describe, expect, it } from "vitest";
import { TransportError } from "./transports.js";
import { ZerozeroClient } from "./zerozero.js";
/**
* A desk that is already willing to sign the client in, and answers photo-sync however the test says.
* Login is the real OAuth dance; only the publish routes vary.
*/
function desk(publish: (pathname: string) => Response): typeof fetch {
return async (input, init) => {
const url = new URL(String(input));
const method = init?.method ?? "GET";
const cookie = new Headers(init?.headers).get("cookie") ?? "";
const has = (name: string) => cookie.split(/;\s*/).some((part) => part.startsWith(`${name}=`));
if (url.hostname === "www.zerozero.pt" && url.pathname === "/oauth.php") {
if (has("zzuser")) {
return new Response(null, {
status: 302,
headers: { location: "https://fotos.zerozero.pt/api/auth/callback?code=c&state=s" },
});
}
return new Response("login", { status: 200, headers: { "set-cookie": "PHPSESSID=s; Domain=.zerozero.pt" } });
}
if (url.hostname === "www.zerozero.pt" && url.pathname === "/ax_login.php" && method === "POST") {
return new Response(JSON.stringify({ status: true }), { headers: { "set-cookie": "zzuser=1; Domain=.zerozero.pt" } });
}
if (url.pathname === "/api/auth/login") {
return Response.json({ authURL: "https://www.zerozero.pt/oauth.php?response_type=code&state=s" });
}
if (url.pathname === "/api/auth/callback") {
return new Response(null, { status: 302, headers: { location: "https://fotos.zerozero.pt/", "set-cookie": "desk=ok; Path=/" } });
}
if (url.pathname === "/api/auth/me") {
if (!has("desk")) return Response.json({ error: "unauthorized" }, { status: 401 });
return Response.json({ role: "photographer", photographer_name: "Kapta+" });
}
if (url.pathname === "/") return new Response("desk", { status: 200 });
if (method === "POST" && url.pathname.startsWith("/api/photo-sync/")) return publish(url.pathname);
return new Response("no", { status: 404 });
};
}
describe("zerozero remove", () => {
it("never asks the desk to delete a \"synced-\" placeholder (a real image is taken back: test/delivery.test.ts)", async () => {
const calls: string[] = [];
@@ -14,3 +53,109 @@ describe("zerozero remove", () => {
expect(calls).toEqual([]);
});
});
describe("zerozero publish", () => {
it("publishes the one photo that was just uploaded", async () => {
const calls: string[] = [];
const client = new ZerozeroClient(
{ username: "kapta", password: "zz-pass" },
desk((pathname) => {
calls.push(pathname);
return Response.json({ synced: 1, failed: 0, failures: [] });
}),
);
await client.publish("12627743", "img-9");
expect(calls).toEqual(["/api/photo-sync/img-9"]);
});
it("publishes the game when the account cannot publish one photo", async () => {
const calls: string[] = [];
const client = new ZerozeroClient(
{ username: "kapta", password: "zz-pass" },
desk((pathname) => {
calls.push(pathname);
if (pathname.startsWith("/api/photo-sync/match/")) return Response.json({ synced: 1, failed: 0, failures: [] });
return Response.json({ error: "forbidden" }, { status: 403 });
}),
);
await client.publish("12627743", "img-9");
expect(calls).toEqual(["/api/photo-sync/img-9", "/api/photo-sync/img-9", "/api/photo-sync/match/12627743"]);
});
it("signs in again when publish answers insufficient permissions", async () => {
const calls: string[] = [];
let refused = false;
const client = new ZerozeroClient(
{ username: "kapta", password: "zz-pass" },
desk((pathname) => {
calls.push(pathname);
if (!refused && pathname === "/api/photo-sync/img-9") {
refused = true;
return Response.json({ error: "Insufficient permissions" }, { status: 403 });
}
return Response.json({ synced: 1, failed: 0, failures: [] });
}),
);
await client.publish("12627743", "img-9");
expect(calls).toEqual(["/api/photo-sync/img-9", "/api/photo-sync/img-9"]);
});
it("publishes the whole game when the desk has no single-photo publish", async () => {
const calls: string[] = [];
const client = new ZerozeroClient(
{ username: "kapta", password: "zz-pass" },
desk((pathname) => {
calls.push(pathname);
if (pathname === "/api/photo-sync/match/12627743") return Response.json({ synced: 1, failed: 0, failures: [] });
return new Response("missing", { status: 404 });
}),
);
await client.publish("12627743", "img-9");
expect(calls).toEqual(["/api/photo-sync/img-9", "/api/photo-sync/match/12627743"]);
});
it("publishes the game when the desk already had the file and there is no image id", async () => {
const calls: string[] = [];
const client = new ZerozeroClient(
{ username: "kapta", password: "zz-pass" },
desk((pathname) => {
calls.push(pathname);
return Response.json({ synced: 0, failed: 0, failures: [] });
}),
);
await client.publish("12627743", "synced-PS_jogo_1.jpg");
expect(calls).toEqual(["/api/photo-sync/match/12627743"]);
});
it("retries when the desk reports that this photo did not publish", async () => {
const client = new ZerozeroClient(
{ username: "kapta", password: "zz-pass" },
desk(() => Response.json({ synced: 0, failed: 1, failures: [{ id: "img-9", error: "desk busy" }] })),
);
const err = await client.publish("12627743", "img-9").then(
() => null,
(error: unknown) => error,
);
expect(err).toBeInstanceOf(TransportError);
expect((err as TransportError).message).toBe("zerozero publish: desk busy");
expect((err as TransportError).transient).toBe(true);
});
it("keeps the upload when the account is not allowed to publish", async () => {
const calls: string[] = [];
const client = new ZerozeroClient(
{ username: "kapta", password: "zz-pass" },
desk((pathname) => {
calls.push(pathname);
return Response.json({ error: "Insufficient permissions" }, { status: 403 });
}),
);
await client.publish("12627743", "img-9");
expect(calls).toEqual([
"/api/photo-sync/img-9",
"/api/photo-sync/img-9",
"/api/photo-sync/match/12627743",
"/api/photo-sync/match/12627743",
]);
});
});
+103 -2
View File
@@ -11,12 +11,16 @@ import { TransportError } from "./transports.js";
* Lisbon time).
* - Upload: tus 1.0 at `/api/upload?match_id=<id>`, metadata `match_id`, `artist` (the author shown with the photo)
* and the file name. The image's id is the upload's id; `DELETE /api/images/<id>` takes it back.
* - Publish: the upload only lands on the desk. The public game shows it after `POST /api/photo-sync/<image id>`
* (the desk's "send now"). When that route is missing, `POST /api/photo-sync/match/<id>` publishes the game.
*/
export const ZEROZERO_URL = "https://fotos.zerozero.pt";
const LOGIN_SITE = "https://www.zerozero.pt";
const CHUNK = 5 * 1024 * 1024;
const TIMEOUT_MS = 60_000;
/** Publishing pushes the file onwards to the public game, which is slower than one tus chunk. */
const PUBLISH_TIMEOUT_MS = 180_000;
export interface ZerozeroGame {
id: string;
@@ -104,7 +108,7 @@ export class ZerozeroClient {
) {}
/** One request with the jar's cookies; redirects followed by hand so every hop's cookies are kept. */
private async request(url: string, init: RequestInit = {}, hops = 10): Promise<{ res: Response; url: string }> {
private async request(url: string, init: RequestInit = {}, hops = 10, timeoutMs = TIMEOUT_MS): Promise<{ res: Response; url: string }> {
let current = url;
let options = init;
for (let i = 0; i <= hops; i++) {
@@ -114,7 +118,7 @@ export class ZerozeroClient {
if (!headers.has("user-agent")) headers.set("user-agent", "PhotoReport/2 (delivery)");
let res: Response;
try {
res = await this.fetchImpl(current, { ...options, headers, redirect: "manual", signal: AbortSignal.timeout(TIMEOUT_MS) });
res = await this.fetchImpl(current, { ...options, headers, redirect: "manual", signal: AbortSignal.timeout(timeoutMs) });
} catch (err) {
throw new TransportError(`zerozero: ${fetchFailure(err)}`, true);
}
@@ -263,6 +267,78 @@ export class ZerozeroClient {
return new URL(url).pathname.split("/").filter(Boolean).pop()!;
}
/**
* Puts an uploaded photo on the public game. The desk keeps it first (`sync_status` pending); without this call
* it never leaves the photographer's page. One photo when the desk allows it, otherwise the whole game.
* `synced-<file name>` is not an image id (the desk already had the file), so the game is published.
*/
async publish(gameId: string, imageId: string): Promise<void> {
const placeholder = imageId.startsWith("synced-");
if (!placeholder) {
const one = await this.postApi(`/photo-sync/${encodeURIComponent(imageId)}`, PUBLISH_TIMEOUT_MS);
// 404/405: this desk has no single-photo publish. 403: this account may still publish the game.
if (one.status !== 404 && one.status !== 405 && one.status !== 403) {
this.assertPublished(one, imageId);
return;
}
}
const match = await this.postApi(`/photo-sync/match/${encodeURIComponent(gameId)}`, PUBLISH_TIMEOUT_MS);
// A photographer account may upload but not publish ("Insufficient permissions"). The file is already on
// the desk; failing the delivery here only blocks the queue. The desk publishes those itself.
if (match.status === 403) return;
const ours = placeholder ? null : imageId;
this.assertPublished(match, ours);
}
private async postApi(path: string, timeoutMs: number, retry = true): Promise<{ status: number; body: unknown }> {
await this.login();
// The desk's own client posts JSON. An empty object is what "send now" sends when it has no extra fields.
const { res } = await this.request(
`${this.base}/api${path}`,
{
method: "POST",
headers: { "content-type": "application/json", accept: "application/json" },
body: "{}",
},
10,
timeoutMs,
);
// 401: logged out. 403 "Insufficient permissions": the cookie is still sent, but the session is no longer
// the photographer. One fresh sign-in. The same refusal after that is the account, not a stale login.
if (res.status === 401 && retry) {
this.account = null;
this.jar.clear();
return this.postApi(path, timeoutMs, false);
}
if (res.status === 403 && retry) {
this.account = null;
this.jar.clear();
return this.postApi(path, timeoutMs, false);
}
const text = await res.text();
let body: unknown = null;
if (text) {
try {
body = JSON.parse(text) as unknown;
} catch {
body = null;
}
}
return { status: res.status, body };
}
private assertPublished(result: { status: number; body: unknown }, imageId: string | null): void {
if (result.status >= 200 && result.status < 300) {
assertSyncBody(result.body, imageId);
return;
}
const detail = errorText(result.body);
const transient = result.status >= 500 || result.status === 429 || result.status === 404;
let message = `zerozero publish: ${result.status}`;
if (detail) message = `${message} ${detail}`;
throw new TransportError(message, transient);
}
/** Takes an uploaded image back. Already gone (or no longer this account's to remove) is not an error. */
async remove(imageId: string): Promise<void> {
// "synced-<file name>" (from `upload`, when the desk already had the file) is not a real image id: there was
@@ -275,6 +351,31 @@ export class ZerozeroClient {
}
}
function errorText(body: unknown): string | null {
if (!body || typeof body !== "object") return null;
const error = (body as { error?: unknown }).error;
if (typeof error !== "string" || !error) return null;
return error.replace(/\s+/g, " ").slice(0, 180);
}
function assertSyncBody(body: unknown, imageId: string | null): void {
if (!body || typeof body !== "object") return;
const record = body as { sync_status?: unknown; syncStatus?: unknown; failures?: unknown; error?: unknown };
const status = record.sync_status ?? record.syncStatus;
if (status === "failed") {
const message = typeof record.error === "string" && record.error ? record.error : "the desk could not publish the photo";
throw new TransportError(`zerozero publish: ${message}`, true);
}
if (!imageId || !Array.isArray(record.failures)) return;
for (const failure of record.failures) {
if (!failure || typeof failure !== "object") continue;
const row = failure as { id?: unknown; error?: unknown };
if (row.id !== imageId) continue;
const message = typeof row.error === "string" && row.error ? row.error : "the desk could not publish the photo";
throw new TransportError(`zerozero publish: ${message}`, true);
}
}
function toGame(r: Record<string, unknown> | null | undefined): ZerozeroGame | null {
if (!r) return null;
const s = (v: unknown) => (typeof v === "string" || typeof v === "number" ? String(v) : null);
+1
View File
@@ -17,6 +17,7 @@ describe("selectionKey", () => {
expect(selectionKey(["Seleção Nacional sub-19 Masculina"])).toBe("m19");
expect(selectionKey(["Portugal", "Espanha", "sub-19"])).toBe("m19");
expect(selectionKey(["Seleção Nacional sub-19 feminina"])).toBe("w19");
expect(selectionKey(["/FPA/Fotos/2026_2027/Seleções Nacionais/W17/20261127 - POR x ITA"])).toBe("w17");
});
it("names no team for a club game, a gala, or a gathering", () => {
+11 -1
View File
@@ -4,7 +4,7 @@ import { tmpdir } from "node:os";
import path from "node:path";
import sharp from "sharp";
import { afterAll, beforeAll, describe, expect, it } from "vitest";
import { cullFromCameraRating, ratingFromTags, readCameraInfo, withCameraRatingChecked } from "./exif.js";
import { cullFromCameraRating, cullFromXmpPacket, ratingFromTags, readCameraInfo, withCameraRatingChecked } from "./exif.js";
describe("on-camera star ratings", () => {
it("maps EXIF Rating and RatingPercent tags", () => {
@@ -26,6 +26,16 @@ describe("on-camera star ratings", () => {
expect(cullFromCameraRating(4)).toEqual({ rating: 4, flag: "PICK" });
});
it("reads Lightroom pick without stars", () => {
expect(cullFromXmpPacket(`<xmpDM:pick>1</xmpDM:pick><xmp:Rating>0</xmp:Rating>`)).toEqual({ flag: "PICK" });
expect(cullFromXmpPacket(`xmpDM:pick="-1"`)).toEqual({ flag: "REJECT" });
expect(cullFromXmpPacket(`<xmp:Rating>3</xmp:Rating><xmp:Label>Blue</xmp:Label>`)).toEqual({
rating: 3,
flag: "PICK",
colorLabel: "BLUE",
});
});
it("marks exif so the backfill does not re-read the same file", () => {
expect(withCameraRatingChecked(undefined)).toEqual({ cameraRatingChecked: true });
expect(withCameraRatingChecked({ owner: "PS" })).toEqual({ owner: "PS", cameraRatingChecked: true });
+38 -3
View File
@@ -1,4 +1,4 @@
import type { PmPhoto } from "@photoreport/metadata";
import { libraryMarksFromXmp, xmpPacketFromJpeg, type PmPhoto } from "@photoreport/metadata";
import exifr from "exifr";
import { type FocusHint, focusFromTags } from "./focus.js";
@@ -90,6 +90,40 @@ export function cullFromCameraRating(rating: number | undefined): { rating: numb
return { rating, flag: "PICK" };
}
/**
* Cull from Lightroom / Photo Mechanic XMP on the file: `xmpDM:pick`, stars, colour.
* Prefer this over stars alone — a flagged file with Rating 0 must still land as PICK.
*/
export type XmpCull = {
rating?: number;
flag?: "PICK" | "REJECT";
colorLabel?: "RED" | "YELLOW" | "GREEN" | "BLUE" | "PURPLE";
};
export function cullFromXmpPacket(xmp: string | null | undefined): XmpCull {
if (!xmp) return {};
const marks = libraryMarksFromXmp(xmp);
const out: XmpCull = {};
if (marks.flag === "REJECT") out.flag = "REJECT";
else if (marks.flag === "PICK") out.flag = "PICK";
const rating = marks.rating;
if (typeof rating === "number" && rating > 0) {
out.rating = rating;
if (!out.flag) out.flag = "PICK";
}
const color = marks.colorLabel;
if (color === "RED" || color === "YELLOW" || color === "GREEN" || color === "BLUE" || color === "PURPLE") {
out.colorLabel = color;
}
return out;
}
/** Read XMP from a JPEG buffer or raw XMP bytes and return library cull fields. */
export function cullFromJpegBytes(bytes: Buffer | Uint8Array): ReturnType<typeof cullFromXmpPacket> {
const view = bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes);
return cullFromXmpPacket(xmpPacketFromJpeg(view));
}
/** Marker in `photos.exif` so the worker does not re-read files that already had no stars. */
export const CAMERA_RATING_CHECKED = "cameraRatingChecked";
@@ -188,7 +222,8 @@ function extraOf(tags: Record<string, unknown>): CameraExtra {
const lat = num(tags.latitude);
const lon = num(tags.longitude);
const alt = num(tags.GPSAltitude);
const extra: CameraExtra = {
// Build then drop undefined keys — exactOptionalPropertyTypes forbids `rollAngle?: number | undefined`.
const draft = {
exposureCompensation: num(tags.ExposureCompensation) ?? num(tags.ExposureBiasValue),
flashFired: flash === undefined ? undefined : (flash & 1) === 1,
meteringMode: metering === undefined ? undefined : (METERING[metering] ?? (metering === 255 ? "Other" : undefined)),
@@ -211,7 +246,7 @@ function extraOf(tags: Record<string, unknown>): CameraExtra {
longitude: lon,
altitude: alt === undefined ? undefined : num(tags.GPSAltitudeRef) === 1 ? -alt : alt,
};
return Object.fromEntries(Object.entries(extra).filter(([, v]) => v !== undefined)) as CameraExtra;
return Object.fromEntries(Object.entries(draft).filter(([, v]) => v !== undefined)) as CameraExtra;
}
/** The focus point in a file (the original, which still has the camera's EXIF). Null when the body wrote none. */
+71 -22
View File
@@ -1,5 +1,5 @@
import { applyRename } from "../library/rename.js";
import { mkdir, rename, rm, stat } from "node:fs/promises";
import { mkdir, readFile, rename, rm, stat } from "node:fs/promises";
import path from "node:path";
import sharp from "sharp";
import type { Db } from "../db.js";
@@ -9,7 +9,14 @@ import { stripNulBytes } from "../lib/sanitize.js";
import type { Broadcaster } from "../realtime.js";
import { LocalStorage, sha256File, UrlSigner, VARIANT_SIZE } from "../storage/storage.js";
import { readEmbeddedIptc } from "./embedded.js";
import { cullFromCameraRating, readCameraInfo, withCameraRatingChecked, withCaptureClockChecked, withCaptureClockRecurate } from "./exif.js";
import {
cullFromCameraRating,
cullFromJpegBytes,
readCameraInfo,
withCameraRatingChecked,
withCaptureClockChecked,
withCaptureClockRecurate,
} from "./exif.js";
import { jpegFileComplete } from "./jpeg.js";
export const ACCEPTED_EXTENSIONS = new Set([".jpg", ".jpeg"]);
@@ -173,6 +180,13 @@ export class IngestService {
const camera = await readCameraInfo(file).catch(() => ({}) as Awaited<ReturnType<typeof readCameraInfo>>);
const embedded = await readEmbeddedIptc(file);
// Lightroom / Photo Mechanic pick, stars and colour on the file — not stars alone.
let xmpCull: Awaited<ReturnType<typeof cullFromJpegBytes>> = {};
try {
xmpCull = cullFromJpegBytes(await readFile(file));
} catch {
xmpCull = {};
}
const capturedAt = camera.capturedAt ? new Date(camera.capturedAt.getTime() + (origin.clockOffsetSec ?? 0) * 1000) : undefined;
// Archive imports name their own event. No camera time: keep the folder/pin the photographer named — do not
// invent "now" (that would also force today's open event). With a capture time, the pin only wins inside its
@@ -215,8 +229,9 @@ export class IngestService {
// Always mark that stars were read, so the worker backfill skips this file.
exif: withCameraRatingChecked(camera.extra && Object.keys(camera.extra).length ? camera.extra : undefined) as Prisma.InputJsonValue,
...(Object.keys(embedded).length && { embeddedIptc: embedded }),
// Stars set on the body (or in Photo Mechanic): rating + Escolhida so filters and live picks see them.
// Stars on the body, then XMP pick/colour from Lightroom / Photo Mechanic (pick with Rating 0 still counts).
...cullFromCameraRating(camera.rating),
...xmpCull,
});
try {
photo = await db.photo.create({ data });
@@ -349,26 +364,37 @@ export class IngestService {
const { db, storage, log } = this.deps;
const key = storage.originalKey(photo.organizationId, photo.sha256, ext === ".jpeg" ? ".jpg" : ext);
const size = (await stat(file)).size;
// Read cull marks before adopt moves the file out of the ingest path.
const existing = await db.photo.findUnique({ where: { id: photo.id }, select: { rating: true, flag: true, colorLabel: true, exif: true } });
const needCull = (existing?.rating ?? photo.rating ?? 0) <= 0 || existing?.flag === "NONE";
const camera = needCull ? await readCameraInfo(file).catch(() => null) : null;
let xmpCull: Awaited<ReturnType<typeof cullFromJpegBytes>> = {};
if (needCull) {
try {
xmpCull = cullFromJpegBytes(await readFile(file));
} catch {
xmpCull = {};
}
}
const cull = { ...cullFromCameraRating(camera?.rating), ...xmpCull };
if (key !== photo.storageKey) await rm(storage.resolve(photo.storageKey), { force: true });
await storage.adopt(file, key);
// Previews (thumb/preview) stay: they already show this photo. Only the stored file changes.
// Faces and shirt numbers were read from the 2048 px preview: read them again from the full photo.
const org = await db.organization.findUnique({ where: { id: photo.organizationId }, select: { biometricsEnabled: true } });
// Preview JPEGs often lack the body's star rating; apply it from the original when still unrated.
const existing = await db.photo.findUnique({ where: { id: photo.id }, select: { rating: true, flag: true, exif: true } });
const camera = (existing?.rating ?? photo.rating ?? 0) > 0 ? null : await readCameraInfo(file).catch(() => null);
const cull = cullFromCameraRating(camera?.rating);
const data: Prisma.PhotoUpdateInput = {
storageKey: key,
byteSize: size,
originalStored: true,
};
if (org?.biometricsEnabled) data.facesStatus = "PENDING";
if (typeof cull.rating === "number" && cull.rating > 0) data.rating = cull.rating;
if (cull.flag && existing?.flag === "NONE") data.flag = cull.flag;
if (cull.colorLabel && existing?.colorLabel === "NONE") data.colorLabel = cull.colorLabel;
if (needCull) data.exif = withCameraRatingChecked(existing?.exif) as Prisma.InputJsonValue;
const updated = await db.photo.update({
where: { id: photo.id },
data: {
storageKey: key,
byteSize: size,
originalStored: true,
...(org?.biometricsEnabled && { facesStatus: "PENDING" }),
...("rating" in cull ? { rating: cull.rating } : {}),
...("flag" in cull && existing?.flag === "NONE" ? { flag: cull.flag } : {}),
...(camera ? { exif: withCameraRatingChecked(existing?.exif) as Prisma.InputJsonValue } : {}),
},
data,
});
log.info({ photoId: photo.id }, "ingest: original replaces the desktop preview");
// Deliveries waiting for it go now.
@@ -484,21 +510,44 @@ export class IngestService {
for (const row of rows) {
const file = storage.resolve(row.storage_key);
const camera = await readCameraInfo(file).catch(() => null);
const cull = cullFromCameraRating(camera?.rating);
let xmpCull: Awaited<ReturnType<typeof cullFromJpegBytes>> = {};
try {
xmpCull = cullFromJpegBytes(await readFile(file));
} catch {
xmpCull = {};
}
const cull = { ...cullFromCameraRating(camera?.rating), ...xmpCull };
const data: Prisma.PhotoUpdateInput = {
exif: withCameraRatingChecked(row.exif) as Prisma.InputJsonValue,
};
if ("rating" in cull) {
const patch: {
rating?: number;
flag?: "PICK" | "REJECT";
colorLabel?: "RED" | "YELLOW" | "GREEN" | "BLUE" | "PURPLE";
} = {};
let changed = false;
if (typeof cull.rating === "number" && cull.rating > 0) {
data.rating = cull.rating;
if (row.flag === "NONE") data.flag = "PICK";
applied++;
patch.rating = cull.rating;
changed = true;
}
if (cull.flag && row.flag === "NONE") {
data.flag = cull.flag;
patch.flag = cull.flag;
changed = true;
}
if (cull.colorLabel) {
data.colorLabel = cull.colorLabel;
patch.colorLabel = cull.colorLabel;
changed = true;
}
if (changed) applied++;
await db.photo.update({ where: { id: row.id }, data });
if ("rating" in cull) {
if (changed) {
broadcaster.library(row.organization_id, {
type: "photo.updated",
ids: [row.id],
patch: { rating: cull.rating, ...(row.flag === "NONE" ? { flag: "PICK" as const } : {}) },
patch,
});
}
}
+2 -1
View File
@@ -1,4 +1,4 @@
import { ensureCloudM19Target } from "./delivery/fpa-m19.js";
import { ensureCloudM19Target, ensureCloudW17Target } from "./delivery/fpa-m19.js";
import { preferIpv4 } from "./lib/prefer-ipv4.js";
import { buildApp, reporterFor } from "./app.js";
import { loadConfig } from "./config.js";
@@ -21,6 +21,7 @@ process.on("SIGTERM", () => void shutdown("SIGTERM"));
process.on("SIGINT", () => void shutdown("SIGINT"));
ensureCloudM19Target(db).catch((err) => app.log.warn({ err }, "delivery: Cloud M19 profile not created"));
ensureCloudW17Target(db).catch((err) => app.log.warn({ err }, "delivery: Cloud W17 profile not created"));
try {
await app.listen({ port: config.PORT, host: "0.0.0.0" });
+11
View File
@@ -388,6 +388,17 @@ export async function registerShopAdminRoutes(app: FastifyInstance, deps: { db:
return { orders: views };
});
/** Payment collected outside the shop. Delivery starts; the admin owns handing the work over. */
app.post("/v1/orders/:id/payment-received", { preHandler: authenticate }, async (req) => {
const { id } = IdParams.parse(req.params);
const order = await db.order.findUnique({ where: { id } });
if (!order) throw notFound("order_not_found");
await requireMembership(db, req, order.organizationId, "ADMIN");
if (order.status !== "PENDING") throw badRequest("order_not_pending");
await shop.markPaid(id, "manual");
return shop.orderView(id, null);
});
app.post("/v1/orders/:id/items/:itemId/shipped", { preHandler: authenticate }, async (req) => {
const { id, itemId } = z.object({ id: z.uuid(), itemId: z.uuid() }).parse(req.params);
const order = await db.order.findUnique({ where: { id }, include: { items: { where: { id: itemId } } } });
+6 -1
View File
@@ -497,7 +497,12 @@ export class ShopService {
await this.markPaid(order.id, press ? "press" : "free");
return { order: await this.orderView(order.id, order.accessToken), checkoutUrl: null, token: order.accessToken };
}
if (!org.stripeSecretSealed || !secrets) throw new ShopError("payments_not_configured", 503);
// No payment method: the order is still accepted. An admin collects the money out of band
// and only then does delivery start. Invoicing stays off until a provider is connected.
if (!org.stripeSecretSealed || !secrets) {
this.deps.log.info({ orderId: order.id }, "shop: order accepted without a payment method");
return { order: await this.orderView(order.id, order.accessToken), checkoutUrl: null, token: order.accessToken };
}
const checkout = await createCheckout(
secrets.open(org.stripeSecretSealed),
{
+36
View File
@@ -111,4 +111,40 @@ describe("EHF matches", () => {
expect(seen.some((u) => u.includes("/men/2026-27/matches/"))).toBe(true);
expect(seen.filter((u) => u.includes("GetMatches")).length).toBe(3);
});
it("reads a national standing list with the hall, the group and the kick-off", async () => {
const fetch: Fetch = async () => ({
ok: true,
status: 200,
json: async () => ({
matches: [
{
matchID: "202712010502014",
venue: {
date: { utc: "2026-11-27T19:00:00Z" },
place: { hallName: "Pavilhão da Associação Atlética de Águas Santas", cityName: "Àguas Santas" },
},
homeTeam: { team: { nationAbbreviation: "POR" } },
guestTeam: { team: { nationAbbreviation: "ITA" } },
comp: { round: { name: "Qualification Tournaments" }, group: { name: "C" } },
},
],
}),
text: async () => "",
arrayBuffer: async () => new ArrayBuffer(0),
});
const rows = await new EhfProvider(fetch, 0).euroCupMenMatches("comp", "139009");
expect(rows).toEqual([
{
matchId: "202712010502014",
startsAt: new Date("2026-11-27T19:00:00Z"),
homeNation: "POR",
awayNation: "ITA",
venue: "Pavilhão da Associação Atlética de Águas Santas",
city: "Àguas Santas",
round: "Qualification Tournaments",
group: "C",
},
]);
});
});
+10
View File
@@ -8,6 +8,8 @@ import {
nationalNamesMatch,
nationalSideFromTexts,
nationalTeamExternalId,
youthEuroRound,
youthNationalTeam,
} from "./national.js";
describe("national call-up", () => {
@@ -76,4 +78,12 @@ describe("nationalTeamExternalId", () => {
expect(nationalTeamExternalId("Roménia", "w18")).toBe("ROU-W18");
expect(nationalCountryLabel("Switzerland")).toBe("Suíça");
});
it("maps the W17 qualification nations onto youth sides", () => {
expect(youthNationalTeam("POR", "w17")).toEqual({ externalId: "W17", name: "Portugal", abbreviation: "POR" });
expect(youthNationalTeam("ITA", "w17")).toEqual({ externalId: "ITA-W17", name: "Itália", abbreviation: "ITA" });
expect(youthNationalTeam("SLO", "w17")?.externalId).toBe("SLO-W17");
expect(youthNationalTeam("FAR", "w17")?.name).toBe("Ilhas Faroé");
expect(youthEuroRound("Qualification Tournaments", "C")).toBe("Qualificação C");
});
});
+64
View File
@@ -171,6 +171,19 @@ export const EHF_EURO_CUP_MEN = {
sheetWindowMs: 3 * 86400_000,
} as const;
/**
* Women's under-17 EHF EURO 2027 qualification (Águas Santas, 27–29 Nov 2026, and the same page
* for the rest of that tournament). Same standing list and match sheet as the men's Euro Cup.
*/
export const EHF_W17_EURO = {
competitionId: "DrPEklHxLKeDu_IajXOQvA",
contentId: "139009",
externalId: "W17-EURO",
name: "W17 EHF EURO",
gender: "F" as const,
side: "w17",
} as const;
const fold = (s: string) => s.normalize("NFD").replace(/[\u0300-\u036f]/g, "").toLowerCase().replace(/\s+/g, " ").trim();
/** Same athlete across FPA call-up spelling and EHF sheet ("Iturriza" / "Iturizza", "Miguel Oliveira" / "Miguel Moreira de Oliveira"). */
@@ -231,6 +244,21 @@ export function nationalCountryLabel(raw: string): string | null {
if (/^(fra|fr|franca|france)$/.test(n)) return "França";
if (/^(ger|deu|alemanha|germany)$/.test(n)) return "Alemanha";
if (/^(swe|suecia|sweden)$/.test(n)) return "Suécia";
if (/^(ita|italy|italia)$/.test(n)) return "Itália";
if (/^(slo|svn|slovenia|eslovenia)$/.test(n)) return "Eslovénia";
if (/^(ukr|ukraine|ucrania)$/.test(n)) return "Ucrânia";
if (/^(isl|iceland|islandia)$/.test(n)) return "Islândia";
if (/^(far|fro|faroe|faroe islands|ilhas faroe)$/.test(n)) return "Ilhas Faroé";
if (/^(tur|turkey|turkiye|turquia)$/.test(n)) return "Turquia";
if (/^(isr|israel)$/.test(n)) return "Israel";
if (/^(mkd|north macedonia|macedonia do norte)$/.test(n)) return "Macedónia do Norte";
if (/^(ltu|lithuania|lituania)$/.test(n)) return "Lituânia";
if (/^(kos|kosovo)$/.test(n)) return "Kosovo";
if (/^(gre|greece|grecia)$/.test(n)) return "Grécia";
if (/^(aut|austria)$/.test(n)) return "Áustria";
if (/^(pol|poland|polonia)$/.test(n)) return "Polónia";
if (/^(fin|finland|finlandia)$/.test(n)) return "Finlândia";
if (/^(lux|luxembourg|luxemburgo)$/.test(n)) return "Luxemburgo";
return null;
}
@@ -248,6 +276,15 @@ const YOUTH_CODE: Record<string, string> = {
hungria: "HUN",
noruega: "NOR",
italia: "ITA",
ucrania: "UKR",
"ilhas faroe": "FAR",
turquia: "TUR",
israel: "ISR",
"macedonia do norte": "MKD",
lituania: "LTU",
kosovo: "KOS",
grecia: "GRE",
luxemburgo: "LUX",
polonia: "POL",
chequia: "CZE",
montenegro: "MNE",
@@ -261,6 +298,33 @@ const YOUTH_CODE: Record<string, string> = {
"paises baixos": "NED",
};
/**
* A youth national side from an EHF nation code or an English/Portuguese country name.
* Portugal's under-17 women are "W17"; Italy is "ITA-W17".
*/
export function youthNationalTeam(
nation: string | null | undefined,
side: string,
): { externalId: string; name: string; abbreviation: string } | null {
if (!nation) return null;
const name = nationalCountryLabel(nation);
if (!name) return null;
const externalId = nationalTeamExternalId(name, side);
if (!externalId) return null;
const abbreviation = YOUTH_CODE[fold(name)];
if (!abbreviation) return null;
return { externalId, name, abbreviation };
}
/** "Qualification Tournaments" + group "C" is what the picker shows as "Qualificação C". */
export function youthEuroRound(round: string | null, group: string | null): string | null {
let name = round;
if (name === "Qualification Tournaments") name = "Qualificação";
if (name && group) return `${name} ${group}`;
if (name) return name;
return group;
}
/** Which national sports team externalId fits this country + side key. */
export function nationalTeamExternalId(country: string, side: string): string | null {
const label = nationalCountryLabel(country) ?? country;
+5 -2
View File
@@ -1538,7 +1538,7 @@ export class EhfProvider {
async euroCupMenMatches(
competitionId: string,
contentId: string,
): Promise<{ matchId: string; startsAt: Date; homeNation: string | null; awayNation: string | null; venue: string | null; city: string | null }[]> {
): Promise<{ matchId: string; startsAt: Date; homeNation: string | null; awayNation: string | null; venue: string | null; city: string | null; round: string | null; group: string | null }[]> {
const data = await get(
this.fetcher,
`https://www.eurohandball.com/umbraco/api/competitionapi/GetStandingMatches?contentId=${encodeURIComponent(contentId)}&competitionId=${encodeURIComponent(competitionId)}`,
@@ -1546,7 +1546,7 @@ export class EhfProvider {
"json",
);
const rows = Array.isArray(obj(data).matches) ? (obj(data).matches as unknown[]) : [];
const out: { matchId: string; startsAt: Date; homeNation: string | null; awayNation: string | null; venue: string | null; city: string | null }[] = [];
const out: { matchId: string; startsAt: Date; homeNation: string | null; awayNation: string | null; venue: string | null; city: string | null; round: string | null; group: string | null }[] = [];
for (const row of rows) {
const m = obj(row);
const matchId = str(m.matchID);
@@ -1557,6 +1557,7 @@ export class EhfProvider {
if (Number.isNaN(at.getTime())) continue;
const hall = str(place.hallName);
const city = str(place.cityName);
const comp = obj(m.comp);
out.push({
matchId,
startsAt: at,
@@ -1564,6 +1565,8 @@ export class EhfProvider {
awayNation: str(obj(obj(m.guestTeam).team).nationAbbreviation) ?? str(obj(obj(m.guestTeam).team).countryAbbreviation),
venue: hall,
city,
round: str(obj(comp.round).name),
group: str(obj(comp.group).name),
});
}
return out;
+161
View File
@@ -17,6 +17,7 @@ import { type ClubCandidate, type JogaClient, chooseClub, jogaCompetitionId, jog
import { sameListedPerson } from "./people.js";
import {
EHF_EURO_CUP_MEN,
EHF_W17_EURO,
ESP_M19_2026,
M19_POR_2026,
NATIONAL_SIDES,
@@ -24,6 +25,8 @@ import {
SUI_EURO_CUP_2026,
nationToSnamTeam,
nationalNamesMatch,
youthEuroRound,
youthNationalTeam,
type NationalCallUp,
} from "./national.js";
import { tallyOf, tallySquadPhotos } from "./squadPhotos.js";
@@ -615,6 +618,7 @@ export class SportsService {
const espHave = await this.deps.db.sportsPlayer.count({ where: { teamId: espM19Id, season, goneAt: null } });
if (espHave === 0) result.players += await this.saveNationalCallUp(espM19Id, season, ESP_M19_2026);
await this.applyEuroCupSheets(now, season, result);
await this.applyYouthEuros(now, season, result);
// People + reference faces: only when an event syncs these teams (`syncEventSquads`), not on every FPA refresh.
await this.fillNationalPhotos(snamId, season);
await this.fillNationalPhotos(suiId, season);
@@ -687,6 +691,20 @@ export class SportsService {
this.deps.log.info({ side: camp.side, players: camp.players.length, source: camp.sourceUrl }, "sports: youth call-up");
}
for (const game of camp.games) {
if (camp.side === EHF_W17_EURO.side) {
const homeTeamId = await this.upsertTeam("FPA", {
externalId: game.homeExternalId,
name: game.homeCountry,
abbreviation: youthAbbrev(game.homeExternalId, camp.side),
});
const awayTeamId = await this.upsertTeam("FPA", {
externalId: game.awayExternalId,
name: game.awayCountry,
abbreviation: youthAbbrev(game.awayExternalId, camp.side),
});
const listed = await this.hasOfficialYouthFixture(homeTeamId, awayTeamId, game.startsAt, EHF_W17_EURO.externalId);
if (listed) continue;
}
const comp = await this.youthCompetition(season, camp.side);
result.fixtures += await this.saveFixture(comp, "FPA", {
externalId: game.externalId,
@@ -806,6 +824,149 @@ export class SportsService {
}
}
/** The FPA camp and the EHF page can disagree by an hour and still be the same match. */
private sameKickoff(startsAt: Date) {
const slackMs = 2 * 60 * 60 * 1000;
return {
gte: new Date(startsAt.getTime() - slackMs),
lte: new Date(startsAt.getTime() + slackMs),
};
}
/** The official under-17 EURO already has this kick-off, so the camp must not add it again as a friendly. */
private async hasOfficialYouthFixture(homeTeamId: string, awayTeamId: string, startsAt: Date, competitionExternalId: string): Promise<boolean> {
const row = await this.deps.db.sportsFixture.findFirst({
where: {
homeTeamId,
awayTeamId,
startsAt: this.sameKickoff(startsAt),
competition: { externalId: competitionExternalId },
},
select: { id: true },
});
return row !== null;
}
/**
* The FPA post lists the same under-17 game as a friendly ("Sub-17 feminina"). One match, one row.
* An event already opened on the friendly keeps that row when it can become the official one.
*/
private async foldYouthFriendly(
officialCompetitionId: string,
officialExternalId: string,
homeTeamId: string,
awayTeamId: string,
startsAt: Date,
): Promise<void> {
const friendly = await this.deps.db.sportsFixture.findFirst({
where: {
homeTeamId,
awayTeamId,
startsAt: this.sameKickoff(startsAt),
competition: { provider: "FPA", externalId: { endsWith: "-AMIG" } },
},
select: { id: true },
});
if (!friendly) return;
const official = await this.deps.db.sportsFixture.findUnique({
where: { competitionId_externalId: { competitionId: officialCompetitionId, externalId: officialExternalId } },
select: { id: true },
});
if (!official) {
await this.deps.db.sportsFixture.update({
where: { id: friendly.id },
data: { competitionId: officialCompetitionId, externalId: officialExternalId },
});
return;
}
if (official.id === friendly.id) return;
await this.deps.db.event.updateMany({
where: { fixtureId: friendly.id },
data: { fixtureId: official.id },
});
await this.deps.db.sportsFixture.delete({ where: { id: friendly.id } });
}
/**
* Women's under-17 EHF EURO qualification on eurohandball.com. The whole tournament is stored so the
* picker can open Portugal–Italy (and the rest of the weekend) before the nominated sheet is published.
* The sheet, when it is out, writes shirt numbers and headshots onto W17 / ITA-W17 / …
*/
private async applyYouthEuros(now: Date, season: string, result: RefreshResult): Promise<void> {
const { db, log } = this.deps;
let matches: Awaited<ReturnType<EhfProvider["euroCupMenMatches"]>>;
try {
matches = await this.ehf.euroCupMenMatches(EHF_W17_EURO.competitionId, EHF_W17_EURO.contentId);
} catch (err) {
result.errors.push(`ehf w17: ${(err as Error).message}`);
return;
}
const listed = matches.flatMap((m) => {
const home = youthNationalTeam(m.homeNation, EHF_W17_EURO.side);
const away = youthNationalTeam(m.awayNation, EHF_W17_EURO.side);
if (!home || !away) return [];
return [{ match: m, home, away }];
});
if (!listed.length) return;
const comp = await db.sportsCompetition.upsert({
where: { provider_externalId: { provider: "FPA", externalId: EHF_W17_EURO.externalId } },
create: {
provider: "FPA",
externalId: EHF_W17_EURO.externalId,
sport: "andebol",
name: EHF_W17_EURO.name,
gender: EHF_W17_EURO.gender,
season,
},
update: { name: EHF_W17_EURO.name, gender: EHF_W17_EURO.gender, season },
});
for (const row of listed) {
const homeTeamId = await this.upsertTeam("FPA", row.home);
const awayTeamId = await this.upsertTeam("FPA", row.away);
await this.foldYouthFriendly(comp.id, row.match.matchId, homeTeamId, awayTeamId, row.match.startsAt);
result.fixtures += await this.saveFixture(comp, "FPA", {
externalId: row.match.matchId,
competition: EHF_W17_EURO.externalId,
season,
home: row.home,
away: row.away,
startsAt: row.match.startsAt,
timeKnown: true,
round: youthEuroRound(row.match.round, row.match.group),
venue: row.match.venue,
city: row.match.city,
});
}
const due = listed.filter((row) => Math.abs(row.match.startsAt.getTime() - now.getTime()) <= EHF_EURO_CUP_MEN.sheetWindowMs);
for (const row of due) {
if (this.deps.ehfDelayMs) await new Promise((r) => setTimeout(r, this.deps.ehfDelayMs));
let sheet: Awaited<ReturnType<EhfProvider["nationalSheet"]>>;
try {
sheet = await this.ehf.nationalSheet(row.match.matchId);
} catch (err) {
result.errors.push(`ehf w17 sheet ${row.match.matchId}: ${(err as Error).message}`);
continue;
}
if (!sheet) continue;
const sides = [
{ nation: sheet.homeNation, players: sheet.home },
{ nation: sheet.awayNation, players: sheet.away },
];
for (const side of sides) {
const team = youthNationalTeam(side.nation, EHF_W17_EURO.side);
if (!team) continue;
const teamId = await this.upsertTeam("FPA", team);
const field = side.players.filter((p) => p.position !== "Equipa técnica");
result.players += await this.mergeNationalSheet(teamId, season, field, []);
await this.fillNationalPhotos(teamId, season);
}
log.info(
{ matchId: row.match.matchId, home: sheet.homeNation, away: sheet.awayNation, players: sheet.home.length + sheet.away.length },
"sports: w17 sheet",
);
}
}
/**
* Write EHF sheet players onto a national team. For Portugal, keep the CIPA from the FPA call-up when the
* name matches; still take the shirt number and headshot from the sheet.
+2 -1
View File
@@ -16,7 +16,7 @@ import { RenderPool, RenderProcess } from "./develop/engine.js";
import { DevelopService, RenderWorker } from "./develop/service.js";
import { FaceProcess, GrowingFacePool } from "./faces/process.js";
import { AutopilotService, AutopilotWorker } from "./autopilot/service.js";
import { ensureCloudM19Target } from "./delivery/fpa-m19.js";
import { ensureCloudM19Target, ensureCloudW17Target } from "./delivery/fpa-m19.js";
import { jogaClientFromConfig } from "./sports/joga.js";
import { SportsService, SportsWorker } from "./sports/service.js";
import { ArchiveService, ArchiveWorker, localDirs } from "./archive/service.js";
@@ -177,6 +177,7 @@ const sports = config.SPORTS_SYNC === "on"
: undefined;
ensureCloudM19Target(db).catch((err) => log.warn({ err }, "delivery: Cloud M19 profile not created"));
ensureCloudW17Target(db).catch((err) => log.warn({ err }, "delivery: Cloud W17 profile not created"));
scanner.start();
if (secrets) archive.start();
autopilot.start();
+10 -6
View File
@@ -218,6 +218,10 @@ describe("learning from corrections", () => {
});
});
/** The JPEG stays 600 px so the suite does not time out. The planner reads this size, which clears the 2400 px floor. */
const PHOTO_W = 6000;
const PHOTO_H = 4000;
describe("autopilot", () => {
let ctx: TestContext;
let dir: string;
@@ -258,7 +262,7 @@ describe("autopilot", () => {
const file = path.join(dir, `IMG_${n}.JPG`);
await writeFile(file, data);
const out = await ingest.ingest(file, { organizationId: orgId, userId, source, originalName: `IMG_${n}.JPG`, eventId });
await ctx.db.photo.update({ where: { id: out.photoId }, data: { capturedAt: new Date(1_800_000_000_000 + at), cameraSerial: "R1-001" } });
await ctx.db.photo.update({ where: { id: out.photoId }, data: { capturedAt: new Date(1_800_000_000_000 + at), cameraSerial: "R1-001", width: PHOTO_W, height: PHOTO_H } });
return out.photoId;
}
@@ -351,7 +355,7 @@ describe("autopilot", () => {
expect(await chosen()).toEqual({ [w0a]: true, [w0b]: false, [w2a]: true, [w2b]: true, [w2c]: false });
// The burst picks are still flagged for the photographer.
expect((await ctx.db.photo.findUniqueOrThrow({ where: { id: w2c } })).flag).toBe("PICK");
});
}, 60_000);
it("two clients: gallery gets the best moments; rest gets seconds and every other pick (warm-up included)", async () => {
const { eventId, orgId, userId } = await setup();
@@ -393,7 +397,7 @@ describe("autopilot", () => {
await service.decideBursts(new Date(start.getTime() + 8 * 60_000));
expect(to(record)).toEqual([a1]);
expect(to(fap).sort()).toEqual([warm, a2, b1, b2].sort());
});
}, 60_000);
it("never edits over a person's edit (made on the desktop app before the photo was uploaded)", async () => {
const { orgId, userId, eventId } = await setup();
@@ -430,7 +434,7 @@ describe("autopilot", () => {
await autopilot.decideBursts(new Date(Date.now() + 20_000));
const edits = await ctx.db.photoEdit.findMany({ where: { photoId: id }, orderBy: { seq: "asc" } });
const values = (edits[0]!.command as { params: { values: Record<string, number> } }).params.values;
expect(values).toMatchObject({ "wb.temp": 5200, "wb.tint": 4, "light.exposure": 0.3, "light.contrast": 15, "color.vibrance": 18, "detail.sharpenAmount": 38.5, "detail.nrLuminance": 22 });
expect(values).toMatchObject({ "wb.temp": 5200, "wb.tint": 4, "light.exposure": 0.3, "light.contrast": 15, "color.vibrance": 18, "detail.sharpenAmount": 31, "detail.nrLuminance": 22 });
});
it("leaves events without autopilot alone", async () => {
@@ -454,7 +458,7 @@ describe("autopilot", () => {
const shrink = (a: number, b: number) => [a + (b - a) * 0.08, b - (b - a) * 0.08] as const;
const [x0, x1] = shrink(r.x0, r.x1);
const [y0, y1] = shrink(r.y0, r.y1);
await develop.append(id, userId, { clientId: "web-1", ops: [{ opId: `h-${id}-1`, command: { command: "develop.set", params: { values: { "light.exposure": 0.5 } } } }, { opId: `h-${id}-2`, command: { command: "crop.set", params: { rect: { x0, y0, x1, y1 }, angle: 1.5, aspect: [600, 400] } } }] });
await develop.append(id, userId, { clientId: "web-1", ops: [{ opId: `h-${id}-1`, command: { command: "develop.set", params: { values: { "light.exposure": 0.5 } } } }, { opId: `h-${id}-2`, command: { command: "crop.set", params: { rect: { x0, y0, x1, y1 }, angle: 1.5, aspect: [PHOTO_W, PHOTO_H] } } }] });
expect(await recordCorrection(ctx.db, id)).toBe(true);
}
// Untouched photos and the autopilot's own edits teach nothing.
@@ -480,7 +484,7 @@ describe("autopilot", () => {
const gone = await ctx.app.inject({ method: "DELETE", url: `/v1/orgs/${orgId}/autopilot/style`, headers: bearer(token) });
expect(gone.json()).toEqual({ forgotten: 5 });
expect(await learntStyle(ctx.db, orgId, userId)).toBeNull();
});
}, 60_000);
it("tells the learner when a person (not the autopilot) edits", async () => {
const { orgId, userId, eventId } = await setup();
+29 -17
View File
@@ -198,10 +198,12 @@ describe("reportage", () => {
expect(shotIntent([person(0.36, 0.15, 0.66, 0.996)])).toBe("closed");
});
it("leaves a wide frame as shot", () => {
it("crops a single person standing in the frame, and keeps them whole", () => {
const speaker = person(0.35, 0.28, 0.52, 0.72);
const room = compose({ ...frame, people: [speaker], balls: [] }, null, { context: "reportage" });
expect(room).toBeNull();
const room = compose({ ...frame, people: [speaker], balls: [] }, null, { context: "reportage" })!;
expect(inside(room.rect, speaker)).toBe(true);
expect(room.rect.x1 - room.rect.x0).toBeLessThan(0.92);
expect(room.rect.y1).toBeGreaterThan(speaker.y1);
const match = compose({ ...frame, people: [speaker], balls: [] }, null, { context: "sport" });
expect(match).not.toBeNull();
});
@@ -216,7 +218,7 @@ describe("reportage", () => {
expect(isLongPrime({ focalLength: 200 })).toBe(false);
});
it("steps a full-length closer on a long prime, and leaves the same frame on a zoom", () => {
it("crops a full-length on a prime and on a zoom, and keeps a suitcase with the person", () => {
const p = person(0.3, 0.12, 0.48, 0.82);
const photo = { ...frame, people: [p], balls: [] };
const prime = compose(photo, null, { context: "reportage", lens: { focalLength: 135, range: [135, 135] } })!;
@@ -225,19 +227,24 @@ describe("reportage", () => {
expect(prime.rect.x0).toBeLessThanOrEqual(p.x0);
expect(prime.rect.x1).toBeGreaterThanOrEqual(p.x1);
const width = prime.rect.x1 - prime.rect.x0;
expect(width).toBeGreaterThan(0.8);
expect(width).toBeGreaterThan(0.7);
expect(width).toBeLessThan(0.92);
const zoom = compose(photo, null, { context: "reportage", lens: { focalLength: 135, range: [70, 200] } });
expect(zoom).toBeNull();
const zoom = compose(photo, null, { context: "reportage", lens: { focalLength: 135, range: [70, 200] } })!;
expect(inside(zoom.rect, p)).toBe(true);
expect(zoom.rect.x1 - zoom.rect.x0).toBeLessThan(0.92);
const wide = person(0.35, 0.28, 0.52, 0.72);
const scene = compose({ ...frame, people: [wide], balls: [] }, null, { context: "reportage", lens: { focalLength: 200, range: [200, 200] } });
expect(scene).toBeNull();
const suitcase = { x0: 0.54, y0: 0.5, x1: 0.64, y1: 0.7, score: 0.8 };
const scene = compose({ ...frame, people: [wide], balls: [], carried: [suitcase] }, null, { context: "reportage", lens: { focalLength: 200, range: [200, 200] } })!;
expect(inside(scene.rect, wide)).toBe(true);
expect(inside(scene.rect, suitcase)).toBe(true);
expect(scene.rect.y1).toBeGreaterThan(suitcase.y1);
});
it("leaves a full-length as it was framed, and a match of the same picture still closes", () => {
it("crops a reportage full-length without a sports fill, and a match of the same picture still closes", () => {
const p = person(0.3, 0.12, 0.48, 0.82);
const room = compose({ ...frame, people: [p], balls: [] }, null, { framing: "tight", context: "reportage" });
expect(room).toBeNull();
const room = compose({ ...frame, people: [p], balls: [] }, null, { framing: "tight", context: "reportage" })!;
expect(inside(room.rect, p)).toBe(true);
expect(room.rect.x1 - room.rect.x0).toBeLessThan(0.92);
const match = compose({ ...frame, people: [p], balls: [] }, null, { framing: "tight", context: "sport" });
expect(match).not.toBeNull();
if (!match) return;
@@ -294,8 +301,10 @@ describe("reportage", () => {
it("does not close a full-length to delete a hand at the edge", () => {
const subject = person(0.22, 0.18, 0.4, 0.82);
const hand = person(0, 0.35, 0.07, 0.5, 0.8);
const c = compose({ ...frame, people: [subject, hand], balls: [] }, null, { context: "reportage" });
expect(c).toBeNull();
const c = compose({ ...frame, people: [subject, hand], balls: [] }, null, { context: "reportage" })!;
expect(inside(c.rect, subject)).toBe(true);
const handIn = Math.max(0, Math.min(c.rect.x1, hand.x1) - Math.max(c.rect.x0, hand.x0)) / (hand.x1 - hand.x0);
expect(handIn).toBeLessThan(0.5);
});
it("drops a person the frame already cut off, and keeps the full-length around the subject", () => {
@@ -308,7 +317,7 @@ describe("reportage", () => {
expect(c.rect.x1).toBeGreaterThanOrEqual(subject.x1);
expect(c.rect.y0).toBeLessThanOrEqual(subject.y0);
expect(c.rect.y1).toBeGreaterThan(subject.y1);
expect(c.rect.y1 - c.rect.y0).toBeGreaterThan(0.8);
expect(c.rect.y1 - c.rect.y0).toBeGreaterThan(0.7);
});
it("crops the whole person at the car, not the sharper face in the window", () => {
@@ -347,8 +356,11 @@ describe("reportage", () => {
{ x0: 0.5, y0: 0.25, x1: 0.56, y1: 0.34 },
{ x0: 0.4, y0: 0.31, x1: 0.45, y1: 0.4 },
],
});
expect(c).toBeNull();
})!;
expect(c.rect.y0).toBeLessThanOrEqual(front.y0);
expect(c.rect.y1).toBeGreaterThan(front.y1 - 1e-6);
expect(c.rect.x0).toBeLessThanOrEqual(front.x0);
expect(c.rect.x1).toBeGreaterThanOrEqual(front.x1);
});
it("leaves a wide shot of small figures as it was framed", () => {
+35
View File
@@ -75,6 +75,8 @@ class FakeNextcloud {
class FakeZerozero {
logins = 0;
removed: string[] = [];
/** Paths of POST /api/photo-sync/… after each upload (the public game, not only the desk). */
syncs: string[] = [];
uploads = new Map<string, { gameId: string; meta: Record<string, string>; data: Buffer; length: number }>();
password = "zz-pass";
@@ -129,6 +131,10 @@ class FakeZerozero {
this.uploads.set(id, { gameId: url.searchParams.get("match_id")!, meta, data: Buffer.alloc(0), length: Number(h.get("upload-length")) });
return new Response(null, { status: 201, headers: { location: `/upload/${id}` } });
}
if (method === "POST" && url.pathname.startsWith("/api/photo-sync/")) {
this.syncs.push(url.pathname);
return Response.json({ synced: 1, failed: 0, failures: [] });
}
const gone = /^\/api\/images\/(.+)$/.exec(url.pathname);
if (gone && method === "DELETE") {
this.removed.push(gone[1]!);
@@ -622,6 +628,8 @@ describe("delivery", () => {
expect(first.meta).toMatchObject({ match_id: "12627747", artist: "Peter Spark / Kapta+", filename: "PS_SC Torreense x Sunderland_1.jpg", filetype: "image/jpeg" });
expect(first.data.length).toBe(first.length);
expect((await sharp(first.data).metadata()).width).toBe(3000);
// The desk upload is not the public game: each photo is published there before the delivery is done.
expect(zz.syncs).toEqual(["/api/photo-sync/img-1", "/api/photo-sync/img-2"]);
// Signed in once for the whole batch.
expect(zz.logins).toBe(1);
@@ -644,6 +652,7 @@ describe("delivery", () => {
expect(zz.removed).toEqual([itemA.remotePath!.split("/")[1]]);
// Same name ({n} kept), shown once in the game.
expect(zz.uploads.get(resent.remotePath!.split("/")[1]!)!.meta.filename).toBe(zz.uploads.get(itemA.remotePath!.split("/")[1]!)!.meta.filename);
expect(zz.syncs.at(-1)).toBe(`/api/photo-sync/${resent.remotePath!.split("/")[1]}`);
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.
@@ -842,6 +851,32 @@ describe("delivery", () => {
expect(broadcaster.sent.filter((s) => s.message.type === "delivery.updated").map((s) => (s.message as { item: { status: string } }).item.status)).toEqual(["QUEUED", "QUEUED", "FAILED", "DONE"]);
});
it("retry is idempotent when the item leaves FAILED between render and click (BIT-33418)", async () => {
const { orgId, token, target } = await setup();
const id = await photo("race.jpg", "2026:09:23 21:10:00");
await delivery.enqueue({ organizationId: orgId, targetId: target.id, photoIds: [id], again: false, requestedById: (await ctx.db.user.findFirstOrThrow()).id });
const [claimed] = await delivery.claim(5);
nc.status = 401;
expect(await delivery.process(claimed!)).toMatchObject({ status: "FAILED", attempts: 1 });
nc.status = undefined;
// Between the desktop rendering the FAILED row and the user clicking "Repetir", the queue worker
// requeued the item (autopilot, queueEdited, queueOrphanRetracts, …) so it is no longer FAILED.
const itemId = (await ctx.db.deliveryItem.findFirstOrThrow({ where: { photoId: id, targetId: target.id } })).id;
await ctx.db.deliveryItem.update({ where: { id: itemId }, data: { status: "QUEUED", attempts: 0, nextAttemptAt: new Date(), lastError: null } });
// The retry must not 404 — it returns the current state, so the desktop's promise resolves and no
// unhandledrejection reaches the error hub.
const retry = await ctx.app.inject({ method: "POST", url: `/v1/orgs/${orgId}/deliveries/${itemId}/retry`, headers: bearer(token) });
expect(retry.statusCode).toBe(200);
expect(retry.json()).toMatchObject({ id: itemId, status: "QUEUED", attempts: 0 });
// A truly missing item still 404s.
const ghost = await ctx.app.inject({ method: "POST", url: `/v1/orgs/${orgId}/deliveries/00000000-0000-4000-8000-000000000000/retry`, headers: bearer(token) });
expect(ghost.statusCode).toBe(404);
expect(ghost.json()).toMatchObject({ error: "item_not_found" });
});
it("writes long venues whole in IIM and XMP, flagged as UTF-8", async () => {
const src = path.join(dir, "src.jpg");
await writeFile(src, await sharp({ create: { width: 300, height: 200, channels: 3, background: "#123456" } }).jpeg().toBuffer());
+25
View File
@@ -212,6 +212,31 @@ describe("shop", () => {
expect((await ctx.db.order.findUniqueOrThrow({ where: { id: order.id } })).status).toBe("FULFILLED");
});
it("accepts an order when Stripe is off, and delivery waits until an admin records the payment", async () => {
const s = await setup();
expect((await s.api("PUT", `/v1/orgs/${s.orgId}/shop-settings`, { stripeSecretKey: "", stripeWebhookSecret: "" })).statusCode).toBe(200);
const g = await gallery(s, { title: "Sem Stripe" });
const created = await pub("POST", "/v1/public/orders", {
gallery: g.slug,
email: "[email protected]",
name: "Ana Costa",
country: "PT",
items: [{ photoId: s.photos[0], productId: s.digital.id, quantity: 1 }],
});
expect(created.statusCode).toBe(201);
const body = created.json() as { order: { id: string; status: string; totalCents: number }; checkoutUrl: string | null };
expect(body.checkoutUrl).toBeNull();
expect(body.order).toMatchObject({ status: "PENDING" });
expect(body.order.totalCents).toBeGreaterThan(0);
expect(await shop.claimDownloads(5)).toEqual([]);
const paid = await s.api("POST", `/v1/orders/${body.order.id}/payment-received`);
expect(paid.statusCode).toBe(200);
expect(paid.json()).toMatchObject({ status: "PAID" });
const [itemId] = await shop.claimDownloads(5);
expect(itemId).toEqual(expect.any(String));
});
it("reverse-charges VAT for EU businesses with a valid number, and gives free galleries away", async () => {
const s = await setup();
const g = await gallery(s, { title: "Clube" });
+140
View File
@@ -733,6 +733,28 @@ describe("sports data service", () => {
log: quiet,
fetch: (async (url, init) => {
const u = String(url);
if (u.includes("GetStandingMatches") && u.includes("contentId=139009"))
return {
ok: true,
status: 200,
json: async () => ({
matches: [
{
matchID: "202712010502014",
venue: {
date: { utc: kick.toISOString() },
place: { hallName: "Pavilhão da Associação Atlética de Águas Santas", cityName: "Àguas Santas" },
},
homeTeam: { team: { nationAbbreviation: "POR" } },
guestTeam: { team: { nationAbbreviation: "ITA" } },
comp: { round: { name: "Qualification Tournaments" }, group: { name: "C" } },
},
],
rounds: [],
}),
text: async () => "",
arrayBuffer: async () => new ArrayBuffer(0),
};
if (u.includes("GetStandingMatches"))
return {
ok: true,
@@ -751,6 +773,45 @@ describe("sports data service", () => {
text: async () => "",
arrayBuffer: async () => new ArrayBuffer(0),
};
if (u.includes("GetMatchDetails") && u.includes("202712010502014"))
return {
ok: true,
status: 200,
json: async () => ({
matchDetails: {
details: {
homeTeam: {
team: { nationAbbreviation: "POR" },
players: [
{
id: "ehf-w17-costa",
shirtNumber: "7",
playingPosition: "Centre Back",
person: { firstName: "Maria", lastName: "Costa", nationAbbreviation: "POR" },
newPhoto: { w512: "https://res.ehf.eu/photo/w17-costa.jpg" },
},
],
officials: [],
},
guestTeam: {
team: { nationAbbreviation: "ITA" },
players: [
{
id: "ehf-w17-rossi",
shirtNumber: "9",
playingPosition: "Left Wing",
person: { firstName: "Giulia", lastName: "Rossi", nationAbbreviation: "ITA" },
newPhoto: { w512: "https://res.ehf.eu/photo/w17-rossi.jpg" },
},
],
officials: [],
},
},
},
}),
text: async () => "",
arrayBuffer: async () => new ArrayBuffer(0),
};
if (u.includes("GetMatchDetails") && u.includes("202811130101002"))
return {
ok: true,
@@ -848,6 +909,85 @@ describe("sports data service", () => {
expect(friendly?.startsAt.toISOString()).toBe("2026-11-05T20:00:00.000Z");
expect(friendly?.venue).toBe("Pavilhão Municipal Fernando Lima");
expect(friendly?.city).toBe("Caminha");
const w17 = await ctx.db.sportsFixture.findFirst({
where: { externalId: "202712010502014" },
include: { homeTeam: true, awayTeam: true, competition: true },
});
expect(w17?.competition.name).toBe("W17 EHF EURO");
expect(w17?.competition.gender).toBe("F");
expect(w17?.round).toBe("Qualificação C");
expect(w17?.venue).toBe("Pavilhão da Associação Atlética de Águas Santas");
expect(w17?.city).toBe("Àguas Santas");
expect(w17?.homeTeam.externalId).toBe("W17");
expect(w17?.homeTeam.name).toBe("Portugal");
expect(w17?.awayTeam.externalId).toBe("ITA-W17");
expect(w17?.awayTeam.name).toBe("Itália");
expect(await ctx.db.sportsPlayer.findFirstOrThrow({ where: { teamId: w17!.homeTeam.id, name: "Maria Costa" } })).toMatchObject({
number: "7",
photoUrl: "https://res.ehf.eu/photo/w17-costa.jpg",
});
expect(await ctx.db.sportsPlayer.findFirstOrThrow({ where: { teamId: w17!.awayTeam.id, name: "Giulia Rossi" } })).toMatchObject({
number: "9",
externalId: "ehf-w17-rossi",
});
const { org } = await seedUser(ctx.db, "[email protected]", { org: "w17dup", role: "OWNER" });
const friendlyComp = await ctx.db.sportsCompetition.create({
data: { provider: "FPA", externalId: "W17-AMIG", sport: "andebol", name: "Sub-17 feminina", gender: "F", season: w17!.season },
});
const duplicate = await ctx.db.sportsFixture.create({
data: {
competitionId: friendlyComp.id,
externalId: "w17-por-ita-20261127",
season: w17!.season,
homeTeamId: w17!.homeTeam.id,
awayTeamId: w17!.awayTeam.id,
startsAt: w17!.startsAt,
timeKnown: true,
round: "Particular",
},
});
const opened = await ctx.db.event.create({
data: {
organizationId: org!.id,
home: "Portugal",
away: "Itália",
startsAt: w17!.startsAt,
ingestFrom: w17!.startsAt,
ingestUntil: w17!.startsAt,
iptcTemplate: {},
fixtureId: duplicate.id,
},
});
await sports.syncNationalCallUps(kick);
const paired = await ctx.db.sportsFixture.findMany({
where: { homeTeamId: w17!.homeTeam.id, awayTeamId: w17!.awayTeam.id, startsAt: w17!.startsAt },
});
expect(paired.map((row) => row.externalId)).toEqual(["202712010502014"]);
expect((await ctx.db.event.findUniqueOrThrow({ where: { id: opened.id } })).fixtureId).toBe(w17!.id);
await ctx.db.sportsFixture.delete({ where: { id: w17!.id } });
const campOnly = await ctx.db.sportsFixture.create({
data: {
competitionId: friendlyComp.id,
externalId: "w17-por-ita-20261127",
season: w17!.season,
homeTeamId: w17!.homeTeam.id,
awayTeamId: w17!.awayTeam.id,
startsAt: w17!.startsAt,
timeKnown: true,
round: "Particular",
},
});
await ctx.db.event.update({ where: { id: opened.id }, data: { fixtureId: campOnly.id } });
await sports.syncNationalCallUps(kick);
const adopted = await ctx.db.sportsFixture.findMany({
where: { homeTeamId: w17!.homeTeam.id, awayTeamId: w17!.awayTeam.id, startsAt: w17!.startsAt },
include: { competition: true },
});
expect(adopted).toHaveLength(1);
expect(adopted[0]).toMatchObject({ id: campOnly.id, externalId: "202712010502014", competition: { name: "W17 EHF EURO" } });
expect((await ctx.db.event.findUniqueOrThrow({ where: { id: opened.id } })).fixtureId).toBe(campOnly.id);
});
});
+5 -1
View File
@@ -5,7 +5,11 @@ import userEvent from "@testing-library/user-event";
import { describe, expect, it, vi } from "vitest";
import { App } from "./App.js";
vi.mock("./library/realtime.js", () => ({ useLibraryLive: () => "live", onSocketLive: () => () => {} }));
vi.mock("./library/realtime.js", () => ({
useLibraryLive: () => "live",
onSocketLive: () => () => {},
isSocketLive: () => false,
}));
const ME: Me = {
user: { id: "u1", email: "[email protected]", name: "Ana", locale: "pt-PT" },
+21 -4
View File
@@ -1,5 +1,7 @@
import { useEffect } from "react";
import { useAuth } from "../auth.js";
import { localPhotos } from "../offline/local.js";
import { isLocalId, offlineQueue } from "../offline/queue.js";
import { isDesktop } from "../platform.js";
import { reconcileSoftCrops } from "./softCropWatch.js";
@@ -8,7 +10,7 @@ const EVERY_MS = 4_000;
/**
* Desktop only: while signed in, notice Lightroom / Photo Mechanic soft-crop writes on local originals
* and apply them as develop crops (same path as cropping in Revelar — including autopilot learning).
* A colour class Photo Mechanic paints on the same file is copied onto the library photo.
* Pick / stars / colour on the same file are copied onto the library photo (offline queue when still local).
*/
export function SoftCropWatch({ enabled = isDesktop(), everyMs = EVERY_MS }: { enabled?: boolean; everyMs?: number }) {
const { api, organization } = useAuth();
@@ -19,9 +21,24 @@ export function SoftCropWatch({ enabled = isDesktop(), everyMs = EVERY_MS }: { e
let timer: ReturnType<typeof setTimeout> | undefined;
const tick = async () => {
try {
await reconcileSoftCrops(async (id, photoId, color) => {
await api.updatePhotos(id, [photoId], { colorLabel: color });
});
await reconcileSoftCrops(
async (id, photoId, color) => {
if (isLocalId(photoId)) {
localPhotos.patch(photoId, { colorLabel: color });
offlineQueue(id).add({ kind: "patch", ids: [photoId], patch: { colorLabel: color } });
return;
}
await api.updatePhotos(id, [photoId], { colorLabel: color });
},
async (id, photoId, patch) => {
if (isLocalId(photoId)) {
localPhotos.patch(photoId, patch);
offlineQueue(id).add({ kind: "patch", ids: [photoId], patch });
return;
}
await api.updatePhotos(id, [photoId], patch);
},
);
} catch {
/* older desktop without local_stat, or offline index miss */
}
+72 -16
View File
@@ -3,7 +3,8 @@ import type { ApiClient, EventSummary } from "@photoreport/sdk";
import { useEffect } from "react";
import { useLibraryLive } from "../library/realtime.js";
import { isDesktop } from "../platform.js";
import { flushAllPhotoFiles, settingsFromDevelop, writePhotoCommands, writePhotoFile, type FileIptc, type FileMarkUpdate } from "./lightroomSidecar.js";
import { rememberPhotoFrame } from "./lightroomCrop.js";
import { flushFailedPhotoFiles, flushRecentPhotoFiles, settingsFromDevelop, writePhotoCommands, writePhotoFile, type FileIptc, type FileMarkUpdate } from "./lightroomSidecar.js";
const LOCAL = "local:";
const idToSha = new Map<string, string>();
@@ -14,18 +15,57 @@ function remember(id: string, sha256: string | null | undefined): void {
idToSha.set(id, sha256);
}
let shaByPhotoId: Map<string, string> | null = null;
let shaByPhotoIdRaw = "";
/** Hash of the original on disk for this server photo, recorded when the file was uploaded. */
function originalSha(photoId: string): string | null {
if (!photoId || photoId.startsWith(LOCAL)) return null;
let raw = "";
try {
raw = localStorage.getItem("pr.localmap") ?? "";
} catch {
return null;
}
if (!shaByPhotoId || raw !== shaByPhotoIdRaw) {
const next = new Map<string, string>();
try {
const map = JSON.parse(raw || "{}") as Record<string, unknown>;
for (const [sha, serverId] of Object.entries(map)) {
if (!sha || typeof serverId !== "string" || !serverId) continue;
next.set(serverId, sha);
}
} catch {
// A broken map falls back to the sha the server stored.
}
shaByPhotoId = next;
shaByPhotoIdRaw = raw;
}
return shaByPhotoId.get(photoId) ?? null;
}
/**
* The file Lightroom has is the original on disk. Its hash is often not the sha the server stored
* (that one can be the preview). Writing the server sha looks up a file that is not in the work folder.
*/
function diskSha(photoId: string, apiSha: string | null | undefined): string | null {
const onDisk = originalSha(photoId);
if (onDisk) return onDisk;
if (apiSha) return apiSha;
return null;
}
/** The original Lightroom has open. The server hash can be the preview, which is not in the work folder. */
export function fileShaForPhoto(photoId: string, apiSha: string | null | undefined): string | null {
return diskSha(photoId, apiSha);
}
function shaOf(id: string): string | null {
if (id.startsWith(LOCAL)) return id.slice(LOCAL.length);
const onDisk = originalSha(id);
if (onDisk) return onDisk;
const known = idToSha.get(id);
if (known) return known;
try {
const map = JSON.parse(localStorage.getItem("pr.localmap") ?? "{}") as Record<string, string>;
for (const [sha, serverId] of Object.entries(map)) {
if (serverId === id) return sha;
}
} catch {
// A broken map only means this photo is written the next time it is seen.
}
return null;
}
@@ -110,10 +150,12 @@ function writeKnown(sha: string, update: FileMarkUpdate, developSeq: number, pho
export function onFileMarkMessage(api: ApiClient, message: LibraryMessage): void {
if (!isDesktop()) return;
if (message.type === "photo.added") {
remember(message.photo.id, message.photo.sha256);
const sha = diskSha(message.photo.id, message.photo.sha256);
if (!sha) return;
remember(message.photo.id, sha);
const marks = marksOf(message.photo.flag, message.photo.rating, message.photo.colorLabel, message.photo.delivery === "DONE");
// Always push the resolved IPTC (and any pick / develop) into the work-folder file Lightroom imports.
writeKnown(message.photo.sha256, marks ?? {}, message.photo.developSeq, message.photo.id, api, true);
writeKnown(sha, marks ?? {}, message.photo.developSeq, message.photo.id, api, true);
return;
}
if (message.type === "photo.updated") {
@@ -161,8 +203,10 @@ function marksOf(flag: string, rating: number, colorLabel: string, sent: boolean
export async function catchUpFileMarks(api: ApiClient, orgId: string): Promise<void> {
if (!isDesktop() || !orgId || caughtUp.has(orgId)) return;
caughtUp.add(orgId);
// Re-apply anything already remembered (survives a desktop update that swallowed earlier writes).
flushAllPhotoFiles();
// Only retry writes that failed. Rewriting every remembered original first left today's files
// waiting behind thousands of older JPEGs, so Lightroom imported them with no metadata.
flushFailedPhotoFiles();
flushRecentPhotoFiles();
let events: EventSummary[] = [];
try {
events = (await api.listEvents(orgId)).events.filter((event) => eventIsCurrent(event, Date.now()));
@@ -186,11 +230,14 @@ export async function catchUpFileMarks(api: ApiClient, orgId: string): Promise<v
offset += page.photos.length;
if (!page.photos.length) break;
for (const photo of page.photos) {
remember(photo.id, photo.sha256);
const sha = diskSha(photo.id, photo.sha256);
if (!sha) continue;
rememberPhotoFrame(sha, photo.width, photo.height);
remember(photo.id, sha);
const sent = photo.delivery === "DONE";
const marks = marksOf(photo.flag, photo.rating, photo.colorLabel, sent);
// Picks, develop and the resolved IPTC (event template + overrides) go into the file Lightroom imports.
writeKnown(photo.sha256, marks ?? {}, photo.developSeq, photo.id, api, true);
writeKnown(sha, marks ?? {}, photo.developSeq, photo.id, api, true);
}
}
}
@@ -202,13 +249,22 @@ export function FileMarksSync({ api, orgId }: { api: ApiClient; orgId: string })
useEffect(() => {
if (!orgId) return;
void catchUpFileMarks(api, orgId);
// The first pass often runs before the session token is ready. Retry until one pass sticks.
// A write also fails while the JPEG is still in the ingest folder; retry those, not the whole library.
const retry = window.setInterval(() => {
flushFailedPhotoFiles();
void catchUpFileMarks(api, orgId);
}, 15 * 1000);
// Periodic retry: a one-shot catch-up at login misses photos that arrive later, and a failed
// ftp_write_xmp must not leave the work folder empty for the rest of the day.
const timer = window.setInterval(() => {
caughtUp.delete(orgId);
void catchUpFileMarks(api, orgId);
}, 10 * 60 * 1000);
return () => window.clearInterval(timer);
return () => {
window.clearInterval(retry);
window.clearInterval(timer);
};
}, [api, orgId]);
return null;
}
@@ -0,0 +1,47 @@
import { describe, expect, it } from "vitest";
import { fromLightroomEdges, toLightroomEdges } from "./lightroomCrop.js";
/** PSR12211.JPG: a 3:2 crop with a strong straighten. Written raw, Lightroom levelled it to about 1.21. */
const shot = { left: 0.024609, top: 0.078821, right: 0.799609, bottom: 0.853821 };
const angle = -5.9;
const width = 6000;
const height = 4000;
function sides(rect: { left: number; top: number; right: number; bottom: number }): { w: number; h: number } {
return { w: rect.right - rect.left, h: rect.bottom - rect.top };
}
describe("Lightroom crop corners", () => {
it("keeps the photograph's aspect after Lightroom levels the straighten", () => {
const stored = toLightroomEdges(shot, angle, width, height);
const shown = fromLightroomEdges(stored, angle, width, height);
const got = sides(shown);
expect(Math.abs(got.w - got.h)).toBeLessThan(0.0001);
expect(stored.left).toBeGreaterThanOrEqual(0);
expect(stored.top).toBeGreaterThanOrEqual(0);
expect(stored.right).toBeLessThanOrEqual(1);
expect(stored.bottom).toBeLessThanOrEqual(1);
const pxW = got.w * width;
const pxH = got.h * height;
expect(pxW / pxH).toBeCloseTo(width / height, 3);
});
it("shrinks a crop that would leave the photo once it is turned", () => {
const full = { left: 0.01, top: 0.01, right: 0.99, bottom: 0.99 };
const stored = toLightroomEdges(full, 2.64, width, height);
expect(stored.left).toBeGreaterThanOrEqual(0);
expect(stored.top).toBeGreaterThanOrEqual(0);
expect(stored.right).toBeLessThanOrEqual(1);
expect(stored.bottom).toBeLessThanOrEqual(1);
const shown = fromLightroomEdges(stored, 2.64, width, height);
const got = sides(shown);
expect(Math.abs(got.w - got.h)).toBeLessThan(0.0001);
expect(got.w).toBeLessThan(0.98);
});
it("leaves a level crop untouched", () => {
const rect = { left: 0.1, top: 0.1, right: 0.8, bottom: 0.8 };
expect(toLightroomEdges(rect, 0, width, height)).toEqual(rect);
expect(fromLightroomEdges(rect, 0, width, height)).toEqual(rect);
});
});
+141
View File
@@ -0,0 +1,141 @@
/**
* Lightroom stores a crop as two opposite corners plus an angle. It then turns those corners
* back around the crop centre, and the levelled rectangle is what the crop tool shows.
* The app's crop is already that levelled rectangle (the photograph's own aspect: equal
* width and height in frame fractions). Writing it straight through makes the levelled
* result a different proportion, which the crop tool labels Custom.
*/
export interface CropEdges {
left: number;
top: number;
right: number;
bottom: number;
}
export interface PhotoFrame {
width: number;
height: number;
}
const frames = new Map<string, PhotoFrame>();
/** Pixel size of a local original, so a later read can turn Lightroom's corners back into the levelled crop. */
export function rememberPhotoFrame(sha256: string, width: number | null | undefined, height: number | null | undefined): void {
if (!sha256) return;
if (typeof width !== "number" || typeof height !== "number") return;
if (!(width > 0) || !(height > 0)) return;
frames.set(sha256, { width, height });
}
export function photoFrame(sha256: string): PhotoFrame | null {
return frames.get(sha256) ?? null;
}
function turn(x: number, y: number, cx: number, cy: number, deg: number): [number, number] {
const th = (deg * Math.PI) / 180;
const dx = x - cx;
const dy = y - cy;
const c = Math.cos(th);
const s = Math.sin(th);
return [dx * c - dy * s + cx, dx * s + dy * c + cy];
}
/** Top-left frame fractions as pixels with y growing up, the space the corner rotation is defined in. */
function pixel(x: number, yTop: number, width: number, height: number): [number, number] {
return [x * width, (1 - yTop) * height];
}
function shrunk(rect: CropEdges, scale: number): CropEdges {
const cx = (rect.left + rect.right) / 2;
const cy = (rect.top + rect.bottom) / 2;
const halfW = ((rect.right - rect.left) / 2) * scale;
const halfH = ((rect.bottom - rect.top) / 2) * scale;
return {
left: cx - halfW,
top: cy - halfH,
right: cx + halfW,
bottom: cy + halfH,
};
}
function cornersFit(rect: CropEdges, angle: number, width: number, height: number): boolean {
const ul = pixel(rect.left, rect.top, width, height);
const lr = pixel(rect.right, rect.bottom, width, height);
const cx = (ul[0] + lr[0]) / 2;
const cy = (ul[1] + lr[1]) / 2;
const a = -angle;
const pts: Array<[number, number]> = [
pixel(rect.left, rect.top, width, height),
pixel(rect.right, rect.top, width, height),
pixel(rect.right, rect.bottom, width, height),
pixel(rect.left, rect.bottom, width, height),
];
const eps = 0.5;
for (const [x, y] of pts) {
const [rx, ry] = turn(x, y, cx, cy, a);
if (rx < -eps || ry < -eps || rx > width + eps || ry > height + eps) return false;
}
return true;
}
function storedEdges(rect: CropEdges, angle: number, width: number, height: number): CropEdges {
const ul = pixel(rect.left, rect.top, width, height);
const lr = pixel(rect.right, rect.bottom, width, height);
const cx = (ul[0] + lr[0]) / 2;
const cy = (ul[1] + lr[1]) / 2;
const a = -angle;
const sul = turn(ul[0], ul[1], cx, cy, a);
const slr = turn(lr[0], lr[1], cx, cy, a);
return {
left: sul[0] / width,
top: 1 - sul[1] / height,
right: slr[0] / width,
bottom: 1 - slr[1] / height,
};
}
function ordered(rect: CropEdges): boolean {
if (!(rect.left < rect.right && rect.top < rect.bottom)) return false;
if (rect.left < -0.000001 || rect.top < -0.000001) return false;
if (rect.right > 1.000001 || rect.bottom > 1.000001) return false;
return true;
}
/**
* Corners to write for `crs:Crop*`. `rect` is the levelled crop (what the tool should show).
* A non-zero angle turns those corners about the crop centre, then shrinks until they stay on the photo.
*/
export function toLightroomEdges(rect: CropEdges, angle: number, width: number, height: number): CropEdges {
if (!(width > 0) || !(height > 0)) return rect;
if (!Number.isFinite(angle) || Math.abs(angle) < 0.05) return rect;
let scale = 1;
let fitted = rect;
for (let i = 0; i < 80; i++) {
fitted = shrunk(rect, scale);
const stored = storedEdges(fitted, angle, width, height);
if (cornersFit(fitted, angle, width, height) && ordered(stored)) return stored;
scale -= 0.012;
if (scale < 0.08) break;
}
return storedEdges(fitted, angle, width, height);
}
/** The levelled crop Lightroom shows for corners it stored. Inverse of `toLightroomEdges` when nothing was shrunk. */
export function fromLightroomEdges(rect: CropEdges, angle: number, width: number, height: number): CropEdges {
if (!(width > 0) || !(height > 0)) return rect;
if (!Number.isFinite(angle) || Math.abs(angle) < 0.05) return rect;
const ul = pixel(rect.left, rect.top, width, height);
const lr = pixel(rect.right, rect.bottom, width, height);
const cx = (ul[0] + lr[0]) / 2;
const cy = (ul[1] + lr[1]) / 2;
const a = -angle;
const uul = turn(ul[0], ul[1], cx, cy, -a);
const ulr = turn(lr[0], lr[1], cx, cy, -a);
return {
left: uul[0] / width,
top: 1 - uul[1] / height,
right: ulr[0] / width,
bottom: 1 - ulr[1] / height,
};
}
@@ -9,6 +9,23 @@ describe("Lightroom sidecar", () => {
expect(xml).not.toContain("crs:Shadows2012");
});
it("turns a straightened crop so Lightroom still shows the photograph's aspect", () => {
const xml = lightroomXmp(
JSON.stringify({
crop: {
geometry: {
angle: -5.9,
rect: { x0: 0.024609, y0: 0.078821, x1: 0.799609, y1: 0.853821 },
aspect: [6000, 4000],
},
},
}),
);
expect(xml).toContain('crs:CropAngle="-5.90"');
expect(xml).not.toContain('crs:CropLeft="0.024609"');
expect(xml).not.toContain('crs:CropTop="0.078821"');
});
it("writes a soft crop in the same crs fields Lightroom and Photo Mechanic read", () => {
const xml = lightroomXmp(JSON.stringify({ crop: { geometry: { angle: -1.91, rect: { x0: 0, y0: 0.126385, x1: 0.861387, y1: 0.926887 } } } }));
expect(xml).toContain('crs:HasCrop="True"');
@@ -60,6 +77,7 @@ describe("Lightroom sidecar", () => {
creator: "Fotógrafo / PhotoReport.pt",
},
);
expect(xml).toContain("<dc:title><rdf:Alt><rdf:li xml:lang=\"x-default\">Pavlidis</rdf:li></rdf:Alt></dc:title>");
expect(xml).toContain('dc:title="Pavlidis"');
expect(xml).toContain("Águas Santas Milaneza x SL Benfica, em Maia");
expect(xml).toContain('photoshop:City="Maia"');
+199 -20
View File
@@ -1,7 +1,10 @@
import type { DevelopState, EditCommand } from "@photoreport/contracts";
import { cropFromXmp } from "@photoreport/metadata";
import { localPhotos } from "../offline/local.js";
import { desktopInvoke, isDesktop } from "../platform.js";
import { fromLightroomEdges, photoFrame, toLightroomEdges, type PhotoFrame } from "./lightroomCrop.js";
/** Soft crop written as crs:Crop* (same numbers SoftCropGuide / Photo Mechanic draw). */
/** Soft crop in the app: the levelled rectangle. The file stores Lightroom's turned corners. */
export interface SoftCrop {
left: number;
top: number;
@@ -150,9 +153,12 @@ function iptcParts(iptc: FileIptc | undefined): { attrs: string[]; children: str
const caption = text("caption");
const creator = text("creator");
const keywords = Array.isArray(iptc.keywords) ? iptc.keywords.map((k) => k.trim()).filter(Boolean) : [];
let children = "";
if (title) {
need("dc", "http://purl.org/dc/elements/1.1/");
// Attribute: shells that only copy attributes onto the camera description. Element: Lightroom's Read Metadata.
attrs.push(`dc:title="${xmlAttr(title)}"`);
children += `<dc:title><rdf:Alt><rdf:li xml:lang="x-default">${xmlText(title)}</rdf:li></rdf:Alt></dc:title>`;
}
if (headline) {
need("photoshop", "http://ns.adobe.com/photoshop/1.0/");
@@ -182,7 +188,6 @@ function iptcParts(iptc: FileIptc | undefined): { attrs: string[]; children: str
need("photoshop", "http://ns.adobe.com/photoshop/1.0/");
attrs.push(`photoshop:Source="${xmlAttr(source)}"`);
}
let children = "";
if (caption) {
need("dc", "http://purl.org/dc/elements/1.1/");
children += `<dc:description><rdf:Alt><rdf:li xml:lang="x-default">${xmlText(caption)}</rdf:li></rdf:Alt></dc:description>`;
@@ -199,7 +204,7 @@ function iptcParts(iptc: FileIptc | undefined): { attrs: string[]; children: str
}
/** Only the sliders that are actually set. Missing ones stay out of the sidecar, so Lightroom is not given a preset. */
export function lightroomXmp(settings: string, marks?: FileMarks, iptc?: FileIptc): string | null {
export function lightroomXmp(settings: string, marks?: FileMarks, iptc?: FileIptc, frame?: PhotoFrame | null): string | null {
let doc: Record<string, unknown>;
try {
const parsed = JSON.parse(settings) as unknown;
@@ -241,12 +246,14 @@ export function lightroomXmp(settings: string, marks?: FileMarks, iptc?: FileIpt
if (sharpen !== undefined) attrs.push(`crs:Sharpness="${crsNumber(sharpen, 0)}"`);
if (nr !== undefined) attrs.push(`crs:ColorNoiseReduction="${crsNumber(nr, 0)}"`);
if (crop) {
const size = frameOf(doc) ?? frame ?? null;
const edges = size ? toLightroomEdges(crop, crop.angle, size.width, size.height) : crop;
attrs.push(
`crs:HasCrop="True"`,
`crs:CropLeft="${crop.left.toFixed(6)}"`,
`crs:CropTop="${crop.top.toFixed(6)}"`,
`crs:CropRight="${crop.right.toFixed(6)}"`,
`crs:CropBottom="${crop.bottom.toFixed(6)}"`,
`crs:CropLeft="${edges.left.toFixed(6)}"`,
`crs:CropTop="${edges.top.toFixed(6)}"`,
`crs:CropRight="${edges.right.toFixed(6)}"`,
`crs:CropBottom="${edges.bottom.toFixed(6)}"`,
`crs:CropAngle="${crsNumber(crop.angle, 2)}"`,
`crs:CropConstrainToUnitSquare="1"`,
`crs:AlreadyApplied="False"`,
@@ -276,7 +283,15 @@ export function lightroomXmp(settings: string, marks?: FileMarks, iptc?: FileIpt
function foldEdit(doc: Record<string, unknown>, command: EditCommand): void {
if (command.command === "develop.set") Object.assign(doc, command.params.values);
else if (command.command === "crop.set") doc.crop = { geometry: { rect: command.params.rect, angle: command.params.angle ?? 0 } };
else if (command.command === "crop.set") {
const geometry: { rect: typeof command.params.rect; angle: number; aspect?: [number, number] } = {
rect: command.params.rect,
angle: command.params.angle ?? 0,
};
const aspect = command.params.aspect;
if (aspect && aspect[0] > 0 && aspect[1] > 0) geometry.aspect = [aspect[0], aspect[1]];
doc.crop = { geometry };
}
else if (command.command === "develop.merge") Object.assign(doc, command.params.partial);
else if (command.command === "develop.reset") {
for (const key of Object.keys(doc)) delete doc[key];
@@ -297,6 +312,56 @@ export function settingsFromDevelop(state: DevelopState): string {
return JSON.stringify(doc);
}
function frameOf(doc: Record<string, unknown>): PhotoFrame | null {
const crop = doc.crop;
if (!crop || typeof crop !== "object") return null;
const geometry = (crop as { geometry?: unknown }).geometry;
if (!geometry || typeof geometry !== "object") return null;
const aspect = (geometry as { aspect?: unknown }).aspect;
if (!Array.isArray(aspect) || aspect.length < 2) return null;
const width = aspect[0];
const height = aspect[1];
if (typeof width !== "number" || typeof height !== "number") return null;
if (!(width > 0) || !(height > 0)) return null;
return { width, height };
}
function docOf(settings: string): Record<string, unknown> | null {
try {
const parsed = JSON.parse(settings) as unknown;
if (!parsed || typeof parsed !== "object") return null;
return parsed as Record<string, unknown>;
} catch {
return null;
}
}
/** Pixel size for this file: the crop's own aspect, then a size learned from the library. */
export function frameForPhoto(sha256: string, settings: string): PhotoFrame | null {
const doc = docOf(settings);
if (doc) {
const fromCrop = frameOf(doc);
if (fromCrop) return fromCrop;
}
const known = photoFrame(sha256);
if (known) return known;
const local = localPhotos.bySha(sha256);
if (local && local.width && local.height && local.width > 0 && local.height > 0) {
return { width: local.width, height: local.height };
}
return null;
}
/** A straighten with no pixel size would be written as a different aspect. Hold the file until the size is known. */
export function cropWaitsForFrame(settings: string, frame: PhotoFrame | null): boolean {
const doc = docOf(settings);
if (!doc) return false;
const crop = cropOf(doc);
if (!crop || Math.abs(crop.angle) < 0.05) return false;
if (frameOf(doc) || frame) return false;
return true;
}
function cropOf(doc: Record<string, unknown>): SoftCrop | null {
const crop = doc.crop;
if (!crop || typeof crop !== "object") return null;
@@ -326,31 +391,82 @@ interface RememberedFile {
iptc: FileIptc;
}
/** Rows this session must write even when the stored history no longer fits. */
const rememberedNow = new Map<string, RememberedFile>();
function loadRemembered(): Record<string, RememberedFile> {
let all: Record<string, RememberedFile> = {};
try {
const raw = localStorage.getItem(FILE_MARKS_KEY);
const parsed = raw ? (JSON.parse(raw) as unknown) : {};
if (!parsed || typeof parsed !== "object") return {};
return parsed as Record<string, RememberedFile>;
if (parsed && typeof parsed === "object") all = parsed as Record<string, RememberedFile>;
} catch {
return {};
all = {};
}
for (const [sha, row] of rememberedNow) {
all[sha] = row;
}
return all;
}
function saveRemembered(all: Record<string, RememberedFile>): void {
// Each row carries the develop JSON. A few thousand of them exceed what the web view will store,
// and a failed save used to drop the write of the file Lightroom imports.
const keys = Object.keys(all);
if (keys.length > 4000) {
for (const key of keys.slice(0, keys.length - 4000)) delete all[key];
const kept = 400;
if (keys.length > kept) {
for (const key of keys.slice(0, keys.length - kept)) {
if (rememberedNow.has(key)) continue;
delete all[key];
}
}
try {
localStorage.setItem(FILE_MARKS_KEY, JSON.stringify(all));
return;
} catch {
// A full localStorage must not stop the edit itself.
// Still over the quota. Keep only what this session is writing.
}
const slim: Record<string, RememberedFile> = {};
for (const [sha, row] of rememberedNow) {
slim[sha] = row;
}
try {
localStorage.setItem(FILE_MARKS_KEY, JSON.stringify(slim));
} catch {
// flushPhotoFile reads rememberedNow, so the file is still written this session.
}
}
const flushTimers = new Map<string, number>();
let flushChain = Promise.resolve();
const flushFailed = new Set<string>();
const flushSoon: string[] = [];
let flushRunning = false;
const FLUSH_TIMEOUT_MS = 20_000;
function enqueueFlush(sha256: string): void {
if (!sha256) return;
if (flushSoon.includes(sha256)) return;
flushSoon.push(sha256);
void runFlushQueue();
}
async function runFlushQueue(): Promise<void> {
if (flushRunning) return;
flushRunning = true;
try {
while (flushSoon.length > 0) {
const sha256 = flushSoon.shift();
if (!sha256) break;
await flushPhotoFile(sha256);
}
} finally {
flushRunning = false;
if (flushSoon.length > 0) {
void runFlushQueue();
}
}
}
function scheduleFlush(sha256: string): void {
const pending = flushTimers.get(sha256);
@@ -359,27 +475,60 @@ function scheduleFlush(sha256: string): void {
sha256,
window.setTimeout(() => {
flushTimers.delete(sha256);
flushChain = flushChain.then(() => flushPhotoFile(sha256)).catch(() => {});
enqueueFlush(sha256);
}, 400),
);
}
function invokeWithTimeout(command: string, args: Record<string, unknown>): Promise<unknown> {
return new Promise((resolve, reject) => {
const timer = window.setTimeout(() => {
reject(new Error("timeout"));
}, FLUSH_TIMEOUT_MS);
desktopInvoke(command, args).then(
(value) => {
window.clearTimeout(timer);
resolve(value);
},
(err: unknown) => {
window.clearTimeout(timer);
reject(err);
},
);
});
}
async function flushPhotoFile(sha256: string): Promise<void> {
const row = loadRemembered()[sha256];
const row = rememberedNow.get(sha256) ?? loadRemembered()[sha256];
if (!row) return;
const xml = lightroomXmp(row.settings, { flag: row.flag, rating: row.rating, colorLabel: row.colorLabel, sent: row.sent }, iptcOf(row.iptc));
const frame = frameForPhoto(sha256, row.settings);
// Without the pixel size a straighten is written as another aspect. Wait, and retry.
if (cropWaitsForFrame(row.settings, frame)) {
flushFailed.add(sha256);
return;
}
const xml = lightroomXmp(row.settings, { flag: row.flag, rating: row.rating, colorLabel: row.colorLabel, sent: row.sent }, iptcOf(row.iptc), frame);
if (!xml) return;
// Write the file first. Soft-crop bookkeeping must not block or abort the Lightroom packet.
try {
await desktopInvoke("ftp_write_xmp", { sha256, xml });
await invokeWithTimeout("ftp_write_xmp", { sha256, xml });
flushFailed.delete(sha256);
} catch (err) {
// The original is often still in the ingest folder. Retry once it has been filed.
flushFailed.add(sha256);
console.error("ftp_write_xmp", sha256.slice(0, 12), err);
return;
}
try {
const { noteOwnSoftCropWrite } = await import("./softCropWatch.js");
const writtenFlag = row.sent || row.flag === "PICK" ? "PICK" : row.flag === "REJECT" ? "REJECT" : row.flag === "NONE" ? "NONE" : undefined;
noteOwnSoftCropWrite(sha256, softCropFromSettings(row.settings), writtenFlag);
const raw = cropFromXmp(xml);
let noted = softCropFromSettings(row.settings);
if (raw && frame && Math.abs(raw.angle) >= 0.05) {
const back = fromLightroomEdges(raw, raw.angle, frame.width, frame.height);
noted = { left: back.left, top: back.top, right: back.right, bottom: back.bottom, angle: raw.angle };
}
noteOwnSoftCropWrite(sha256, noted, writtenFlag);
} catch {
// Watcher is optional; the file already has the marks.
}
@@ -391,6 +540,35 @@ export function flushAllPhotoFiles(): void {
for (const sha256 of Object.keys(loadRemembered())) scheduleFlush(sha256);
}
/** Writes that failed (file still in ingest, or the shell was busy) — not the whole library. */
export function flushFailedPhotoFiles(): void {
if (!isDesktop()) return;
for (const sha256 of flushFailed) scheduleFlush(sha256);
}
/**
* The photos remembered most recently (today's event is at the end of the list). Written first,
* so a catch-up that has not reached the server yet still updates the files Lightroom imports.
*/
export function flushRecentPhotoFiles(): void {
if (!isDesktop()) return;
const keys = Object.keys(loadRemembered());
const start = Math.max(0, keys.length - 120);
const recent = keys.slice(start);
for (let index = recent.length - 1; index >= 0; index -= 1) {
const sha256 = recent[index];
if (!sha256) continue;
scheduleFlush(sha256);
}
}
/** The original just moved into the work folder. Write the marks already waiting for it. */
export function retryPhotoFile(sha256: string): void {
if (!isDesktop() || !sha256) return;
if (!loadRemembered()[sha256]) return;
scheduleFlush(sha256);
}
export interface FileMarkUpdate {
settings?: string;
flag?: string | null;
@@ -433,6 +611,7 @@ export function writePhotoFile(sha256: string, update: FileMarkUpdate): void {
iptc: "iptc" in update ? iptcOf(update.iptc) : prev.iptc,
};
all[sha256] = next;
rememberedNow.set(sha256, next);
saveRemembered(all);
scheduleFlush(sha256);
}
@@ -0,0 +1,25 @@
import { describe, expect, it } from "vitest";
import { cullPatchFromMarks, hasDiskMarks, marksFromXmpText } from "./readFileMarks.js";
describe("marksFromXmpText", () => {
it("reads pick without stars", () => {
const marks = marksFromXmpText(`<xmpDM:pick>1</xmpDM:pick><xmp:Rating>0</xmp:Rating>`);
expect(marks.flag).toBe("PICK");
expect(marks.rating).toBe(0);
expect(hasDiskMarks(marks)).toBe(true);
expect(cullPatchFromMarks(marks)).toEqual({ flag: "PICK" });
});
it("turns stars into a pick when the flag is absent", () => {
const marks = marksFromXmpText(`<xmp:Rating>4</xmp:Rating>`);
expect(cullPatchFromMarks(marks)).toEqual({ flag: "PICK", rating: 4 });
});
it("reads soft crop edges", () => {
const marks = marksFromXmpText(
`crs:HasCrop="True" crs:CropLeft="0.1" crs:CropTop="0.05" crs:CropRight="0.9" crs:CropBottom="0.95" crs:CropAngle="1.5"`,
);
expect(marks.crop).toEqual({ left: 0.1, top: 0.05, right: 0.9, bottom: 0.95, angle: 1.5 });
expect(hasDiskMarks(marks)).toBe(true);
});
});
+132
View File
@@ -0,0 +1,132 @@
import {
colorClassFromXmp,
cropFromXmp,
libraryMarksFromXmp,
xmpPacketFromJpeg,
type SoftCrop,
type XmpColor,
} from "@photoreport/metadata";
import type { ColorLabel, PhotoFlag } from "@photoreport/contracts";
import { desktopInvoke, isDesktop } from "../platform.js";
import { localXmpText } from "./softCrop.js";
/** Cull marks and soft crop read from a JPEG / XMP packet on disk. */
export interface DiskFileMarks {
flag: PhotoFlag;
rating: number;
colorLabel: ColorLabel;
crop: SoftCrop | null;
}
const EMPTY: DiskFileMarks = {
flag: "NONE",
rating: 0,
colorLabel: "NONE",
crop: null,
};
/** Parse cull marks and soft crop from an XMP packet (embedded or sidecar text). */
export function marksFromXmpText(xmp: string | null | undefined): DiskFileMarks {
if (!xmp) return { ...EMPTY };
const marks = libraryMarksFromXmp(xmp);
const color = colorClassFromXmp(xmp);
let flag: PhotoFlag = "NONE";
if (marks.flag === "PICK" || marks.flag === "REJECT") flag = marks.flag;
let rating = 0;
if (typeof marks.rating === "number" && marks.rating > 0) rating = Math.min(5, marks.rating);
let colorLabel: ColorLabel = "NONE";
if (color && color !== "NONE") colorLabel = color;
else if (
marks.colorLabel === "RED" ||
marks.colorLabel === "YELLOW" ||
marks.colorLabel === "GREEN" ||
marks.colorLabel === "BLUE" ||
marks.colorLabel === "PURPLE"
) {
colorLabel = marks.colorLabel;
}
return {
flag,
rating,
colorLabel,
crop: cropFromXmp(xmp),
};
}
/** Parse marks from JPEG bytes (hand import / FTP original). */
export function marksFromJpegBytes(bytes: ArrayBuffer | Uint8Array): DiskFileMarks {
const view = bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes);
return marksFromXmpText(xmpPacketFromJpeg(view));
}
/** True when the packet carries something the library should keep. */
export function hasDiskMarks(marks: DiskFileMarks): boolean {
if (marks.flag !== "NONE") return true;
if (marks.rating > 0) return true;
if (marks.colorLabel !== "NONE") return true;
if (marks.crop) return true;
return false;
}
/** Library patch for cull fields only (crop is a develop op). */
export function cullPatchFromMarks(marks: DiskFileMarks): {
flag?: PhotoFlag;
rating?: number;
colorLabel?: ColorLabel;
} {
const patch: { flag?: PhotoFlag; rating?: number; colorLabel?: ColorLabel } = {};
if (marks.flag !== "NONE") patch.flag = marks.flag;
else if (marks.rating > 0) patch.flag = "PICK";
if (marks.rating > 0) patch.rating = marks.rating;
if (marks.colorLabel !== "NONE") patch.colorLabel = marks.colorLabel;
return patch;
}
/** Soft crop as the develop command Revelar / the offline queue already understand. */
export function cropCommandFromMarks(marks: DiskFileMarks): {
command: "crop.set";
params: {
rect: { x0: number; y0: number; x1: number; y1: number };
angle: number;
aspect: null;
};
} | null {
if (!marks.crop) return null;
return {
command: "crop.set",
params: {
rect: {
x0: marks.crop.left,
y0: marks.crop.top,
x1: marks.crop.right,
y1: marks.crop.bottom,
},
angle: marks.crop.angle,
aspect: null,
},
};
}
/** Read marks for a work-folder original already known by SHA (catalog / local index). */
export async function marksFromLocalSha(sha256: string): Promise<DiskFileMarks> {
if (!isDesktop() || !sha256) return { ...EMPTY };
const xmp = await localXmpText(sha256);
return marksFromXmpText(xmp);
}
/**
* Read marks from a JPEG still in the local FTP ingest tree (path from `ftp_take`).
* Prefer `marksFromLocalSha` after `ftp_info` (sidecar + embedded). This path only sees the embedded packet.
*/
export async function marksFromFtpPath(path: string): Promise<DiskFileMarks> {
if (!isDesktop() || !path) return { ...EMPTY };
try {
const raw = await desktopInvoke<number[] | Uint8Array>("ftp_read", { path });
const bytes = raw instanceof Uint8Array ? raw : new Uint8Array(raw);
return marksFromJpegBytes(bytes);
} catch {
return { ...EMPTY };
}
}
export type { SoftCrop, XmpColor };
+11 -1
View File
@@ -1,5 +1,6 @@
import { cropFromXmp, type SoftCrop, xmpPacketFromJpeg } from "@photoreport/metadata";
import { desktopInvoke, isDesktop } from "../platform.js";
import { fromLightroomEdges, photoFrame } from "./lightroomCrop.js";
const cache = new Map<string, SoftCrop | null>();
const inflight = new Map<string, Promise<SoftCrop | null>>();
@@ -39,7 +40,16 @@ export async function softCropFor(sha256: string): Promise<SoftCrop | null> {
const work = (async () => {
try {
const xmp = await localXmpText(sha256);
const crop = xmp ? cropFromXmp(xmp) : null;
const raw = xmp ? cropFromXmp(xmp) : null;
if (!raw || Math.abs(raw.angle) < 0.05) {
cache.set(sha256, raw);
return raw;
}
const frame = photoFrame(sha256);
// The file stores turned corners. Without the photo size they are not the crop to draw.
if (!frame) return raw;
const back = fromLightroomEdges(raw, raw.angle, frame.width, frame.height);
const crop = { left: back.left, top: back.top, right: back.right, bottom: back.bottom, angle: raw.angle };
cache.set(sha256, crop);
return crop;
} catch {
+99 -16
View File
@@ -1,14 +1,17 @@
import { colorClassFromXmp, cropFromXmp, type SoftCrop, type XmpColor } from "@photoreport/metadata";
import { colorClassFromXmp, cropFromXmp, libraryMarksFromXmp, type SoftCrop, type XmpColor } from "@photoreport/metadata";
import type { ColorLabel, PhotoFlag } from "@photoreport/contracts";
import { desktopInvoke, isDesktop } from "../platform.js";
import { offlineQueue } from "../offline/queue.js";
import { fromLightroomEdges, photoFrame } from "./lightroomCrop.js";
import { forgetSoftCrop, localXmpText } from "./softCrop.js";
/**
* Watch local originals for soft-crop changes written outside this app (Lightroom / Photo Mechanic).
* When the XMP crop changes, apply the same rectangle as a develop `crop.set` so Revelar, export and
* the autopilot learner all see it — the same path as cropping inside the app.
* Watch local originals for soft-crop and cull-mark changes written outside this app (Lightroom /
* Photo Mechanic). Crop → develop `crop.set`; pick / stars / colour → library patch. Same path as
* editing inside the app, including the autopilot learner.
*/
const STORE_KEY = "softcrop:watch";
/** v2: re-read every watched file once after JPEG-sidecar + cull fixes (BIT-33124). */
const STORE_KEY = "softcrop:watch:v2";
const MAX_WATCH = 800;
const OWN_WRITE_GRACE_MS = 4_000;
@@ -26,6 +29,8 @@ export interface WatchedSoftCrop {
color?: string | undefined;
/** Pick last written or read. A later change in Lightroom is applied once. */
flag?: string | undefined;
/** Stars last read from the file. */
rating?: number | undefined;
}
/** Return true when the crop was applied into an open develop session (skip a second queue write). */
@@ -105,12 +110,21 @@ function cropsEqual(a: SoftCrop, b: SoftCrop): boolean {
/** Apply a colour Photo Mechanic wrote into the original. */
export type ApplyExternalColor = (orgId: string, photoId: string, color: XmpColor) => Promise<void>;
/** Apply pick / stars / colour from the file into the library. */
export type ApplyExternalMarks = (
orgId: string,
photoId: string,
patch: { flag?: PhotoFlag; rating?: number; colorLabel?: ColorLabel },
) => Promise<void>;
/**
* One pass: re-read soft crops whose file (or sidecar) mtime moved, apply as develop crop when the
* rectangle changed, and copy a colour class Photo Mechanic wrote onto the library photo.
* Returns how many photos received a new crop.
* One pass: re-read soft crops and cull marks whose file (or sidecar) mtime moved.
* Crop → develop; pick / stars / colour → library. Returns how many photos got a new crop.
*/
export async function reconcileSoftCrops(applyColor?: ApplyExternalColor): Promise<number> {
export async function reconcileSoftCrops(
applyColor?: ApplyExternalColor,
applyMarks?: ApplyExternalMarks,
): Promise<number> {
if (!isDesktop()) return 0;
const rows = load();
if (!rows.length) return 0;
@@ -123,9 +137,9 @@ export async function reconcileSoftCrops(applyColor?: ApplyExternalColor): Promi
next.push(row);
continue;
}
// A row saved before colours were copied has no `color`. Read it once even if the mtime is already known,
// so a colour painted earlier still arrives. "" means we looked and the file names no colour.
if (stat.mtimeMs && stat.mtimeMs === row.mtimeMs && row.color !== undefined) {
// First pass (no color/flag yet) always re-reads; later only when the file moves.
const seenCull = row.color !== undefined && row.flag !== undefined;
if (stat.mtimeMs && stat.mtimeMs === row.mtimeMs && seenCull) {
next.push(row);
continue;
}
@@ -135,10 +149,70 @@ export async function reconcileSoftCrops(applyColor?: ApplyExternalColor): Promi
}
forgetSoftCrop(row.sha256);
const xmp = await localXmpText(row.sha256);
const crop = xmp ? cropFromXmp(xmp) : null;
const color = xmp ? colorClassFromXmp(xmp) : null;
if (!xmp) {
// No packet yet (sidecar still writing). Remember mtime; a later sidecar bumps it via local_stat.
next.push({
...row,
mtimeMs: stat.mtimeMs || row.mtimeMs,
color: row.color !== undefined ? row.color : "",
flag: row.flag !== undefined ? row.flag : "NONE",
rating: row.rating !== undefined ? row.rating : 0,
});
continue;
}
const rawCrop = cropFromXmp(xmp);
// A straighten is stored as turned corners. Without the photo size those corners are not the crop we show.
if (rawCrop && Math.abs(rawCrop.angle) >= 0.05 && !photoFrame(row.sha256)) {
next.push(row);
continue;
}
let crop = rawCrop;
if (rawCrop && Math.abs(rawCrop.angle) >= 0.05) {
const frame = photoFrame(row.sha256);
if (frame) {
const back = fromLightroomEdges(rawCrop, rawCrop.angle, frame.width, frame.height);
crop = { left: back.left, top: back.top, right: back.right, bottom: back.bottom, angle: rawCrop.angle };
}
}
const color = colorClassFromXmp(xmp);
const marks = libraryMarksFromXmp(xmp);
let colorApplied = color ? row.color : (row.color ?? "");
if (color && color !== row.color && applyColor) {
let flagApplied = row.flag ?? "NONE";
let ratingApplied = row.rating ?? 0;
const patch: { flag?: PhotoFlag; rating?: number; colorLabel?: ColorLabel } = {};
if (color && color !== "NONE" && color !== row.color) {
patch.colorLabel = color;
colorApplied = color;
}
let nextFlag: PhotoFlag = "NONE";
if (marks.flag === "PICK" || marks.flag === "REJECT") nextFlag = marks.flag;
if (nextFlag !== (row.flag ?? "NONE") && nextFlag !== "NONE") {
patch.flag = nextFlag;
flagApplied = nextFlag;
}
const nextRating = typeof marks.rating === "number" && marks.rating > 0 ? marks.rating : 0;
if (nextRating > 0 && nextRating !== (row.rating ?? 0)) {
patch.rating = nextRating;
ratingApplied = nextRating;
if (!patch.flag && nextFlag === "NONE") patch.flag = "PICK";
}
if (Object.keys(patch).length && applyMarks) {
try {
await applyMarks(row.orgId, row.photoId, patch);
} catch {
if (applyColor && patch.colorLabel) {
try {
await applyColor(row.orgId, row.photoId, patch.colorLabel as XmpColor);
} catch {
next.push(row);
continue;
}
} else {
next.push(row);
continue;
}
}
} else if (color && color !== row.color && applyColor) {
try {
await applyColor(row.orgId, row.photoId, color);
colorApplied = color;
@@ -149,7 +223,14 @@ export async function reconcileSoftCrops(applyColor?: ApplyExternalColor): Promi
}
const fingerprint = softCropFingerprint(crop);
if (!crop || fingerprint === row.fingerprint) {
next.push({ ...row, mtimeMs: stat.mtimeMs || row.mtimeMs, fingerprint, color: colorApplied });
next.push({
...row,
mtimeMs: stat.mtimeMs || row.mtimeMs,
fingerprint,
color: colorApplied,
flag: flagApplied,
rating: ratingApplied,
});
continue;
}
const command = {
@@ -171,6 +252,8 @@ export async function reconcileSoftCrops(applyColor?: ApplyExternalColor): Promi
mtimeMs: stat.mtimeMs || row.mtimeMs,
fingerprint,
color: colorApplied,
flag: flagApplied,
rating: ratingApplied,
ownWriteUntil: now + OWN_WRITE_GRACE_MS,
});
}
+6 -1
View File
@@ -42,6 +42,8 @@ export const t = {
label: "sem ligação",
waiting: (n: number) => (n === 1 ? "1 alteração à espera de ligação" : `${n} alterações à espera de ligação`),
waitingHelp: "Feito sem ligação ao servidor: fica guardado neste computador e é enviado sozinho quando a ligação voltar.",
pending: (n: number) => (n === 1 ? "1 alteração por enviar" : `${n} alterações por enviar`),
pendingHelp: "A ligação está feita. Estas alterações seguem para o servidor.",
queuedDelivery: "Sem ligação: o envio fica à espera e sai sozinho quando a ligação voltar.",
editingOffline: "Sem ligação: as edições ficam guardadas neste computador e são enviadas quando a ligação voltar.",
},
@@ -711,7 +713,7 @@ export const t = {
startsAt: "Início",
photographers: "Fotógrafos",
pickMatch: "Escolher o jogo",
pickMatchHelp: "Jogos da Liga Portugal, FPF, FPA, EHF Euro Cup (seleções) e UEFA (Champions, Liga Europa, Conference, Champions feminina e de futsal) dos próximos dias (ao pesquisar, também os dos últimos 10 dias). Preenche o evento e junta os plantéis às pessoas. As fotos de 2 h antes até 4 h depois do apito vão para este evento.",
pickMatchHelp: "Jogos da Liga Portugal, FPF, FPA, EHF Euro Cup (seleções), W17 EHF EURO (qualificação de sub-17 feminina) e UEFA (Champions, Liga Europa, Conference, Champions feminina e de futsal) dos próximos dias (ao pesquisar, também os dos últimos 10 dias). Preenche o evento e junta os plantéis às pessoas. As fotos de 2 h antes até 4 h depois do apito vão para este evento.",
squadFromMatch: "Usar o plantel de um jogo",
squadFromMatchHelp: "Treino ou sessão: fica com os jogadores desse jogo, sem ser o jogo (legenda e hora são as tuas).",
searchMatch: "Equipa, competição ou pavilhão",
@@ -1111,6 +1113,8 @@ export const t = {
orderStatus: { PENDING: "por pagar", PAID: "paga", FULFILLED: "concluída", CANCELLED: "cancelada", REFUNDED: "reembolsada" },
itemStatus: { PENDING: "a preparar", RUNNING: "a preparar", READY: "pronto", SHIPPED: "enviado", FAILED: "falhou" },
markShipped: "Marcar enviada",
collectPayment: "Pagamento recebido",
confirmCollectPayment: "Recebeste o pagamento fora da loja? A encomenda passa a paga e ficas responsável por entregar o trabalho.",
reverseCharge: "Autoliquidação",
noOrders: "Sem encomendas.",
productsHelp: "Preços com IVA incluído. JPEG: tamanho do lado maior (0 = original). Impressões: tamanho e prazo de envio.",
@@ -1337,6 +1341,7 @@ export const t = {
level: "Nivelar",
autoCropHelp: "Recorte automático à volta de quem a foto é: a bola e quem a disputa, ou o grupo principal, sem cortar corpos a meio.",
autoCropNone: "Não encontrei um assunto claro nesta foto para recortar.",
autoCropKept: "A foto já está enquadrada à volta de quem está nela.",
autoCropMissing: "O recorte automático ainda não está instalado neste servidor.",
levelHelp: "Endireita a foto pelo horizonte ou pelas linhas verticais.",
levelNone: "Não encontrei horizonte nem linhas verticais claras nesta foto: endireita com o ângulo.",
+7 -3
View File
@@ -5,6 +5,10 @@ import { EventsPanel } from "./EventsPanel.js";
import { PhotoContextMenu } from "./PhotoContextMenu.js";
function event(id: string, title: string): EventSummary {
const startsAt = new Date(Date.now() - 86_400_000);
const iso = startsAt.toISOString();
const at = (offsetMs: number) =>
new Date(startsAt.getTime() + offsetMs).toISOString();
return {
id,
organizationId: "org",
@@ -20,9 +24,9 @@ function event(id: string, title: string): EventSummary {
competitionCode: null,
round: null,
matchNumber: null,
startsAt: "2026-11-21T10:56:00.000Z",
ingestFrom: "2026-11-21T08:56:00.000Z",
ingestUntil: "2026-11-21T14:56:00.000Z",
startsAt: iso,
ingestFrom: at(-2 * 3_600_000),
ingestUntil: at(4 * 3_600_000),
iptcTemplate: {},
archivedAt: null,
photographers: [],
+10 -4
View File
@@ -1,6 +1,8 @@
import type { SoftCrop } from "@photoreport/metadata";
import type { ColorLabel, PhotoSummary } from "@photoreport/contracts";
import { memo, useEffect, useRef, useState } from "react";
import { fileShaForPhoto } from "../desktop/fileMarks.js";
import { rememberPhotoFrame } from "../desktop/lightroomCrop.js";
import { softCropFor } from "../desktop/softCrop.js";
import { watchSoftCropPhoto } from "../desktop/softCropWatch.js";
import { t } from "../i18n.js";
@@ -41,19 +43,23 @@ const Cell = memo(function Cell({ photo, index, src, orgId, selected, focused, o
const [softCrop, setSoftCrop] = useState<SoftCrop | null>(null);
useEffect(() => setImgFailed(false), [shown]);
useEffect(() => {
if (!isDesktop() || !photo.sha256) {
const sha = fileShaForPhoto(photo.id, photo.sha256);
if (!isDesktop() || !sha) {
setSoftCrop(null);
return;
}
if (orgId) watchSoftCropPhoto(orgId, photo.id, photo.sha256);
if (orgId) {
rememberPhotoFrame(sha, photo.width, photo.height);
watchSoftCropPhoto(orgId, photo.id, sha);
}
let alive = true;
void softCropFor(photo.sha256).then((crop) => {
void softCropFor(sha).then((crop) => {
if (alive) setSoftCrop(crop);
});
return () => {
alive = false;
};
}, [orgId, photo.id, photo.sha256]);
}, [orgId, photo.id, photo.sha256, photo.width, photo.height]);
return (
<button
ref={ref}
+42 -3
View File
@@ -8,6 +8,7 @@ import { localId, offlineQueue } from "../offline/queue.js";
import { useCallback, useEffect, useRef, useState } from "react";
import { t } from "../i18n.js";
import { SnapshotMenu } from "./SnapshotMenu.js";
import { retryPhotoFile } from "../desktop/lightroomSidecar.js";
import { asArrayBuffer, prefs } from "../platform.js";
import type { DesktopOrigin, PreviewOf, UploadStatus } from "./uploads.js";
@@ -185,9 +186,43 @@ export function useLocalFtp(add: Add, enabled: boolean, invoke: Invoke = tauriIn
} catch {
/* no blob URLs here (tests): shown without a thumbnail */
}
localPhotos.put(localPhoto({ sha256: info.sha256, name: f.name, width: info.width, height: info.height, capturedAt, eventId, url }));
// Preview strips XMP — read pick / stars / colour / soft crop from the indexed original (sidecar or embedded).
const { marksFromLocalSha, cullPatchFromMarks, cropCommandFromMarks, hasDiskMarks } = await import(
"../desktop/readFileMarks.js"
);
const disk = await marksFromLocalSha(info.sha256);
const cull = cullPatchFromMarks(disk);
localPhotos.put(
localPhoto({
sha256: info.sha256,
name: f.name,
width: info.width,
height: info.height,
capturedAt,
eventId,
url,
...cull,
}),
);
if (orgId) {
const id = localId(info.sha256);
if (hasDiskMarks(disk)) {
if (Object.keys(cull).length) {
offlineQueue(orgId).add({ kind: "patch", ids: [id], patch: cull });
}
const cropOp = cropCommandFromMarks(disk);
if (cropOp) offlineQueue(orgId).enqueueEdit(id, cropOp);
}
// Always watch: marks written later in Photo Mechanic / Lightroom still land in the library.
const { watchSoftCropPhoto } = await import("../desktop/softCropWatch.js");
watchSoftCropPhoto(orgId, id, info.sha256);
}
// Culled before a restart (still offline): it comes back as it was left.
for (const op of orgId ? offlineQueue(orgId).pending : []) if (op.kind === "patch" && op.ids.includes(localId(info.sha256))) localPhotos.patch(localId(info.sha256), op.patch as Partial<PhotoSummary>);
for (const op of orgId ? offlineQueue(orgId).pending : []) {
if (op.kind === "patch" && op.ids.includes(localId(info.sha256))) {
localPhotos.patch(localId(info.sha256), op.patch as Partial<PhotoSummary>);
}
}
}
// The preview is on screen. The next photo does not wait for this one's upload: a slow network must
// not stop the grid or Revelar.
@@ -208,7 +243,11 @@ export function useLocalFtp(add: Add, enabled: boolean, invoke: Invoke = tauriIn
sentEvent = to.title;
sentDate = to.date;
}
invoke("ftp_sent", { path: f.path, event: sentEvent, date: sentDate }).catch(() => {});
invoke("ftp_sent", { path: f.path, event: sentEvent, date: sentDate })
.then(() => {
retryPhotoFile(info.sha256);
})
.catch(() => {});
// Changes made to it meanwhile now go to the server's copy.
if (photo && orgId) {
offlineQueue(orgId).uploaded(info.sha256, photo.id);
+7
View File
@@ -139,6 +139,13 @@ const PRESETS = {
longEdge: 4000,
...DESTINATION_EXAMPLES.fpaM19,
},
fpaW17: {
label: "Cloud W17",
kind: "NEXTCLOUD",
baseUrl: "https://cloud.photoreport.pt",
longEdge: 4000,
...DESTINATION_EXAMPLES.fpaW17,
},
liga: {
label: "Estrutura Liga",
kind: "NEXTCLOUD",
+6 -1
View File
@@ -3,6 +3,7 @@ import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { t } from "../i18n.js";
import { cache } from "../offline/cache.js";
import { eventForArrival, exifDateTime, lisbonInstant } from "../offline/local.js";
import { retryPhotoFile } from "../desktop/lightroomSidecar.js";
import { asArrayBuffer, prefs } from "../platform.js";
import { type FtpTarget, type IncomingFile, type Invoke, eventLabel } from "./LocalFtp.js";
import type { PreviewOf, UploadStatus } from "./uploads.js";
@@ -112,7 +113,11 @@ export function useUsbCamera(add: Add, enabled: boolean, target: FtpTarget | nul
path: f.path,
event: filed ? eventLabel(filed) : (to?.title ?? ""),
date: filed ? filed.startsAt.slice(0, 10) : (to?.date ?? ""),
}).catch(() => {});
})
.then(() => {
retryPhotoFile(original.sha256);
})
.catch(() => {});
} else {
setCounts((c) => ({ ...c, failed: c.failed + 1 }));
}
+29
View File
@@ -2,6 +2,7 @@ import type { PhotoSummary } from "@photoreport/contracts";
import type { EventSummary } from "@photoreport/sdk";
import { eventForArrival, exifDateTime, lisbonInstant, localPhoto, localPhotos } from "../offline/local.js";
import { localId, offlineQueue } from "../offline/queue.js";
import { isDesktop } from "../platform.js";
import type { DesktopOrigin } from "./uploads.js";
/** SHA-256 hex of the bytes (same fingerprint the desktop shell uses for the original). */
@@ -74,6 +75,19 @@ export async function showLocalJpeg(args: {
}
const capturedAt = lisbonInstant(exifDateTime(previewBytes));
const eventId = events ? eventForArrival(args.eventId ?? null, events, capturedAt) : (args.eventId ?? null);
// Hand-dropped JPEGs keep embedded XMP. Desktop previews strip it — read the indexed original by SHA.
const {
marksFromJpegBytes,
marksFromLocalSha,
cullPatchFromMarks,
cropCommandFromMarks,
hasDiskMarks,
} = await import("../desktop/readFileMarks.js");
let disk = marksFromJpegBytes(previewBytes);
if (!hasDiskMarks(disk) && origin && origin !== "original" && origin.sha256) {
disk = await marksFromLocalSha(origin.sha256);
}
const cull = cullPatchFromMarks(disk);
localPhotos.put(
localPhoto({
sha256,
@@ -83,8 +97,23 @@ export async function showLocalJpeg(args: {
capturedAt,
eventId,
url,
...cull,
}),
);
if (orgId) {
const id = localId(sha256);
if (hasDiskMarks(disk)) {
if (Object.keys(cull).length) {
offlineQueue(orgId).add({ kind: "patch", ids: [id], patch: cull });
}
const cropOp = cropCommandFromMarks(disk);
if (cropOp) offlineQueue(orgId).enqueueEdit(id, cropOp);
}
if (isDesktop()) {
const { watchSoftCropPhoto } = await import("../desktop/softCropWatch.js");
watchSoftCropPhoto(orgId, id, sha256);
}
}
if (orgId) {
for (const op of offlineQueue(orgId).pending) {
if (op.kind === "patch" && op.ids.includes(localId(sha256))) {
+33 -3
View File
@@ -6,10 +6,24 @@ import { io } from "socket.io-client";
export type LiveState = "connecting" | "live" | "offline";
const liveListeners = new Set<() => void>();
let liveSockets = 0;
/** At least one library socket is connected. Several screens each open their own. */
export function isSocketLive(): boolean {
return liveSockets > 0;
}
function noteSocket(up: boolean): void {
if (up) liveSockets += 1;
else liveSockets = Math.max(0, liveSockets - 1);
if (!up) return;
for (const fn of [...liveListeners]) fn();
}
/** The library socket connected. Waiting edits go out on this, not on a timer. */
export function onSocketLive(fn: () => void): () => void {
liveListeners.add(fn);
if (liveSockets > 0) fn();
return () => liveListeners.delete(fn);
}
@@ -33,17 +47,33 @@ export function useLibraryLive(api: ApiClient, onMessage: (message: LibraryMessa
);
},
});
let connected = false;
const mark = (up: boolean) => {
if (up === connected) return;
connected = up;
noteSocket(up);
};
socket.on("connect", () => {
setState("live");
for (const fn of liveListeners) fn();
mark(true);
});
socket.on("disconnect", () => {
setState("offline");
mark(false);
});
socket.on("connect_error", () => {
setState("offline");
mark(false);
});
socket.on("disconnect", () => setState("offline"));
socket.on("connect_error", () => setState("offline"));
socket.on(LIBRARY_CHANNEL, (message: LibraryMessage) => handler.current(message));
socket.on("desk", (command: DeskCommand) => {
window.dispatchEvent(new CustomEvent("photoreport-desk", { detail: command }));
});
return () => {
socket.off("connect");
socket.off("disconnect");
socket.off("connect_error");
mark(false);
socket.close();
};
}, [api]);
+3 -2
View File
@@ -1,5 +1,5 @@
import type { Detections } from "../../../api/src/composition/compose.js";
import { YOLOX_SIZE, decodeYolox, nmsKeep, sharpnessOf, PERSON, BALL } from "../../../api/src/composition/yolox.js";
import { BACKPACK, BALL, HANDBAG, PERSON, SUITCASE, YOLOX_SIZE, decodeYolox, nmsKeep, sharpnessOf } from "../../../api/src/composition/yolox.js";
import type { ApiClient } from "@photoreport/sdk";
import { kv } from "./kv.js";
@@ -96,7 +96,8 @@ export async function detectPreview(api: ApiClient, orgId: string, jpeg: ArrayBu
const grey = new Uint8Array(greyW * greyH);
for (let i = 0; i < grey.length; i++) grey[i] = Math.round(0.299 * rgba[i * 4]! + 0.587 * rgba[i * 4 + 1]! + 0.114 * rgba[i * 4 + 2]!);
sharpnessOf(grey, greyW, greyH, people);
return { width, height, people, balls: nmsKeep(all.filter((d) => d.cls === BALL)) };
const carried = nmsKeep(all.filter((d) => d.cls === BACKPACK || d.cls === HANDBAG || d.cls === SUITCASE));
return { width, height, people, balls: nmsKeep(all.filter((d) => d.cls === BALL)), carried };
} catch {
return null;
} finally {
+23 -4
View File
@@ -156,7 +156,26 @@ export function eventForArrival(pinnedId: string | null, events: RoutedEvent[],
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 {
export function localPhoto(p: {
sha256: string;
name: string;
width: number;
height: number;
capturedAt: string | null;
eventId: string | null;
url: string;
/** Cull marks already on the file (XMP pick / stars / colour). */
flag?: PhotoSummary["flag"];
rating?: number;
colorLabel?: PhotoSummary["colorLabel"];
}): PhotoSummary {
let flag: PhotoSummary["flag"] = "NONE";
if (p.flag) flag = p.flag;
let rating = 0;
if (typeof p.rating === "number" && p.rating > 0) rating = Math.min(5, Math.round(p.rating));
if (flag === "NONE" && rating > 0) flag = "PICK";
let colorLabel: PhotoSummary["colorLabel"] = "NONE";
if (p.colorLabel) colorLabel = p.colorLabel;
return {
id: localId(p.sha256),
eventId: p.eventId,
@@ -175,9 +194,9 @@ export function localPhoto(p: { sha256: string; name: string; width: number; hei
aperture: null,
exposureTime: null,
iso: null,
rating: 0,
flag: "NONE",
colorLabel: "NONE",
rating,
flag,
colorLabel,
players: [],
uploader: null,
developSeq: 0,
+23
View File
@@ -86,6 +86,29 @@ describe("offline queue", () => {
expect(q.size).toBe(0);
});
it("sends a pick queued after the photo is already on the server", async () => {
const q = new OfflineQueue("o1", store);
q.uploaded("abc", "server-1");
q.enqueueEdit(localId("abc"), { command: "develop.set", params: { values: { "light.exposure": 0.4 } } });
q.add({ kind: "patch", ids: [localId("abc")], patch: { flag: "PICK" } });
const sent: string[][] = [];
const edits: string[] = [];
const api = {
updatePhotos: vi.fn(async (_org: string, ids: string[]) => {
sent.push(ids);
return { updated: ids.length };
}),
postEdits: vi.fn(async (photoId: string) => {
edits.push(photoId);
return { developSeq: 1, ops: [] };
}),
} as unknown as ApiClient;
await q.flush(api);
expect(sent).toEqual([["server-1"]]);
expect(edits).toEqual(["server-1"]);
expect(q.size).toBe(0);
});
it("drops what the server refuses for good", async () => {
const q = new OfflineQueue("o1", store);
q.add({ kind: "patch", ids: ["gone"], patch: { flag: "PICK" } });
+27 -10
View File
@@ -202,34 +202,51 @@ export class OfflineQueue {
/** Develop edits made offline on photos no longer open (or uploaded since). Repeated ops are ignored by the server. */
private async flushOutboxes(api: ApiClient): Promise<void> {
let changed = false;
const notify = () => {
if (!changed) return;
changed = false;
for (const fn of this.listeners) fn();
};
for (const key of this.outboxKeys()) {
const photoId = key.slice(OUTBOX.length);
let photoId = key.slice(OUTBOX.length);
if (isLocalId(photoId)) {
// Edited in Revelar before (and after) the upload: those edits follow the photo.
// Edited before the upload finished: those edits follow the photo, then go out in this same pass.
const id = this.serverId(photoId);
if (id) this.uploaded(photoId.slice(LOCAL.length), id);
continue;
if (!id) continue;
this.uploaded(photoId.slice(LOCAL.length), id);
photoId = id;
changed = true;
}
const storeKey = `${OUTBOX}${photoId}`;
let ops: { opId: string; command: unknown }[];
try {
ops = JSON.parse(this.store.get(key) ?? "[]") as { opId: string; command: unknown }[];
ops = JSON.parse(this.store.get(storeKey) ?? "[]") as { opId: string; command: unknown }[];
} catch {
this.store.remove(key);
this.store.remove(storeKey);
changed = true;
continue;
}
if (!ops.length) {
this.store.remove(key);
this.store.remove(storeKey);
changed = true;
continue;
}
try {
await api.postEdits(photoId, { clientId: "offline-queue", ops } as unknown as Parameters<ApiClient["postEdits"]>[1]);
} catch (err) {
if (isNetworkError(err) || (err instanceof ApiError && (err.status === 401 || err.status === 429))) return;
if (isNetworkError(err) || (err instanceof ApiError && (err.status === 401 || err.status === 429))) {
notify();
return;
}
}
// Sent (or refused for good). An editor still open on the photo keeps its own copy and resends harmlessly.
if (this.store.get(key) === JSON.stringify(ops)) this.store.remove(key);
if (this.store.get(storeKey) === JSON.stringify(ops)) {
this.store.remove(storeKey);
changed = true;
}
}
for (const fn of this.listeners) fn();
notify();
}
}
+29 -8
View File
@@ -1,7 +1,7 @@
import type { PhotoPatch } from "@photoreport/contracts";
import type { ApiClient } from "@photoreport/sdk";
import { useEffect, useSyncExternalStore } from "react";
import { onSocketLive } from "../library/realtime.js";
import { isSocketLive, onSocketLive } from "../library/realtime.js";
import { localPhotos } from "./local.js";
import { isLocalId, isNetworkError, offlineQueue, type OfflineQueue } from "./queue.js";
@@ -9,23 +9,44 @@ import { isLocalId, isNetworkError, offlineQueue, type OfflineQueue } from "./qu
* Sends what was kept while the socket was down, the moment it is live again. A change made while the socket is
* already live goes out in `patchPhotos` itself. The socket is the clock: down, keep it; live, send it.
*/
const SEND_DELAY_MS = 40;
const SEND_AGAIN_MS = 1500;
const SEND_TRIES = 5;
export function useOfflineSync(api: ApiClient, orgId: string): void {
useEffect(() => {
if (!orgId) return;
const queue = offlineQueue(orgId);
return onSocketLive(() => {
let tries = 0;
const send = () => {
let tries = 0;
let timer = 0;
const send = () => {
if (!isSocketLive()) return;
window.clearTimeout(timer);
timer = window.setTimeout(() => {
void queue.flush(api).then(() => {
// Still waiting (the link dropped mid-send): try again while this connection stays up.
if (queue.size > 0 && tries < 5) {
// Still waiting (the link dropped mid-send, or a photo was still uploading): try again.
if (queue.size > 0 && isSocketLive() && tries < SEND_TRIES) {
tries += 1;
window.setTimeout(send, 1500);
window.setTimeout(send, SEND_AGAIN_MS);
}
if (queue.size === 0) tries = 0;
});
};
}, SEND_DELAY_MS);
};
// A pick made while the socket is already up never sees another "connect". Send those too.
const stopLive = onSocketLive(() => {
tries = 0;
send();
});
const stopQueue = queue.subscribe(() => {
tries = 0;
send();
});
return () => {
window.clearTimeout(timer);
stopLive();
stopQueue();
};
}, [api, orgId]);
}
+1 -1
View File
@@ -136,7 +136,7 @@ export function DeliveryPage() {
</td>
<td className="border-b border-line px-3 py-1.5 text-right">
{i.status === "FAILED" && (
<button className="pr-quiet" onClick={() => void api.retryDelivery(orgId, i.id).then(load)}>
<button className="pr-quiet" onClick={() => void api.retryDelivery(orgId, i.id).then(load, () => load())}>
{t.retry}
</button>
)}
+24 -11
View File
@@ -38,6 +38,8 @@ import { ALL_PHOTOS, applyPatch, isMac, type LibraryFilter, matchesFilter, patch
import { t } from "../i18n.js";
import { useLibraryLive } from "../library/realtime.js";
import { forgetSoftCrop, softCropFor } from "../desktop/softCrop.js";
import { fileShaForPhoto } from "../desktop/fileMarks.js";
import { rememberPhotoFrame } from "../desktop/lightroomCrop.js";
import { onSoftCropApplied, watchSoftCropPhoto } from "../desktop/softCropWatch.js";
import { writeLightroomSidecar } from "../desktop/lightroomSidecar.js";
import { isDesktop, localOriginalToView, prefs } from "../platform.js";
@@ -235,25 +237,29 @@ export function DevelopPage() {
// Embed the develop crop into the JPEG as crs:Crop* (AlreadyApplied=False), the same Soft Crop Photo Mechanic reads.
useEffect(() => {
if (!isDesktop() || !session?.loaded || session.hasPending || session.seq < 1 || !current?.sha256) return;
const sha = current.sha256;
const sha = current?.id ? fileShaForPhoto(current.id, current.sha256) : null;
if (!isDesktop() || !session?.loaded || session.hasPending || session.seq < 1 || !sha) return;
const settings = session.settings;
const timer = setTimeout(() => {
forgetSoftCrop(sha);
void writeLightroomSidecar(sha, settings);
}, 500);
return () => clearTimeout(timer);
}, [session, version, current?.sha256]);
}, [session, version, current?.id, current?.sha256]);
// Watch the local file while this photo is open: Lightroom / Photo Mechanic crop changes become develop crops.
useEffect(() => {
if (!isDesktop() || !orgId || !current?.id || !current.sha256) return;
watchSoftCropPhoto(orgId, current.id, current.sha256);
}, [orgId, current?.id, current?.sha256]);
if (!isDesktop() || !orgId || !current?.id) return;
const sha = fileShaForPhoto(current.id, current.sha256);
if (!sha) return;
rememberPhotoFrame(sha, current.width, current.height);
watchSoftCropPhoto(orgId, current.id, sha);
}, [orgId, current?.id, current?.sha256, current?.width, current?.height]);
// A file that already has a Lightroom soft crop and no develop crop yet: start from that rectangle.
useEffect(() => {
if (!isDesktop() || !session?.loaded || !current?.sha256 || session.hasPending || session.seq > 0) return;
const sha = current?.id ? fileShaForPhoto(current.id, current.sha256) : null;
if (!isDesktop() || !session?.loaded || !sha || session.hasPending || session.seq > 0) return;
const currentCrop = cropOf(session.settings);
const full =
currentCrop.rect.x0 <= 0.001 &&
@@ -263,7 +269,7 @@ export function DevelopPage() {
Math.abs(currentCrop.angle) < 0.05;
if (!full) return;
let alive = true;
void softCropFor(current.sha256).then((soft) => {
void softCropFor(sha).then((soft) => {
if (!alive || !soft || !session) return;
session.edit(
{
@@ -280,7 +286,7 @@ export function DevelopPage() {
return () => {
alive = false;
};
}, [session, version, current?.sha256]);
}, [session, version, current?.id, current?.sha256]);
// Soft crop applied by the file watcher while this session is open: paint it immediately.
useEffect(() => {
@@ -577,8 +583,15 @@ export function DevelopPage() {
const c0 = cropOf(session.settings);
const aspect: [number, number] | null = c0.aspect ?? (choice === "original" || choice === null ? null : choice);
try {
const { crop } = await api.request<{ crop: { rect: Crop["rect"]; reason: string } | null }>("POST", `/v1/photos/${current.id}/auto-crop`, { aspect });
if (!crop) return setNote(t.dev.autoCropNone);
const answer = await api.request<{
crop: { rect: Crop["rect"]; reason: string } | null;
found?: boolean;
}>("POST", `/v1/photos/${current.id}/auto-crop`, { aspect });
if (!answer.crop) {
if (answer.found) return setNote(t.dev.autoCropKept);
return setNote(t.dev.autoCropNone);
}
const crop = answer.crop;
const c = cropOf(session.settings);
const rect = constrainRotated(crop.rect, c.angle, sourceSize.w, sourceSize.h);
session.edit({ command: "crop.set", params: { rect, angle: c.angle, aspect: c.aspect ?? (aspect ?? [sourceSize.w, sourceSize.h]) } });
+2 -2
View File
@@ -902,8 +902,8 @@ export function LibraryPage() {
)}
<span className="ml-auto flex items-center gap-3 font-mono text-[11px] text-faint">
{waitingChanges > 0 && (
<span className="text-star" title={t.offline.waitingHelp}>
{t.offline.waiting(waitingChanges)}
<span className="text-star" title={live === "live" ? t.offline.pendingHelp : t.offline.waitingHelp}>
{live === "live" ? t.offline.pending(waitingChanges) : t.offline.waiting(waitingChanges)}
</span>
)}
<span>
+10
View File
@@ -387,6 +387,16 @@ function Orders({ orgId, isAdmin }: { orgId: string; isAdmin: boolean }) {
{o.invoice.number}
</a>
)}
{isAdmin && o.status === "PENDING" && !o.checkoutUrl && o.totalCents > 0 && (
<button
className="ml-3 underline"
onClick={() => {
if (window.confirm(t.shop.confirmCollectPayment)) void api.recordPayment(o.id).then(replace);
}}
>
{t.shop.collectPayment}
</button>
)}
{isAdmin && (o.status === "PAID" || o.status === "FULFILLED") && (
<button
className="ml-3 underline"
+6 -4
View File
@@ -12,9 +12,9 @@ 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**): pulses the PTP session so the body stays
shootable (no permanent computer/busy screen), pulls new shots to the open event, syncs the clock. EOS Utility
must not hold the cable.
- USB tether (Library → **USB**): a short PTP session lists the card and downloads what was asked, then
closes so the body can shoot. macOS uses Image Capture (`camera_mac.m`). Linux uses libgphoto2. Windows uses
the portable-device API. EOS Utility must not hold the cable. The Mac build is the one that sets the camera clock.
- 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;
@@ -41,7 +41,9 @@ signed shell at once; the API reads the latest
installer through, so the private repository stays private. Installers are signed with the release key
(`tauri signer generate`): the private key and its password are the Gitea secrets `TAURI_SIGNING_PRIVATE_KEY` and
`TAURI_SIGNING_PRIVATE_KEY_PASSWORD`, the public key is the variable `TAURI_UPDATER_PUBKEY` (compiled into the app
as `PHOTOREPORT_UPDATER_PUBKEY`). A build without the public key never updates itself.
as `PHOTOREPORT_UPDATER_PUBKEY`). A release build also reads that same public key from `updater-pubkey.txt` when the
variable is unset, and checks again in the background, so the installed app replaces itself. A debug build without
the variable never updates itself.
## Local FTP (camera → this computer → event)
+9256
View File
File diff suppressed because it is too large. Load diff
+22
View File
@@ -9,6 +9,13 @@ description = "PhotoReport desktop: the web app in a native shell, with keychain
name = "photoreport_desktop_lib"
crate-type = ["staticlib", "cdylib", "rlib"]
# Production serves the interface from this computer. Without this feature Tauri treats every
# build as development and the window opens http://localhost:5173, which stays blank unless
# `tauri dev` is running. `tauri dev` turns the feature off and uses the dev server.
[features]
default = ["custom-protocol"]
custom-protocol = ["tauri/custom-protocol"]
[build-dependencies]
tauri-build = { version = "2", features = [] }
cc = "1"
@@ -44,6 +51,21 @@ rustls = { version = "0.23", default-features = false, features = ["ring"] }
[target.'cfg(all(target_os = "macos", target_arch = "aarch64"))'.dependencies]
ort = { version = "=2.0.0-rc.14", default-features = false, features = ["std", "download-binaries", "copy-dylibs", "api-31", "tls-native", "coreml"] }
# Linux USB: libgphoto2 (PTP). The Mac build keeps Image Capture and does not link this.
[target.'cfg(all(unix, not(target_os = "macos")))'.dependencies]
gphoto2 = "=3.4.1"
# Windows USB: the portable-device API, which speaks PTP through the driver Windows already loaded.
[target.'cfg(target_os = "windows")'.dependencies]
windows = { version = "0.61", features = [
"Win32_Devices_PortableDevices",
"Win32_Foundation",
"Win32_System_Com",
"Win32_System_Com_StructuredStorage",
"Win32_System_Ole",
"Win32_System_Variant",
] }
# Release builds: no symbols or debug info, whole-program optimisation, no unwinding tables. The binary only tells
# a disassembler what machine code does, not what the functions were called.
[profile.release]
+29 -1
View File
@@ -1,4 +1,5 @@
fn main() {
publish_updater_key();
let target = std::env::var("CARGO_CFG_TARGET_OS").unwrap_or_default();
if target == "macos" {
// ImageCaptureCore: PTP cameras (they never mount as a volume).
@@ -32,6 +33,7 @@ fn main() {
"ftp_retry",
"ftp_read",
"ftp_sent",
"ftp_write_xmp",
"ftp_open_folder",
"ftp_save_settings",
"local_original",
@@ -86,6 +88,27 @@ fn main() {
link_coreml_compiler_rt();
}
/// Release builds always carry the official update key, so an installed app can replace itself from the API.
/// `option_env!` is not a cargo fingerprint: the key has to be passed with `cargo:rustc-env` or a later compile
/// keeps the previous value. A debug build stays without it unless the variable is set for that compile.
fn publish_updater_key() {
println!("cargo:rerun-if-env-changed=PHOTOREPORT_UPDATER_PUBKEY");
let manifest = std::env::var("CARGO_MANIFEST_DIR").unwrap_or_else(|_| ".".to_string());
let path = std::path::Path::new(&manifest).join("updater-pubkey.txt");
println!("cargo:rerun-if-changed={}", path.display());
let from_env = std::env::var("PHOTOREPORT_UPDATER_PUBKEY").unwrap_or_default();
let mut key = from_env.trim().to_string();
let profile = std::env::var("PROFILE").unwrap_or_default();
if key.is_empty() && profile == "release" {
let from_file = std::fs::read_to_string(&path).unwrap_or_default();
key = from_file.trim().to_string();
}
if key.is_empty() {
return;
}
println!("cargo:rustc-env=PHOTOREPORT_UPDATER_PUBKEY={key}");
}
/// ONNX Runtime's Core ML objects call `___isPlatformVersionAtLeast`. That helper lives in compiler-rt, which Rust's
/// linker does not pull in, so the desktop build (deployment target 11) fails on the arm64 slice.
fn link_coreml_compiler_rt() {
@@ -95,7 +118,12 @@ fn link_coreml_compiler_rt() {
return;
}
let Ok(output) = std::process::Command::new("xcrun")
.args(["--sdk", "macosx", "clang", "-print-file-name=libclang_rt.osx.a"])
.args([
"--sdk",
"macosx",
"clang",
"-print-file-name=libclang_rt.osx.a",
])
.output()
else {
return;
@@ -29,6 +29,7 @@
"allow-ftp-retry",
"allow-ftp-read",
"allow-ftp-sent",
"allow-ftp-write-xmp",
"allow-ftp-open-folder",
"allow-ftp-save-settings",
"allow-local-original",
+13
View File
@@ -0,0 +1,13 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<!-- The bundled ONNX runtime is not an Apple-signed library. Notarisation requires the hardened runtime, and that runtime refuses the library unless this is set. -->
<key>com.apple.security.cs.disable-library-validation</key>
<true/>
<key>com.apple.security.cs.allow-unsigned-executable-memory</key>
<true/>
<key>com.apple.security.cs.allow-jit</key>
<true/>
</dict>
</plist>
@@ -0,0 +1,11 @@
# Automatically generated - DO NOT EDIT!
[[permission]]
identifier = "allow-ftp-write-xmp"
description = "Enables the ftp_write_xmp command without any pre-configured scope."
commands.allow = ["ftp_write_xmp"]
[[permission]]
identifier = "deny-ftp-write-xmp"
description = "Denies the ftp_write_xmp command without any pre-configured scope."
commands.deny = ["ftp_write_xmp"]
+109 -21
View File
@@ -1,13 +1,17 @@
//! USB tether (macOS). A Canon (or any PTP body) does not show up as a disk; ImageCaptureCore
//! (`camera_mac.m`) briefly opens a PTP session to list/download, then closes it so the body can
//! shoot (a held session + `requestEnableTethering` put many cameras on the computer/busy screen).
//! The session stays off until the photographer turns the cable on. Nothing is copied until they
//! pick files (`camera_import`) or auto-ingest asks. Chosen files land in `<ingest>/.usb` and the
//! web app polls `camera_take` to file them like a local-FTP photo.
//! USB tether. A PTP body does not show up as a disk.
//! macOS uses Image Capture (`camera_mac.m`): a short session lists and downloads, then closes so
//! the body can shoot. Linux uses libgphoto2 and Windows the portable-device API (`camera_link`),
//! with the same open-then-close rhythm. Nothing is copied until the photographer picks files
//! (`camera_import`) or auto-ingest asks. Chosen files land in `<ingest>/.usb`.
use std::collections::HashSet;
use std::path::Path;
use std::sync::{Mutex, OnceLock};
#[cfg(not(target_os = "macos"))]
#[path = "camera_link.rs"]
mod link;
use serde::{Deserialize, Serialize};
use crate::ftp::{FtpState, IncomingFile};
@@ -51,7 +55,7 @@ pub struct CameraFile {
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CameraStatus {
/// False on systems without ImageCaptureCore (the button stays hidden).
/// False only when this build has no USB backend (the button stays hidden).
pub supported: bool,
pub tether: bool,
pub devices: Vec<CameraDevice>,
@@ -74,7 +78,11 @@ enum CameraEvent {
files: Vec<CameraFile>,
},
#[serde(rename = "file")]
File { path: String, name: String, size: u64 },
File {
path: String,
name: String,
size: u64,
},
}
struct Inner {
@@ -111,6 +119,47 @@ fn queue() -> &'static Mutex<Vec<String>> {
Q.get_or_init(|| Mutex::new(Vec::new()))
}
#[cfg_attr(target_os = "macos", allow(dead_code))]
pub(crate) fn enqueue_line(line: String) {
if let Ok(mut q) = queue().lock() {
q.push(line);
}
}
/// One still on the card, before it is marked new or already fetched.
pub(crate) struct ListedShot {
pub name: String,
pub size: u64,
pub created_ms: Option<i64>,
}
/// The first listing of a tether session is the baseline (nothing is "new"). Later listings mark
/// names that were not on that baseline. `fetched` is what this computer already copied.
pub(crate) fn files_on_card(
shots: &[ListedShot],
known: &HashSet<String>,
fetched: &HashSet<String>,
listing_is_live: bool,
) -> Vec<CameraFile> {
let mut files = Vec::new();
for shot in shots {
let is_new = if listing_is_live {
!known.contains(&shot.name)
} else {
false
};
let imported = fetched.contains(&shot.name);
files.push(CameraFile {
name: shot.name.clone(),
size: shot.size,
created_ms: shot.created_ms,
is_new,
imported,
});
}
files
}
impl CameraState {
fn drain(&self) {
let pending = match queue().lock() {
@@ -211,7 +260,10 @@ fn apply_event(inner: &mut Inner, line: &str) {
};
match event {
CameraEvent::Devices { devices } => inner.devices = devices,
CameraEvent::Catalog { camera_id: _, files } => {
CameraEvent::Catalog {
camera_id: _,
files,
} => {
inner.files = files;
inner.catalog_gen = inner.catalog_gen.wrapping_add(1);
}
@@ -223,16 +275,10 @@ fn apply_event(inner: &mut Inner, line: &str) {
}
}
#[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;
@@ -266,7 +312,9 @@ fn set_download_dir(dir: &str) {
}
#[cfg(not(target_os = "macos"))]
fn set_download_dir(_dir: &str) {}
fn set_download_dir(dir: &str) {
link::set_dir(dir);
}
#[cfg(target_os = "macos")]
fn set_tether_native(on: bool) {
@@ -274,7 +322,9 @@ fn set_tether_native(on: bool) {
}
#[cfg(not(target_os = "macos"))]
fn set_tether_native(_on: bool) {}
fn set_tether_native(on: bool) {
link::set_tether(on);
}
#[cfg(target_os = "macos")]
fn sync_native() {
@@ -282,7 +332,9 @@ fn sync_native() {
}
#[cfg(not(target_os = "macos"))]
fn sync_native() {}
fn sync_native() {
link::request_sync();
}
#[cfg(target_os = "macos")]
fn import_native(names_json: &str) {
@@ -293,7 +345,9 @@ fn import_native(names_json: &str) {
}
#[cfg(not(target_os = "macos"))]
fn import_native(_names_json: &str) {}
fn import_native(names_json: &str) {
link::import_json(names_json);
}
#[cfg(target_os = "macos")]
fn refresh_catalog_native() {
@@ -301,7 +355,9 @@ fn refresh_catalog_native() {
}
#[cfg(not(target_os = "macos"))]
fn refresh_catalog_native() {}
fn refresh_catalog_native() {
link::refresh();
}
/// Starts the browser once. Safe to call at launch; callbacks only enqueue a string.
pub fn start(ftp: &FtpState) {
@@ -313,6 +369,8 @@ pub fn start(ftp: &FtpState) {
}
unsafe { pr_camera_start(on_camera_json) }
}
#[cfg(not(target_os = "macos"))]
link::start();
let dir = ftp.ingest_dir();
let _ = std::fs::create_dir_all(dir.join(".usb"));
set_download_dir(&dir.join(".usb").to_string_lossy());
@@ -364,6 +422,33 @@ pub fn camera_refresh(cam: tauri::State<'_, CameraState>) -> CameraStatus {
mod tests {
use super::*;
#[test]
fn the_first_listing_is_not_a_new_shot_and_a_later_one_is() {
let shots = vec![
ListedShot {
name: "old.JPG".into(),
size: 10,
created_ms: Some(1),
},
ListedShot {
name: "new.JPG".into(),
size: 20,
created_ms: Some(2),
},
];
let mut known = HashSet::new();
known.insert("old.JPG".to_string());
let mut fetched = HashSet::new();
fetched.insert("old.JPG".to_string());
let first = files_on_card(&shots[..1], &known, &fetched, false);
assert!(!first[0].is_new);
assert!(first[0].imported);
let live = files_on_card(&shots, &known, &fetched, true);
assert!(!live[0].is_new);
assert!(live[1].is_new);
assert!(!live[1].imported);
}
#[test]
fn a_chosen_shot_queues_the_jpeg_and_the_raw() {
let mut inner = Inner {
@@ -424,7 +509,10 @@ mod tests {
catalog_gen: 1,
};
apply_event(&mut inner, r#"{"kind":"devices","devices":[]}"#);
apply_event(&mut inner, r#"{"kind":"catalog","cameraId":"abc","files":[]}"#);
apply_event(
&mut inner,
r#"{"kind":"catalog","cameraId":"abc","files":[]}"#,
);
assert!(inner.devices.is_empty());
assert!(inner.files.is_empty());
assert_eq!(inner.catalog_gen, 2);
+182
View File
@@ -0,0 +1,182 @@
//! Linux USB via libgphoto2. The camera is opened for this pass only and dropped before we return,
//! which closes the PTP session.
use std::path::Path;
pub struct Shot {
pub folder: String,
pub name: String,
pub size: u64,
pub created_ms: Option<i64>,
}
pub struct Report {
pub model: Option<String>,
pub id: String,
pub error: Option<String>,
pub shots: Vec<Shot>,
pub downloaded: Vec<(String, u64)>,
pub clock: Option<String>,
pub clock_unsupported: bool,
}
pub fn pulse(dir: &Path, wanted: &[String], _sync_clock: bool) -> Result<Report, String> {
let context = gphoto2::Context::new().map_err(|err| err.to_string())?;
let mut listed = context
.list_cameras()
.wait()
.map_err(|err| err.to_string())?;
let Some(desc) = listed.next() else {
return Ok(empty());
};
let camera = context
.get_camera(&desc)
.wait()
.map_err(|err| err.to_string())?;
let model = camera.abilities().model().to_string();
let roots = card_roots(&camera);
let fs = camera.fs();
let mut shots = Vec::new();
for root in roots {
walk(&fs, &root, 0, &mut shots)?;
}
let mut downloaded = Vec::new();
let mut error = None;
for shot in &shots {
let asked = wanted.iter().any(|name| name == &shot.name);
if !asked {
continue;
}
match copy_one(&fs, dir, shot) {
Ok(size) => downloaded.push((shot.name.clone(), size)),
Err(err) => error = Some(err),
}
}
// Dropping `camera` closes the session before the caller waits.
drop(fs);
drop(camera);
Ok(Report {
model: Some(model),
id: "gphoto".into(),
error,
shots,
downloaded,
clock: None,
// libgphoto2 clock widgets differ per body; the panel says the clock was not set.
clock_unsupported: true,
})
}
fn empty() -> Report {
Report {
model: None,
id: "gphoto".into(),
error: None,
shots: Vec::new(),
downloaded: Vec::new(),
clock: None,
clock_unsupported: false,
}
}
fn card_roots(camera: &gphoto2::Camera) -> Vec<String> {
let mut roots = Vec::new();
if let Ok(storages) = camera.storages().wait() {
for storage in storages {
let Some(base) = storage.base_directory() else {
continue;
};
let text = base.to_string();
if text.is_empty() {
continue;
}
if !roots.iter().any(|have| have == &text) {
roots.push(text);
}
}
}
if roots.is_empty() {
roots.push("/".to_string());
}
roots
}
fn walk(
fs: &gphoto2::filesys::CameraFS<'_>,
folder: &str,
depth: u32,
shots: &mut Vec<Shot>,
) -> Result<(), String> {
if depth > 12 {
return Ok(());
}
let files = match fs.list_files(folder).wait() {
Ok(files) => files,
Err(err) if folder != "/" => {
let _ = err;
return Ok(());
}
Err(err) => return Err(err.to_string()),
};
for name in files {
if !is_still(&name) {
continue;
}
let info = fs.file_info(folder, &name).wait().ok();
let size = info
.as_ref()
.and_then(|info| info.file().size())
.unwrap_or(0);
let created_ms = info
.as_ref()
.and_then(|info| info.file().mtime())
.map(|mtime| {
let seconds = mtime as i64;
seconds.saturating_mul(1000)
});
shots.push(Shot {
folder: folder.to_string(),
name,
size,
created_ms,
});
}
let folders = match fs.list_folders(folder).wait() {
Ok(folders) => folders,
Err(_) => return Ok(()),
};
for name in folders {
let child = child_folder(folder, &name);
walk(fs, &child, depth + 1, shots)?;
}
Ok(())
}
fn copy_one(fs: &gphoto2::filesys::CameraFS<'_>, dir: &Path, shot: &Shot) -> Result<u64, String> {
let dest = dir.join(&shot.name);
if let Ok(meta) = std::fs::metadata(&dest) {
if meta.len() > 0 {
return Ok(meta.len());
}
}
let _ = std::fs::create_dir_all(dir);
fs.download_to(&shot.folder, &shot.name, &dest)
.wait()
.map_err(|err| err.to_string())?;
let meta = std::fs::metadata(&dest).map_err(|err| err.to_string())?;
Ok(meta.len())
}
fn child_folder(parent: &str, name: &str) -> String {
if name.starts_with('/') {
return name.to_string();
}
if parent == "/" {
return format!("/{name}");
}
format!("{parent}/{name}")
}
fn is_still(name: &str) -> bool {
crate::ftp::is_jpeg_name(name) || crate::ftp::is_raw_name(name)
}
+298
View File
@@ -0,0 +1,298 @@
//! USB on Linux (libgphoto2) and Windows (portable devices). Same rhythm as the Mac: open, list,
//! download what was asked, drop the session so the shutter is free, then wait before the next open.
//! The Mac path stays in `camera_mac.m` and is not used here.
use std::collections::HashSet;
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Mutex, OnceLock};
use std::time::Duration;
use serde::Serialize;
use super::{CameraDevice, ListedShot, enqueue_line, files_on_card};
#[cfg(all(unix, not(target_os = "macos")))]
#[path = "camera_gphoto.rs"]
mod backend;
#[cfg(target_os = "windows")]
#[path = "camera_wpd.rs"]
mod backend;
/// How long the body stays free between card reads. Matches the Mac poll.
const FREE_MS: u64 = 2500;
const STEP_MS: u64 = 200;
struct Link {
tether: AtomicBool,
sync: AtomicBool,
refresh: AtomicBool,
dir: Mutex<String>,
pending: Mutex<Vec<String>>,
/// Names on the card the first time this tether session listed it. `None` until that pass.
known: Mutex<Option<HashSet<String>>>,
fetched: Mutex<HashSet<String>>,
}
fn link() -> &'static Link {
static LINK: OnceLock<Link> = OnceLock::new();
LINK.get_or_init(|| Link {
tether: AtomicBool::new(false),
sync: AtomicBool::new(false),
refresh: AtomicBool::new(false),
dir: Mutex::new(String::new()),
pending: Mutex::new(Vec::new()),
known: Mutex::new(None),
fetched: Mutex::new(HashSet::new()),
})
}
pub fn start() {
static STARTED: AtomicBool = AtomicBool::new(false);
if STARTED.swap(true, Ordering::SeqCst) {
return;
}
std::thread::Builder::new()
.name("photoreport-usb".into())
.spawn(|| {
#[cfg(target_os = "windows")]
backend::init_thread();
loop {
if !link().tether.load(Ordering::SeqCst) {
std::thread::sleep(Duration::from_millis(STEP_MS));
continue;
}
pulse_once();
let mut waited = 0u64;
while waited < FREE_MS && link().tether.load(Ordering::SeqCst) {
if link().refresh.swap(false, Ordering::SeqCst) {
break;
}
let waiting = link()
.pending
.lock()
.map(|p| !p.is_empty())
.unwrap_or(false);
if waiting {
break;
}
std::thread::sleep(Duration::from_millis(STEP_MS));
waited += STEP_MS;
}
}
})
.ok();
}
pub fn set_dir(dir: &str) {
if let Ok(mut slot) = link().dir.lock() {
*slot = dir.to_string();
}
load_fetched(Path::new(dir));
}
pub fn set_tether(on: bool) {
link().tether.store(on, Ordering::SeqCst);
if !on {
if let Ok(mut known) = link().known.lock() {
*known = None;
}
publish_idle();
return;
}
link().refresh.store(true, Ordering::SeqCst);
}
pub fn request_sync() {
link().sync.store(true, Ordering::SeqCst);
link().refresh.store(true, Ordering::SeqCst);
}
pub fn refresh() {
link().refresh.store(true, Ordering::SeqCst);
}
pub fn import_json(names_json: &str) {
let Ok(names) = serde_json::from_str::<Vec<String>>(names_json) else {
return;
};
if let Ok(mut pending) = link().pending.lock() {
for name in names {
if !pending.iter().any(|have| have == &name) {
pending.push(name);
}
}
}
link().refresh.store(true, Ordering::SeqCst);
}
fn pulse_once() {
let dir = link().dir.lock().map(|d| d.clone()).unwrap_or_default();
if dir.is_empty() {
return;
}
let wanted = link().pending.lock().map(|p| p.clone()).unwrap_or_default();
let sync = link().sync.swap(false, Ordering::SeqCst);
let report = backend::pulse(Path::new(&dir), &wanted, sync);
match report {
Ok(report) => apply_report(&dir, report),
Err(err) => publish_busy(&err),
}
}
fn apply_report(dir: &str, report: backend::Report) {
let Some(model) = report.model else {
publish_devices(Vec::new());
publish_files("usb", Vec::new());
return;
};
let shots: Vec<ListedShot> = report
.shots
.iter()
.map(|shot| ListedShot {
name: shot.name.clone(),
size: shot.size,
created_ms: shot.created_ms,
})
.collect();
let listing_is_live = {
let Ok(mut known) = link().known.lock() else {
return;
};
if known.is_none() {
let mut names = HashSet::new();
for shot in &shots {
names.insert(shot.name.clone());
}
*known = Some(names);
false
} else {
true
}
};
let known = link()
.known
.lock()
.ok()
.and_then(|k| k.clone())
.unwrap_or_default();
let fetched = link().fetched.lock().map(|f| f.clone()).unwrap_or_default();
let files = files_on_card(&shots, &known, &fetched, listing_is_live);
let mut clock = report.clock;
if clock.is_none() && report.clock_unsupported {
clock = Some("unsupported".to_string());
}
let id = report.id.clone();
publish_devices(vec![CameraDevice {
id: id.clone(),
name: model,
vendor_id: 0,
product_id: 0,
state: "tethered".to_string(),
error: report.error,
clock,
clock_offset: None,
catalog_ready: true,
}]);
publish_files(&id, files);
remember_downloaded(dir, &report.downloaded);
}
fn remember_downloaded(dir: &str, downloaded: &[(String, u64)]) {
if downloaded.is_empty() {
return;
}
let Ok(mut fetched) = link().fetched.lock() else {
return;
};
let Ok(mut pending) = link().pending.lock() else {
return;
};
for (name, size) in downloaded {
if *size == 0 {
continue;
}
fetched.insert(name.clone());
pending.retain(|want| want != name);
let path = PathBuf::from(dir).join(name);
let line = serde_json::json!({
"kind": "file",
"path": path,
"name": name,
"size": size,
});
enqueue_line(line.to_string());
}
write_fetched(Path::new(dir), &fetched);
}
fn publish_idle() {
publish_devices(Vec::new());
publish_files("usb", Vec::new());
}
fn publish_busy(err: &str) {
publish_devices(vec![CameraDevice {
id: "usb".into(),
name: "USB".into(),
vendor_id: 0,
product_id: 0,
state: "busy".into(),
error: Some(err.to_string()),
clock: None,
clock_offset: None,
catalog_ready: false,
}]);
}
fn publish_devices(devices: Vec<CameraDevice>) {
let line = serde_json::json!({ "kind": "devices", "devices": devices });
enqueue_line(line.to_string());
}
fn publish_files(camera_id: &str, files: Vec<super::CameraFile>) {
#[derive(Serialize)]
#[serde(rename_all = "camelCase")]
struct Catalog<'a> {
kind: &'static str,
camera_id: &'a str,
files: &'a [super::CameraFile],
}
let line = serde_json::to_string(&Catalog {
kind: "catalog",
camera_id,
files: &files,
});
if let Ok(line) = line {
enqueue_line(line);
}
}
fn fetched_path(dir: &Path) -> PathBuf {
dir.join(".fetched")
}
fn load_fetched(dir: &Path) {
let text = std::fs::read_to_string(fetched_path(dir)).unwrap_or_default();
let Ok(mut fetched) = link().fetched.lock() else {
return;
};
fetched.clear();
for line in text.lines() {
if !line.is_empty() {
fetched.insert(line.to_string());
}
}
}
fn write_fetched(dir: &Path, fetched: &HashSet<String>) {
let mut names: Vec<&String> = fetched.iter().collect();
names.sort();
let mut text = String::new();
for name in names {
text.push_str(name);
text.push('\n');
}
let _ = std::fs::write(fetched_path(dir), text);
}
+325
View File
@@ -0,0 +1,325 @@
//! Windows USB via the portable-device API (the PTP driver Windows already owns). The device is
//! opened for this pass and released before we return, so the body is not left on the computer screen.
// The whole module is COM. Edition 2024 does not treat an `unsafe fn` body as an unsafe block.
#![allow(unsafe_op_in_unsafe_fn)]
use std::path::Path;
use windows::{
Win32::{
Devices::PortableDevices::{
IEnumPortableDeviceObjectIDs, IPortableDevice, IPortableDeviceContent,
IPortableDeviceKeyCollection, IPortableDeviceManager, IPortableDeviceValues,
PortableDevice, PortableDeviceKeyCollection, PortableDeviceManager,
PortableDeviceValues, WPD_CLIENT_MAJOR_VERSION, WPD_CLIENT_MINOR_VERSION,
WPD_CLIENT_NAME, WPD_CLIENT_REVISION, WPD_DEVICE_OBJECT_ID, WPD_OBJECT_DATE_CREATED,
WPD_OBJECT_ORIGINAL_FILE_NAME, WPD_OBJECT_SIZE, WPD_RESOURCE_DEFAULT,
},
System::Com::{
CLSCTX_INPROC_SERVER, COINIT_MULTITHREADED, CoCreateInstance, CoInitializeEx,
CoTaskMemFree, IStream, STGM_READ,
StructuredStorage::{PROPVARIANT, PropVariantClear},
},
System::Variant::VT_FILETIME,
},
core::{PCWSTR, PWSTR, w},
};
pub struct Shot {
pub name: String,
pub size: u64,
pub created_ms: Option<i64>,
object_id: String,
}
pub struct Report {
pub model: Option<String>,
pub id: String,
pub error: Option<String>,
pub shots: Vec<Shot>,
pub downloaded: Vec<(String, u64)>,
pub clock: Option<String>,
pub clock_unsupported: bool,
}
pub fn init_thread() {
unsafe {
let _ = CoInitializeEx(None, COINIT_MULTITHREADED);
}
}
pub fn pulse(dir: &Path, wanted: &[String], _sync_clock: bool) -> Result<Report, String> {
unsafe { read_card(dir, wanted) }
}
unsafe fn read_card(dir: &Path, wanted: &[String]) -> Result<Report, String> {
let manager: IPortableDeviceManager =
CoCreateInstance(&PortableDeviceManager, None, CLSCTX_INPROC_SERVER)
.map_err(|err| err.to_string())?;
let mut count = 0u32;
manager
.GetDevices(std::ptr::null_mut(), &mut count)
.map_err(|err| err.to_string())?;
if count == 0 {
return Ok(empty());
}
let mut ids = vec![PWSTR::null(); count as usize];
manager
.GetDevices(ids.as_mut_ptr(), &mut count)
.map_err(|err| err.to_string())?;
let device_id = ids.first().copied().unwrap_or(PWSTR::null());
let id_text = if device_id.is_null() {
String::new()
} else {
device_id.to_string().unwrap_or_default()
};
for id in &ids {
if !id.is_null() && id.0 != device_id.0 {
CoTaskMemFree(Some(id.0 as *const _));
}
}
if id_text.is_empty() {
return Ok(empty());
}
let device: IPortableDevice = CoCreateInstance(&PortableDevice, None, CLSCTX_INPROC_SERVER)
.map_err(|err| err.to_string())?;
let client: IPortableDeviceValues =
CoCreateInstance(&PortableDeviceValues, None, CLSCTX_INPROC_SERVER)
.map_err(|err| err.to_string())?;
client
.SetStringValue(&WPD_CLIENT_NAME, w!("PhotoReport"))
.map_err(|err| err.to_string())?;
client
.SetUnsignedIntegerValue(&WPD_CLIENT_MAJOR_VERSION, 1)
.map_err(|err| err.to_string())?;
client
.SetUnsignedIntegerValue(&WPD_CLIENT_MINOR_VERSION, 0)
.map_err(|err| err.to_string())?;
client
.SetUnsignedIntegerValue(&WPD_CLIENT_REVISION, 0)
.map_err(|err| err.to_string())?;
let wide_id = wide(&id_text);
let device_name = friendly_name(&manager, PCWSTR(wide_id.as_ptr()));
device
.Open(PCWSTR(wide_id.as_ptr()), &client)
.map_err(|err| err.to_string())?;
let content = device.Content().map_err(|err| err.to_string())?;
let mut shots = Vec::new();
collect(&content, WPD_DEVICE_OBJECT_ID, 0, &mut shots).map_err(|err| err.to_string())?;
let mut downloaded = Vec::new();
let mut error = None;
for shot in &shots {
let asked = wanted.iter().any(|name| name == &shot.name);
if !asked {
continue;
}
match copy_one(&content, dir, shot) {
Ok(size) => downloaded.push((shot.name.clone(), size)),
Err(err) => error = Some(err),
}
}
if !device_id.is_null() {
CoTaskMemFree(Some(device_id.0 as *const _));
}
// `device` drops here, which closes the PTP session.
Ok(Report {
model: Some(device_name),
id: "wpd".into(),
error,
shots,
downloaded,
clock: None,
clock_unsupported: true,
})
}
fn empty() -> Report {
Report {
model: None,
id: "wpd".into(),
error: None,
shots: Vec::new(),
downloaded: Vec::new(),
clock: None,
clock_unsupported: false,
}
}
unsafe fn friendly_name(manager: &IPortableDeviceManager, id: PCWSTR) -> String {
let mut chars = 0u32;
if manager
.GetDeviceFriendlyName(id, PWSTR::null(), &mut chars)
.is_err()
|| chars <= 1
{
return "USB camera".to_string();
}
let mut buf = vec![0u16; chars as usize];
if manager
.GetDeviceFriendlyName(id, PWSTR(buf.as_mut_ptr()), &mut chars)
.is_err()
{
return "USB camera".to_string();
}
let end = (chars as usize).saturating_sub(1).min(buf.len());
let name = String::from_utf16_lossy(&buf[..end]);
if name.is_empty() {
return "USB camera".to_string();
}
name
}
unsafe fn collect(
content: &IPortableDeviceContent,
parent: PCWSTR,
depth: u32,
shots: &mut Vec<Shot>,
) -> windows::core::Result<()> {
if depth > 12 {
return Ok(());
}
let enumerator: IEnumPortableDeviceObjectIDs = content.EnumObjects(0, parent, None)?;
loop {
let mut batch = [PWSTR::null(); 32];
let mut fetched = 0u32;
let hr = enumerator.Next(&mut batch, &mut fetched);
if hr.is_err() || fetched == 0 {
break;
}
for id in batch.iter().take(fetched as usize) {
if id.is_null() {
continue;
}
let object_id = id.to_string().unwrap_or_default();
CoTaskMemFree(Some(id.0 as *const _));
if object_id.is_empty() {
continue;
}
if let Some(shot) = shot_of(content, &object_id)? {
shots.push(shot);
}
let child = wide(&object_id);
collect(content, PCWSTR(child.as_ptr()), depth + 1, shots)?;
}
}
Ok(())
}
unsafe fn shot_of(
content: &IPortableDeviceContent,
object_id: &str,
) -> windows::core::Result<Option<Shot>> {
let keys: IPortableDeviceKeyCollection =
CoCreateInstance(&PortableDeviceKeyCollection, None, CLSCTX_INPROC_SERVER)?;
keys.Add(&WPD_OBJECT_ORIGINAL_FILE_NAME)?;
keys.Add(&WPD_OBJECT_SIZE)?;
keys.Add(&WPD_OBJECT_DATE_CREATED)?;
let properties = content.Properties()?;
let object_wide = wide(object_id);
let values = properties.GetValues(PCWSTR(object_wide.as_ptr()), &keys)?;
let name_ptr = values
.GetStringValue(&WPD_OBJECT_ORIGINAL_FILE_NAME)
.unwrap_or(PWSTR::null());
if name_ptr.is_null() {
return Ok(None);
}
let name = name_ptr.to_string().unwrap_or_default();
CoTaskMemFree(Some(name_ptr.0 as *const _));
if !is_still(&name) {
return Ok(None);
}
let size = values
.GetUnsignedLargeIntegerValue(&WPD_OBJECT_SIZE)
.unwrap_or(0);
let created_ms = filetime_ms(&values);
Ok(Some(Shot {
name,
size,
created_ms,
object_id: object_id.to_string(),
}))
}
unsafe fn filetime_ms(values: &IPortableDeviceValues) -> Option<i64> {
let mut variant = values.GetValue(&WPD_OBJECT_DATE_CREATED).ok()?;
let ms = filetime_of(&variant);
let _ = PropVariantClear(&mut variant);
ms
}
/// 100-nanosecond ticks since 1601-01-01, which is how a portable device stores a capture time.
unsafe fn filetime_of(variant: &PROPVARIANT) -> Option<i64> {
let header = &variant.Anonymous.Anonymous;
if header.vt != VT_FILETIME {
return None;
}
let filetime = header.Anonymous.filetime;
let ticks = (u64::from(filetime.dwHighDateTime) << 32) | u64::from(filetime.dwLowDateTime);
const EPOCH_DIFF: u64 = 116_444_736_000_000_000;
if ticks < EPOCH_DIFF {
return None;
}
let unix_100ns = ticks - EPOCH_DIFF;
Some((unix_100ns / 10_000) as i64)
}
unsafe fn copy_one(
content: &IPortableDeviceContent,
dir: &Path,
shot: &Shot,
) -> Result<u64, String> {
let dest = dir.join(&shot.name);
if let Ok(meta) = std::fs::metadata(&dest) {
if meta.len() > 0 {
return Ok(meta.len());
}
}
std::fs::create_dir_all(dir).map_err(|err| err.to_string())?;
let resources = content.Transfer().map_err(|err| err.to_string())?;
let object_wide = wide(&shot.object_id);
let mut stream: Option<IStream> = None;
let mut optimal = 0u32;
resources
.GetStream(
PCWSTR(object_wide.as_ptr()),
&WPD_RESOURCE_DEFAULT,
STGM_READ.0 as u32,
&mut optimal,
&mut stream,
)
.map_err(|err| err.to_string())?;
let stream = stream.ok_or("no_stream")?;
let mut file = std::fs::File::create(&dest).map_err(|err| err.to_string())?;
let mut buffer = vec![0u8; 1024 * 256];
loop {
let mut read = 0u32;
let hr = stream.Read(
buffer.as_mut_ptr() as *mut _,
buffer.len() as u32,
Some(&mut read),
);
if hr.is_err() {
let _ = std::fs::remove_file(&dest);
return Err(hr.to_string());
}
if read == 0 {
break;
}
use std::io::Write;
file.write_all(&buffer[..read as usize])
.map_err(|err| err.to_string())?;
}
let meta = std::fs::metadata(&dest).map_err(|err| err.to_string())?;
Ok(meta.len())
}
fn is_still(name: &str) -> bool {
crate::ftp::is_jpeg_name(name) || crate::ftp::is_raw_name(name)
}
fn wide(text: &str) -> Vec<u16> {
text.encode_utf16().chain(std::iter::once(0)).collect()
}
+4 -1
View File
@@ -932,7 +932,10 @@ mod tests {
let (take, held) = days_that_fit(days, Some(55));
assert_eq!(take.len(), 1);
assert_eq!(take[0].key, "2026-11-03");
assert_eq!(held, vec!["2026-11-04".to_string(), "2026-11-05".to_string()]);
assert_eq!(
held,
vec!["2026-11-04".to_string(), "2026-11-05".to_string()]
);
let (all, none) = days_that_fit(
vec![DayPlan {
key: "2026-11-04".into(),
+1 -5
View File
@@ -126,11 +126,7 @@ impl Deliveries {
Path::new(f)
.canonicalize()
.ok()
.and_then(|root| {
canon
.parent()
.map(|p| p.starts_with(&root))
})
.and_then(|root| canon.parent().map(|p| p.starts_with(&root)))
.unwrap_or(false)
});
if !allowed && !allowed_xmp {
+70 -8
View File
@@ -266,6 +266,7 @@ fn jpeg_paths(dir: &Path, out: &mut Vec<PathBuf>) {
}
}
#[cfg(not(target_os = "windows"))]
fn memory_gb() -> f64 {
let pages = unsafe { libc::sysconf(libc::_SC_PHYS_PAGES) };
let size = unsafe { libc::sysconf(libc::_SC_PAGESIZE) };
@@ -275,6 +276,34 @@ fn memory_gb() -> f64 {
(pages as f64) * (size as f64) / 1e9
}
#[cfg(target_os = "windows")]
fn memory_gb() -> f64 {
#[repr(C)]
struct MemoryStatus {
length: u32,
memory_load: u32,
total_phys: u64,
avail_phys: u64,
total_page: u64,
avail_page: u64,
total_virtual: u64,
avail_virtual: u64,
avail_extended_virtual: u64,
}
#[link(name = "kernel32")]
unsafe extern "system" {
fn GlobalMemoryStatusEx(status: *mut MemoryStatus) -> i32;
}
unsafe {
let mut status = std::mem::zeroed::<MemoryStatus>();
status.length = std::mem::size_of::<MemoryStatus>() as u32;
if GlobalMemoryStatusEx(&mut status) == 0 || status.total_phys == 0 {
return 8.0;
}
status.total_phys as f64 / 1e9
}
}
/// 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 {
@@ -334,21 +363,47 @@ fn cpu_ticks() -> Option<(u64, u64)> {
}
}
#[cfg(not(any(target_os = "macos", target_os = "linux")))]
/// `GetSystemTimes`: kernel time already includes idle, so the total is kernel plus user.
#[cfg(target_os = "windows")]
fn cpu_ticks() -> Option<(u64, u64)> {
#[link(name = "kernel32")]
unsafe extern "system" {
fn GetSystemTimes(idle: *mut u64, kernel: *mut u64, user: *mut u64) -> i32;
}
unsafe {
let mut idle = 0u64;
let mut kernel = 0u64;
let mut user = 0u64;
if GetSystemTimes(&mut idle, &mut kernel, &mut user) == 0 {
return None;
}
let total = kernel.saturating_add(user);
if total == 0 {
return None;
}
Some((idle, total))
}
}
#[cfg(not(any(target_os = "macos", target_os = "linux", target_os = "windows")))]
fn cpu_ticks() -> Option<(u64, u64)> {
None
}
/// Share of the CPU that was busy between two samples. `idle` is included in `total`.
fn cpu_fraction(idle_delta: u64, total_delta: u64) -> Option<f64> {
if total_delta == 0 {
return None;
}
Some(1.0 - (idle_delta as f64) / (total_delta as f64))
}
fn cpu_used(prev: &mut Option<(u64, u64)>) -> Option<f64> {
let now = cpu_ticks()?;
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))
}
let idle_delta = now.0.saturating_sub(idle);
let total_delta = now.1.saturating_sub(total);
cpu_fraction(idle_delta, total_delta)
});
*prev = Some(now);
used
@@ -747,6 +802,13 @@ pub fn faces_read(path: String) -> Result<tauri::ipc::Response, String> {
mod tests {
use super::*;
#[test]
fn cpu_fraction_counts_idle_inside_the_total() {
let busy = cpu_fraction(25, 100);
assert_eq!(busy, Some(0.75));
assert_eq!(cpu_fraction(0, 0), None);
}
#[test]
fn base64_round_trip_of_a_short_buffer() {
let raw = b"faces";
+197 -23
View File
@@ -568,8 +568,13 @@ 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())?;
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 {
@@ -705,10 +710,7 @@ impl FtpState {
finished.remove(&f.name);
seen.remove(&f.path);
taken.insert(f.path.clone());
ready.push(IncomingFile {
login,
..f
});
ready.push(IncomingFile { login, ..f });
} else {
seen.insert(f.path.clone(), (f.size, f.modified_ms));
}
@@ -894,6 +896,7 @@ fn merge_xmp_packet(existing: &str, incoming: &str) -> String {
// A later pick must not wipe a crop already written, and a later crop must not wipe the pick.
let combined = combine_descriptions(our_description(existing).as_deref(), &incoming_desc);
let mut base = strip_our_description(existing);
let had_camera = base.contains("<rdf:Description");
// Lightroom reads the camera's lowercase `xmpDM:pick` and ignores a second description. Stamp that one.
if let Some(pick) = attr_of(&combined, "xmpDM:pick") {
let good = if pick == "1" { "True" } else { "False" };
@@ -903,11 +906,26 @@ fn merge_xmp_packet(existing: &str, incoming: &str) -> String {
for (key, xmlns_key, xmlns) in [
("xmp:Rating", "xmlns:xmp", "http://ns.adobe.com/xap/1.0/"),
("xmp:Label", "xmlns:xmp", "http://ns.adobe.com/xap/1.0/"),
("dc:title", "xmlns:dc", "http://purl.org/dc/elements/1.1/"),
("photoshop:Headline", "xmlns:photoshop", "http://ns.adobe.com/photoshop/1.0/"),
("photoshop:City", "xmlns:photoshop", "http://ns.adobe.com/photoshop/1.0/"),
("photoshop:Credit", "xmlns:photoshop", "http://ns.adobe.com/photoshop/1.0/"),
("photoshop:Source", "xmlns:photoshop", "http://ns.adobe.com/photoshop/1.0/"),
(
"photoshop:Headline",
"xmlns:photoshop",
"http://ns.adobe.com/photoshop/1.0/",
),
(
"photoshop:City",
"xmlns:photoshop",
"http://ns.adobe.com/photoshop/1.0/",
),
(
"photoshop:Credit",
"xmlns:photoshop",
"http://ns.adobe.com/photoshop/1.0/",
),
(
"photoshop:Source",
"xmlns:photoshop",
"http://ns.adobe.com/photoshop/1.0/",
),
(
"iptcCore:Location",
"xmlns:iptcCore",
@@ -919,10 +937,39 @@ fn merge_xmp_packet(existing: &str, incoming: &str) -> String {
base = stamp_attr(&base, key, &value, xmlns_key, xmlns);
}
}
// Caption, title, keywords and creator are RDF elements. Lightroom reads them from the first
// description and ignores the same elements on the packet this app appends afterwards.
for (tag, xmlns_key, xmlns) in [
(
"dc:description",
"xmlns:dc",
"http://purl.org/dc/elements/1.1/",
),
("dc:title", "xmlns:dc", "http://purl.org/dc/elements/1.1/"),
("dc:creator", "xmlns:dc", "http://purl.org/dc/elements/1.1/"),
("dc:subject", "xmlns:dc", "http://purl.org/dc/elements/1.1/"),
] {
let Some(block) = structured_block(&combined, tag) else {
continue;
};
if had_camera {
base = upsert_first_child(&base, tag, &block, xmlns_key, xmlns);
}
}
if let Some(idx) = base.rfind("</rdf:RDF>") {
// Moved onto the camera description. Leave them off the second packet so a rescan
// does not list the keywords twice. A file with no camera packet keeps them here.
let mut appended = combined.clone();
if had_camera {
for tag in ["dc:description", "dc:title", "dc:creator", "dc:subject"] {
if let Some((start, end)) = find_element(&appended, tag) {
appended.replace_range(start..end, "");
}
}
}
let mut out = String::new();
out.push_str(&base[..idx]);
out.push_str(&combined);
out.push_str(&appended);
out.push('\n');
out.push_str(&base[idx..]);
return out;
@@ -1137,6 +1184,100 @@ fn inject_after_about(xml: &str, extra: &str) -> String {
out
}
/// One element (`<dc:description>…</dc:description>` or a self-closing tag), not a longer name that shares the prefix.
fn find_element(xml: &str, tag: &str) -> Option<(usize, usize)> {
let needle = format!("<{tag}");
let mut from = 0;
while let Some(rel) = xml[from..].find(&needle) {
let start = from + rel;
let boundary = xml.as_bytes().get(start + needle.len()).copied();
let is_tag = boundary == Some(b'>')
|| boundary == Some(b' ')
|| boundary == Some(b'/')
|| boundary == Some(b'\n')
|| boundary == Some(b'\t');
if !is_tag {
from = start + needle.len();
continue;
}
let rest = &xml[start..];
let Some(gt) = rest.find('>') else {
return None;
};
if gt > 0 && rest.as_bytes()[gt - 1] == b'/' {
return Some((start, start + gt + 1));
}
let close = format!("</{tag}>");
let Some(close_at) = rest.find(&close) else {
return None;
};
return Some((start, start + close_at + close.len()));
}
None
}
fn element_block(xml: &str, tag: &str) -> Option<String> {
let (start, end) = find_element(xml, tag)?;
Some(xml[start..end].to_string())
}
/// The element Lightroom reads, or a title that arrived as an attribute turned into `rdf:Alt`.
fn structured_block(xml: &str, tag: &str) -> Option<String> {
if let Some(block) = element_block(xml, tag) {
return Some(block);
}
if tag != "dc:title" {
return None;
}
let title = attr_of(xml, "dc:title")?;
Some(format!(
"<dc:title><rdf:Alt><rdf:li xml:lang=\"x-default\">{title}</rdf:li></rdf:Alt></dc:title>"
))
}
/// Puts `block` inside the first `rdf:Description` (the camera packet Lightroom reads on rescan).
fn upsert_first_child(xml: &str, tag: &str, block: &str, xmlns_key: &str, xmlns: &str) -> String {
let Some(start) = xml.find("<rdf:Description") else {
return xml.to_string();
};
let len = description_len(&xml[start..]);
let mut desc = xml[start..start + len].to_string();
if let Some((child_start, child_end)) = find_element(&desc, tag) {
desc.replace_range(child_start..child_end, "");
}
if !desc.contains(xmlns_key) {
desc = inject_after_about(&desc, &format!("{xmlns_key}=\"{xmlns}\""));
}
desc = insert_child_block(&desc, block);
let mut out = String::new();
out.push_str(&xml[..start]);
out.push_str(&desc);
out.push_str(&xml[start + len..]);
out
}
fn insert_child_block(desc: &str, block: &str) -> String {
let Some(gt) = desc.find('>') else {
return desc.to_string();
};
if gt > 0 && desc.as_bytes()[gt - 1] == b'/' {
let mut out = String::new();
out.push_str(&desc[..gt - 1]);
out.push('>');
out.push_str(block);
out.push_str("</rdf:Description>");
return out;
}
let Some(close) = desc.rfind("</rdf:Description>") else {
return desc.to_string();
};
let mut out = String::new();
out.push_str(&desc[..close]);
out.push_str(block);
out.push_str(&desc[close..]);
out
}
fn xmp_app1(packet: &str) -> Result<Vec<u8>, String> {
let body = packet.as_bytes();
let size = 2 + XMP_HEADER.len() + body.len();
@@ -1186,7 +1327,10 @@ fn find_xmp_app1(data: &[u8]) -> Result<Option<(usize, usize)>, String> {
}
let start = i - 2;
let end = i + len;
if marker == 0xE1 && len >= 2 + XMP_HEADER.len() && &data[i + 2..i + 2 + XMP_HEADER.len()] == XMP_HEADER {
if marker == 0xE1
&& len >= 2 + XMP_HEADER.len()
&& &data[i + 2..i + 2 + XMP_HEADER.len()] == XMP_HEADER
{
return Ok(Some((start, end)));
}
i = end;
@@ -1232,7 +1376,9 @@ fn embed_xmp_jpeg(path: &Path, xml: &str) -> Result<(), String> {
};
let tmp = path.with_file_name(format!(
"{}.photoreport-part",
path.file_name().and_then(|s| s.to_str()).unwrap_or("photo.jpg")
path.file_name()
.and_then(|s| s.to_str())
.unwrap_or("photo.jpg")
));
std::fs::write(&tmp, &next).map_err(|e| e.to_string())?;
std::fs::rename(&tmp, path).map_err(|e| {
@@ -1452,9 +1598,18 @@ pub fn ftp_sent(
event: String,
date: String,
) -> Result<String, String> {
// Canonical path while the file is still in ingest: that is the string `ftp_info` stored.
let source = std::fs::canonicalize(&path)
.map(|p| p.to_string_lossy().into_owned())
.unwrap_or_else(|_| path.clone());
let target = state.sent(&path, &event, &date)?;
if let Ok(sha) = crate::local::sha256_file(Path::new(&target)) {
index.record(&sha, Path::new(&target));
let filed = PathBuf::from(&target);
index.retarget(&source, &filed);
if source != path {
index.retarget(&path, &filed);
}
if let Ok(sha) = crate::local::sha256_file(&filed) {
index.record(&sha, &filed);
}
Ok(target)
}
@@ -1593,7 +1748,10 @@ mod tests {
member_user_id: String::new(),
}],
ingest: dir.join("ingest").to_string_lossy().into_owned(),
work_folder: dir.join("work/{date} - {event}").to_string_lossy().into_owned(),
work_folder: dir
.join("work/{date} - {event}")
.to_string_lossy()
.into_owned(),
auto_start: false,
upload_originals: false,
})
@@ -1618,11 +1776,7 @@ mod tests {
.unwrap();
assert_eq!(PathBuf::from(&again), moved);
assert!(!ingest.join("IMG_0001.JPG").exists());
assert!(!moved
.parent()
.unwrap()
.join("IMG_0001-1.JPG")
.exists());
assert!(!moved.parent().unwrap().join("IMG_0001-1.JPG").exists());
let _ = std::fs::remove_dir_all(&dir);
}
@@ -1886,10 +2040,30 @@ mod tests {
assert!(both.contains("<xmp:Rating>4</xmp:Rating>"));
assert!(!both.contains("<xmp:Rating>0</xmp:Rating>"));
assert!(both.contains("xmpDM:pick=\"1\""));
assert!(both.contains("dc:title=\"Jogador\""));
let first_end = both.find("</rdf:Description>").expect("camera description");
let first = &both[..first_end];
assert!(first.contains("<dc:title><rdf:Alt><rdf:li xml:lang=\"x-default\">Jogador</rdf:li></rdf:Alt></dc:title>"));
assert!(!first.contains("photoreport:embed"));
assert!(both.contains("photoreport:embed=\"1\""));
}
/// Lightroom's Read Metadata uses the first description. Caption, keywords and creator have to be there.
#[test]
fn caption_lands_on_the_camera_description() {
let camera = r#"<?xpacket begin="" id="W5M0MpCehiHzreSzNTczkc9d"?><x:xmpmeta xmlns:x="adobe:ns:meta/"><rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"><rdf:Description rdf:about="" xmlns:xmp="http://ns.adobe.com/xap/1.0/"><xmp:Rating>0</xmp:Rating></rdf:Description></rdf:RDF></x:xmpmeta>"#;
let incoming = r#"<?xml version="1.0"?><x:xmpmeta xmlns:x="adobe:ns:meta/"><rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"><rdf:Description rdf:about="" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:photoshop="http://ns.adobe.com/photoshop/1.0/" xmlns:xmpDM="http://ns.adobe.com/xmp/1.0/DynamicMedia/" photoshop:City="Maia" xmpDM:pick="1" xmpDM:good="True"><dc:title><rdf:Alt><rdf:li xml:lang="x-default">SNAF</rdf:li></rdf:Alt></dc:title><dc:description><rdf:Alt><rdf:li xml:lang="x-default">Concentração no Hotel</rdf:li></rdf:Alt></dc:description><dc:creator><rdf:Seq><rdf:li>Peter Spark</rdf:li></rdf:Seq></dc:creator><dc:subject><rdf:Bag><rdf:li>ANDEBOL</rdf:li></rdf:Bag></dc:subject></rdf:Description></rdf:RDF></x:xmpmeta>"#;
let both = merge_xmp_packet(camera, incoming);
let first_end = both.find("</rdf:Description>").expect("camera description");
let first = &both[..first_end];
assert!(first.contains("Concentração no Hotel"));
assert!(first.contains(">SNAF<"));
assert!(first.contains("Peter Spark"));
assert!(first.contains("ANDEBOL"));
assert!(first.contains("photoshop:City=\"Maia\""));
assert!(first.contains("xmpDM:pick=\"1\""));
assert!(!first.contains("photoreport:embed"));
}
/// A JPEG with no camera XMP must still get a full packet Lightroom can parse.
#[test]
fn empty_camera_packet_is_wrapped() {
+1
View File
@@ -102,6 +102,7 @@ pub fn run() {
// `tauri dev` serves the dev server: nothing to update.
if !cfg!(debug_assertions) {
ui::watch(app.handle().clone());
updater::watch(app.handle().clone());
}
// Always the interface on this computer (`tauri dev`: the dev server). No download to start, and it
// works without a network; new versions arrive in the background (see `ui`).
+146 -25
View File
@@ -95,9 +95,68 @@ impl LocalIndex {
impl LocalIndex {
/// The file recorded for this hash, even if it changed since it arrived (another app, Photo Mechanic, wrote
/// captions into it): the same photo, with other metadata. Never handed out as the fingerprinted original.
///
/// Filing moves the photo out of the ingest folder and a later rewrite changes its hash, so the arrival
/// hash can still point at a path that is gone. The copy filed under the same name is that photo.
pub fn find_changed(&self, sha256: &str) -> Option<PathBuf> {
let path = PathBuf::from(self.with(|m| m.get(sha256).cloned())?);
path.is_file().then_some(path)
let recorded = PathBuf::from(self.with(|m| m.get(sha256).cloned())?);
if recorded.is_file() {
return Some(recorded);
}
let name = recorded.file_name()?.to_owned();
let mut found = self.with(|m| {
let mut hits = Vec::new();
for (other, path) in m.iter() {
if other == sha256 {
continue;
}
let candidate = Path::new(path);
if candidate.file_name() != Some(name.as_os_str()) {
continue;
}
if !candidate.is_file() {
continue;
}
hits.push(PathBuf::from(path));
}
hits
});
// Two different shoots can reuse a camera name. One remaining file is the one that was filed.
if found.len() != 1 {
return None;
}
let path = found.pop()?;
self.record(sha256, &path);
Some(path)
}
/// The arrival hash keeps pointing at the file after it leaves the ingest folder. The bytes at the
/// destination may already differ (captions written in), so recording only the new hash would lose it.
pub fn retarget(&self, from: &str, to: &Path) {
let to_owned = to.to_string_lossy().into_owned();
if from == to_owned {
return;
}
let file = self.file();
let snapshot = self.with(|m| {
let mut changed = false;
for path in m.values_mut() {
if path == from {
*path = to_owned.clone();
changed = true;
}
}
if !changed {
return None;
}
serde_json::to_vec(m).ok()
});
if let Some(bytes) = snapshot {
if let Some(dir) = file.parent() {
let _ = std::fs::create_dir_all(dir);
}
let _ = std::fs::write(file, bytes);
}
}
}
@@ -187,7 +246,9 @@ pub async fn local_stat(
sha256: String,
) -> Result<LocalStat, String> {
let path = index.find_changed(&sha256).ok_or("not_found")?;
let meta = tokio::fs::metadata(&path).await.map_err(|e| e.to_string())?;
let meta = tokio::fs::metadata(&path)
.await
.map_err(|e| e.to_string())?;
let mut size = meta.len();
let mut mtime_ms = meta
.modified()
@@ -195,45 +256,57 @@ pub async fn local_stat(
.and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
.map(|d| d.as_millis() as u64)
.unwrap_or(0);
// JPEG carries its XMP inside the file, so only a raw's sidecar moves the mtime.
let sidecar = path.with_extension("xmp");
let jpeg = path
.file_name()
.and_then(|n| n.to_str())
.is_some_and(crate::ftp::is_jpeg_name);
if !jpeg && let Ok(side) = tokio::fs::metadata(&sidecar).await {
size = size.saturating_add(side.len());
if let Some(ms) = side
.modified()
.ok()
.and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
.map(|d| d.as_millis() as u64)
{
mtime_ms = mtime_ms.max(ms);
// Sidecar next to the file (RAW always; JPEG when Photo Mechanic / Bridge wrote one).
for side in xmp_sidecar_paths(&path) {
if let Ok(meta) = tokio::fs::metadata(&side).await {
size = size.saturating_add(meta.len());
if let Some(ms) = meta
.modified()
.ok()
.and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
.map(|d| d.as_millis() as u64)
{
mtime_ms = mtime_ms.max(ms);
}
}
}
Ok(LocalStat { size, mtime_ms })
}
/// `photo.xmp` and `photo.jpg.xmp` beside an original — Photo Mechanic writes both forms for JPEG.
fn xmp_sidecar_paths(path: &Path) -> Vec<PathBuf> {
let mut out = Vec::with_capacity(2);
out.push(path.with_extension("xmp"));
if let Some(name) = path.file_name().and_then(|n| n.to_str()) {
if let Some(parent) = path.parent() {
out.push(parent.join(format!("{name}.xmp")));
}
}
out
}
/// The XMP packet (or the head of the file) for a local original, so the app can draw Lightroom's soft crop
/// without loading a 12 MB JPEG. Also tries `name.xmp` beside a raw. `not_found` when this computer lacks it.
/// without loading a 12 MB JPEG. Sidecar first (RAW and JPEG), then the packet embedded in a JPEG.
/// `not_found` when this computer lacks the file.
#[tauri::command]
pub async fn local_xmp(
index: tauri::State<'_, LocalIndex>,
sha256: String,
) -> Result<tauri::ipc::Response, String> {
let path = index.find_changed(&sha256).ok_or("not_found")?;
for side in xmp_sidecar_paths(&path) {
if side.is_file() {
let bytes = tokio::fs::read(&side).await.map_err(|e| e.to_string())?;
if !bytes.is_empty() {
return Ok(tauri::ipc::Response::new(bytes));
}
}
}
let jpeg = path
.file_name()
.and_then(|n| n.to_str())
.is_some_and(crate::ftp::is_jpeg_name);
// JPEG: the packet embedded in the file. RAW: the .xmp beside it. Lightroom does not use a JPEG sidecar.
if !jpeg {
let sidecar = path.with_extension("xmp");
if sidecar.is_file() {
let bytes = tokio::fs::read(&sidecar).await.map_err(|e| e.to_string())?;
return Ok(tauri::ipc::Response::new(bytes));
}
return Ok(tauri::ipc::Response::new(Vec::<u8>::new()));
}
let bytes = tokio::task::spawn_blocking(move || read_jpeg_xmp_head(&path))
@@ -338,6 +411,54 @@ mod tests {
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn finds_the_filed_copy_when_the_ingest_path_is_gone() {
let dir = std::env::temp_dir().join(format!("pr-local-filed-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
let ingest = dir.join("ingest");
let work = dir.join("work");
std::fs::create_dir_all(&ingest).unwrap();
std::fs::create_dir_all(&work).unwrap();
let arrived = ingest.join("PSR14526.JPG");
std::fs::write(&arrived, b"camera jpeg").unwrap();
let arrival = sha256_file(&arrived).unwrap();
let filed = work.join("PSR14526.JPG");
std::fs::write(&filed, b"camera jpeg plus captions").unwrap();
let rewritten = sha256_file(&filed).unwrap();
let index = LocalIndex {
file: Some(dir.join("index.json")),
..Default::default()
};
index.record(&arrival, &arrived);
index.record(&rewritten, &filed);
std::fs::remove_file(&arrived).unwrap();
assert_eq!(index.find_changed(&arrival), Some(filed.clone()));
assert_eq!(index.find(&arrival), None);
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn retarget_keeps_the_arrival_hash_on_the_filed_path() {
let dir = std::env::temp_dir().join(format!("pr-local-retarget-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
let arrived = dir.join("from.JPG");
let filed = dir.join("to.JPG");
std::fs::write(&arrived, b"same").unwrap();
std::fs::write(&filed, b"same").unwrap();
let sha = sha256_file(&arrived).unwrap();
let index = LocalIndex {
file: Some(dir.join("index.json")),
..Default::default()
};
index.record(&sha, &arrived);
index.retarget(arrived.to_str().unwrap(), &filed);
assert_eq!(index.find_changed(&sha), Some(filed));
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()));
+53 -3
View File
@@ -4,8 +4,10 @@
//!
//! The app asks the API (`/v1/desktop/update/{target}/{arch}/{version}`), which reads the latest `desktop-v*`
//! release. Installers are signed at build time with the release key; the matching public key is compiled in
//! (`PHOTOREPORT_UPDATER_PUBKEY`). A build without it (a developer's) never updates itself: there is nothing to
//! check a download against.
//! (`PHOTOREPORT_UPDATER_PUBKEY`, from the environment or `updater-pubkey.txt` on a release build). A debug build
//! without that variable never updates itself: there is nothing to check a download against.
use std::sync::atomic::{AtomicBool, Ordering};
use serde::Serialize;
use tauri_plugin_updater::UpdaterExt;
@@ -61,9 +63,22 @@ pub async fn update_check(app: tauri::AppHandle) -> Result<Option<UpdateInfo>, S
}
/// Downloads the new shell, checks its signature, installs it and restarts the app.
/// The page and the background check both call this; only one download runs.
#[tauri::command]
pub async fn update_install(app: tauri::AppHandle) -> Result<(), String> {
let update = updater(&app)?
let started = INSTALLING.compare_exchange(false, true, Ordering::SeqCst, Ordering::SeqCst);
if started.is_err() {
return Ok(());
}
let result = install_now(&app).await;
if result.is_err() {
INSTALLING.store(false, Ordering::SeqCst);
}
result
}
async fn install_now(app: &tauri::AppHandle) -> Result<(), String> {
let update = updater(app)?
.check()
.await
.map_err(|e| e.to_string())?
@@ -75,6 +90,33 @@ pub async fn update_install(app: tauri::AppHandle) -> Result<(), String> {
app.restart();
}
static INSTALLING: AtomicBool = AtomicBool::new(false);
const FIRST: std::time::Duration = std::time::Duration::from_secs(3);
const EVERY: std::time::Duration = std::time::Duration::from_secs(60);
/// Checks for a newer shell while the app runs and installs it. The window does not have to ask.
pub fn watch(app: tauri::AppHandle) {
if PUBKEY.is_none() {
return;
}
tauri::async_runtime::spawn(async move {
tokio::time::sleep(FIRST).await;
loop {
match update_check(app.clone()).await {
Ok(Some(_)) => {
if let Err(err) = update_install(app.clone()).await {
eprintln!("shell update: {err}");
}
}
Ok(None) => {}
Err(err) => eprintln!("shell update: {err}"),
}
tokio::time::sleep(EVERY).await;
}
});
}
#[cfg(test)]
mod tests {
use super::*;
@@ -88,4 +130,12 @@ mod tests {
);
assert!(url.starts_with("http"));
}
#[test]
fn release_builds_ship_the_update_key() {
let key = include_str!("../updater-pubkey.txt").trim();
assert!(key.starts_with("dW50cnVzdGVk"));
assert!(key.len() > 80);
assert!(!key.chars().any(|c| c.is_whitespace()));
}
}
@@ -0,0 +1 @@
dW50cnVzdGVkIGNvbW1lbnQ6IG1pbmlzaWduIHB1YmxpYyBrZXk6IEExODYxQ0JERTgzQzIwMTkKUldRWklEem92UnlHb2RUc0RRN2plalV0bndQVTVySFJQOGtuM3pQNDFtaDZFSld6ZnZya1FCeFEK
+3 -1
View File
@@ -39,7 +39,9 @@ export default async function OrderPage({ params, searchParams }: { params: Prom
</header>
{order.status === "PENDING" && (
<p className="notice" style={{ marginTop: 24 }}>
Assim que o pagamento for confirmado (por Multibanco pode demorar algumas horas) as fotos aparecem aqui e enviamos-te um email.
{order.checkoutUrl
? "Assim que o pagamento for confirmado (por Multibanco pode demorar algumas horas) as fotos aparecem aqui e enviamos-te um email."
: "A encomenda ficou registada. O pagamento combina-se à parte; quando estiver confirmado, as fotos aparecem aqui e enviamos-te um email."}
{order.checkoutUrl && (
<>
{" "}
+48 -10
View File
@@ -330,14 +330,20 @@ every 6 hours (`SPORTS_SYNC=off` turns it off). It is shared by every organisati
sides (`M19`, `ESP-M19`), and merges the Men's EHF EURO Cup match sheets from `www.eurohandball.com`
(`GetStandingMatches` / `GetMatchDetails` — same shape as club sheets, with shirt numbers and `res.ehf.eu`
headshots for the nominated 16). Portuguese CIPAs from the FPA call-up stay as `externalId` when the name
matches; photo/number come from the sheet. Youth camps (sub-17, sub-19, sub-20, men or women) come from
matches; photo/number come from the sheet. The same pass reads the Women's U17 EHF EURO qualification
(`W17-EURO`, content `139009`: Portugal–Italy `202712010502014`, 27 Nov 2026 19:00 in Águas Santas, and the
rest of that tournament). Portugal is team `W17`; every other country is `<code>-W17` (Italy is `ITA-W17`). The nominated sheet
fills numbers and headshots once the EHF publishes it. The FPA camp lists that same match as a friendly
(`Sub-17 feminina`): it is folded into `W17-EURO`, and an event already opened on it stays on the one fixture.
Youth camps (sub-17, sub-19, sub-20, men or women) come from
recent posts on `portal.fpa.pt`: the call-up PDF (CIPA, no shirt number from the list order) and the
"Jogos Particulares" calendar. A sheet with a real squad replaces that age group; a post the site does not
return leaves the plantel we already have. The November 2026 M19 list and the Spain name list are only the
seed when that team is still empty. Those friendlies are fixtures (`m19-por-esp-20261105`,
`m19-esp-por-20261107`) so picking the game links that plantel, not the senior one. A folder or title that
says sub-19 / M19 (not "Encontro Nacional") is that age group. Cloud delivery for these games is the
destination "Cloud M19" (`/FPA/Fotos/{season}/Seleções Nacionais/M19/…`), created from the organisation's
destination "Cloud M19" (`/FPA/Fotos/{season}/Seleções Nacionais/M19/…`) and "Cloud W17"
(`…/Seleções Nacionais/W17/…`), each created from the organisation's
existing FPA Nextcloud account and never sent on arrival. FPA licence or an older EHF club photo fills
gaps. People and reference faces are created when the event syncs those teams (`POST …/squads/sync`), not on
every sports refresh. Example match: Portugal–Switzerland `202811130101002`.
@@ -396,8 +402,9 @@ A match does not stop when the venue's internet does. The desktop app keeps work
photo in the event of its capture time (the same rule as the server), with id `local:<sha256>`. It can be culled,
named and edited before it is uploaded; the server's copy replaces it when the upload is done, keeping what was done.
- **Changes wait, in order** (`offline/queue.ts`, localStorage): culling, players, IPTC and "send to" made without a
network are kept and sent when the server answers (every 10 s and on `online`); changes to a photo not uploaded yet
wait for it. Develop edits use the per-photo outbox (`develop/session.ts`) and follow the photo to its server id.
network are kept and sent when the socket is up, including a change made while it was already up. Changes to a
photo not uploaded yet wait for it. Develop edits use the per-photo outbox (`develop/session.ts`) and follow the
photo to its server id.
- **Uploads wait instead of failing**: the queue pauses on a network error and resumes when the connection is back.
- The autopilot runs on the server when the photo arrives, and never over a person's edit (made offline first).
@@ -473,9 +480,14 @@ The same queue also delivers to SFTP, FTP/FTPS and Dropbox (`delivery/transports
- **ZeroZero** (`fotos.zerozero.pt`, `delivery/zerozero.ts`): the photographer's zerozero.pt account. The server
signs in through zerozero.pt's OAuth (`/api/auth/login` → `oauth.php` → `ax_login.php` → `/api/auth/callback`,
cookies kept in a small jar), and uploads with tus to `/api/upload?match_id=<game>` with the file name and the
author (`artist`: the photographer's name from the IPTC creator). The "folder" is the game: chosen for the
event by pasting the game's link (kept in `events.zerozero_game_id`), or found among the desk's upcoming games
by both teams and kick-off within 3 hours. The delivered item's remote path is `<game>/<image id>`
author (`artist`: the photographer's name from the IPTC creator). The upload only reaches the photographer's
desk. The public game shows the photo after publish: `POST /api/photo-sync/<image id>`, or
`POST /api/photo-sync/match/<game>` when the desk has no single-image publish (the same call as
"Sincronizar com zerozero"). A 403 signs in again once (a stale session uses that status, not 401). The same
refusal after the new login still counts as delivered: the file is on the desk. Any other publish failure fails
the delivery. The "folder" is the game:
chosen for the event by pasting the game's link (kept in `events.zerozero_game_id`), or found among the desk's
upcoming games by both teams and kick-off within 3 hours. The delivered item's remote path is `<game>/<image id>`
(`DELETE /api/images/<id>` takes it back).
Each target also has Photo Mechanic's uploader output options: fit-in-box size, JPEG quality, output
@@ -485,9 +497,35 @@ credentials, another name and folder).
**Cull marks and IPTC on the work-folder original.** While the desktop app is open it writes into the local
original Lightroom imports (JPEG: embedded XMP; RAW: `.xmp` beside it): pick / reject / stars / colour
(`xmpDM:pick`, `xmp:Rating`, `xmp:Label`), develop soft crop (`crs:Crop*`), and the resolved IPTC (caption,
title, city, keywords, creator…). The camera's XMP stays; PhotoReport stamps the flag onto that first
description so Lightroom Classic ≥ 13.2 Attribute filters see it. A catch-up pass covers photos already
picked before this screen was open.
title, city, keywords, creator…). The camera's XMP stays. PhotoReport stamps the flag and the newsroom
fields onto that first description — caption and title as `rdf:Alt`, keywords as `rdf:Bag`, creator as
`rdf:Seq` — because Lightroom Classic reads that description on import and on Read Metadata from Files and
ignores the same fields on a second packet. A write that fails while the file is still in the ingest folder
is retried once the original is filed, and again while the app stays open. A catch-up pass covers photos
already picked before this screen was open, without rewriting every older original first. The write addresses
the original by the hash recorded when that file was uploaded (`pr.localmap`), not by the preview hash the
server may store on the photo.
**Cull marks from disk into the library (XMP → library).** On local FTP arrival, hand import, and server
ingest, PhotoReport reads the same XMP fields back into the library (pick / reject / stars / colour). Soft
crop becomes a develop `crop.set`. The desktop watcher re-reads work-folder originals while the app is open
(every few seconds, for photos on screen and photos that arrived on this computer), so a pick, a star, a colour
or a crop painted in Lightroom / Photo Mechanic lands without another import and is sent to the server. The
2048 px FTP preview is never the source of marks — the original JPEG is, found by the hash recorded at upload
(`pr.localmap`), not by the preview hash the server may store.
What comes back from the file: the crop, the pick or reject, the stars and the colour. Exposure, white balance
and the other develop sliders are written out for Lightroom, and are not read back. Lightroom has to write the
change into the file (automatically write changes into XMP, or save metadata to the file). A change that stays
only in the Lightroom catalog is invisible.
A straightened crop is stored as the corners Lightroom turns back around the crop centre. Writing the levelled
rectangle plus the angle makes Lightroom show another proportion (Custom). The levelled result is always the
photograph's own aspect. The autopilot never chooses another one (`docs/photo-editing-rules.md`).
A photo that was already delivered is sent again to that same destination about a minute after the edit
settles, under the same file name, replacing the previous file. A destination that takes the untouched
original is not sent again: it has no edit to carry.
**Cull marks on delivery.** The same pick / reject / stars / colour are written into the delivered JPEG
(plus digiKam `PickLabel` and IPTC Urgency for Photo Mechanic). When the desktop app is open it watches local
+13 -3
View File
@@ -131,9 +131,19 @@ downloads only the files that changed, checks each hash and uses the new version
photographer reloads). The installer's own copy is the fallback, and wins when it is newer.
macOS builds on a Mac registered once as a runner (`bash infra/desktop/macos-runner.sh`, with a registration token
from Gitea → Actions → Runners; label `macos`, a launchd service of that user). Its builds carry the updater key, so
apps installed from a release update themselves; an app compiled by hand without the key never does. A release made
while the Mac is off waits for it.
from Gitea → Actions → Runners; label `macos`, a launchd service of that user). Release builds carry the updater
public key (`updater-pubkey.txt`, or `TAURI_UPDATER_PUBKEY` when CI sets it), so an installed app replaces itself
from the next signed `desktop-v*` release. A debug build without the variable never does. A release made while the
Mac is off waits for it.
Windows `.msi` builds on a runner labelled `windows` (Git bash, and the WebView2 step in the workflow). None is
registered yet, so a `desktop-v*` tag waits for that job until one is online. Linux installs `libgphoto2-dev`
for the USB camera.
Notarisation uses a Developer ID in `APPLE_SIGNING_IDENTITY` plus either `APPLE_ID`, `APPLE_PASSWORD` and
`APPLE_TEAM_ID`, or `APPLE_API_ISSUER`, `APPLE_API_KEY` and `APPLE_API_KEY_PATH`. Those secrets are not on this
Gitea yet, so Mac builds stay signed without notarisation. When the identity is set, the hardened runtime is on
and `apps/desktop/src-tauri/entitlements.plist` lets the bundled ONNX library load.
## Importing the old app.photoreport.pt
+9 -6
View File
@@ -44,6 +44,9 @@ Following the AP and NPPA codes:
- **Shape:** the autopilot keeps the photograph's own aspect (non-negotiable). The crop may move anywhere across
the frame, including a tighter window, but it is not turned into another format. A square, a 4:5, a 16:9, or a
portrait crop of a landscape frame is not an autopilot crop. An editor, by hand, may still choose another aspect.
A file written for Lightroom stores a straightened crop as the corners Lightroom turns back around the crop
centre, so the crop tool still shows this aspect. Writing the levelled rectangle together with the angle makes
Lightroom call it Custom.
- **Lead room (sport):** leave space in the direction the player looks or runs; put their back nearer the opposite
edge. Dead space behind the facing direction is wrong. Without a reliable facing signal (face on the body, or
the ball in play), keep the subject centred as before. Reportage and open team frames do not force lead room.
@@ -58,12 +61,12 @@ Following the AP and NPPA codes:
mid-thigh when the foot already leaves the photo. The face is big (a median face of 14% of the frame height)
near the top.
- **"full"** keeps whole bodies when they fit: Peter's usual crop, about two thirds of the frame.
- **Reportage** reads the shot the way a picture editor does, and trusts the framing. A long shot (the person
under half the picture) is the place. A full-length, or a conversation whose bodies are whole, is already the
photograph: the space around them was left on purpose, and it is not closed to match a sports fill. A prime of
100mm or longer is the exception on a single full-length: that lens cannot zoom, so the crop may step in to
about 85% of the frame, still centred on the photograph. A zoom (even at 200mm) is not that exception — the
photographer could have zoomed, so the space stays. A long shot and a group stay on a prime too. A frame the
- **Reportage** reads the shot the way a picture editor does. One clear person is the subject — someone
walking in the middle, a suitcase or a bag beside them — even when they take less than half the frame.
The crop keeps the whole body and what they carry, cuts empty floor and edge clutter, and keeps the
photograph's aspect. It does not say there is no subject. It is not a sports fill. A conversation (several
people whose bodies are whole) stays as framed. A distant figure, under about a fifth of the frame, is the
place and stays. A figure that already fills the height stays. A zoom at its wide end stays. A frame the
camera already cut (the feet leave the picture, and the person is large) is only finished, at mid-limb, and a
person the frame already cut off at the edge is left out. The sports framing on the event is ignored, including
a crop learnt from matches. A later frame of that moment may still be a half or a three-quarter. A whole hand
+4
View File
@@ -84,6 +84,10 @@ CFG
export APPLE_SIGNING_IDENTITY="$local_id"
# Not a Developer ID: no notarisation, so no hardened runtime (it would refuse the bundled ONNX library).
extra+=(--config '{"bundle":{"macOS":{"hardenedRuntime":false}}}')
else
# Developer ID. Notarisation (when APPLE_ID / APPLE_PASSWORD / APPLE_TEAM_ID, or the API key, are set)
# requires the hardened runtime. The entitlements let the bundled ONNX library load.
extra+=(--config '{"bundle":{"macOS":{"hardenedRuntime":true,"entitlements":"entitlements.plist"}}}')
fi
echo "Signing as: $APPLE_SIGNING_IDENTITY"
+10
View File
@@ -0,0 +1,10 @@
# WebView2 is the window engine of the Windows installer. Windows 11 already has it.
# A desktop-v tag on a Windows runner installs the evergreen runtime when this key is missing.
$ErrorActionPreference = "Stop"
$key = "HKLM:\SOFTWARE\WOW6432Node\Microsoft\EdgeUpdate\Clients\{F3017226-FE2A-4295-8BDF-00C3A9A7E4C5}"
if (Test-Path $key) {
exit 0
}
$dest = Join-Path $env:TEMP "webview2-bootstrapper.exe"
Invoke-WebRequest -Uri "https://go.microsoft.com/fwlink/p/?LinkId=2124703" -OutFile $dest
Start-Process $dest -ArgumentList "/silent", "/install" -Wait
+15
View File
@@ -238,6 +238,21 @@ describe("delivery paths", () => {
expect(renderFileName(DESTINATION_EXAMPLES.fpaM19.fileName, { ...m19, n: 3 }, "R1_0003.JPG")).toBe("PS_POR x ESP_3.jpg");
});
it("matches the women's under-17 cloud folder", () => {
const w17 = buildVars({
home: "Portugal",
away: "Itália",
homeShort: "POR",
awayShort: "ITA",
competition: "W17 EHF EURO",
startsAt: new Date("2026-11-27T19:00:00Z"),
});
expect(renderFolder(DESTINATION_EXAMPLES.fpaW17.folder, w17)).toBe(
"/FPA/Fotos/2026_2027/Seleções Nacionais/W17/20261127 - POR x ITA/",
);
expect(renderFileName(DESTINATION_EXAMPLES.fpaW17.fileName, { ...w17, n: 1 }, "R1_0001.JPG")).toBe("PS_POR x ITA_1.jpg");
});
it("matches the Liga folder and keeps the camera name", () => {
const liga = buildVars({ home: "Casa Pia", away: "Sporting", round: 1, matchNumber: 1, startsAt: new Date("2025-08-09T18:00:00Z") });
expect(renderFolder(DESTINATION_EXAMPLES.liga.folder, liga)).toBe("/LPBetclic 25-26/Jornada 1/1. Casa Pia x Sporting/");
+5
View File
@@ -82,6 +82,11 @@ export const DESTINATION_EXAMPLES = {
folder: "/FPA/Fotos/{season}/Seleções Nacionais/M19/{dateCompact} - {homeShort} x {awayShort}/",
fileName: "PS_{homeShort} x {awayShort}_{n}.jpg",
},
/** Women's under-17. Same account as the club cloud; its own folder under Seleções Nacionais. */
fpaW17: {
folder: "/FPA/Fotos/{season}/Seleções Nacionais/W17/{dateCompact} - {homeShort} x {awayShort}/",
fileName: "PS_{homeShort} x {awayShort}_{n}.jpg",
},
liga: {
folder: "/LPBetclic {seasonShort}/Jornada {round}/{matchNumber}. {home} x {away}/",
fileName: "{originalName}",
+5
View File
@@ -591,6 +591,11 @@ export class ApiClient {
return this.request<OrderView>("POST", `/v1/orders/${orderId}/items/${itemId}/shipped`);
}
/** Payment taken outside the shop. The caller is responsible for delivering the work. */
recordPayment(orderId: string) {
return this.request<OrderView>("POST", `/v1/orders/${orderId}/payment-received`);
}
retryOrder(orderId: string) {
return this.request<OrderView>("POST", `/v1/orders/${orderId}/retry`);
}