Compare commits
72
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f5f7c2fa59 | ||
|
|
b1dde5657a | ||
|
|
41598aa1ae | ||
|
|
2645138f54 | ||
|
|
8fcf62f8be | ||
|
|
1ed6d144d3 | ||
|
|
2a839d8305 | ||
|
|
f20dea883e | ||
|
|
a9ae5ce6ad | ||
|
|
42912453e2 | ||
|
|
3fd6a6f1cc | ||
|
|
4d3a9dfc07 | ||
|
|
a781be6d9e | ||
|
|
df741d8268 | ||
|
|
3f8e36f6e3 | ||
|
|
7173c88e08 | ||
|
|
176f15a5a0 | ||
|
|
4e88244a8b | ||
|
|
549def64f7 | ||
|
|
bf2d8b4b6a | ||
|
|
7080a1d7fe | ||
|
|
2c8adede4c | ||
|
|
22c1d0530b | ||
|
|
1279294e8d | ||
|
|
341c41b617 | ||
|
|
140bdc2d68 | ||
|
|
cc759dda4f | ||
|
|
f7570f8706 | ||
|
|
c089868d59 | ||
|
|
9c5463f337 | ||
|
|
fbdc728ae7 | ||
|
|
dc977fdb6b | ||
|
|
097ee18572 | ||
|
|
a1a8c74a70 | ||
|
|
ef35c2e569 | ||
|
|
107e4be5e3 | ||
|
|
d9ca281706 | ||
|
|
0afa84c211 | ||
|
|
0ef50c98cd | ||
|
|
985188812a | ||
|
|
3751589db0 | ||
|
|
0179e2bd86 | ||
|
|
73b3b65925 | ||
|
|
7a552e2c81 | ||
|
|
c652715707 | ||
|
|
b1561da69a | ||
|
|
b540ab447b | ||
|
|
0b7af4f992 | ||
|
|
018cefaf7a | ||
|
|
f847cbff56 | ||
|
|
1b1dadda6c | ||
|
|
1dbd4156df | ||
|
|
c5e90e6d89 | ||
|
|
9d0b19d1f0 | ||
|
|
faaa3406d2 | ||
|
|
697676de56 | ||
|
|
7edac9dae1 | ||
|
|
602c64ca0d | ||
|
|
a8e5d97954 | ||
|
|
ea669672d4 | ||
|
|
ece55190c3 | ||
|
|
824ca7ae49 | ||
|
|
21e33ba0c6 | ||
|
|
66ac11621c | ||
|
|
eb81f69fb8 | ||
|
|
cb67b0c329 | ||
|
|
e096c6153e | ||
|
|
fa2e494d99 | ||
|
|
ee617b12de | ||
|
|
a8a887e82f | ||
|
|
3a2828e4ca | ||
|
|
9d79270859 |
No files matched your search
@@ -27,7 +27,7 @@ jobs:
|
||||
- uses: pnpm/action-setup@v4
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: 22
|
||||
node-version: 24.22.1
|
||||
cache: pnpm
|
||||
- run: pnpm install --frozen-lockfile
|
||||
- run: pnpm -r build
|
||||
|
||||
@@ -45,7 +45,7 @@ jobs:
|
||||
- uses: pnpm/action-setup@v4
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: 22
|
||||
node-version: 24.22.1
|
||||
- uses: dtolnay/rust-toolchain@stable
|
||||
- name: Both Mac processors (universal app)
|
||||
if: runner.os == 'macOS'
|
||||
|
||||
Generated
+1702
-5
File diff suppressed because it is too large.
Load diff
@@ -20,6 +20,10 @@ lightcraft-merge = { git = "https://github.com/storytold/lightcraft", rev = "5fe
|
||||
lightcraft-raw = { git = "https://github.com/storytold/lightcraft", rev = "5fe74557eca64638b1f9015c9769f7e52a889fa2" }
|
||||
lightcraft-color = { git = "https://github.com/storytold/lightcraft", rev = "5fe74557eca64638b1f9015c9769f7e52a889fa2" }
|
||||
lightcraft-meta = { git = "https://github.com/storytold/lightcraft", rev = "5fe74557eca64638b1f9015c9769f7e52a889fa2" }
|
||||
# Photo Merge only. The develop crates do not export the colour-tag step a raw without matrices
|
||||
# needs before write_linear_dng. Desktop turns this on; the browser engine does not.
|
||||
lightcraft-engine = { git = "https://github.com/storytold/lightcraft", rev = "5fe74557eca64638b1f9015c9769f7e52a889fa2" }
|
||||
lightcraft-catalog = { git = "https://github.com/storytold/lightcraft", rev = "5fe74557eca64638b1f9015c9769f7e52a889fa2" }
|
||||
serde = { version = "1", features = ["derive"] }
|
||||
serde_json = "1"
|
||||
thiserror = "2"
|
||||
|
||||
@@ -0,0 +1,3 @@
|
||||
-- Handball: a person's federation licence number (CIPA).
|
||||
ALTER TABLE "people" ADD COLUMN "licence" TEXT;
|
||||
CREATE UNIQUE INDEX "people_organization_id_licence_key" ON "people"("organization_id", "licence");
|
||||
@@ -0,0 +1,4 @@
|
||||
-- Editors on the cloud: search the archive by uploading a photo of a person (news desk). Off by default;
|
||||
-- on for FPA archives already connected with that look.
|
||||
ALTER TABLE "cloud_sources" ADD COLUMN "photo_find_enabled" BOOLEAN NOT NULL DEFAULT false;
|
||||
UPDATE "cloud_sources" SET "photo_find_enabled" = true WHERE "look" = 'fpa';
|
||||
+6
@@ -0,0 +1,6 @@
|
||||
-- Per-send override: photographer asked for the camera original on this item.
|
||||
ALTER TABLE "delivery_items" ADD COLUMN "force_originals" BOOLEAN NOT NULL DEFAULT false;
|
||||
|
||||
-- Optional on a destination: wait a little for faces when the pad needs {players}.
|
||||
-- Off by default — a send the photographer asked for must leave at once; names can resend later.
|
||||
ALTER TABLE "delivery_targets" ADD COLUMN "wait_for_faces" BOOLEAN NOT NULL DEFAULT false;
|
||||
@@ -559,6 +559,9 @@ model DeliveryTarget {
|
||||
/// The original as it arrived (no resizing, no recompression), with the metadata written into it and renamed:
|
||||
/// a copy for one's own backup, like Photo Mechanic's Live Ingest destination.
|
||||
originals Boolean @default(false)
|
||||
/// Wait a little for faces when the pad/path needs `{players}` (automatic every-arrival or when opted in).
|
||||
/// Off by default: a send the photographer asked for leaves at once; names can update the file later.
|
||||
waitForFaces Boolean @default(false) @map("wait_for_faces")
|
||||
/// Every photo that arrives (FTP, the desktop app, uploads) is sent here on its own, as soon as it is in an event.
|
||||
onArrival Boolean @default(false) @map("on_arrival")
|
||||
/// With `onArrival`: only the photos of these FTP logins (ids; empty: everyone's). The central FTP then works as
|
||||
@@ -615,6 +618,8 @@ model DeliveryItem {
|
||||
replacesPath String? @map("replaces_path")
|
||||
/// Queued to be taken back from the destination (the photo was rejected or un-picked): the worker removes it.
|
||||
retract Boolean @default(false)
|
||||
/// This send asked for the camera original (overrides the destination's resize recipe for this item only).
|
||||
forceOriginals Boolean @default(false) @map("force_originals")
|
||||
byteSize Int? @map("byte_size")
|
||||
requestedById String? @map("requested_by_id") @db.Uuid
|
||||
nextAttemptAt DateTime @default(now()) @map("next_attempt_at")
|
||||
@@ -659,6 +664,8 @@ model Person {
|
||||
referenceEmbedding Float[] @default([]) @map("reference_embedding")
|
||||
/// The squad entry this person came from (kept in step when squads change).
|
||||
sportsPlayerId String? @map("sports_player_id") @db.Uuid
|
||||
/// Handball: the federation licence number (CIPA), when the person was added by it or seen on a match report.
|
||||
licence String?
|
||||
/// Face recognition turned off for this person (an archive editor): no centroid, no reference, never suggested;
|
||||
/// still named by hand.
|
||||
recognitionOffAt DateTime? @map("recognition_off_at")
|
||||
@@ -673,6 +680,7 @@ model Person {
|
||||
|
||||
@@unique([organizationId, name])
|
||||
@@unique([organizationId, sportsPlayerId])
|
||||
@@unique([organizationId, licence])
|
||||
@@map("people")
|
||||
}
|
||||
|
||||
@@ -1631,6 +1639,8 @@ model CloudSource {
|
||||
status String @default("LOGIN")
|
||||
/// How the archive's site looks: "liga" (Liga Portugal), "fpa" (Federação de Andebol), or null (PhotoReport).
|
||||
look String?
|
||||
/// Editors on the cloud may upload a photo and search for that face across the archive (news desk). Off by default.
|
||||
photoFindEnabled Boolean @default(false) @map("photo_find_enabled")
|
||||
/// The archive's own address ("arquivo.ligaportugal.pt"): the site serves this archive at its root there.
|
||||
hostname String? @unique
|
||||
/// Nextcloud login flow v2: where to poll for the app password while status is LOGIN (sealed token).
|
||||
|
||||
+24
-12
@@ -145,18 +145,8 @@ export async function buildApp({ config, db, realtime, fetchImpl, reporter: give
|
||||
await registerPhotoRoutes(app, { db, sessions, storage, signer, broadcaster, archive, resend: (orgId, ids) => delivery.resendPhotos(orgId, ids) });
|
||||
await registerArchiveRoutes(app, { db, sessions, archive, storageRoot: config.STORAGE_ROOT, minFreeBytes: config.ARCHIVE_MIN_FREE_GB * 1e9 });
|
||||
// The API never runs the face engine: it confirms and merges groups; the worker detects and groups.
|
||||
const faces = new FaceService({ db, storage, broadcaster, log: app.log });
|
||||
await registerArchiveViewerRoutes(app, { db, secrets, signer, archive, tokens: new ViewerTokens(config.JWT_SECRET), faces, storage, secret: config.JWT_SECRET, fetchImpl });
|
||||
await registerCompositionRoutes(app, { db, sessions, storage, storageRoot: config.STORAGE_ROOT });
|
||||
await registerSearchRoutes(app, { db, sessions, signer });
|
||||
await registerFtpRoutes(app, { db, sessions, ingestRoot: config.INGEST_ROOT, hookSecret: config.SFTPGO_HOOK_KEY });
|
||||
const ingest = new IngestService({ db, storage, signer, broadcaster, ingestRoot: config.INGEST_ROOT, log: app.log });
|
||||
ingest.arrivals = (photo) => delivery.queueArrival(photo);
|
||||
await registerUploadRoutes(app, { db, sessions, ingest, storage, signer });
|
||||
// The worker writes the heartbeat. Tests have no worker, so they say the engine is on unless a case says otherwise.
|
||||
const facesOnline = engineOnline ?? (() => (config.NODE_ENV === "test" ? true : faceEnginePaths(config) !== null && faceWorkerLive(config.STORAGE_ROOT)));
|
||||
await registerFaceRoutes(app, { db, sessions, faces, signer, storage, engineOnline: facesOnline });
|
||||
// Search by photo (library and "Encontra-te" on the sites): the API's own face engine, started on demand.
|
||||
const faces = new FaceService({ db, storage, broadcaster, log: app.log, resend: (orgId, ids) => delivery.resendPhotos(orgId, ids) });
|
||||
// Search by photo (library, archive editors, "Encontra-te"): the API's own face engine, started on demand.
|
||||
const facePaths = faceEnginePaths(config);
|
||||
const slots = scanSlots();
|
||||
const lookupEngine = new IdleEngine(
|
||||
@@ -168,6 +158,28 @@ export async function buildApp({ config, db, realtime, fetchImpl, reporter: give
|
||||
);
|
||||
app.addHook("onClose", async () => (faceEngine ? undefined : lookupEngine.close()));
|
||||
const lookup = new FaceLookup({ db, engine: () => lookupEngine.get() });
|
||||
await registerArchiveViewerRoutes(app, {
|
||||
db,
|
||||
secrets,
|
||||
signer,
|
||||
archive,
|
||||
tokens: new ViewerTokens(config.JWT_SECRET),
|
||||
faces,
|
||||
storage,
|
||||
secret: config.JWT_SECRET,
|
||||
fetchImpl,
|
||||
sports,
|
||||
lookup,
|
||||
});
|
||||
await registerCompositionRoutes(app, { db, sessions, storage, storageRoot: config.STORAGE_ROOT });
|
||||
await registerSearchRoutes(app, { db, sessions, signer });
|
||||
await registerFtpRoutes(app, { db, sessions, ingestRoot: config.INGEST_ROOT, hookSecret: config.SFTPGO_HOOK_KEY });
|
||||
const ingest = new IngestService({ db, storage, signer, broadcaster, ingestRoot: config.INGEST_ROOT, log: app.log });
|
||||
ingest.arrivals = (photo) => delivery.queueArrival(photo);
|
||||
await registerUploadRoutes(app, { db, sessions, ingest, storage, signer });
|
||||
// The worker writes the heartbeat. Tests have no worker, so they say the engine is on unless a case says otherwise.
|
||||
const facesOnline = engineOnline ?? (() => (config.NODE_ENV === "test" ? true : faceEnginePaths(config) !== null && faceWorkerLive(config.STORAGE_ROOT)));
|
||||
await registerFaceRoutes(app, { db, sessions, faces, signer, storage, engineOnline: facesOnline });
|
||||
let jerseyOnce: Promise<JerseyReader | null> | null = null;
|
||||
const jerseyOf = (): Promise<JerseyReader | null> => {
|
||||
if (jersey !== undefined) return Promise.resolve(jersey);
|
||||
|
||||
@@ -26,6 +26,7 @@ describe("corrupt / incomplete archive sources (BIT-31621)", () => {
|
||||
expect(isCorruptSourceMessage("premature end of JPEG")).toBe(true);
|
||||
expect(isCorruptSourceMessage("Input file contains unsupported image format")).toBe(true);
|
||||
expect(isCorruptSourceMessage("VipsForeignLoad: \"/tmp/x/original.jpg\" is not a known file format")).toBe(true);
|
||||
expect(isCorruptSourceMessage("VipsJpeg: Invalid SOS parameters for sequential JPEG")).toBe(true);
|
||||
expect(isCorruptSourceMessage("ffmpeg exited 234: Stream map '0:v:0' matches no streams")).toBe(false);
|
||||
expect(isCorruptSourceMessage("GET /a failed: 503")).toBe(false);
|
||||
});
|
||||
|
||||
@@ -24,7 +24,7 @@ export class IncompleteDownload extends Error {
|
||||
|
||||
/** ffprobe/ffmpeg/sharp messages that mean the cloud file itself is damaged, not our pipeline. */
|
||||
export function isCorruptSourceMessage(message: string): boolean {
|
||||
return /moov atom not found|premature end|not a known file format|corrupt (?:jpeg )?header|Corrupt JPEG|Input file has corrupt header|Input file contains unsupported image format|unsupported image format|Invalid data found when processing input/i.test(
|
||||
return /moov atom not found|premature end|not a known file format|corrupt (?:jpeg )?header|Corrupt JPEG|Input file has corrupt header|Input file contains unsupported image format|unsupported image format|Invalid data found when processing input|Invalid SOS parameters/i.test(
|
||||
message,
|
||||
);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,321 @@
|
||||
import type { FastifyInstance, FastifyRequest } from "fastify";
|
||||
import { eventName } from "@photoreport/metadata";
|
||||
import { z } from "zod";
|
||||
import { Prisma } from "../generated/prisma/client.js";
|
||||
import type { Db } from "../db.js";
|
||||
import { facesOut, lookupFailed, lookupImage, LookupQuery } from "../faces/lookupRoutes.js";
|
||||
import type { FaceLookup } from "../faces/lookup.js";
|
||||
import { cosine, POSSIBLE_BELOW, THRESHOLDS } from "../faces/math.js";
|
||||
import { conflict, forbidden, notFound } from "../lib/errors.js";
|
||||
import type { UrlSigner } from "../storage/storage.js";
|
||||
import { faceBox } from "./people.js";
|
||||
import { publishedPhotos } from "./gallery.js";
|
||||
import type { Viewer } from "./viewer.js";
|
||||
|
||||
/**
|
||||
* Search the archive by a photo: for editors on the cloud (same rights as "Rever rostos"), when the archive has
|
||||
* the option on and the organization has biometrics on. The search photo is read in memory and never kept.
|
||||
*
|
||||
* Registry first: the probe is compared to registered people (FPA licence / Liga headshot centroids). A clear
|
||||
* match loads that person's archive photos by person_id — no blind scan of every face group. Only when nobody
|
||||
* in the registry is sure enough do we fall back to HNSW over the viewer's face groups.
|
||||
*/
|
||||
interface Deps {
|
||||
db: Db;
|
||||
signer: UrlSigner;
|
||||
lookup: FaceLookup;
|
||||
viewerOf: (req: FastifyRequest, sourceId?: string) => Viewer;
|
||||
visibleFolders: (v: Viewer) => Promise<string[] | "all">;
|
||||
editableFolders: (v: Viewer) => Promise<string[] | "all">;
|
||||
}
|
||||
|
||||
const SourceParams = z.object({ sourceId: z.uuid() });
|
||||
const EVENTS_TTL_MS = 5 * 60_000;
|
||||
const NEAREST = 400;
|
||||
const MAX_PHOTOS = 500;
|
||||
/** How many registry candidates to keep for the editor (strong + possible). */
|
||||
const PEOPLE_LIMIT = 8;
|
||||
|
||||
type CardLevel = "confirmed" | "probable" | "similar";
|
||||
type Via = "registry" | "faces";
|
||||
|
||||
const levelOf = (score: number, match: number): CardLevel => (score >= match ? "probable" : "similar");
|
||||
|
||||
export async function registerArchiveFindRoutes(app: FastifyInstance, deps: Deps) {
|
||||
const { db, signer, lookup, viewerOf, visibleFolders, editableFolders } = deps;
|
||||
|
||||
/** Event ids of a viewer's archive scope: the heavy DISTINCT over cloud_files, reused while they search. */
|
||||
const eventsCache = new Map<string, { at: number; ids: string[] }>();
|
||||
|
||||
const scopeOf = async (v: Viewer): Promise<{ sql: Prisma.Sql; key: string } | null> => {
|
||||
const visible = await visibleFolders(v);
|
||||
if (visible !== "all" && !visible.length) return null;
|
||||
const key = visible === "all" ? "all" : [...visible].sort().join(",");
|
||||
const sql =
|
||||
visible === "all"
|
||||
? Prisma.sql`cf.source_id = ${v.s}::uuid AND cf.status = 'DONE' AND cf.photo_id IS NOT NULL AND ${publishedPhotos}`
|
||||
: Prisma.sql`cf.source_id = ${v.s}::uuid AND cf.status = 'DONE' AND cf.photo_id IS NOT NULL AND cf.folder_id = ANY(${visible}::uuid[]) AND ${publishedPhotos}`;
|
||||
return { sql, key };
|
||||
};
|
||||
|
||||
const requireFind = async (v: Viewer) => {
|
||||
const editable = await editableFolders(v);
|
||||
if (editable !== "all" && !editable.length) throw forbidden("archive_edit_required");
|
||||
const source = await db.cloudSource.findUnique({
|
||||
where: { id: v.s },
|
||||
select: { id: true, organizationId: true, photoFindEnabled: true, organization: { select: { biometricsEnabled: true } } },
|
||||
});
|
||||
if (!source) throw notFound("source_not_found");
|
||||
if (!source.photoFindEnabled || !source.organization.biometricsEnabled) throw conflict("find_unavailable");
|
||||
return source;
|
||||
};
|
||||
|
||||
const eventsInScope = async (sourceId: string, scope: Prisma.Sql, cacheKey: string): Promise<string[]> => {
|
||||
const key = `${sourceId}:${cacheKey}`;
|
||||
const hit = eventsCache.get(key);
|
||||
if (hit && Date.now() - hit.at < EVENTS_TTL_MS) return hit.ids;
|
||||
const rows = await db.$queryRaw<{ event_id: string }[]>`
|
||||
SELECT DISTINCT ph.event_id AS event_id
|
||||
FROM photos ph
|
||||
JOIN cloud_files cf ON cf.photo_id = ph.id AND ${scope}
|
||||
WHERE ph.event_id IS NOT NULL`;
|
||||
const ids = rows.map((r) => r.event_id);
|
||||
eventsCache.set(key, { at: Date.now(), ids });
|
||||
return ids;
|
||||
};
|
||||
|
||||
/**
|
||||
* Face groups in the viewer's events like the probe. Production (512-d) uses the HNSW index; shorter test
|
||||
* vectors fall back to a cosine over the float array. Used only when the registry has no sure person.
|
||||
*/
|
||||
const nearGroups = async (eventIds: string[], embedding: number[], model: string) => {
|
||||
if (!eventIds.length) return [] as { id: string; personId: string | null; score: number }[];
|
||||
const match = (THRESHOLDS[model] ?? { match: 0.5 }).match;
|
||||
const floor = match - POSSIBLE_BELOW;
|
||||
if (embedding.length === 512) {
|
||||
const literal = `[${embedding.map((n) => (Number.isFinite(n) ? n : 0)).join(",")}]`;
|
||||
const rows = await db.$queryRaw<{ id: string; person_id: string | null; score: number }[]>`
|
||||
SELECT id, person_id, score FROM (
|
||||
SELECT g.id, g.person_id, (1 - (g.centroid_vec <=> ${literal}::vector))::float AS score
|
||||
FROM face_groups g
|
||||
WHERE g.ignored_at IS NULL AND g.model = ${model} AND g.centroid_vec IS NOT NULL AND g.size > 0
|
||||
AND g.event_id = ANY(${eventIds}::uuid[])
|
||||
ORDER BY g.centroid_vec <=> ${literal}::vector
|
||||
LIMIT ${NEAREST}
|
||||
) ranked
|
||||
WHERE score >= ${floor}`;
|
||||
return rows.map((r) => ({ id: r.id, personId: r.person_id, score: Number(r.score) }));
|
||||
}
|
||||
const groups = await db.$queryRaw<{ id: string; centroid: unknown; person_id: string | null }[]>`
|
||||
SELECT g.id, g.centroid, g.person_id
|
||||
FROM face_groups g
|
||||
WHERE g.ignored_at IS NULL AND g.model = ${model} AND g.size > 0 AND cardinality(g.centroid) > 0
|
||||
AND g.event_id = ANY(${eventIds}::uuid[])`;
|
||||
const asVector = (v: unknown): number[] =>
|
||||
Array.isArray(v) ? v.map(Number) : typeof v === "string" ? v.replace(/[{}]/g, "").split(",").filter(Boolean).map(Number) : [];
|
||||
return groups
|
||||
.map((g) => ({ id: g.id, personId: g.person_id, score: cosine(embedding, asVector(g.centroid)) }))
|
||||
.filter((x) => x.score >= floor)
|
||||
.sort((a, b) => b.score - a.score)
|
||||
.slice(0, NEAREST);
|
||||
};
|
||||
|
||||
/** Licence / headshot / federation label for the people the registry returned. */
|
||||
const enrichPeople = async (ids: string[]) => {
|
||||
if (!ids.length) return new Map<string, { licence: string | null; reference: string | null; registry: "fpa" | "liga" | "uefa" | "ehf" | "fpf" | null }>();
|
||||
const rows = await db.$queryRaw<{ id: string; licence: string | null; reference: boolean; provider: string | null }[]>`
|
||||
SELECT p.id, p.licence, p.reference_key IS NOT NULL AS reference, t.provider
|
||||
FROM people p
|
||||
LEFT JOIN sports_players sp ON sp.id = p.sports_player_id
|
||||
LEFT JOIN sports_teams t ON t.id = sp.team_id
|
||||
WHERE p.id = ANY(${ids}::uuid[])`;
|
||||
const asRegistry = (provider: string | null, licence: string | null): "fpa" | "liga" | "uefa" | "ehf" | "fpf" | null => {
|
||||
if (licence || provider === "FPA") return "fpa";
|
||||
if (provider === "LIGA" || provider === "LPFP") return "liga";
|
||||
if (provider === "UEFA") return "uefa";
|
||||
if (provider === "EHF") return "ehf";
|
||||
if (provider === "FPF") return "fpf";
|
||||
return null;
|
||||
};
|
||||
return new Map(
|
||||
rows.map((r) => [
|
||||
r.id,
|
||||
{
|
||||
licence: r.licence,
|
||||
reference: r.reference ? signer.personUrl(r.id) : null,
|
||||
registry: asRegistry(r.provider, r.licence),
|
||||
},
|
||||
]),
|
||||
);
|
||||
};
|
||||
|
||||
const photoCards = async (
|
||||
shown: { photoId: string; faceId: string; score: number; level: CardLevel; sharpness: number | null }[],
|
||||
scope: Prisma.Sql,
|
||||
) => {
|
||||
if (!shown.length) return [];
|
||||
const ids = shown.map((h) => h.photoId);
|
||||
const faceIds = shown.map((h) => h.faceId);
|
||||
const [links, photos, faceRows] = await Promise.all([
|
||||
db.$queryRaw<{ photo_id: string; folder_id: string }[]>`
|
||||
SELECT DISTINCT ON (cf.photo_id) cf.photo_id, cf.folder_id
|
||||
FROM cloud_files cf
|
||||
WHERE cf.photo_id = ANY(${ids}::uuid[]) AND ${scope}
|
||||
ORDER BY cf.photo_id, cf.path`,
|
||||
db.photo.findMany({
|
||||
where: { id: { in: ids } },
|
||||
select: { id: true, width: true, height: true, players: true, capturedAt: true, renderedSeq: true, developSnapshot: true, originalName: true },
|
||||
}),
|
||||
db.face.findMany({ where: { id: { in: faceIds } }, select: { id: true, x0: true, y0: true, x1: true, y1: true } }),
|
||||
]);
|
||||
const folderOf = new Map(links.map((r) => [r.photo_id, r.folder_id]));
|
||||
const folders = await db.cloudFolder.findMany({ where: { id: { in: [...new Set(folderOf.values())] } }, include: { event: true } });
|
||||
const galleries = new Map(
|
||||
folders.map((f) => [f.id, { id: f.id, title: f.event ? eventName(f.event) : (f.path.split("/").pop() ?? ""), startsAt: f.event?.startsAt ?? null, competition: f.event?.competition ?? null }]),
|
||||
);
|
||||
const byId = new Map(photos.map((p) => [p.id, p]));
|
||||
const faceById = new Map(faceRows.map((f) => [f.id, f]));
|
||||
return shown
|
||||
.filter((h) => byId.has(h.photoId) && folderOf.has(h.photoId))
|
||||
.map((h) => {
|
||||
const p = byId.get(h.photoId)!;
|
||||
const f = faceById.get(h.faceId);
|
||||
return {
|
||||
id: p.id,
|
||||
name: p.originalName,
|
||||
width: p.width,
|
||||
height: p.height,
|
||||
players: p.players,
|
||||
capturedAt: p.capturedAt,
|
||||
thumb: signer.url(p.id, "thumb", p.renderedSeq),
|
||||
preview: signer.url(p.id, "preview", p.renderedSeq),
|
||||
level: h.level,
|
||||
score: h.score,
|
||||
face: f ? faceBox(f, p) : null,
|
||||
gallery: galleries.get(folderOf.get(h.photoId)!) ?? null,
|
||||
};
|
||||
});
|
||||
};
|
||||
|
||||
/** Starts the face engine so the first real search does not wait on model load. */
|
||||
app.get("/v1/archive/:sourceId/find/ready", async (req) => {
|
||||
const { sourceId } = SourceParams.parse(req.params);
|
||||
const v = viewerOf(req, sourceId);
|
||||
await requireFind(v);
|
||||
return { ready: lookup.available };
|
||||
});
|
||||
|
||||
/**
|
||||
* A photo of the person against the registry, then their archive photos (or a blind face-group search when
|
||||
* nobody in the registry is sure). The uploaded file is not stored.
|
||||
*/
|
||||
app.post("/v1/archive/:sourceId/find", { config: { rateLimit: { max: 30, timeWindow: "1 minute" } } }, async (req) => {
|
||||
const { sourceId } = SourceParams.parse(req.params);
|
||||
const q = LookupQuery.parse(req.query);
|
||||
const v = viewerOf(req, sourceId);
|
||||
const source = await requireFind(v);
|
||||
const scoped = await scopeOf(v);
|
||||
if (!scoped) return { faces: [], used: 0, via: "faces" as Via, identity: null, people: [], total: 0, photos: [] };
|
||||
const { sql: scope, key: scopeKey } = scoped;
|
||||
|
||||
const image = await lookupImage(req);
|
||||
const read = await lookup.facesIn(image).catch(lookupFailed);
|
||||
const used = Math.min(q.face, read.faces.length - 1);
|
||||
const probe = read.faces[used]!;
|
||||
const match = (THRESHOLDS[read.model] ?? { match: 0.5 }).match;
|
||||
|
||||
// 1) Registry first: FPA / Liga / UEFA people with a face on file (smaller set than every photo).
|
||||
const matched = await lookup.people(source.organizationId, probe.embedding, read.model, PEOPLE_LIMIT);
|
||||
const extra = await enrichPeople(matched.map((p) => p.id));
|
||||
const people = matched.map((p) => {
|
||||
const e = extra.get(p.id);
|
||||
return {
|
||||
id: p.id,
|
||||
name: p.name,
|
||||
club: p.club,
|
||||
number: p.number,
|
||||
score: p.score,
|
||||
level: p.level,
|
||||
licence: e?.licence ?? null,
|
||||
reference: e?.reference ?? null,
|
||||
registry: e?.registry ?? null,
|
||||
};
|
||||
});
|
||||
const sure = people.filter((p) => p.level === "strong");
|
||||
|
||||
const best = new Map<string, { faceId: string; score: number; level: CardLevel; sharpness: number | null }>();
|
||||
const keep = (photoId: string, faceId: string, score: number, level: CardLevel, sharpness: number | null) => {
|
||||
const was = best.get(photoId);
|
||||
if (!was || score > was.score) best.set(photoId, { faceId, score, level, sharpness });
|
||||
};
|
||||
|
||||
let via: Via = "faces";
|
||||
|
||||
if (sure.length) {
|
||||
// 2a) Known person: archive photos already named (or suggested) as them — no blind group scan.
|
||||
via = "registry";
|
||||
const sureIds = sure.map((p) => p.id);
|
||||
const scoreOf = new Map(sure.map((p) => [p.id, p.score]));
|
||||
const named = await db.$queryRaw<{ id: string; photo_id: string; sharpness: number | null; person_id: string | null; suggested_person_id: string | null }[]>`
|
||||
SELECT f.id, f.photo_id, f.sharpness, g.person_id, g.suggested_person_id
|
||||
FROM faces f
|
||||
JOIN face_groups g ON g.id = f.group_id
|
||||
JOIN cloud_files cf ON cf.photo_id = f.photo_id AND ${scope}
|
||||
WHERE g.ignored_at IS NULL
|
||||
AND (g.person_id = ANY(${sureIds}::uuid[]) OR g.suggested_person_id = ANY(${sureIds}::uuid[]))`;
|
||||
for (const f of named) {
|
||||
const personId = f.person_id ?? f.suggested_person_id!;
|
||||
const score = scoreOf.get(personId) ?? sure[0]!.score;
|
||||
keep(f.photo_id, f.id, score, f.person_id ? "confirmed" : "probable", f.sharpness);
|
||||
}
|
||||
} else {
|
||||
// 2b) Nobody sure in the registry: fall back to face groups in the viewer's galleries.
|
||||
const eventIds = await eventsInScope(sourceId, scope, scopeKey);
|
||||
if (!eventIds.length) {
|
||||
return { faces: facesOut(read.faces), used, via, identity: null, people, total: 0, photos: [] };
|
||||
}
|
||||
const groups = await nearGroups(eventIds, probe.embedding, read.model);
|
||||
if (groups.length) {
|
||||
const faces = await db.$queryRaw<{ id: string; photo_id: string; group_id: string; sharpness: number | null }[]>`
|
||||
SELECT f.id, f.photo_id, f.group_id, f.sharpness
|
||||
FROM faces f
|
||||
JOIN cloud_files cf ON cf.photo_id = f.photo_id AND ${scope}
|
||||
WHERE f.group_id = ANY(${groups.map((g) => g.id)}::uuid[])`;
|
||||
const byGroup = new Map(groups.map((g) => [g.id, g]));
|
||||
for (const f of faces) {
|
||||
const g = byGroup.get(f.group_id)!;
|
||||
const level: CardLevel = g.personId && g.score >= match ? "confirmed" : levelOf(g.score, match);
|
||||
keep(f.photo_id, f.id, g.score, level, f.sharpness);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const hits = [...best.entries()]
|
||||
.map(([photoId, h]) => ({ photoId, ...h }))
|
||||
.sort((a, b) => b.score - a.score || (b.sharpness ?? 0) - (a.sharpness ?? 0));
|
||||
const shown = hits.slice(0, MAX_PHOTOS);
|
||||
const top = sure[0] ?? null;
|
||||
const identity = top
|
||||
? {
|
||||
id: top.id,
|
||||
name: top.name,
|
||||
club: top.club,
|
||||
number: top.number,
|
||||
licence: top.licence,
|
||||
reference: top.reference,
|
||||
registry: top.registry,
|
||||
score: top.score,
|
||||
}
|
||||
: null;
|
||||
|
||||
return {
|
||||
faces: facesOut(read.faces),
|
||||
used,
|
||||
via,
|
||||
identity,
|
||||
people,
|
||||
total: hits.length,
|
||||
photos: await photoCards(shown, scope),
|
||||
};
|
||||
});
|
||||
}
|
||||
@@ -6,6 +6,8 @@ import type { Db } from "../db.js";
|
||||
import { FaceRejected, type FaceService } from "../faces/service.js";
|
||||
import { AppError, forbidden, notFound } from "../lib/errors.js";
|
||||
import type { UrlSigner } from "../storage/storage.js";
|
||||
import { fpaLatestRole, type SportsService } from "../sports/service.js";
|
||||
import type { FpaMember } from "../sports/providers.js";
|
||||
import { galleryMemberIds } from "./gallery.js";
|
||||
import { clubKey, faceBox } from "./people.js";
|
||||
import type { Viewer } from "./viewer.js";
|
||||
@@ -27,6 +29,8 @@ interface Deps {
|
||||
faces: FaceService;
|
||||
viewerOf: (req: FastifyRequest, sourceId?: string) => Viewer;
|
||||
editableFolders: (v: Viewer) => Promise<string[] | "all">;
|
||||
/** Handball: people by their federation licence (CIPA), for FPA archives. */
|
||||
sports?: Pick<SportsService, "fpa" | "personFromFpaLicence"> | undefined;
|
||||
/** After "Juntar nomes": lists built with the old names are dropped. */
|
||||
onClubsChanged?: (sourceId: string) => void | Promise<void>;
|
||||
}
|
||||
@@ -46,6 +50,7 @@ const ReviewQuery = z.object({
|
||||
const Act = z.object({ action: z.enum(["confirm", "reject", "ignore", "undo"]), personId: z.uuid().optional() });
|
||||
const ChooseQuery = z.object({ q: z.string().trim().min(2).max(80) });
|
||||
const Merge = z.object({ into: z.string().trim().min(1).max(120), names: z.array(z.string().trim().min(1).max(120)).min(1).max(20) });
|
||||
const Licence = z.object({ licence: z.string().trim().regex(/^\d{3,9}$/) });
|
||||
const Unmerge = z.object({ name: z.string().trim().min(1).max(120) });
|
||||
const Recognition = z.object({ enabled: z.boolean(), removeConfirmed: z.boolean().default(false) });
|
||||
|
||||
@@ -77,12 +82,17 @@ export async function registerArchiveReviewRoutes(app: FastifyInstance, deps: De
|
||||
const log = (v: Viewer, action: string, data: { personId?: string | null; groupId?: string | null; faces?: number }) =>
|
||||
db.archiveFaceAction.create({ data: { sourceId: v.s, viewer: v.n, action, personId: data.personId ?? null, groupId: data.groupId ?? null, faces: data.faces ?? 0 } });
|
||||
|
||||
/** What this viewer may do: review faces (some folder with edit rights), act on people (edits everything). */
|
||||
/** What this viewer may do: review faces (some folder with edit rights), act on people (edits everything), search by photo. */
|
||||
app.get("/v1/archive/:sourceId/me", async (req) => {
|
||||
const { sourceId } = SourceParams.parse(req.params);
|
||||
const v = viewerOf(req, sourceId);
|
||||
const editable = await editableFolders(v);
|
||||
const canReview = editable === "all" || editable.length > 0;
|
||||
const source = await db.cloudSource.findUnique({
|
||||
where: { id: sourceId },
|
||||
select: { photoFindEnabled: true, organization: { select: { biometricsEnabled: true } } },
|
||||
});
|
||||
const canFind = canReview && !!source?.photoFindEnabled && !!source.organization.biometricsEnabled;
|
||||
const pending = canReview
|
||||
? await (async () => {
|
||||
const scope = await editScope(v);
|
||||
@@ -95,7 +105,7 @@ export async function registerArchiveReviewRoutes(app: FastifyInstance, deps: De
|
||||
return row?.n ?? 0;
|
||||
})()
|
||||
: 0;
|
||||
return { name: v.n, canReview, canManagePeople: editable === "all", pending };
|
||||
return { name: v.n, canReview, canManagePeople: editable === "all", canFind, pending };
|
||||
});
|
||||
|
||||
/**
|
||||
@@ -107,11 +117,11 @@ export async function registerArchiveReviewRoutes(app: FastifyInstance, deps: De
|
||||
const v = viewerOf(req, sourceId);
|
||||
const { q } = ChooseQuery.parse(req.query);
|
||||
if (!(await editScope(v))) throw forbidden("archive_edit_required");
|
||||
const source = await db.cloudSource.findUnique({ where: { id: sourceId }, select: { organizationId: true } });
|
||||
const source = await db.cloudSource.findUnique({ where: { id: sourceId }, select: { organizationId: true, look: true } });
|
||||
if (!source) throw notFound("source_not_found");
|
||||
const like = `%${q.replace(/[\\%_]/g, "")}%`;
|
||||
const rows = await db.$queryRaw<{ id: string; name: string; club: string | null; number: string | null; reference: boolean }[]>`
|
||||
SELECT p.id, p.name,
|
||||
const rows = await db.$queryRaw<{ id: string; name: string; club: string | null; number: string | null; reference: boolean; licence: string | null }[]>`
|
||||
SELECT p.id, p.name, p.licence,
|
||||
COALESCE(p.club, t.name) AS club,
|
||||
COALESCE(p.number, sp.number) AS number,
|
||||
p.reference_key IS NOT NULL AS reference
|
||||
@@ -127,14 +137,77 @@ export async function registerArchiveReviewRoutes(app: FastifyInstance, deps: De
|
||||
OR COALESCE(sp.full_name, '') ILIKE ${like}
|
||||
OR p.number = ${q}
|
||||
OR sp.number = ${q}
|
||||
OR p.licence = ${q}
|
||||
OR sp.external_id = ${q}
|
||||
)
|
||||
ORDER BY (p.number = ${q} OR sp.number = ${q}) DESC, (p.reference_key IS NOT NULL) DESC, length(p.name)
|
||||
ORDER BY (p.licence = ${q} OR sp.external_id = ${q}) DESC, (p.number = ${q} OR sp.number = ${q}) DESC, (p.reference_key IS NOT NULL) DESC, length(p.name)
|
||||
LIMIT 8`;
|
||||
// A licence number nobody here has yet: who the federation says it is, to add them.
|
||||
const fpa = fpaArchive(source) && /^\d{5,9}$/.test(q) && !rows.some((r) => r.licence === q) ? await memberOf(q) : null;
|
||||
return {
|
||||
people: rows.map((r) => ({ id: r.id, name: r.name, club: r.club, number: r.number, reference: r.reference ? signer.personUrl(r.id) : null })),
|
||||
people: rows.map((r) => ({ id: r.id, name: r.name, club: r.club, number: r.number, reference: r.reference ? signer.personUrl(r.id) : null, ...(r.licence && { licence: r.licence }) })),
|
||||
...(fpa && { fpa: memberOut(fpa) }),
|
||||
};
|
||||
});
|
||||
|
||||
/** Handball archives look people up by licence. Kept a while: typing a number asks once per number. */
|
||||
const fpaArchive = (source: { look: string | null }) => !!deps.sports && source.look === "fpa";
|
||||
const memberCache = new Map<string, { at: number; member: Promise<FpaMember | null> }>();
|
||||
const memberOf = (licence: string): Promise<FpaMember | null> => {
|
||||
const hit = memberCache.get(licence);
|
||||
if (hit && Date.now() - hit.at < 30 * 60_000) return hit.member;
|
||||
const member = deps.sports!.fpa.member(licence).catch(() => null);
|
||||
memberCache.set(licence, { at: Date.now(), member });
|
||||
if (memberCache.size > 500) for (const [k, m] of memberCache) if (Date.now() - m.at > 30 * 60_000) memberCache.delete(k);
|
||||
return member;
|
||||
};
|
||||
const memberOut = (m: FpaMember) => {
|
||||
const latest = fpaLatestRole(m);
|
||||
return {
|
||||
licence: m.licence,
|
||||
name: m.name,
|
||||
photo: m.photo,
|
||||
club: latest?.club ?? null,
|
||||
role: latest ? `${latest.role} · ${latest.season}` : m.registeredAs,
|
||||
// Every season, newest first, as "2024/25 · Treinador · Estarreja AC" (no birth date: not needed here).
|
||||
history: [...m.registrations]
|
||||
.sort((a, b) => b.season.localeCompare(a.season))
|
||||
.slice(0, 12)
|
||||
.map((r) => [r.season, r.level ? `${r.role} ${r.level}` : r.role, r.club].filter(Boolean).join(" · ")),
|
||||
};
|
||||
};
|
||||
|
||||
/** Who a licence number is, for those who review (to add them before naming a face). */
|
||||
app.get("/v1/archive/:sourceId/fpa/:licence", async (req) => {
|
||||
const { sourceId } = SourceParams.parse(req.params);
|
||||
const { licence } = Licence.parse(req.params);
|
||||
const v = viewerOf(req, sourceId);
|
||||
if (!(await editScope(v))) throw forbidden("archive_edit_required");
|
||||
const source = await db.cloudSource.findUnique({ where: { id: sourceId }, select: { organizationId: true, look: true } });
|
||||
if (!source || !fpaArchive(source)) throw notFound("fpa_not_available");
|
||||
const member = await memberOf(licence);
|
||||
if (!member) throw notFound("fpa_member_not_found");
|
||||
const person = await db.person.findFirst({ where: { organizationId: source.organizationId, licence }, select: { id: true, name: true } });
|
||||
return { member: memberOut(member), person };
|
||||
});
|
||||
|
||||
/**
|
||||
* Adds (or brings up to date) a person from their licence: name, club, and the licence photo as the reference,
|
||||
* so recognition finds them in event photos where no match report names them.
|
||||
*/
|
||||
app.post("/v1/archive/:sourceId/people/from-licence", async (req) => {
|
||||
const { sourceId } = SourceParams.parse(req.params);
|
||||
const v = viewerOf(req, sourceId);
|
||||
if (!(await editScope(v))) throw forbidden("archive_edit_required");
|
||||
const { licence } = Licence.parse(req.body);
|
||||
const source = await db.cloudSource.findUnique({ where: { id: sourceId }, select: { organizationId: true, look: true } });
|
||||
if (!source || !fpaArchive(source)) throw notFound("fpa_not_available");
|
||||
const done = await deps.sports!.personFromFpaLicence(source.organizationId, licence);
|
||||
memberCache.delete(licence);
|
||||
await log(v, done.created ? "person_from_licence" : "person_licence_update", { personId: done.person.id });
|
||||
return { person: { ...done.person, licence, reference: done.reference }, created: done.created, member: memberOut(done.member) };
|
||||
});
|
||||
|
||||
/**
|
||||
* Face groups to review in the viewer's editable folders, one card per group: its sharpest faces, who it is
|
||||
* (named) or might be (suggested, with how sure), its event; and the people with suggestions waiting.
|
||||
|
||||
@@ -23,6 +23,8 @@ const Update = z.object({
|
||||
rootPath: z.string().trim().min(1).max(500).optional(),
|
||||
paused: z.boolean().optional(),
|
||||
look: z.enum(ARCHIVE_LOOKS).nullable().optional(),
|
||||
/** Editors on the cloud may search the archive by uploading a photo of a person. */
|
||||
photoFindEnabled: z.boolean().optional(),
|
||||
/** The archive's own address (a host name, no scheme or path); empty or null takes it away. */
|
||||
hostname: z
|
||||
.string()
|
||||
@@ -116,6 +118,7 @@ export async function registerArchiveRoutes(app: FastifyInstance, deps: { db: Db
|
||||
baseUrl: s.baseUrl,
|
||||
rootPath: s.rootPath,
|
||||
look: s.look,
|
||||
photoFindEnabled: s.photoFindEnabled,
|
||||
hostname: s.hostname,
|
||||
account: s.username || null,
|
||||
status: s.status,
|
||||
@@ -193,6 +196,7 @@ export async function registerArchiveRoutes(app: FastifyInstance, deps: { db: Db
|
||||
...(status && { status }),
|
||||
...(status === "READY" && { nextScanAt: new Date() }),
|
||||
...(body.look !== undefined && { look: body.look }),
|
||||
...(body.photoFindEnabled !== undefined && { photoFindEnabled: body.photoFindEnabled }),
|
||||
...(hostname !== undefined && { hostname }),
|
||||
},
|
||||
});
|
||||
|
||||
@@ -221,6 +221,7 @@ export class ArchiveService {
|
||||
if (!/^https?:\/\/[^/]+/i.test(baseUrl)) throw new ArchiveRejected("invalid_url");
|
||||
const box = this.box();
|
||||
const flow = await startLogin(baseUrl, this.fetchImpl);
|
||||
const look = lookFor(input.name, input.rootPath);
|
||||
const source = await this.deps.db.cloudSource.create({
|
||||
data: {
|
||||
organizationId,
|
||||
@@ -228,7 +229,9 @@ export class ArchiveService {
|
||||
name: input.name.trim() || new URL(baseUrl).hostname,
|
||||
baseUrl,
|
||||
rootPath: normalisePath(input.rootPath),
|
||||
look: lookFor(input.name, input.rootPath),
|
||||
look,
|
||||
// FPA news desk: editors on the cloud may search by photo from day one; other archives stay off.
|
||||
photoFindEnabled: look === "fpa",
|
||||
status: "LOGIN",
|
||||
loginPoll: box.seal(JSON.stringify({ endpoint: flow.endpoint, token: flow.token, loginUrl: flow.loginUrl } satisfies LoginState)),
|
||||
loginExpires: new Date(Date.now() + LOGIN_TTL_MS),
|
||||
|
||||
@@ -10,12 +10,15 @@ import { AppError, badRequest, notFound, unauthorized } from "../lib/errors.js";
|
||||
import type { LocalStorage, UrlSigner } from "../storage/storage.js";
|
||||
import { CloudClient, pollLogin, startLogin } from "./nextcloud.js";
|
||||
import { GALLERY_KINDS, galleryMemberIds, gallerySeasons, listStoredGalleries, publishedPhotos, seasonOf } from "./gallery.js";
|
||||
import type { SportsService } from "../sports/service.js";
|
||||
import { readStoredRaws, readStoredTeams } from "./directory.js";
|
||||
import type { FaceService } from "../faces/service.js";
|
||||
import { clubKind, faceBox, facesOfPhotos, registerArchivePeopleRoutes } from "./people.js";
|
||||
import { registerArchiveDownloadRoutes } from "./downloads.js";
|
||||
import { registerArchiveFindRoutes } from "./find.js";
|
||||
import { registerArchiveReviewRoutes } from "./review.js";
|
||||
import type { ArchiveService } from "./service.js";
|
||||
import type { FaceLookup } from "../faces/lookup.js";
|
||||
import { sendFile, VIDEO_FILES, VIDEO_VARIANTS } from "./video.js";
|
||||
import { peopleInVideos } from "./video-faces.js";
|
||||
|
||||
@@ -109,7 +112,20 @@ const ListQuery = z.object({
|
||||
|
||||
export async function registerArchiveViewerRoutes(
|
||||
app: FastifyInstance,
|
||||
deps: { db: Db; secrets: SecretBox | undefined; signer: UrlSigner; archive: ArchiveService; tokens: ViewerTokens; faces: FaceService; storage: LocalStorage; secret: string; fetchImpl?: typeof fetch | undefined },
|
||||
deps: {
|
||||
db: Db;
|
||||
secrets: SecretBox | undefined;
|
||||
signer: UrlSigner;
|
||||
archive: ArchiveService;
|
||||
tokens: ViewerTokens;
|
||||
faces: FaceService;
|
||||
storage: LocalStorage;
|
||||
secret: string;
|
||||
fetchImpl?: typeof fetch | undefined;
|
||||
sports?: Pick<SportsService, "fpa" | "personFromFpaLicence"> | undefined;
|
||||
/** Search by photo for editors (absent → find route not registered). */
|
||||
lookup?: FaceLookup;
|
||||
},
|
||||
) {
|
||||
const { db, signer, tokens } = deps;
|
||||
const fetchImpl = deps.fetchImpl ?? fetch;
|
||||
@@ -730,12 +746,16 @@ export async function registerArchiveViewerRoutes(
|
||||
faces: deps.faces,
|
||||
viewerOf,
|
||||
editableFolders,
|
||||
sports: deps.sports,
|
||||
onClubsChanged: async (sourceId) => {
|
||||
forgetLists(sourceId, "teams");
|
||||
await deps.archive.markDirectoryDirty(sourceId);
|
||||
await deps.archive.rebuildDirectory(sourceId);
|
||||
},
|
||||
});
|
||||
if (deps.lookup) {
|
||||
await registerArchiveFindRoutes(app, { db, signer, lookup: deps.lookup, viewerOf, visibleFolders, editableFolders });
|
||||
}
|
||||
await registerArchiveDownloadRoutes(app, { db, storage: deps.storage, secret: deps.secret, viewerOf, visibleFolders });
|
||||
}
|
||||
|
||||
|
||||
@@ -136,8 +136,14 @@ export class AutopilotService {
|
||||
const detections = load ? await (await load).detect(preview) : null;
|
||||
const focusFile = photo.originalStored ? storage.resolve(photo.storageKey) : preview;
|
||||
const focus = focusFromExifJson(photo.exif) ?? (existsSync(focusFile) ? await readFocusPoint(focusFile) : null);
|
||||
// Faces tell a whole figure from a bust. They may not be ready yet; the crop still refuses a slice.
|
||||
const faces = reportage ? (await db.face.findMany({ where: { photoId }, select: { x0: true, y0: true, x1: true, y1: true } })).map((f) => ({ x0: f.x0, y0: f.y0, x1: f.x1, y1: f.y1 })) : [];
|
||||
// Faces tell a whole figure from a bust, and block a soft / faceless body in front from being the subject.
|
||||
// They may not be ready yet; the crop still refuses a soft AF point without a face when faces exist.
|
||||
const faces = (await db.face.findMany({ where: { photoId }, select: { x0: true, y0: true, x1: true, y1: true } })).map((f) => ({
|
||||
x0: f.x0,
|
||||
y0: f.y0,
|
||||
x1: f.x1,
|
||||
y1: f.y1,
|
||||
}));
|
||||
const planned = planFrame({
|
||||
detections,
|
||||
width: W,
|
||||
|
||||
@@ -3,7 +3,8 @@
|
||||
* first pass. Pure geometry over detections (people, balls, and how sharp each person is), so it is fast,
|
||||
* testable and easy to tune. Tuned against Peter's own Lightroom crops (handball, October 2026):
|
||||
*
|
||||
* - The subject is who is in focus, not who is biggest: blurred players in the foreground are scenery.
|
||||
* - The subject is who is in focus with a visible face, not who is biggest: blurred / faceless players in
|
||||
* the foreground are scenery (even when the AF point landed on them).
|
||||
* - With a ball in play, the ball and the sharp players contesting it come along. Which ball that is
|
||||
* depends on the sport: handball plays it in the hands, football plays it on the ground.
|
||||
* - The crop is usually two thirds of the frame (the same shape), the subject in the middle across, the upper
|
||||
@@ -200,17 +201,30 @@ function forReportage(d: Detections, faces: readonly Box[]): Detections {
|
||||
}
|
||||
|
||||
/** Who the photo is about. Null when there is nobody clear enough (empty pitch, distant crowd). */
|
||||
export function findSubject(d: Detections, focus?: FocusHint | null, opts?: { reportage?: boolean; sport?: string | null }): { box: Box; reason: Composition["reason"]; people: Detection[]; ball?: Box } | null {
|
||||
export function findSubject(
|
||||
d: Detections,
|
||||
focus?: FocusHint | null,
|
||||
opts?: { reportage?: boolean; sport?: string | null; faces?: readonly Box[] },
|
||||
): { box: Box; reason: Composition["reason"]; people: Detection[]; ball?: Box } | null {
|
||||
const people = d.people.filter((p) => p.score >= MIN_PERSON && h(p) >= MIN_HEIGHT);
|
||||
if (!people.length) return null;
|
||||
// The main subject: the person the camera focused on, when that point lands on someone. Otherwise in focus
|
||||
// first, then a reasonable size, then whole in the photo. In reportage a whole figure beats a sharper bust.
|
||||
// The main subject: the person the camera focused on, when that point lands on someone who is sharp and
|
||||
// whose face is visible. A soft / faceless body in the foreground (AF on the jump in front) is scenery —
|
||||
// never the crop's subject when a sharp face sits behind. Otherwise: in focus, then size, then whole.
|
||||
const faces = opts?.faces ?? [];
|
||||
const faced = faces.length ? people.filter((p) => faceOf(p, faces)) : people;
|
||||
const candidates = faced.length ? faced : people;
|
||||
const weight = (p: Detection) => sharp(p) ** 2 * Math.min(1, h(p) / 0.3) * (atEdge(p) ? 0.4 : 1) * (0.5 + 0.5 * p.score);
|
||||
const whole = opts?.reportage ? people.filter((p) => !p.fragment) : people;
|
||||
const pool = whole.length ? whole : people;
|
||||
const aimed = focus ? personAtFocus(pool, focus) : null;
|
||||
const main = aimed ?? pool.reduce((a, b) => (weight(b) > weight(a) ? b : a));
|
||||
if (!aimed && weight(main) < 0.05) return null;
|
||||
const whole = opts?.reportage ? candidates.filter((p) => !p.fragment) : candidates;
|
||||
const pool = whole.length ? whole : candidates;
|
||||
const sharpest = Math.max(1e-6, ...people.map(sharp));
|
||||
const aimed = focus ? personAtFocus(pool, focus) ?? personAtFocus(people, focus) : null;
|
||||
const aimedOk =
|
||||
!!aimed &&
|
||||
sharp(aimed) >= TUNING.inFocus * sharpest &&
|
||||
(!faces.length || faced.length === 0 || !!faceOf(aimed, faces));
|
||||
const main = (aimedOk ? aimed : null) ?? pool.reduce((a, b) => (weight(b) > weight(a) ? b : a));
|
||||
if (!aimedOk && weight(main) < 0.05) return null;
|
||||
// Reportage keeps a conversation together: someone in the shade is still part of it. A match stays stricter.
|
||||
// A body the frame has already cut in half is not part of that conversation, unless it is the subject.
|
||||
const withMain = opts?.reportage ? 0.35 : TUNING.inFocus;
|
||||
@@ -283,7 +297,8 @@ function personAtFocus(people: Detection[], focus: FocusHint): Detection | null
|
||||
*/
|
||||
export function compose(d: Detections, aspect: number | null = null, opts: ComposeOptions = {}): Composition | null {
|
||||
const reportage = opts.context === "reportage";
|
||||
const found = findSubject(reportage ? forReportage(d, opts.faces ?? []) : d, opts.focus, { reportage, sport: opts.sport ?? null });
|
||||
const faces = opts.faces ?? [];
|
||||
const found = findSubject(reportage ? forReportage(d, faces) : d, opts.focus, { reportage, sport: opts.sport ?? null, faces });
|
||||
if (!found) return null;
|
||||
const { box: s, reason, people: inSubject, ball } = found;
|
||||
const ratio = (aspect ?? d.width / d.height) * (d.height / d.width); // width/height in frame fractions
|
||||
@@ -515,7 +530,8 @@ function planCut(p: Detection, at: number): number | null {
|
||||
*/
|
||||
export function planCrop(d: Detections, which: keyof typeof PLANS, aspect: number | null = null, opts: ComposeOptions = {}): Box | null {
|
||||
const reportage = opts.context === "reportage";
|
||||
const found = findSubject(reportage ? forReportage(d, opts.faces ?? []) : d, opts.focus, { reportage, sport: opts.sport ?? null });
|
||||
const faces = opts.faces ?? [];
|
||||
const found = findSubject(reportage ? forReportage(d, faces) : d, opts.focus, { reportage, sport: opts.sport ?? null, faces });
|
||||
if (!found) return null;
|
||||
const { box: s, reason, people: inSubject } = found;
|
||||
const tallest = Math.max(...inSubject.map(h));
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { findSubject, type Detection } from "./compose.js";
|
||||
import { compose, findSubject, type Detection } from "./compose.js";
|
||||
|
||||
const person = (x0: number, y0: number, x1: number, y1: number, score = 0.9): Detection => ({ x0, y0, x1, y1, score, sharpness: 1 });
|
||||
const frame = { width: 6000, height: 4000, balls: [] };
|
||||
@@ -20,4 +20,22 @@ describe("focus point", () => {
|
||||
const missed = findSubject({ ...frame, people: [big, aimed] }, { x: 0.95, y: 0.05 })!;
|
||||
expect(missed.box.x0).toBeLessThan(0.2);
|
||||
});
|
||||
|
||||
it("ignores AF on a soft faceless jumper in front when a sharp face sits behind", () => {
|
||||
const jumper = { ...person(0.35, 0.05, 0.72, 0.95, 0.95), sharpness: 0.2 };
|
||||
const withBall = { ...person(0.28, 0.28, 0.42, 0.72, 0.9), sharpness: 1 };
|
||||
const mate = { ...person(0.18, 0.3, 0.3, 0.7, 0.85), sharpness: 0.95 };
|
||||
const faces = [
|
||||
{ x0: 0.3, y0: 0.28, x1: 0.38, y1: 0.38 },
|
||||
{ x0: 0.2, y0: 0.3, x1: 0.27, y1: 0.39 },
|
||||
];
|
||||
const found = findSubject({ width: 6000, height: 4000, people: [jumper, withBall, mate], balls: [] }, { x: 0.55, y: 0.35 }, { faces })!;
|
||||
expect(found.people.map((p) => p.x0)).toContain(withBall.x0);
|
||||
expect(found.people.map((p) => p.x0)).not.toContain(jumper.x0);
|
||||
const c = compose({ width: 6000, height: 4000, people: [jumper, withBall, mate], balls: [] }, null, {
|
||||
focus: { x: 0.55, y: 0.35 },
|
||||
faces,
|
||||
})!;
|
||||
expect(c.subject.y0).toBeGreaterThan(jumper.y0 + 0.1);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,29 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { NEWSROOM_TEMPLATE, GENERAL_TEMPLATE } from "@photoreport/metadata";
|
||||
import { deliveryWantsPlayerNames } from "./service.js";
|
||||
|
||||
describe("deliveryWantsPlayerNames", () => {
|
||||
const plain = { folderTemplate: "/{event}/", fileNameTemplate: "{originalName}", iptcOverrides: null };
|
||||
|
||||
it("is true when the event IPTC pad uses {players}", () => {
|
||||
expect(deliveryWantsPlayerNames(plain, NEWSROOM_TEMPLATE)).toBe(true);
|
||||
});
|
||||
|
||||
it("is true when the destination folder template uses {players}", () => {
|
||||
expect(deliveryWantsPlayerNames({ ...plain, folderTemplate: "/{players}/" }, {})).toBe(true);
|
||||
});
|
||||
|
||||
it("is false when neither path nor IPTC asks for player names", () => {
|
||||
const noPlayers = { ...GENERAL_TEMPLATE, title: "{event}", personsShown: undefined };
|
||||
expect(deliveryWantsPlayerNames(plain, noPlayers)).toBe(false);
|
||||
});
|
||||
|
||||
it("respects destination IPTC overrides that drop {players}", () => {
|
||||
expect(
|
||||
deliveryWantsPlayerNames(
|
||||
{ ...plain, iptcOverrides: { title: "{event}", personsShown: [] } },
|
||||
NEWSROOM_TEMPLATE,
|
||||
),
|
||||
).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -49,6 +49,8 @@ const TargetBase = z.object({
|
||||
srgb: z.boolean(),
|
||||
/** The original as it arrived, metadata written in, renamed (no resizing or recompression). */
|
||||
originals: z.boolean(),
|
||||
/** Wait a little for faces when the pad needs `{players}` (off by default). */
|
||||
waitForFaces: z.boolean(),
|
||||
/** Everything that arrives is sent here on its own. */
|
||||
onArrival: z.boolean(),
|
||||
/** With onArrival: only these FTP logins' photos (empty: everyone's). */
|
||||
@@ -80,6 +82,7 @@ const TargetFields = TargetBase.extend({
|
||||
keepExif: TargetBase.shape.keepExif.default(true),
|
||||
srgb: TargetBase.shape.srgb.default(false),
|
||||
originals: TargetBase.shape.originals.default(false),
|
||||
waitForFaces: TargetBase.shape.waitForFaces.default(false),
|
||||
onArrival: TargetBase.shape.onArrival.default(false),
|
||||
arrivalLogins: TargetBase.shape.arrivalLogins.default([]),
|
||||
untouched: TargetBase.shape.untouched.default(false),
|
||||
@@ -267,7 +270,14 @@ export async function registerDeliveryRoutes(
|
||||
const body = DeliveryRequest.parse(req.body);
|
||||
await requireMembership(db, req, orgId, "INGESTER");
|
||||
try {
|
||||
const result = await delivery.enqueue({ organizationId: orgId, targetId: body.targetId, photoIds: body.photoIds, again: body.again, requestedById: currentUserId(req) });
|
||||
const result = await delivery.enqueue({
|
||||
organizationId: orgId,
|
||||
targetId: body.targetId,
|
||||
photoIds: body.photoIds,
|
||||
again: body.again,
|
||||
originals: body.originals,
|
||||
requestedById: currentUserId(req),
|
||||
});
|
||||
return reply.code(202).send({ queued: result.queued.map(toItemSummary), skipped: result.skipped });
|
||||
} catch (err) {
|
||||
return fail(err);
|
||||
@@ -297,7 +307,14 @@ export async function registerDeliveryRoutes(
|
||||
);
|
||||
if (body.dryRun || !chosen.length) return { chosen, rest, queued: [], skipped: [] };
|
||||
try {
|
||||
const result = await delivery.enqueue({ organizationId: orgId, targetId: body.targetId, photoIds: chosen, again: body.again, requestedById: currentUserId(req) });
|
||||
const result = await delivery.enqueue({
|
||||
organizationId: orgId,
|
||||
targetId: body.targetId,
|
||||
photoIds: chosen,
|
||||
again: body.again,
|
||||
originals: body.originals,
|
||||
requestedById: currentUserId(req),
|
||||
});
|
||||
return reply.code(202).send({ chosen, rest, queued: result.queued.map(toItemSummary), skipped: result.skipped });
|
||||
} catch (err) {
|
||||
return fail(err);
|
||||
|
||||
@@ -1,5 +1,14 @@
|
||||
import type { DeliveryItemSummary } from "@photoreport/contracts";
|
||||
import { buildVars, createdStamp, eventName, LOCAL_COPY_FOLDER, PathTemplateError, renderFileName, renderFolder } from "@photoreport/metadata";
|
||||
import {
|
||||
buildVars,
|
||||
createdStamp,
|
||||
eventName,
|
||||
IptcTemplate,
|
||||
LOCAL_COPY_FOLDER,
|
||||
PathTemplateError,
|
||||
renderFileName,
|
||||
renderFolder,
|
||||
} from "@photoreport/metadata";
|
||||
import type { Db } from "../db.js";
|
||||
import type { DeliveryItem, DeliveryTarget } from "../generated/prisma/client.js";
|
||||
import type { IngestLogger } from "../ingest/service.js";
|
||||
@@ -23,9 +32,25 @@ export const MAX_ATTEMPTS = 5;
|
||||
export const ORIGINAL_WAIT_MS = 72 * 3600_000;
|
||||
/** How often it asks that computer again while waiting. */
|
||||
export const ORIGINAL_ASK_MS = 60_000;
|
||||
/** How long a delivery waits for the photo's faces to be read (the players' names), checking this often. */
|
||||
/**
|
||||
* Automatic "every arrival" deliveries may wait this long for faces when the pad needs `{players}`.
|
||||
* A send the photographer asked for never waits — the cloud copy must leave at once.
|
||||
*/
|
||||
export const FACES_WAIT_MS = 3 * 60_000;
|
||||
export const FACES_ASK_MS = 20_000;
|
||||
|
||||
const PLAYER_VARS = /\{players\}|\{persons\}|\{prsn\}/i;
|
||||
|
||||
/** True when this delivery's folder, file name or IPTC pad will put player names on the file. */
|
||||
export function deliveryWantsPlayerNames(
|
||||
target: { folderTemplate: string; fileNameTemplate: string; iptcOverrides: unknown },
|
||||
eventIptc: unknown,
|
||||
): boolean {
|
||||
if (PLAYER_VARS.test(target.folderTemplate) || PLAYER_VARS.test(target.fileNameTemplate)) return true;
|
||||
const overrides = IptcTemplate.partial().safeParse(target.iptcOverrides ?? {});
|
||||
const template = { ...IptcTemplate.parse(eventIptc ?? {}), ...(overrides.success ? overrides.data : {}) };
|
||||
return PLAYER_VARS.test(JSON.stringify(template));
|
||||
}
|
||||
/** Running items older than this belonged to a worker that died; they go back in the queue. */
|
||||
const STALE_RUNNING_MS = 10 * 60_000;
|
||||
/** A delivered photo edited again is sent again once its edits have paused this long. */
|
||||
@@ -87,6 +112,7 @@ export async function syncLocalMirror(db: Db, secrets: { seal(plain: string): st
|
||||
srgb: target.srgb,
|
||||
originals: target.originals,
|
||||
untouched: target.untouched,
|
||||
waitForFaces: false,
|
||||
onArrival: false,
|
||||
arrivalLogins: [] as string[],
|
||||
disabledAt: null,
|
||||
@@ -185,6 +211,8 @@ export class DeliveryService {
|
||||
photoIds: string[];
|
||||
again: boolean;
|
||||
requestedById: string | null;
|
||||
/** Camera original for this batch (overrides the destination's resize recipe). */
|
||||
originals?: boolean;
|
||||
/** Set when this is the local copy of a delivery to that target. */
|
||||
via?: string;
|
||||
/** Photo id → sequence of the export this copies, so `{n}` in the file name matches the file that was sent. */
|
||||
@@ -235,7 +263,17 @@ export class DeliveryService {
|
||||
if (fixed === undefined || fixed >= next) next = sequence + 1;
|
||||
created.push(
|
||||
await tx.deliveryItem.create({
|
||||
data: { organizationId: input.organizationId, targetId: target.id, photoId: photo.id, eventId, sequence, requestedById: input.requestedById, viaTargetId: input.via ?? null },
|
||||
data: {
|
||||
organizationId: input.organizationId,
|
||||
targetId: target.id,
|
||||
photoId: photo.id,
|
||||
eventId,
|
||||
sequence,
|
||||
requestedById: input.requestedById,
|
||||
viaTargetId: input.via ?? null,
|
||||
// Per-send "Enviar originais" (destination may still resize by default).
|
||||
forceOriginals: Boolean(input.originals),
|
||||
},
|
||||
}),
|
||||
);
|
||||
}
|
||||
@@ -248,9 +286,13 @@ export class DeliveryService {
|
||||
if (!input.via && queued.length) {
|
||||
const photoIds = queued.map((q) => q.photoId);
|
||||
if (target.copyTargetId && target.copyTargetId !== target.id) {
|
||||
await this.enqueue({ ...input, targetId: target.copyTargetId, photoIds, via: target.id }).catch((err: unknown) =>
|
||||
this.deps.log.warn({ err, targetId: target.id, copyTargetId: target.copyTargetId }, "delivery: copy not queued"),
|
||||
);
|
||||
await this.enqueue({
|
||||
...input,
|
||||
targetId: target.copyTargetId,
|
||||
photoIds,
|
||||
via: target.id,
|
||||
...(input.originals !== undefined ? { originals: input.originals } : {}),
|
||||
}).catch((err: unknown) => this.deps.log.warn({ err, targetId: target.id, copyTargetId: target.copyTargetId }, "delivery: copy not queued"));
|
||||
}
|
||||
// The same export, also saved under the computer folder (date, game, destination name).
|
||||
if (target.kind !== "LOCAL" && target.localFolder && target.localMachine) {
|
||||
@@ -274,6 +316,28 @@ export class DeliveryService {
|
||||
|
||||
private editsCheckedAt = 0;
|
||||
|
||||
/**
|
||||
* Deliveries still on a destination whose photo was rejected without going through the library PATCH (a direct
|
||||
* DB update, an emergency script): queue them for removal. Un-picked (NONE) photos are not swept here — a
|
||||
* destination may have been given a non-pick on purpose; only the library PATCH (PICK → NONE) retracts those.
|
||||
*/
|
||||
async queueOrphanRetracts(): Promise<number> {
|
||||
const rows = await this.deps.db.$queryRaw<{ id: string; organization_id: string }[]>`
|
||||
UPDATE delivery_items di SET status = 'QUEUED', retract = true, attempts = 0, next_attempt_at = now(),
|
||||
last_error = NULL, finished_at = NULL, updated_at = now()
|
||||
FROM photos p
|
||||
WHERE p.id = di.photo_id
|
||||
AND di.status IN ('DONE', 'WAITING') AND di.retract = false
|
||||
AND p.flag = 'REJECT'
|
||||
RETURNING di.id, di.organization_id`;
|
||||
for (const r of rows) {
|
||||
const item = await this.deps.db.deliveryItem.findUnique({ where: { id: r.id } });
|
||||
if (item) this.deps.broadcaster.library(item.organizationId, { type: "delivery.updated", item: toItemSummary(item) });
|
||||
}
|
||||
if (rows.length) this.deps.log.info({ count: rows.length }, "delivery: rejected photos still on a destination, taken back");
|
||||
return rows.length;
|
||||
}
|
||||
|
||||
/**
|
||||
* Delivered photos edited again since (a crop put right, a colour fixed), once the edits have paused for a
|
||||
* minute: sent again to where they went, with the same name (a file is replaced; on ZeroZero the new one goes up
|
||||
@@ -321,10 +385,11 @@ export class DeliveryService {
|
||||
|
||||
/** Atomically takes up to `limit` due items (safe with several workers). */
|
||||
async claim(limit: number): Promise<string[]> {
|
||||
// Every half minute: delivered photos edited again join the queue.
|
||||
// Every half minute: edited re-sends and rejected photos left on a destination join the queue.
|
||||
if (Date.now() - this.editsCheckedAt > 30_000) {
|
||||
this.editsCheckedAt = Date.now();
|
||||
await this.queueEdited().catch((err) => this.deps.log.warn({ err }, "delivery: edited photos not checked"));
|
||||
await this.queueOrphanRetracts().catch((err) => this.deps.log.warn({ err }, "delivery: orphan retracts not checked"));
|
||||
}
|
||||
if (limit <= 0) return [];
|
||||
const rows = await this.deps.db.$queryRaw<{ id: string }[]>`
|
||||
@@ -424,10 +489,30 @@ export class DeliveryService {
|
||||
this.deps.broadcaster.library(saved.organizationId, { type: "delivery.updated", item: toItemSummary(saved) });
|
||||
return saved;
|
||||
}
|
||||
// Rejected after this item was queued (or a flag flip that skipped retractPhotos): never upload; the next claim
|
||||
// removes anything already on the destination.
|
||||
if (item.photo.flag === "REJECT") {
|
||||
const saved = await db.deliveryItem.update({
|
||||
where: { id: itemId },
|
||||
data: item.remotePath || item.target.kind === "LOCAL"
|
||||
? { status: "QUEUED", retract: true, attempts: Math.max(0, item.attempts - 1), nextAttemptAt: new Date(), lastError: null, finishedAt: null }
|
||||
: { status: "RETRACTED", retract: false, finishedAt: new Date() },
|
||||
});
|
||||
this.deps.broadcaster.library(saved.organizationId, { type: "delivery.updated", item: toItemSummary(saved) });
|
||||
return saved;
|
||||
}
|
||||
let update: Partial<DeliveryItem>;
|
||||
// The players' names come from the faces (who is where, face and shirt number): give their reading a moment,
|
||||
// so a photo does not leave without names. Waiting does not count as an attempt.
|
||||
if (!(item.target.originals && item.target.untouched) && Date.now() - item.createdAt.getTime() < FACES_WAIT_MS && (item.photo.facesStatus === "NONE" || item.photo.facesStatus === "PENDING")) {
|
||||
// Waiting for faces is opt-in per destination (`waitForFaces`). A send the photographer asked for must
|
||||
// leave at once; when names appear later the file is rewritten (resendPhotos). NONE never becomes DONE
|
||||
// by waiting, so it never blocks.
|
||||
const facesInFlight = item.photo.facesStatus === "PENDING" || item.photo.facesStatus === "RUNNING";
|
||||
if (
|
||||
item.target.waitForFaces &&
|
||||
facesInFlight &&
|
||||
!(item.target.originals && item.target.untouched) &&
|
||||
Date.now() - item.createdAt.getTime() < FACES_WAIT_MS &&
|
||||
deliveryWantsPlayerNames(item.target, item.event?.iptcTemplate)
|
||||
) {
|
||||
const org = await db.organization.findUnique({ where: { id: item.organizationId }, select: { biometricsEnabled: true } });
|
||||
if (org?.biometricsEnabled) {
|
||||
const saved = await db.deliveryItem.update({
|
||||
@@ -469,6 +554,9 @@ export class DeliveryService {
|
||||
const viaTarget = item.viaTargetId ? await db.deliveryTarget.findUnique({ where: { id: item.viaTargetId } }) : null;
|
||||
const sameExport = Boolean(item.target.mirrorOfId && viaTarget);
|
||||
const recipe = sameExport && viaTarget ? viaTarget : item.target;
|
||||
// Per-send "Enviar originais" beats the destination's resize; untouched only applies when the destination says so.
|
||||
const sendOriginals = recipe.originals || item.forceOriginals;
|
||||
const untouched = recipe.originals && recipe.untouched;
|
||||
const iptc = await iptcForPhoto(db, item.photoId, (viaTarget ?? item.target).iptcOverrides);
|
||||
const source = cloud?.file ?? storage.resolve(item.photo.storageKey);
|
||||
// Photos from before the camera details were kept: read them from the file being sent.
|
||||
@@ -479,11 +567,11 @@ export class DeliveryService {
|
||||
if (!sameExport && item.target.kind === "ZEROZERO") folder = `${await this.zerozeroGameId(item.target, item.event)}/`;
|
||||
// {originalName} is the name given on arrival when the photo was renamed (as Photo Mechanic renames the file).
|
||||
// Untouched: the camera's own name, as a local FTP would have received it.
|
||||
const fileName = renderFileName(recipe.fileNameTemplate, named, recipe.originals && recipe.untouched ? item.photo.originalName : deliveredName(item.photo));
|
||||
const edit = await this.editFor(item.photoId, item.photo.developSeq);
|
||||
const fileName = renderFileName(recipe.fileNameTemplate, named, sendOriginals && untouched ? item.photo.originalName : deliveredName(item.photo));
|
||||
const edit = sendOriginals ? undefined : await this.editFor(item.photoId, item.photo.developSeq);
|
||||
const created = item.photo.capturedAt ? createdStamp(item.photo.capturedAt) : undefined;
|
||||
const rendered = recipe.originals
|
||||
? recipe.untouched
|
||||
const rendered = sendOriginals
|
||||
? untouched
|
||||
? await readFile(source)
|
||||
: await originalWithMetadata(source, iptc?.values ?? {}, created)
|
||||
: await renderDelivery(source, iptc?.values ?? {}, { longEdge: recipe.longEdge, quality: recipe.jpegQuality, sharpen: recipe.sharpen, dpi: recipe.dpi, exif: recipe.keepExif, srgb: recipe.srgb }, created, edit);
|
||||
|
||||
@@ -62,6 +62,27 @@ export function newer(candidate: string, current: string): boolean {
|
||||
/** The full installer a person downloads and opens, per platform. */
|
||||
const INSTALLER: Record<string, RegExp> = { darwin: /\.dmg$/, windows: /\.msi$|-setup\.exe$/, linux: /\.AppImage$/ };
|
||||
|
||||
/** Version embedded in a Tauri minisign trusted comment, if any (`file:…\tversion:X.Y.Z`). */
|
||||
export function signedVersion(signature: string): string | null {
|
||||
for (const line of signature.split(/\r?\n/)) {
|
||||
let raw: Buffer;
|
||||
try {
|
||||
raw = Buffer.from(line, "base64");
|
||||
} catch {
|
||||
continue;
|
||||
}
|
||||
const text = raw.toString("utf8");
|
||||
const m = /\bversion:([0-9]+\.[0-9]+\.[0-9]+(?:[-.+][\w.-]+)?)/.exec(text);
|
||||
if (m) return m[1]!;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/** Newest asset with this name (Gitea keeps duplicates when a tag is rebuilt). */
|
||||
function latestAsset(assets: GiteaAsset[], name: string): GiteaAsset | undefined {
|
||||
return assets.filter((a) => a.name === name).sort((a, b) => b.id - a.id)[0];
|
||||
}
|
||||
|
||||
export class DesktopReleases {
|
||||
private cache: { at: number; releases: GiteaRelease[] } | null = null;
|
||||
|
||||
@@ -85,17 +106,6 @@ export class DesktopReleases {
|
||||
return all;
|
||||
}
|
||||
|
||||
/** The newest release that has this platform's update (a newer one may still be building, or wait for its Mac). */
|
||||
private async forPlatform(target: string, arch: string): Promise<{ release: GiteaRelease; manifest: GiteaAsset } | null> {
|
||||
// Universal macOS builds serve both Apple chips.
|
||||
const names = [`update-${target}-${arch}.json`, ...(target === "darwin" ? ["update-darwin-universal.json"] : [])];
|
||||
for (const release of await this.releases()) {
|
||||
const manifest = names.map((n) => release.assets.find((a) => a.name === n)).find(Boolean);
|
||||
if (manifest) return { release, manifest };
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private async download(asset: GiteaAsset): Promise<Response> {
|
||||
const res = await this.fetchImpl(asset.browser_download_url, { headers: { authorization: `token ${this.config.token}` } });
|
||||
if (!res.ok) throw new Error(`gitea asset ${asset.name}: ${res.status}`);
|
||||
@@ -111,28 +121,34 @@ export class DesktopReleases {
|
||||
arch: string,
|
||||
current: string,
|
||||
): Promise<{ version: string; notes: string; pub_date?: string; url: string; signature: string; installer?: string } | null> {
|
||||
const found = await this.forPlatform(target, arch);
|
||||
if (!found) return null;
|
||||
const { release } = found;
|
||||
const manifest = Manifest.parse(await (await this.download(found.manifest)).json());
|
||||
if (!newer(manifest.version, current)) return null;
|
||||
if (!release.assets.some((a) => a.name === manifest.file)) return null;
|
||||
const installer = release.assets.find((a) => INSTALLER[target]?.test(a.name));
|
||||
return {
|
||||
version: manifest.version,
|
||||
notes: manifest.notes ?? release.body ?? "",
|
||||
...(manifest.pub_date ?? release.published_at ? { pub_date: (manifest.pub_date ?? release.published_at)! } : {}),
|
||||
url: `/v1/desktop/download/${release.id}/${encodeURIComponent(manifest.file)}`,
|
||||
signature: manifest.signature,
|
||||
...(installer ? { installer: `/v1/desktop/download/${release.id}/${encodeURIComponent(installer.name)}` } : {}),
|
||||
};
|
||||
// Walk newest → older: a release whose manifest/signature disagree (re-tagged build) is skipped.
|
||||
const names = [`update-${target}-${arch}.json`, ...(target === "darwin" ? ["update-darwin-universal.json"] : [])];
|
||||
for (const release of await this.releases()) {
|
||||
const manifestAsset = names.map((n) => latestAsset(release.assets, n)).find(Boolean);
|
||||
if (!manifestAsset) continue;
|
||||
const manifest = Manifest.parse(await (await this.download(manifestAsset)).json());
|
||||
if (!newer(manifest.version, current)) return null;
|
||||
const signed = signedVersion(manifest.signature);
|
||||
if (signed && signed !== manifest.version) continue;
|
||||
if (!latestAsset(release.assets, manifest.file)) continue;
|
||||
const installer = [...release.assets].filter((a) => INSTALLER[target]?.test(a.name)).sort((a, b) => b.id - a.id)[0];
|
||||
return {
|
||||
version: manifest.version,
|
||||
notes: manifest.notes ?? release.body ?? "",
|
||||
...(manifest.pub_date ?? release.published_at ? { pub_date: (manifest.pub_date ?? release.published_at)! } : {}),
|
||||
url: `/v1/desktop/download/${release.id}/${encodeURIComponent(manifest.file)}`,
|
||||
signature: manifest.signature,
|
||||
...(installer ? { installer: `/v1/desktop/download/${release.id}/${encodeURIComponent(installer.name)}` } : {}),
|
||||
};
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/** The installer itself, streamed from a desktop release. */
|
||||
async file(releaseId: number, name: string): Promise<{ body: Readable; size: string | null } | null> {
|
||||
const release = (await this.releases()).find((r) => r.id === releaseId);
|
||||
if (!release) return null;
|
||||
const asset = release.assets.find((a) => a.name === name);
|
||||
const asset = latestAsset(release.assets, name);
|
||||
if (!asset || /\.json$/.test(name)) return null;
|
||||
const res = await this.download(asset);
|
||||
if (!res.body) return null;
|
||||
@@ -165,7 +181,13 @@ export async function registerDesktopRoutes(app: FastifyInstance, deps: { releas
|
||||
|
||||
app.get("/v1/desktop/download/:releaseId/:name", async (req, reply) => {
|
||||
const { releaseId, name } = z.object({ releaseId: z.coerce.number().int().positive(), name: z.string().min(1).max(200) }).parse(req.params);
|
||||
const file = releases ? await releases.file(releaseId, name) : null;
|
||||
let file: { body: Readable; size: string | null } | null;
|
||||
try {
|
||||
file = releases ? await releases.file(releaseId, name) : null;
|
||||
} catch (err) {
|
||||
req.log.warn({ err }, "desktop download failed");
|
||||
return reply.code(503).send({ error: "download_unavailable" });
|
||||
}
|
||||
if (!file) return reply.code(404).send({ error: "not_found" });
|
||||
if (file.size) reply.header("content-length", file.size);
|
||||
return reply.header("content-type", "application/octet-stream").header("content-disposition", `attachment; filename="${name.replace(/[^\w.-]+/g, "_")}"`).send(file.body);
|
||||
|
||||
@@ -180,6 +180,7 @@ export class FaceLookup {
|
||||
/ NULLIF(sqrt((SELECT sum(a * a) FROM unnest(p.centroid) AS u(a))), 0) AS score
|
||||
FROM people p
|
||||
WHERE p.organization_id = ${orgId}::uuid AND p.model = ${model} AND cardinality(p.centroid) = ${embedding.length}
|
||||
AND p.recognition_off_at IS NULL
|
||||
AND (${only}::uuid[] IS NULL OR p.id = ANY(${only}::uuid[]))
|
||||
) s
|
||||
WHERE score >= ${match - POSSIBLE_BELOW}
|
||||
|
||||
@@ -85,6 +85,8 @@ export class FaceService {
|
||||
videoTools?: VideoTools | undefined;
|
||||
/** Frames per second looked at in a video. */
|
||||
videoFps?: number | undefined;
|
||||
/** When player names land on a photo already delivered, rewrite the file at each destination (IPTC). */
|
||||
resend?: (organizationId: string, photoIds: readonly string[]) => Promise<number>;
|
||||
},
|
||||
) {}
|
||||
|
||||
@@ -902,6 +904,14 @@ export class FaceService {
|
||||
for (const photo of pending) {
|
||||
broadcaster.library(photo.organizationId, { type: "photo.updated", ids: [photo.id], patch: { players: photo.players } });
|
||||
}
|
||||
// A send that left without names gets the updated IPTC: same path, file replaced (like the Info window).
|
||||
const byOrg = new Map<string, string[]>();
|
||||
for (const photo of pending) {
|
||||
byOrg.set(photo.organizationId, [...(byOrg.get(photo.organizationId) ?? []), photo.id]);
|
||||
}
|
||||
for (const [organizationId, photoIds] of byOrg) {
|
||||
await this.deps.resend?.(organizationId, photoIds).catch((err) => this.deps.log.warn({ err, organizationId, n: photoIds.length }, "faces: delivered photos not resent after names"));
|
||||
}
|
||||
}
|
||||
|
||||
/** Names a group: an existing person, or a new one. Every photo with a face in the group gets the name. */
|
||||
|
||||
@@ -0,0 +1,59 @@
|
||||
import { exiftool } from "exiftool-vendored";
|
||||
import { mkdtemp, rm, writeFile } from "node:fs/promises";
|
||||
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";
|
||||
|
||||
describe("on-camera star ratings", () => {
|
||||
it("maps EXIF Rating and RatingPercent tags", () => {
|
||||
expect(ratingFromTags({})).toBeUndefined();
|
||||
expect(ratingFromTags({ Rating: 0 })).toBeUndefined();
|
||||
expect(ratingFromTags({ Rating: 3 })).toBe(3);
|
||||
expect(ratingFromTags({ Rating: "5" })).toBe(5);
|
||||
expect(ratingFromTags({ Rating: 9 })).toBe(5);
|
||||
expect(ratingFromTags({ RatingPercent: 0 })).toBeUndefined();
|
||||
expect(ratingFromTags({ RatingPercent: 1 })).toBe(1);
|
||||
expect(ratingFromTags({ RatingPercent: 75 })).toBe(4);
|
||||
expect(ratingFromTags({ RatingPercent: 99 })).toBe(5);
|
||||
});
|
||||
|
||||
it("turns any star into a library pick", () => {
|
||||
expect(cullFromCameraRating(undefined)).toEqual({});
|
||||
expect(cullFromCameraRating(0)).toEqual({});
|
||||
expect(cullFromCameraRating(1)).toEqual({ rating: 1, flag: "PICK" });
|
||||
expect(cullFromCameraRating(4)).toEqual({ rating: 4, flag: "PICK" });
|
||||
});
|
||||
|
||||
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 });
|
||||
});
|
||||
});
|
||||
|
||||
describe("readCameraInfo rating from files", () => {
|
||||
let dir: string;
|
||||
beforeAll(async () => {
|
||||
dir = await mkdtemp(path.join(tmpdir(), "pr-rating-"));
|
||||
});
|
||||
afterAll(async () => {
|
||||
await exiftool.end();
|
||||
await rm(dir, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
async function file(name: string, args: string[]): Promise<string> {
|
||||
const p = path.join(dir, name);
|
||||
await writeFile(p, await sharp({ create: { width: 64, height: 48, channels: 3, background: "#456" } }).jpeg().toBuffer());
|
||||
await exiftool.write(p, {}, { writeArgs: ["-overwrite_original", ...args] });
|
||||
return p;
|
||||
}
|
||||
|
||||
it("reads EXIF Rating and XMP xmp:Rating", async () => {
|
||||
expect((await readCameraInfo(await file("rated-exif.jpg", ["-EXIF:Rating=4"]))).rating).toBe(4);
|
||||
expect((await readCameraInfo(await file("rated-xmp.jpg", ["-XMP-xmp:Rating=2"]))).rating).toBe(2);
|
||||
const bare = path.join(dir, "bare.jpg");
|
||||
await writeFile(bare, await sharp({ create: { width: 8, height: 8, channels: 3, background: "#000" } }).jpeg().toBuffer());
|
||||
expect((await readCameraInfo(bare)).rating).toBeUndefined();
|
||||
});
|
||||
});
|
||||
@@ -54,9 +54,45 @@ export interface CameraInfo {
|
||||
aperture?: number | undefined;
|
||||
exposureTime?: number | undefined;
|
||||
iso?: number | undefined;
|
||||
/** 1–5 when the photographer set stars on the body (EXIF/XMP Rating). Absent or 0 = unrated. */
|
||||
rating?: number | undefined;
|
||||
extra?: CameraExtra | undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* Stars written on the camera (or in Photo Mechanic before upload). EXIF `Rating` (0–5) and Microsoft
|
||||
* `RatingPercent` (0 / 1 / 25 / 50 / 75 / 99). Zero or missing means unrated — not a deliberate 0-star mark.
|
||||
*/
|
||||
export function ratingFromTags(tags: Record<string, unknown>): number | undefined {
|
||||
const percent = num(tags.RatingPercent);
|
||||
if (percent !== undefined) {
|
||||
if (percent <= 0) return undefined;
|
||||
if (percent <= 12) return 1;
|
||||
if (percent <= 37) return 2;
|
||||
if (percent <= 62) return 3;
|
||||
if (percent <= 87) return 4;
|
||||
return 5;
|
||||
}
|
||||
const raw = tags.Rating ?? tags.rating;
|
||||
const r = typeof raw === "string" && raw.trim() !== "" ? Number(raw) : num(raw);
|
||||
if (r === undefined || !Number.isFinite(r) || r <= 0) return undefined;
|
||||
return Math.max(1, Math.min(5, Math.round(r)));
|
||||
}
|
||||
|
||||
/** Library cull from on-camera stars: keep the rating and mark as a pick (Escolhida) when there is at least one. */
|
||||
export function cullFromCameraRating(rating: number | undefined): { rating: number; flag: "PICK" } | Record<string, never> {
|
||||
if (rating === undefined || rating <= 0) return {};
|
||||
return { rating, flag: "PICK" };
|
||||
}
|
||||
|
||||
/** Marker in `photos.exif` so the worker does not re-read files that already had no stars. */
|
||||
export const CAMERA_RATING_CHECKED = "cameraRatingChecked";
|
||||
|
||||
export function withCameraRatingChecked(exif: unknown): Record<string, unknown> {
|
||||
const base = exif && typeof exif === "object" && !Array.isArray(exif) ? { ...(exif as Record<string, unknown>) } : {};
|
||||
return { ...base, [CAMERA_RATING_CHECKED]: true };
|
||||
}
|
||||
|
||||
const TIME_ZONE = "Europe/Lisbon";
|
||||
|
||||
/** Offset of a time zone at a given UTC instant, in minutes (Lisbon: 0 in winter, 60 in summer). */
|
||||
@@ -171,12 +207,13 @@ export async function readFocusPoint(file: string | Buffer): Promise<FocusHint |
|
||||
}
|
||||
|
||||
export async function readCameraInfo(file: string | Buffer): Promise<CameraInfo> {
|
||||
// XMP on: bodies and Photo Mechanic often put stars only in xmp:Rating.
|
||||
const tags = (await exifr.parse(file, {
|
||||
tiff: true,
|
||||
exif: true,
|
||||
gps: true,
|
||||
iptc: false,
|
||||
xmp: false,
|
||||
xmp: true,
|
||||
icc: false,
|
||||
reviveValues: false,
|
||||
translateValues: false,
|
||||
@@ -205,6 +242,7 @@ export async function readCameraInfo(file: string | Buffer): Promise<CameraInfo>
|
||||
aperture: num(tags.FNumber),
|
||||
exposureTime: num(tags.ExposureTime),
|
||||
iso,
|
||||
rating: ratingFromTags(tags),
|
||||
extra: Object.keys(extra).length ? extra : undefined,
|
||||
};
|
||||
}
|
||||
+126
-21
@@ -9,11 +9,23 @@ 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 { readCameraInfo } from "./exif.js";
|
||||
import { cullFromCameraRating, readCameraInfo, withCameraRatingChecked } from "./exif.js";
|
||||
import { jpegFileComplete } from "./jpeg.js";
|
||||
|
||||
export const ACCEPTED_EXTENSIONS = new Set([".jpg", ".jpeg"]);
|
||||
|
||||
/**
|
||||
* Open events (treino, long ingest windows without a hard match end) must not keep swallowing photos after the
|
||||
* photographer has stopped for more than this: a later burst is another session (inbox or another event).
|
||||
*/
|
||||
export const INGEST_SESSION_GAP_MS = 60 * 60 * 1000;
|
||||
|
||||
/** True when this capture still belongs to the same shooting session as `lastCapturedAt` (or there is no prior photo). */
|
||||
export function withinIngestSession(at: Date, lastCapturedAt: Date | null | undefined): boolean {
|
||||
if (!lastCapturedAt) return true;
|
||||
return at.getTime() - lastCapturedAt.getTime() <= INGEST_SESSION_GAP_MS;
|
||||
}
|
||||
|
||||
export type IngestOutcome =
|
||||
| { status: "ingested"; photoId: string; eventId: string | null }
|
||||
| { status: "duplicate"; photoId: string }
|
||||
@@ -97,8 +109,8 @@ export class IngestService {
|
||||
return { status: "skipped", reason: "unknown_login" };
|
||||
}
|
||||
|
||||
// "Receber FTP aqui": the login sends everything to the event chosen in the library, whatever the camera's
|
||||
// clock says, until the time set; then (or with that event put away) by the time again.
|
||||
// "Receber FTP aqui": pin is a preferred event for captures that still sit in its ingest window (and session).
|
||||
// Outside that window the clock routes — a leftover pin on the afternoon training must not take the morning studio.
|
||||
const target =
|
||||
account.targetEventId && (!account.targetUntil || account.targetUntil > new Date())
|
||||
? await db.event.findFirst({ where: { id: account.targetEventId, organizationId: account.organizationId, archivedAt: null }, select: { id: true } })
|
||||
@@ -161,16 +173,19 @@ export class IngestService {
|
||||
const camera = await readCameraInfo(file).catch(() => ({}) as Awaited<ReturnType<typeof readCameraInfo>>);
|
||||
const embedded = await readEmbeddedIptc(file);
|
||||
const capturedAt = camera.capturedAt ? new Date(camera.capturedAt.getTime() + (origin.clockOffsetSec ?? 0) * 1000) : undefined;
|
||||
const at = capturedAt ?? new Date();
|
||||
// Archive imports name their own event. A file with no camera time, or a time outside that event's window,
|
||||
// must not fall through onto whatever is live today.
|
||||
// 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
|
||||
// ingest window; otherwise the clock (closest start when windows overlap) decides.
|
||||
const requestedEventId = origin.inbox
|
||||
? null
|
||||
: origin.held && origin.eventId
|
||||
? origin.eventId
|
||||
: origin.source === "CLOUD"
|
||||
? await this.namedEvent(orgId, origin.eventId)
|
||||
: (await this.requestedEvent(orgId, origin.eventId, at)) ?? (await this.routeToEvent(orgId, origin.userId, at));
|
||||
: !capturedAt
|
||||
? await this.namedEvent(orgId, origin.eventId)
|
||||
: (await this.requestedEvent(orgId, origin.userId, origin.eventId, capturedAt)) ??
|
||||
(await this.routeToEvent(orgId, origin.userId, capturedAt));
|
||||
const storageKey = storage.originalKey(orgId, sha256, ext === ".jpeg" ? ".jpg" : ext);
|
||||
const size = (await stat(file)).size;
|
||||
await storage.adopt(file, storageKey);
|
||||
@@ -196,8 +211,11 @@ export class IngestService {
|
||||
aperture: camera.aperture ?? null,
|
||||
exposureTime: camera.exposureTime ?? null,
|
||||
iso: camera.iso ?? null,
|
||||
...(camera.extra && Object.keys(camera.extra).length && { exif: camera.extra }),
|
||||
// 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.
|
||||
...cullFromCameraRating(camera.rating),
|
||||
});
|
||||
try {
|
||||
photo = await db.photo.create({ data });
|
||||
@@ -326,7 +344,7 @@ export class IngestService {
|
||||
}
|
||||
|
||||
/** The full original of a photo that so far only had the desktop's preview (moved into place: `file` is consumed). */
|
||||
async storeOriginal(photo: { id: string; organizationId: string; sha256: string; storageKey: string }, file: string, ext: string): Promise<{ status: "ingested"; photoId: string; eventId: string | null }> {
|
||||
async storeOriginal(photo: { id: string; organizationId: string; sha256: string; storageKey: string; rating?: number }, file: string, ext: string): Promise<{ status: "ingested"; photoId: string; eventId: string | null }> {
|
||||
const { db, storage, log } = this.deps;
|
||||
const key = storage.originalKey(photo.organizationId, photo.sha256, ext === ".jpeg" ? ".jpg" : ext);
|
||||
const size = (await stat(file)).size;
|
||||
@@ -335,9 +353,21 @@ export class IngestService {
|
||||
// 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 updated = await db.photo.update({
|
||||
where: { id: photo.id },
|
||||
data: { storageKey: key, byteSize: size, originalStored: true, ...(org?.biometricsEnabled && { facesStatus: "PENDING" }) },
|
||||
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 } : {}),
|
||||
},
|
||||
});
|
||||
log.info({ photoId: photo.id }, "ingest: original replaces the desktop preview");
|
||||
// Deliveries waiting for it go now.
|
||||
@@ -357,27 +387,35 @@ export class IngestService {
|
||||
}
|
||||
|
||||
/**
|
||||
* The event asked for on the upload (the one open in the library, or the desktop's pinned FTP target).
|
||||
* Kept, unless it is a game already put away and this photo was taken outside that game's window: then the
|
||||
* clock decides, so a pin left on yesterday's match does not take today's event.
|
||||
* The event asked for on the upload (open library / desktop pin). Kept only while the capture sits in that
|
||||
* event's ingest window and the photographer has not paused more than {@link INGEST_SESSION_GAP_MS} since
|
||||
* their last photo there — otherwise the clock (or inbox) decides.
|
||||
*/
|
||||
private async requestedEvent(organizationId: string, requested: string | undefined, at: Date): Promise<string | undefined> {
|
||||
private async requestedEvent(
|
||||
organizationId: string,
|
||||
userId: string,
|
||||
requested: string | undefined,
|
||||
at: Date,
|
||||
): Promise<string | undefined> {
|
||||
if (!requested) return undefined;
|
||||
const event = await this.deps.db.event.findFirst({
|
||||
where: { id: requested, organizationId },
|
||||
select: { archivedAt: true, ingestFrom: true, ingestUntil: true },
|
||||
select: { ingestFrom: true, ingestUntil: true },
|
||||
});
|
||||
if (!event) return undefined;
|
||||
if (event.archivedAt && (at < event.ingestFrom || at > event.ingestUntil)) return undefined;
|
||||
if (at < event.ingestFrom || at > event.ingestUntil) return undefined;
|
||||
if (!(await this.sameSession(requested, userId, at))) return undefined;
|
||||
return requested;
|
||||
}
|
||||
|
||||
/**
|
||||
* The event this photo belongs to: one the photographer is assigned to (or an event with no assignments,
|
||||
* open to everyone) whose ingest window contains the capture time. The latest-starting one wins.
|
||||
* open to everyone) whose ingest window contains the capture time, without a >1 h shooting gap. When two
|
||||
* windows overlap (studio at 14:00 and training at 16:30), the start closest to the capture wins — not the
|
||||
* latest event on the calendar.
|
||||
*/
|
||||
async routeToEvent(organizationId: string, userId: string, at: Date): Promise<string | null> {
|
||||
const event = await this.deps.db.event.findFirst({
|
||||
const events = await this.deps.db.event.findMany({
|
||||
where: {
|
||||
organizationId,
|
||||
archivedAt: null,
|
||||
@@ -385,10 +423,77 @@ export class IngestService {
|
||||
ingestUntil: { gte: at },
|
||||
OR: [{ assignments: { some: { userId } } }, { assignments: { none: {} } }],
|
||||
},
|
||||
orderBy: { startsAt: "desc" },
|
||||
select: { id: true },
|
||||
take: 20,
|
||||
select: { id: true, startsAt: true },
|
||||
});
|
||||
return event?.id ?? null;
|
||||
events.sort((a, b) => Math.abs(a.startsAt.getTime() - at.getTime()) - Math.abs(b.startsAt.getTime() - at.getTime()));
|
||||
for (const event of events) {
|
||||
if (await this.sameSession(event.id, userId, at)) return event.id;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/** Last capture by this photographer in the event; none yet → new session may start. */
|
||||
private async sameSession(eventId: string, userId: string, at: Date): Promise<boolean> {
|
||||
const last = await this.deps.db.photo.findFirst({
|
||||
where: {
|
||||
eventId,
|
||||
uploaderId: userId,
|
||||
capturedAt: { not: null, lt: at },
|
||||
},
|
||||
orderBy: { capturedAt: "desc" },
|
||||
select: { capturedAt: true },
|
||||
});
|
||||
return withinIngestSession(at, last?.capturedAt);
|
||||
}
|
||||
|
||||
/**
|
||||
* Photos ingested before on-camera stars were read: re-open the original in storage, apply Rating, and mark
|
||||
* the row so it is not scanned again. Newest first; the worker calls this in small batches.
|
||||
* Does not touch photos the photographer already rated, or a REJECT flag.
|
||||
*/
|
||||
async backfillCameraRatings(limit = 25): Promise<number> {
|
||||
const { db, storage, log, broadcaster } = this.deps;
|
||||
const rows = await db.$queryRaw<
|
||||
Array<{ id: string; organization_id: string; storage_key: string; flag: "NONE" | "PICK" | "REJECT"; exif: unknown }>
|
||||
>`
|
||||
SELECT id, organization_id, storage_key, flag, exif
|
||||
FROM photos
|
||||
WHERE rating = 0
|
||||
AND original_stored
|
||||
AND status = 'READY'
|
||||
AND (
|
||||
exif IS NULL
|
||||
OR jsonb_typeof(exif::jsonb) <> 'object'
|
||||
OR COALESCE((exif::jsonb->>'cameraRatingChecked')::boolean, false) IS NOT TRUE
|
||||
)
|
||||
ORDER BY created_at DESC
|
||||
LIMIT ${limit}
|
||||
`;
|
||||
let applied = 0;
|
||||
for (const row of rows) {
|
||||
const file = storage.resolve(row.storage_key);
|
||||
const camera = await readCameraInfo(file).catch(() => null);
|
||||
const cull = cullFromCameraRating(camera?.rating);
|
||||
const data: Prisma.PhotoUpdateInput = {
|
||||
exif: withCameraRatingChecked(row.exif) as Prisma.InputJsonValue,
|
||||
};
|
||||
if ("rating" in cull) {
|
||||
data.rating = cull.rating;
|
||||
if (row.flag === "NONE") data.flag = "PICK";
|
||||
applied++;
|
||||
}
|
||||
await db.photo.update({ where: { id: row.id }, data });
|
||||
if ("rating" in cull) {
|
||||
broadcaster.library(row.organization_id, {
|
||||
type: "photo.updated",
|
||||
ids: [row.id],
|
||||
patch: { rating: cull.rating, ...(row.flag === "NONE" ? { flag: "PICK" as const } : {}) },
|
||||
});
|
||||
}
|
||||
}
|
||||
if (rows.length) log.info({ scanned: rows.length, applied }, "ingest: camera rating backfill");
|
||||
return applied;
|
||||
}
|
||||
|
||||
private async makeDerivatives(orgId: string, sha256: string, storageKey: string): Promise<{ width: number; height: number }> {
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { INGEST_SESSION_GAP_MS, withinIngestSession } from "./service.js";
|
||||
|
||||
describe("withinIngestSession", () => {
|
||||
const at = new Date("2026-11-03T16:00:00Z");
|
||||
|
||||
it("allows the first photo of an event", () => {
|
||||
expect(withinIngestSession(at, null)).toBe(true);
|
||||
expect(withinIngestSession(at, undefined)).toBe(true);
|
||||
});
|
||||
|
||||
it("keeps photos inside a one-hour pause", () => {
|
||||
expect(withinIngestSession(at, new Date(at.getTime() - INGEST_SESSION_GAP_MS))).toBe(true);
|
||||
expect(withinIngestSession(at, new Date(at.getTime() - 30 * 60_000))).toBe(true);
|
||||
});
|
||||
|
||||
it("ends the session after more than one hour without shots", () => {
|
||||
expect(withinIngestSession(at, new Date(at.getTime() - INGEST_SESSION_GAP_MS - 1))).toBe(false);
|
||||
expect(withinIngestSession(at, new Date(at.getTime() - 2 * 60 * 60_000))).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -25,11 +25,13 @@ export async function joinedEvent(db: Db, eventId: string, ids: string[]): Promi
|
||||
/**
|
||||
* Photos waiting in "Sem evento" taken during this event's ingest window (by the photographers it is assigned to,
|
||||
* or anyone when it has none): photos sent before the event was created, or before its times were corrected.
|
||||
* When another open event's window also covers the capture and starts closer to it, leave the photo in the inbox
|
||||
* (or for that other event) — otherwise creating a 16:30 training steals a 14:00 studio card from the overlap.
|
||||
*/
|
||||
export async function claimInbox(db: Db, eventId: string): Promise<string[]> {
|
||||
const event = await db.event.findUnique({
|
||||
where: { id: eventId },
|
||||
select: { organizationId: true, archivedAt: true, ingestFrom: true, ingestUntil: true, assignments: { select: { userId: true } } },
|
||||
select: { organizationId: true, archivedAt: true, ingestFrom: true, ingestUntil: true, startsAt: true, assignments: { select: { userId: true } } },
|
||||
});
|
||||
if (!event || event.archivedAt) return [];
|
||||
const photos = await db.photo.findMany({
|
||||
@@ -39,14 +41,35 @@ export async function claimInbox(db: Db, eventId: string): Promise<string[]> {
|
||||
capturedAt: { gte: event.ingestFrom, lte: event.ingestUntil },
|
||||
...(event.assignments.length && { uploaderId: { in: event.assignments.map((a) => a.userId) } }),
|
||||
},
|
||||
select: { id: true },
|
||||
select: { id: true, capturedAt: true },
|
||||
take: 20_000,
|
||||
});
|
||||
const ids = photos.map((p) => p.id);
|
||||
if (!photos.length) return [];
|
||||
const rivals = await db.event.findMany({
|
||||
where: {
|
||||
organizationId: event.organizationId,
|
||||
archivedAt: null,
|
||||
id: { not: eventId },
|
||||
ingestFrom: { lte: event.ingestUntil },
|
||||
ingestUntil: { gte: event.ingestFrom },
|
||||
},
|
||||
select: { id: true, startsAt: true, ingestFrom: true, ingestUntil: true },
|
||||
});
|
||||
const ids = photos
|
||||
.filter((p) => {
|
||||
if (!p.capturedAt) return true;
|
||||
const t = p.capturedAt.getTime();
|
||||
const better = rivals.some((r) => {
|
||||
if (t < r.ingestFrom.getTime() || t > r.ingestUntil.getTime()) return false;
|
||||
return Math.abs(r.startsAt.getTime() - t) < Math.abs(event.startsAt.getTime() - t);
|
||||
});
|
||||
return !better;
|
||||
})
|
||||
.map((p) => p.id);
|
||||
if (!ids.length) return [];
|
||||
// Only the ones still in the inbox (another event may have claimed some meanwhile).
|
||||
await db.photo.updateMany({ where: { id: { in: ids }, eventId: null }, data: { eventId } });
|
||||
const claimed = (await db.photo.findMany({ where: { id: { in: ids }, eventId }, select: { id: true } })).map((p) => p.id);
|
||||
await joinedEvent(db, eventId, claimed);
|
||||
return claimed;
|
||||
}
|
||||
}
|
||||
@@ -344,8 +344,9 @@ const FPA_GAME_OFFICIAL: [RegExp, string][] = [
|
||||
/**
|
||||
* The FPA's public pages, the same the portal links to: the agenda (JSON), a club's games of a season and level
|
||||
* (JSON), the match report ("Boletim do Jogo": every player with shirt number and licence number, the bench officials
|
||||
* with their letter, the referees), a match page (the referees, published before the match) and an athlete's page
|
||||
* (the licence photo). Asked for sparingly and cached in the database.
|
||||
* with their letter, the referees), a match page (the referees, published before the match), a club's full register
|
||||
* (`getCipClubeEpoca`: every associate with licence and photo) and an athlete's page (the licence photo). Asked for
|
||||
* sparingly and cached in the database. Shared shape with ehf-stats / livereport (`WsFpa.clubAssociates`).
|
||||
*/
|
||||
export class FpaProvider {
|
||||
static readonly AGENDA = "https://ws.fpa.pt/index.php/getAgendaJogosFAP/";
|
||||
@@ -421,11 +422,155 @@ export class FpaProvider {
|
||||
return parseFpaMatchPage(await this.html(`${FpaProvider.PORTAL}/jogo/${encodeURIComponent(gameId)}/`));
|
||||
}
|
||||
|
||||
/**
|
||||
* Someone registered with the federation, by licence number (CIPA, as printed on match reports and the portal):
|
||||
* name, licence photo and every registration (season, as what, where). The portal's page gives the federation's
|
||||
* internal id, which the registrations are kept under (it is not the licence number). Null when unknown.
|
||||
*/
|
||||
async member(licence: string): Promise<FpaMember | null> {
|
||||
if (!/^\d{1,9}$/.test(licence)) return null;
|
||||
const page = parseFpaMemberPage(await this.html(`${FpaProvider.PORTAL}/associado/${encodeURIComponent(licence)}/`));
|
||||
if (!page) return null;
|
||||
let registrations: FpaRegistration[] = [];
|
||||
if (page.internalId) {
|
||||
const rows = await get(this.fetcher, `${FpaProvider.WS}/getCipaInscricoes/${encodeURIComponent(page.internalId)}`, { accept: "application/json" }, "json");
|
||||
if (Array.isArray(rows)) registrations = (rows as Record<string, unknown>[]).map(fpaRegistration).filter((r): r is FpaRegistration => !!r);
|
||||
}
|
||||
return { ...page, licence, registrations };
|
||||
}
|
||||
|
||||
/** An athlete's licence photo (by licence number), if the federation has one. */
|
||||
async athletePhoto(cipa: string): Promise<string | null> {
|
||||
const html = await this.html(`${FpaProvider.PORTAL}/associado/${encodeURIComponent(cipa)}/`);
|
||||
return /https:\/\/si\.fpa\.pt\/blob\/obj_anexo\/FOTO_CIPA\/\d+_\d+\.(?:jpe?g|png)/i.exec(html)?.[0] ?? null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Everyone registered at a club for a season (athletes, coaches, officials, referees), with licence number and
|
||||
* licence photo when the federation has one. This is the club register — not only the people named on a match
|
||||
* sheet. Season ids are the portal's (`373` = 2025/26); see `fpaEpochFor`.
|
||||
*/
|
||||
async clubAssociates(clubId: string, seasonId: string): Promise<FpaClubAssociate[]> {
|
||||
if (!/^\d+$/.test(clubId) || !/^\d+$/.test(seasonId)) return [];
|
||||
const path = ["getCipClubeEpoca", clubId, seasonId].map(encodeURIComponent).join("/");
|
||||
const rows = await get(this.fetcher, `${FpaProvider.WS}/${path}`, { accept: "application/json" }, "json");
|
||||
await this.pause();
|
||||
if (!Array.isArray(rows)) return [];
|
||||
const out: FpaClubAssociate[] = [];
|
||||
const seen = new Set<string>();
|
||||
for (const raw of rows as Record<string, unknown>[]) {
|
||||
const a = fpaClubAssociate(raw);
|
||||
if (!a || seen.has(a.licence)) continue;
|
||||
seen.add(a.licence);
|
||||
out.push(a);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
}
|
||||
|
||||
/** Someone on a club's FPA register for a season (from `getCipClubeEpoca`). */
|
||||
export interface FpaClubAssociate {
|
||||
licence: string;
|
||||
/** Federation internal id (portal history); not the printed CIPA. */
|
||||
internalId: string | null;
|
||||
name: string;
|
||||
photo: string | null;
|
||||
kind: "athlete" | "coach" | "official" | "referee" | "other";
|
||||
}
|
||||
|
||||
/** Handball seasons start in August; portal epoch ids advance one per year (2025/26 = 373). */
|
||||
export function fpaEpochFor(date: Date = new Date()): string {
|
||||
const year = date.getUTCFullYear();
|
||||
const start = date.getUTCMonth() >= 7 ? year : year - 1;
|
||||
return String(start - 1652);
|
||||
}
|
||||
|
||||
function fpaClubAssociate(r: Record<string, unknown>): FpaClubAssociate | null {
|
||||
const licence = String(r.CIP_NUMERO ?? "").trim().replace(/\.0+$/, "");
|
||||
const name = cellText(String(r.CIP_NOME ?? ""));
|
||||
if (!/^\d{1,9}$/.test(licence) || !name) return null;
|
||||
const photo = str(r.URL_FOTO);
|
||||
const kind: FpaClubAssociate["kind"] =
|
||||
String(r.ATLETA ?? "").toUpperCase() === "S"
|
||||
? "athlete"
|
||||
: String(r.TECNICO ?? "").toUpperCase() === "S"
|
||||
? "coach"
|
||||
: String(r.OFICIAL ?? "").toUpperCase() === "S"
|
||||
? "official"
|
||||
: String(r.ARBITRO ?? "").toUpperCase() === "S"
|
||||
? "referee"
|
||||
: "other";
|
||||
return {
|
||||
licence,
|
||||
internalId: str(r.ID_CIPA),
|
||||
name,
|
||||
photo: photo && /^https:\/\/si\.fpa\.pt\//i.test(photo) ? photo : null,
|
||||
kind,
|
||||
};
|
||||
}
|
||||
|
||||
/** A registration of a member for one season: athlete, coach, official, table official or referee. */
|
||||
export interface FpaRegistration {
|
||||
season: string;
|
||||
kind: "athlete" | "coach" | "official" | "table" | "referee" | "other";
|
||||
/** "Atleta", "Treinador", "Delegado técnico", "Árbitro regional"... */
|
||||
role: string;
|
||||
/** The club or team ("AA AVANCA", "Sel.Nac.M"); null for referees. */
|
||||
club: string | null;
|
||||
clubName: string | null;
|
||||
/** The age level for athletes ("Juvenis F"). */
|
||||
level: string | null;
|
||||
association: string | null;
|
||||
}
|
||||
|
||||
export interface FpaMember {
|
||||
licence: string;
|
||||
internalId: string | null;
|
||||
name: string;
|
||||
photo: string | null;
|
||||
/** "Árbitro, Oficial, Técnico, Atleta", as the portal says. */
|
||||
registeredAs: string | null;
|
||||
registrations: FpaRegistration[];
|
||||
}
|
||||
|
||||
const FPA_KINDS: Record<string, FpaRegistration["kind"]> = { AT01: "athlete", TEC: "coach", OFI: "official", OMS: "table", ARB: "referee" };
|
||||
|
||||
function fpaRegistration(r: Record<string, unknown>): FpaRegistration | null {
|
||||
const season = str(r.EPO_DESCRICAO);
|
||||
if (!season) return null;
|
||||
const code = str(r.GCI_TIP_INSCRICAO_TI013) ?? "";
|
||||
const kind = FPA_KINDS[code] ?? (code.startsWith("AT") ? "athlete" : "other");
|
||||
const detail = str(r.FOF_ABREV) ?? str(r.CJU_ABREV);
|
||||
const role =
|
||||
kind === "athlete" ? "Atleta" : kind === "coach" ? "Treinador" : kind === "table" ? "Oficial de mesa" : kind === "referee" ? (detail ?? "Árbitro") : (detail ? detail.charAt(0) + detail.slice(1).toLowerCase() : "Oficial");
|
||||
return { season, kind, role: fpaAccents(role), club: str(r.CLU_ABREV), clubName: str(r.CLU_NOME), level: str(r.ESC_DESCRICAO), association: str(r.ASS_ABREV) };
|
||||
}
|
||||
|
||||
/** The federation's codes are written without accents ("Delegado tecnico", "Funcionario"). */
|
||||
function fpaAccents(s: string): string {
|
||||
const fix: Record<string, string> = { tecnico: "técnico", tecnica: "técnica", funcionario: "funcionário", medico: "médico", fisioterapeuta: "fisioterapeuta", seccionista: "seccionista", estagiario: "estagiário", arb: "Árb" };
|
||||
return s.replace(/\p{L}+/gu, (w) => {
|
||||
const f = fix[w.toLowerCase()];
|
||||
if (!f) return w;
|
||||
return w[0] === w[0]!.toUpperCase() ? f[0]!.toUpperCase() + f.slice(1) : f;
|
||||
});
|
||||
}
|
||||
|
||||
/** A member's page on the portal: name, photo, the internal id its history is under. Null for an unknown licence. */
|
||||
export function parseFpaMemberPage(html: string): Omit<FpaMember, "licence" | "registrations"> | null {
|
||||
const $ = cheerio.load(html);
|
||||
const box = $(".association-detail");
|
||||
const name = box.find("h3").first().text().replace(/\s+/g, " ").trim();
|
||||
if (!box.length || !name) return null;
|
||||
let registeredAs: string | null = null;
|
||||
box.find("tr").each((_, tr) => {
|
||||
const cells = $(tr).children("td");
|
||||
if (/inscrito como/i.test(cells.first().text())) registeredAs = cells.eq(1).text().replace(/\s+/g, " ").trim() || null;
|
||||
});
|
||||
const photo = box.find("img").attr("src") ?? null;
|
||||
// The history table's settings carry the internal id ("cipa":"203445"); the photo's file name ends with it too.
|
||||
const internalId = /TABLE_CONTENT_\d+\s*=\s*\{[^;]*?"cipa"\s*:\s*"(\d+)"/.exec(html)?.[1] ?? /FOTO_CIPA\/\d+_(\d+)\./i.exec(photo ?? "")?.[1] ?? null;
|
||||
return { name, photo: photo && /^https:\/\/si\.fpa\.pt\//.test(photo) ? photo : null, registeredAs, internalId };
|
||||
}
|
||||
|
||||
export interface FpaBoletim {
|
||||
|
||||
@@ -14,7 +14,12 @@ import { tallyOf, tallySquadPhotos } from "./squadPhotos.js";
|
||||
import {
|
||||
type Fetch,
|
||||
type FixtureData,
|
||||
type FpaClubAssociate,
|
||||
type FpaMember,
|
||||
FpaProvider,
|
||||
type FpaRegistration,
|
||||
fpaEpochFor,
|
||||
fpaShortName,
|
||||
FpfProvider,
|
||||
LIGA_COMPETITIONS,
|
||||
type LigaClubCompetition,
|
||||
@@ -60,6 +65,13 @@ const FPA_REPORTS_PER_REFRESH = 30;
|
||||
const FPA_RETRY_MS = 3 * 86400_000;
|
||||
/** Reports read before licence numbers were kept, read again per refresh until none are left. */
|
||||
const FPA_REREADS_PER_REFRESH = 40;
|
||||
/**
|
||||
* Clubs whose full FPA register (every associate with a licence photo) is pulled per refresh — not only the people
|
||||
* on match sheets. Covers coaches, officials, youth and anyone else the federation lists for the club.
|
||||
*/
|
||||
const FPA_ASSOCIATE_CLUBS_PER_REFRESH = 12;
|
||||
/** Skip a club's register again until this long has passed (the list changes slowly). */
|
||||
const FPA_ASSOCIATE_RETRY_MS = 7 * 86400_000;
|
||||
/** The handball referees and table officials, kept as one "team" so their licence (and photo) is known by name. */
|
||||
const FPA_REFEREES_TEAM = { externalId: "ARBITRAGEM", name: REFEREES };
|
||||
/** Officials of the game who become people of an event (faces to name): on the pitch, and at the table. */
|
||||
@@ -505,6 +517,7 @@ export class SportsService {
|
||||
}
|
||||
await this.fpaSquads(fixtures, now, result);
|
||||
await this.fpaReferees(now, result);
|
||||
await this.fpaAssociates(fixtures, now, result);
|
||||
if (result.errors.length) log.warn({ errors: result.errors.slice(0, 10) }, "sports: fpa refresh had errors");
|
||||
log.info({ ...result, errors: result.errors.length }, "sports: fpa refreshed");
|
||||
return result;
|
||||
@@ -513,6 +526,15 @@ export class SportsService {
|
||||
private readonly fpaTried = new Map<string, number>();
|
||||
/** Reports read again for licence numbers (once each: some list none). */
|
||||
private readonly fpaReread = new Set<string>();
|
||||
/** Last time a club's full associate register was pulled. */
|
||||
private readonly fpaAssociateAt = new Map<string, number>();
|
||||
|
||||
/** Clears in-memory FPA retry clocks (tests after a DB reset; production keeps them for the process). */
|
||||
resetFpaClocks(): void {
|
||||
this.fpaTried.clear();
|
||||
this.fpaReread.clear();
|
||||
this.fpaAssociateAt.clear();
|
||||
}
|
||||
|
||||
private fpaCompetition(f: FixtureData): Promise<SportsCompetition> {
|
||||
return this.deps.db.sportsCompetition.upsert({
|
||||
@@ -1176,6 +1198,9 @@ export class SportsService {
|
||||
const { db, log } = this.deps;
|
||||
let person = await db.person.findUnique({ where: { organizationId_sportsPlayerId: { organizationId: orgId, sportsPlayerId: p.id } } });
|
||||
let created = false;
|
||||
// Handball: someone added by their licence number is the same person on the match report.
|
||||
if (!person && team.provider === "FPA" && p.externalId)
|
||||
person = await db.person.findFirst({ where: { organizationId: orgId, licence: p.externalId, sportsPlayerId: null } });
|
||||
if (!person) person = await this.personForIdentity(orgId, p);
|
||||
if (!person) {
|
||||
const byName = await db.person.findUnique({ where: { organizationId_name: { organizationId: orgId, name: p.name } } });
|
||||
@@ -1219,6 +1244,147 @@ export class SportsService {
|
||||
if (photo && !person.referenceKey) headshots.push({ personId: person.id, url: photo });
|
||||
}
|
||||
|
||||
/**
|
||||
* A person from their handball federation licence (CIPA): the name, club and role of their latest registration,
|
||||
* and (with biometrics on) the licence photo as the reference, so they are recognised in event photos too (a
|
||||
* coach, a delegate, a former player), not only where a match report names them. The same licence is always the
|
||||
* same person: one already added, or seen on a match report, is brought up to date instead.
|
||||
*/
|
||||
async personFromFpaLicence(orgId: string, licence: string): Promise<{ person: { id: string; name: string; club: string | null }; member: FpaMember; created: boolean; reference: boolean }> {
|
||||
const { db, log } = this.deps;
|
||||
const member = await this.fpa.member(licence.trim());
|
||||
if (!member) throw notFound("fpa_member_not_found");
|
||||
const org = await db.organization.findUnique({ where: { id: orgId }, select: { biometricsEnabled: true } });
|
||||
if (!org) throw notFound("organization_not_found");
|
||||
const latest = fpaLatestRole(member);
|
||||
const club = latest?.club ?? null;
|
||||
let person = await db.person.findUnique({ where: { organizationId_licence: { organizationId: orgId, licence: member.licence } } });
|
||||
if (!person) {
|
||||
// Seen on a match report: the squad entry with this licence.
|
||||
const players = await db.sportsPlayer.findMany({ where: { externalId: member.licence, team: { provider: "FPA" } }, select: { id: true } });
|
||||
if (players.length) person = await db.person.findFirst({ where: { organizationId: orgId, sportsPlayerId: { in: players.map((p) => p.id) }, licence: null } });
|
||||
}
|
||||
let created = false;
|
||||
if (!person) {
|
||||
const short = fpaShortName(member.name);
|
||||
const same = await db.person.findUnique({ where: { organizationId_name: { organizationId: orgId, name: short } } });
|
||||
// A name taken by someone else: the full name, and if that is taken too (by another licence), the licence
|
||||
// number — guaranteed free — tells the two apart for sure.
|
||||
let name = !same ? short : member.name;
|
||||
let other = same ? await db.person.findUnique({ where: { organizationId_name: { organizationId: orgId, name } } }) : null;
|
||||
if (other && other.licence && other.licence !== member.licence) {
|
||||
name = `${member.name} (${member.licence})`;
|
||||
other = await db.person.findUnique({ where: { organizationId_name: { organizationId: orgId, name } } });
|
||||
}
|
||||
person = other ?? (await db.person.create({ data: { organizationId: orgId, name, club, licence: member.licence } }));
|
||||
created = !other;
|
||||
}
|
||||
if (person.licence !== member.licence || (!person.club && club)) {
|
||||
person = await db.person.update({ where: { id: person.id }, data: { licence: member.licence, ...(!person.club && club && { club }) } });
|
||||
}
|
||||
let reference = false;
|
||||
if (org.biometricsEnabled && member.photo && !person.referenceKey && !person.recognitionOffAt) {
|
||||
try {
|
||||
reference = await this.saveHeadshot(orgId, person.id, member.photo);
|
||||
} catch (err) {
|
||||
log.warn({ err, licence: member.licence }, "sports: fpa licence photo failed");
|
||||
}
|
||||
}
|
||||
return { person: { id: person.id, name: person.name, club: person.club }, member, created, reference };
|
||||
}
|
||||
|
||||
/**
|
||||
* Full FPA club registers into people (every associate the federation lists for the club this season, with
|
||||
* licence photo). Match sheets alone miss coaches, officials, youth and anyone not on a boletim — this closes
|
||||
* that gap for face search. Clubs come from the agenda; a few per refresh, then again after a week.
|
||||
*/
|
||||
private async fpaAssociates(agenda: FixtureData[], now: Date, result: RefreshResult): Promise<void> {
|
||||
const { db, log } = this.deps;
|
||||
const clubIds = [...new Set(agenda.flatMap((f) => [f.home.clubId, f.away.clubId]).filter((id): id is string => !!id && /^\d+$/.test(id)))];
|
||||
const due = clubIds.filter((id) => {
|
||||
const at = this.fpaAssociateAt.get(id);
|
||||
return !at || now.getTime() - at >= FPA_ASSOCIATE_RETRY_MS;
|
||||
});
|
||||
if (!due.length) return;
|
||||
const orgs = await db.organization.findMany({ where: { biometricsEnabled: true }, select: { id: true } });
|
||||
if (!orgs.length) return;
|
||||
const epoch = fpaEpochFor(now);
|
||||
let clubs = 0;
|
||||
for (const clubId of due) {
|
||||
if (clubs >= FPA_ASSOCIATE_CLUBS_PER_REFRESH) break;
|
||||
clubs++;
|
||||
this.fpaAssociateAt.set(clubId, now.getTime());
|
||||
let associates: FpaClubAssociate[];
|
||||
try {
|
||||
associates = await this.fpa.clubAssociates(clubId, epoch);
|
||||
} catch (err) {
|
||||
result.errors.push(`fpa associates ${clubId}: ${(err as Error).message}`);
|
||||
continue;
|
||||
}
|
||||
if (!associates.length) continue;
|
||||
for (const org of orgs) {
|
||||
for (const a of associates) {
|
||||
try {
|
||||
const done = await this.personFromFpaAssociate(org.id, a);
|
||||
if (done.created) result.players++;
|
||||
} catch (err) {
|
||||
log.warn({ err, licence: a.licence, org: org.id }, "sports: fpa associate failed");
|
||||
}
|
||||
}
|
||||
}
|
||||
log.info({ clubId, associates: associates.length, orgs: orgs.length }, "sports: fpa club register");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Someone from a club's FPA register row (licence + name + photo already known — no second portal hit).
|
||||
* Same person as `personFromFpaLicence` when the licence matches.
|
||||
*/
|
||||
async personFromFpaAssociate(
|
||||
orgId: string,
|
||||
a: FpaClubAssociate,
|
||||
clubName: string | null = null,
|
||||
): Promise<{ person: { id: string; name: string; club: string | null }; created: boolean; reference: boolean }> {
|
||||
const { db, log } = this.deps;
|
||||
const org = await db.organization.findUnique({ where: { id: orgId }, select: { biometricsEnabled: true } });
|
||||
if (!org) throw notFound("organization_not_found");
|
||||
let person = await db.person.findUnique({ where: { organizationId_licence: { organizationId: orgId, licence: a.licence } } });
|
||||
if (!person) {
|
||||
const players = await db.sportsPlayer.findMany({ where: { externalId: a.licence, team: { provider: "FPA" } }, select: { id: true } });
|
||||
if (players.length) person = await db.person.findFirst({ where: { organizationId: orgId, sportsPlayerId: { in: players.map((p) => p.id) }, licence: null } });
|
||||
}
|
||||
let created = false;
|
||||
if (!person) {
|
||||
const short = fpaShortName(a.name);
|
||||
const same = await db.person.findUnique({ where: { organizationId_name: { organizationId: orgId, name: short } } });
|
||||
// A name taken by someone else: the full name, and if that is taken too (by another licence), the licence
|
||||
// number — guaranteed free — tells the two apart for sure.
|
||||
let name = !same ? short : a.name;
|
||||
let other = same ? await db.person.findUnique({ where: { organizationId_name: { organizationId: orgId, name } } }) : null;
|
||||
if (other && other.licence && other.licence !== a.licence) {
|
||||
name = `${a.name} (${a.licence})`;
|
||||
other = await db.person.findUnique({ where: { organizationId_name: { organizationId: orgId, name } } });
|
||||
}
|
||||
person = other ?? (await db.person.create({ data: { organizationId: orgId, name, club: clubName, licence: a.licence } }));
|
||||
created = !other;
|
||||
}
|
||||
if (person.licence !== a.licence || (!person.club && clubName)) {
|
||||
person = await db.person.update({
|
||||
where: { id: person.id },
|
||||
data: { licence: a.licence, ...(!person.club && clubName ? { club: clubName } : {}) },
|
||||
});
|
||||
}
|
||||
let reference = false;
|
||||
if (org.biometricsEnabled && a.photo && !person.referenceKey && !person.recognitionOffAt) {
|
||||
try {
|
||||
reference = await this.saveHeadshot(orgId, person.id, a.photo);
|
||||
} catch (err) {
|
||||
log.warn({ err, licence: a.licence }, "sports: fpa associate photo failed");
|
||||
}
|
||||
}
|
||||
return { person: { id: person.id, name: person.name, club: person.club }, created, reference };
|
||||
}
|
||||
|
||||
/** The person already created for this human at another club or in another season. */
|
||||
private async personForIdentity(orgId: string, p: SportsPlayer) {
|
||||
const match: ({ externalId: string } | { birthDate: string; fullName: string })[] = [];
|
||||
@@ -1483,3 +1649,20 @@ export class SportsWorker {
|
||||
if (!drained) this.opts.log.warn({}, "sports: stop timed out with work still running");
|
||||
}
|
||||
}
|
||||
|
||||
/** The role a member is best known by now: the latest season's, a player or coach before an official. */
|
||||
export function fpaLatestRole(member: FpaMember): { season: string; role: string; club: string | null } | null {
|
||||
const order: FpaRegistration["kind"][] = ["athlete", "coach", "official", "table", "referee", "other"];
|
||||
const regs = [...member.registrations].sort((a, b) => b.season.localeCompare(a.season) || order.indexOf(a.kind) - order.indexOf(b.kind) || Number(a.club === "F.A.P.") - Number(b.club === "F.A.P."));
|
||||
const r = regs[0];
|
||||
if (!r) return null;
|
||||
return { season: r.season, role: r.role, club: r.clubName ? fpaClubName(r.clubName) : r.club };
|
||||
}
|
||||
|
||||
/** "Estarreja Andebol Clube" as is; "Selecções Nacionais Masculinas" → "Seleção Nacional Masculina"; capitals fixed. */
|
||||
export function fpaClubName(name: string): string {
|
||||
const sel = /^selec[cç][oõ]es nacionais (masculinas|femininas)/i.exec(name);
|
||||
if (sel) return `Seleção Nacional ${sel[1]!.toLowerCase().startsWith("m") ? "Masculina" : "Feminina"}`;
|
||||
if (/^federa[cç]ao andebol portugal$/i.test(name)) return "Federação de Andebol de Portugal";
|
||||
return name === name.toUpperCase() ? name.toLowerCase().replace(/(^|\s)\p{L}/gu, (m) => m.toUpperCase()) : name;
|
||||
}
|
||||
+17
-1
@@ -134,7 +134,17 @@ const faceEngine =
|
||||
const jersey = faceEngine && config.JERSEY_MODEL_DIR ? await JerseyModel.load(config.JERSEY_MODEL_DIR) : undefined;
|
||||
if (jersey) log.info({ dir: config.JERSEY_MODEL_DIR }, "shirt-number model loaded");
|
||||
const faceService = faceEngine
|
||||
? new FaceService({ db, storage, broadcaster, log, engine: faceEngine, jersey, videoTools, videoFps: config.ARCHIVE_VIDEO_FACE_FPS })
|
||||
? new FaceService({
|
||||
db,
|
||||
storage,
|
||||
broadcaster,
|
||||
log,
|
||||
engine: faceEngine,
|
||||
jersey,
|
||||
videoTools,
|
||||
videoFps: config.ARCHIVE_VIDEO_FACE_FPS,
|
||||
resend: (orgId, ids) => deliveryService.resendPhotos(orgId, ids),
|
||||
})
|
||||
: undefined;
|
||||
const faces = faceService
|
||||
? new FaceWorker(faceService, {
|
||||
@@ -171,6 +181,11 @@ faces?.start();
|
||||
renders?.start();
|
||||
fulfilment.start();
|
||||
invoices.start();
|
||||
// Photos that arrived before on-camera stars were read: apply Rating from the original in storage.
|
||||
const ratingBackfill = setInterval(() => {
|
||||
void ingest.backfillCameraRatings(25).catch((err) => log.warn({ err }, "ingest: camera rating backfill failed"));
|
||||
}, 60_000);
|
||||
void ingest.backfillCameraRatings(25).catch((err) => log.warn({ err }, "ingest: camera rating backfill failed"));
|
||||
log.info({ ingestRoot: config.INGEST_ROOT, storage: config.STORAGE_ROOT }, "worker started");
|
||||
|
||||
/** Drain in-flight jobs before ending the Prisma/pg pool (BIT-31189). Leave headroom under PM2 kill_timeout. */
|
||||
@@ -181,6 +196,7 @@ const shutdown = async (signal: string) => {
|
||||
shuttingDown = true;
|
||||
log.info({ signal }, "worker stopping");
|
||||
// Stop claiming first, then wait for ticks/in-flight work so `$disconnect` does not race Prisma queries.
|
||||
clearInterval(ratingBackfill);
|
||||
await Promise.all([
|
||||
scanner.stop(DRAIN_MS),
|
||||
archive.stop(DRAIN_MS),
|
||||
|
||||
@@ -10,6 +10,7 @@ import { canonicalTeam, describeFolder, directorySides, exhibitionName, galleryR
|
||||
import { CloudClient, parseMultistatus } from "../src/archive/nextcloud.js";
|
||||
import { ArchiveService, localDirs } from "../src/archive/service.js";
|
||||
import { FaceService } from "../src/faces/service.js";
|
||||
import { normalize } from "../src/faces/math.js";
|
||||
import type { FaceAnalysis, FaceEngine } from "../src/faces/process.js";
|
||||
import { execFileSync } from "node:child_process";
|
||||
import { SecretBox } from "../src/delivery/secrets.js";
|
||||
@@ -18,6 +19,24 @@ import { MemoryBroadcaster } from "../src/realtime.js";
|
||||
import { LocalStorage, UrlSigner } from "../src/storage/storage.js";
|
||||
import { bearer, createTestApp, login, resetDb, seedUser, type TestContext } from "./helpers.js";
|
||||
|
||||
/** Face for archive search-by-photo tests: a fixed direction plus optional noise. */
|
||||
function faceVec(seed: number, noise = 0): number[] {
|
||||
const rand = (k: number) => {
|
||||
const x = Math.sin(k * 127.1 + 311.7) * 43758.5453;
|
||||
return (x - Math.floor(x)) * 2 - 1;
|
||||
};
|
||||
return normalize(Array.from({ length: 64 }, (_, i) => rand(seed * 1000 + i) + (noise ? rand(noise * 7919 + i) * 0.15 : 0)));
|
||||
}
|
||||
|
||||
class FindEngine implements FaceEngine {
|
||||
readonly model = "auraface-v1";
|
||||
next: FaceAnalysis = { width: 800, height: 1000, faces: [] };
|
||||
async analyse(): Promise<FaceAnalysis> {
|
||||
return this.next;
|
||||
}
|
||||
async close(): Promise<void> {}
|
||||
}
|
||||
|
||||
const KEY = Buffer.alloc(32, 7).toString("base64");
|
||||
const quiet = { info: () => {}, warn: () => {} };
|
||||
|
||||
@@ -553,12 +572,24 @@ describe("archive from a Nextcloud", () => {
|
||||
let orgId: string;
|
||||
let ownerId: string;
|
||||
let worker: ArchiveService;
|
||||
const findEngine = new FindEngine();
|
||||
|
||||
const fetchProxy: typeof fetch = (input, init) => cloud.fetch(input, init);
|
||||
// The cloud, and the handball federation's portal for a licence lookup.
|
||||
const fetchProxy: typeof fetch = (input, init) => {
|
||||
const u = new URL(typeof input === "string" ? input : input instanceof URL ? input.href : input.url);
|
||||
if (u.host === "portal.fpa.pt")
|
||||
return Promise.resolve(
|
||||
u.pathname === "/associado/198159/"
|
||||
? new Response('<div class="association-detail"><h3>Maria Ema Bastos Silva</h3><img src="https://si.fpa.pt/blob/obj_anexo/FOTO_CIPA/1_203445.JPG"></div><script>var TABLE_CONTENT_1 = {"cipa":"203445"};</script>', { headers: { "content-type": "text/html" } })
|
||||
: new Response("<html></html>", { headers: { "content-type": "text/html" } }),
|
||||
);
|
||||
if (u.host === "ws.fpa.pt") return Promise.resolve(Response.json([{ EPO_DESCRICAO: "2024/25", GCI_TIP_INSCRICAO_TI013: "TEC", CLU_ABREV: "ESTARREJA AC", CLU_NOME: "Estarreja Andebol Clube" }]));
|
||||
return cloud.fetch(input, init);
|
||||
};
|
||||
|
||||
beforeAll(async () => {
|
||||
storageRoot = await mkdtemp(path.join(tmpdir(), "pr-archive-test-"));
|
||||
ctx = await createTestApp({ DELIVERY_SECRET_KEY: KEY, STORAGE_ROOT: storageRoot }, undefined, fetchProxy);
|
||||
ctx = await createTestApp({ DELIVERY_SECRET_KEY: KEY, STORAGE_ROOT: storageRoot }, undefined, fetchProxy, undefined, findEngine);
|
||||
});
|
||||
afterAll(async () => {
|
||||
await ctx.app.close();
|
||||
@@ -1120,6 +1151,17 @@ describe("archive from a Nextcloud", () => {
|
||||
const scoped = res.json() as { gallery: { id: string; title: string } | null; counts: Record<string, number> };
|
||||
expect(scoped.gallery?.id).toBe(gid);
|
||||
expect(scoped.counts.suggested).toBe(2);
|
||||
// Handball archives: a licence number nobody has yet is looked up at the federation, and the person added.
|
||||
await ctx.db.cloudSource.update({ where: { id: source.id }, data: { look: "fpa" } });
|
||||
res = await ctx.app.inject({ method: "GET", url: `/v1/archive/${source.id}/people/search?q=198159`, headers: as(editor) });
|
||||
expect(res.json()).toMatchObject({ people: [], fpa: { licence: "198159", name: "Maria Ema Bastos Silva", club: "Estarreja Andebol Clube", role: "Treinador · 2024/25" } });
|
||||
res = await ctx.app.inject({ method: "POST", url: `/v1/archive/${source.id}/people/from-licence`, headers: as(reader), payload: { licence: "198159" } });
|
||||
expect(res.statusCode).toBe(403);
|
||||
res = await ctx.app.inject({ method: "POST", url: `/v1/archive/${source.id}/people/from-licence`, headers: as(editor), payload: { licence: "198159" } });
|
||||
expect(res.json()).toMatchObject({ created: true, person: { name: "Maria Silva", club: "Estarreja Andebol Clube", licence: "198159" } });
|
||||
res = await ctx.app.inject({ method: "GET", url: `/v1/archive/${source.id}/people/search?q=198159`, headers: as(editor) });
|
||||
expect(res.json().fpa).toBeUndefined();
|
||||
expect(res.json().people).toMatchObject([{ name: "Maria Silva", licence: "198159" }]);
|
||||
// "Juntar nomes" is for those who edit everything.
|
||||
res = await ctx.app.inject({ method: "POST", url: `/v1/archive/${source.id}/clubs/merge`, headers: as(editor), payload: { into: "Sporting CP", names: ["Sporting"] } });
|
||||
expect(res.statusCode).toBe(403);
|
||||
@@ -1341,11 +1383,87 @@ describe("archive from a Nextcloud", () => {
|
||||
expect(photos.every((f) => f.photo?.eventId === fixed.eventId)).toBe(true);
|
||||
});
|
||||
|
||||
it("lets cloud editors search the archive by a photo when the option is on", async () => {
|
||||
await ctx.db.organization.update({ where: { id: orgId }, data: { biometricsEnabled: true, biometricsLegalBasis: "teste" } });
|
||||
const source = await connect();
|
||||
cloud.authorised = true;
|
||||
await ctx.app.inject({ method: "GET", url: `/v1/cloud-sources/${source.id}`, headers: bearer(token) });
|
||||
await worker.scan(source.id);
|
||||
for (const id of await worker.claim(10)) await worker.index(id);
|
||||
|
||||
const photo = await ctx.db.photo.findFirstOrThrow({ where: { originalName: "PS_0001.jpg" } });
|
||||
const martim = await ctx.db.person.create({
|
||||
data: { organizationId: orgId, name: "Martim Costa", club: "Sporting CP", number: "21", centroid: faceVec(1), model: "auraface-v1" },
|
||||
});
|
||||
const group = await ctx.db.faceGroup.create({
|
||||
data: { organizationId: orgId, eventId: photo.eventId!, centroid: faceVec(1, 2), model: "auraface-v1", size: 1, personId: martim.id },
|
||||
});
|
||||
await ctx.db.face.create({
|
||||
data: {
|
||||
organizationId: orgId,
|
||||
photoId: photo.id,
|
||||
groupId: group.id,
|
||||
x0: 0.4,
|
||||
y0: 0.2,
|
||||
x1: 0.5,
|
||||
y1: 0.35,
|
||||
score: 0.9,
|
||||
sharpness: 120,
|
||||
embedding: faceVec(1, 3),
|
||||
model: "auraface-v1",
|
||||
},
|
||||
});
|
||||
|
||||
const po01 = cloud.idOf("/FPA/Fotos/2025_2026/Competições Nacionais/PO01");
|
||||
cloud.viewers.set("abc", { password: "abc-pass", shared: [po01], edit: [po01] });
|
||||
cloud.viewers.set("leitor", { password: "l-pass", shared: [po01] });
|
||||
const signIn = async (who: string) => {
|
||||
cloud.loginAs = who;
|
||||
cloud.authorised = false;
|
||||
const { state } = (await ctx.app.inject({ method: "POST", url: `/v1/archive/${source.id}/login` })).json() as { state: string };
|
||||
cloud.authorised = true;
|
||||
return ((await ctx.app.inject({ method: "POST", url: "/v1/archive/login/poll", payload: { state } })).json() as { token: string }).token;
|
||||
};
|
||||
const as = (t: string) => ({ authorization: `Archive ${t}` });
|
||||
const editor = await signIn("abc");
|
||||
const reader = await signIn("leitor");
|
||||
|
||||
expect((await ctx.app.inject({ method: "GET", url: `/v1/archive/${source.id}/me`, headers: as(editor) })).json()).toMatchObject({ canFind: true, canReview: true });
|
||||
expect((await ctx.app.inject({ method: "GET", url: `/v1/archive/${source.id}/me`, headers: as(reader) })).json()).toMatchObject({ canFind: false });
|
||||
|
||||
const probe = await sharp({ create: { width: 800, height: 1000, channels: 3, background: "#777" } }).jpeg().toBuffer();
|
||||
const multipart = (data: Buffer) => {
|
||||
const boundary = "----pr-find";
|
||||
const head = Buffer.from(`--${boundary}\r\nContent-Disposition: form-data; name="file"; filename="retrato.jpg"\r\nContent-Type: image/jpeg\r\n\r\n`);
|
||||
return { payload: Buffer.concat([head, data, Buffer.from(`\r\n--${boundary}--\r\n`)]), type: `multipart/form-data; boundary=${boundary}` };
|
||||
};
|
||||
findEngine.next = {
|
||||
width: 800,
|
||||
height: 1000,
|
||||
faces: [{ x0: 0.3, y0: 0.2, x1: 0.7, y1: 0.6, score: 0.95, sharpness: 300, landmarks: [], embedding: faceVec(1) }],
|
||||
};
|
||||
const mp = multipart(probe);
|
||||
let res = await ctx.app.inject({ method: "POST", url: `/v1/archive/${source.id}/find`, headers: { ...as(editor), "content-type": mp.type }, payload: mp.payload });
|
||||
expect(res.statusCode).toBe(200);
|
||||
const body = res.json() as { people: { name: string }[]; photos: { id: string }[]; total: number };
|
||||
expect(body.people[0]?.name).toBe("Martim Costa");
|
||||
expect(body.photos.map((p) => p.id)).toContain(photo.id);
|
||||
|
||||
res = await ctx.app.inject({ method: "POST", url: `/v1/archive/${source.id}/find`, headers: { ...as(reader), "content-type": mp.type }, payload: mp.payload });
|
||||
expect(res.statusCode).toBe(403);
|
||||
|
||||
await ctx.app.inject({ method: "PATCH", url: `/v1/cloud-sources/${source.id}`, headers: bearer(token), payload: { photoFindEnabled: false } });
|
||||
res = await ctx.app.inject({ method: "POST", url: `/v1/archive/${source.id}/find`, headers: { ...as(editor), "content-type": mp.type }, payload: mp.payload });
|
||||
expect(res.statusCode).toBe(409);
|
||||
expect(res.json()).toMatchObject({ error: "find_unavailable" });
|
||||
expect((await ctx.app.inject({ method: "GET", url: `/v1/archive/${source.id}/me`, headers: as(editor) })).json()).toMatchObject({ canFind: false });
|
||||
});
|
||||
|
||||
it("gives the archive's site its owner's look, which can be changed", async () => {
|
||||
const source = await connect();
|
||||
cloud.authorised = true;
|
||||
let res = await ctx.app.inject({ method: "GET", url: `/v1/cloud-sources/${source.id}`, headers: bearer(token) });
|
||||
expect(res.json()).toMatchObject({ look: "fpa" });
|
||||
expect(res.json()).toMatchObject({ look: "fpa", photoFindEnabled: true });
|
||||
expect((await ctx.app.inject({ method: "GET", url: `/v1/archive/${source.id}` })).json()).toMatchObject({ look: "fpa", name: "Cloud FPA" });
|
||||
res = await ctx.app.inject({ method: "PATCH", url: `/v1/cloud-sources/${source.id}`, headers: bearer(token), payload: { look: "liga" } });
|
||||
expect(res.json()).toMatchObject({ look: "liga" });
|
||||
|
||||
@@ -455,23 +455,98 @@ describe("delivery", () => {
|
||||
expect((localOnly.json() as { localFolder: null }).localFolder).toBeNull();
|
||||
});
|
||||
|
||||
it("waits a little for the faces to be read before sending, so the names go with the photo", async () => {
|
||||
it("a send the photographer asked for does not wait for faces", async () => {
|
||||
const { orgId, token, target } = await setup();
|
||||
await ctx.db.organization.update({ where: { id: orgId }, data: { biometricsEnabled: true, biometricsLegalBasis: "test" } });
|
||||
const id = await photo("faces.jpg", "2026:09:23 21:10:00");
|
||||
const id = await photo("faces-manual.jpg", "2026:09:23 21:10:00");
|
||||
await ctx.db.photo.update({ where: { id }, data: { facesStatus: "PENDING" } });
|
||||
await ctx.app.inject({ method: "POST", url: `/v1/orgs/${orgId}/deliveries`, headers: bearer(token), payload: { targetId: target.id, photoIds: [id] } });
|
||||
await drain();
|
||||
expect(nc.files.size).toBe(1);
|
||||
const item = await ctx.db.deliveryItem.findFirstOrThrow({ where: { photoId: id, targetId: target.id } });
|
||||
expect(item.lastError).not.toBe("waiting_for_faces");
|
||||
});
|
||||
|
||||
it("a destination with waitForFaces waits while faces are being read when the pad needs player names", async () => {
|
||||
const { orgId, token, eventId } = await setup();
|
||||
await ctx.db.organization.update({ where: { id: orgId }, data: { biometricsEnabled: true, biometricsLegalBasis: "test" } });
|
||||
const created = await ctx.app.inject({
|
||||
method: "POST",
|
||||
url: `/v1/orgs/${orgId}/delivery-targets`,
|
||||
headers: bearer(token),
|
||||
payload: {
|
||||
name: "Backup faces",
|
||||
kind: "NEXTCLOUD",
|
||||
baseUrl: "https://cloud.test",
|
||||
username: "photoreport",
|
||||
password: "app-password-123",
|
||||
folderTemplate: "/Backup/{event}/",
|
||||
fileNameTemplate: "{originalName}",
|
||||
waitForFaces: true,
|
||||
},
|
||||
});
|
||||
expect(created.statusCode).toBe(201);
|
||||
const targetId = (created.json() as { id: string }).id;
|
||||
const id = await photo("faces-arrival.jpg", "2026:09:23 21:10:00");
|
||||
await ctx.db.photo.update({ where: { id }, data: { facesStatus: "PENDING", eventId } });
|
||||
await ctx.app.inject({ method: "POST", url: `/v1/orgs/${orgId}/deliveries`, headers: bearer(token), payload: { targetId, photoIds: [id] } });
|
||||
const [itemId] = await delivery.claim(10);
|
||||
const waiting = await delivery.process(itemId!);
|
||||
expect([waiting.status, waiting.lastError, waiting.attempts]).toEqual(["QUEUED", "waiting_for_faces", 0]);
|
||||
expect(nc.files.size).toBe(0);
|
||||
// Read: it goes.
|
||||
await ctx.db.photo.update({ where: { id }, data: { facesStatus: "DONE" } });
|
||||
await ctx.db.deliveryItem.update({ where: { id: itemId! }, data: { nextAttemptAt: new Date() } });
|
||||
await drain();
|
||||
expect(nc.files.size).toBe(1);
|
||||
});
|
||||
|
||||
it("does not wait for faces that were never started (NONE), even with waitForFaces", async () => {
|
||||
const { orgId, token, eventId } = await setup();
|
||||
await ctx.db.organization.update({ where: { id: orgId }, data: { biometricsEnabled: true, biometricsLegalBasis: "test" } });
|
||||
const created = await ctx.app.inject({
|
||||
method: "POST",
|
||||
url: `/v1/orgs/${orgId}/delivery-targets`,
|
||||
headers: bearer(token),
|
||||
payload: {
|
||||
name: "Backup none",
|
||||
kind: "NEXTCLOUD",
|
||||
baseUrl: "https://cloud.test",
|
||||
username: "photoreport",
|
||||
password: "app-password-123",
|
||||
folderTemplate: "/Backup/{event}/",
|
||||
fileNameTemplate: "{originalName}",
|
||||
waitForFaces: true,
|
||||
},
|
||||
});
|
||||
const targetId = (created.json() as { id: string }).id;
|
||||
const id = await photo("faces-none.jpg", "2026:09:23 21:10:00");
|
||||
await ctx.db.photo.update({ where: { id }, data: { facesStatus: "NONE", eventId } });
|
||||
await ctx.app.inject({ method: "POST", url: `/v1/orgs/${orgId}/deliveries`, headers: bearer(token), payload: { targetId, photoIds: [id] } });
|
||||
await drain();
|
||||
const item = await ctx.db.deliveryItem.findFirstOrThrow({ where: { photoId: id, targetId } });
|
||||
expect(item.lastError).not.toBe("waiting_for_faces");
|
||||
expect(nc.files.size).toBe(1);
|
||||
});
|
||||
|
||||
it("Enviar originais forces the camera file even when the destination resizes", async () => {
|
||||
const { orgId, token, target } = await setup();
|
||||
const id = await photo("orig.jpg", "2026:09:23 21:10:00", { width: 1200, height: 800 });
|
||||
await ctx.app.inject({
|
||||
method: "POST",
|
||||
url: `/v1/orgs/${orgId}/deliveries`,
|
||||
headers: bearer(token),
|
||||
payload: { targetId: target.id, photoIds: [id], originals: true },
|
||||
});
|
||||
await drain();
|
||||
const item = await ctx.db.deliveryItem.findFirstOrThrow({ where: { photoId: id, targetId: target.id } });
|
||||
expect(item.forceOriginals).toBe(true);
|
||||
expect(item.status).toBe("DONE");
|
||||
const [buf] = [...nc.files.values()];
|
||||
const meta = await sharp(buf!).metadata();
|
||||
expect(meta.width).toBe(1200);
|
||||
expect(meta.height).toBe(800);
|
||||
});
|
||||
|
||||
it("an IPTC change in the Info window sends the photo again where it went, replacing the old file", async () => {
|
||||
const { orgId, token, target } = await setup();
|
||||
const id = await photo("info.jpg", "2026:09:23 21:10:00");
|
||||
@@ -571,6 +646,12 @@ describe("delivery", () => {
|
||||
expect(zz.uploads.get(resent.remotePath!.split("/")[1]!)!.meta.filename).toBe(zz.uploads.get(itemA.remotePath!.split("/")[1]!)!.meta.filename);
|
||||
expect(await delivery.queueEdited()).toBe(0);
|
||||
|
||||
// A reject that bypassed the library PATCH (flag flipped in the DB) is still taken back on the next sweep.
|
||||
await ctx.db.photo.update({ where: { id: b }, data: { flag: "REJECT" } });
|
||||
expect(await delivery.queueOrphanRetracts()).toBe(1);
|
||||
expect(await ctx.db.deliveryItem.findFirstOrThrow({ where: { photoId: b } })).toMatchObject({ status: "QUEUED", retract: true });
|
||||
expect(await delivery.queueOrphanRetracts()).toBe(0);
|
||||
|
||||
// A wrong password stops at once, with the desk's message.
|
||||
await ctx.app.inject({ method: "PATCH", url: `/v1/orgs/${orgId}/delivery-targets/${targetId}`, headers: bearer(token), payload: { password: "errada" } });
|
||||
const failed = await ctx.app.inject({ method: "POST", url: `/v1/orgs/${orgId}/delivery-targets/${targetId}/test`, headers: bearer(token) });
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import Fastify from "fastify";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { DesktopReleases, newer } from "../src/desktop/updates.js";
|
||||
import { DesktopReleases, newer, registerDesktopRoutes, signedVersion } from "../src/desktop/updates.js";
|
||||
|
||||
const API = "https://git.example/api/v1/repos/o/r";
|
||||
|
||||
@@ -27,6 +28,51 @@ describe("desktop updates", () => {
|
||||
expect(newer("1.0.0", "1.0.0-beta.2")).toBe(true);
|
||||
});
|
||||
|
||||
it("reads the version Tauri embeds in a signature trusted comment", () => {
|
||||
const sig = Buffer.from("trusted comment: timestamp:1\tfile:PhotoReport.app.tar.gz\tversion:0.3.24\n").toString("base64");
|
||||
expect(signedVersion(sig)).toBe("0.3.24");
|
||||
expect(signedVersion("dW50cnVzdGVkIGNvbW1lbnQ6IHNpZw==")).toBeNull();
|
||||
});
|
||||
|
||||
it("skips a release whose manifest version disagrees with the signature (re-tagged build)", async () => {
|
||||
const badSig = Buffer.from("trusted comment: timestamp:1\tfile:PhotoReport.app.tar.gz\tversion:0.3.24\n").toString("base64");
|
||||
const goodSig = Buffer.from("trusted comment: timestamp:2\tfile:PhotoReport.app.tar.gz\tversion:0.3.25\n").toString("base64");
|
||||
const releases = [
|
||||
{
|
||||
id: 20,
|
||||
tag_name: "desktop-v0.3.25",
|
||||
draft: false,
|
||||
prerelease: false,
|
||||
body: "",
|
||||
published_at: null,
|
||||
assets: [asset(1, "update-darwin-universal.json"), asset(2, "PhotoReport.app.tar.gz"), asset(3, "PhotoReport_0.3.24_universal.dmg")],
|
||||
},
|
||||
{
|
||||
id: 19,
|
||||
tag_name: "desktop-v0.3.24",
|
||||
draft: false,
|
||||
prerelease: false,
|
||||
body: "ok",
|
||||
published_at: null,
|
||||
assets: [asset(10, "update-darwin-universal.json"), asset(11, "PhotoReport.app.tar.gz"), asset(12, "PhotoReport_0.3.24_universal.dmg")],
|
||||
},
|
||||
];
|
||||
const files: Record<string, unknown> = {
|
||||
// First download is the bad 0.3.25 manifest (same filename across releases; fake fetch keys by basename).
|
||||
"update-darwin-universal.json": { version: "0.3.25", file: "PhotoReport.app.tar.gz", signature: badSig },
|
||||
"PhotoReport.app.tar.gz": "bytes",
|
||||
};
|
||||
const r = new DesktopReleases({ api: API, token: "t" }, fakeGitea(releases, files).impl);
|
||||
// Bad newest release is skipped; nothing older matches 0.3.25 either with this stub, so null — then swap to good.
|
||||
expect(await r.updateFor("darwin", "aarch64", "0.3.24")).toBeNull();
|
||||
files["update-darwin-universal.json"] = { version: "0.3.25", file: "PhotoReport.app.tar.gz", signature: goodSig };
|
||||
const r2 = new DesktopReleases({ api: API, token: "t" }, fakeGitea(releases, files).impl);
|
||||
expect(await r2.updateFor("darwin", "aarch64", "0.3.24")).toMatchObject({
|
||||
version: "0.3.25",
|
||||
installer: "/v1/desktop/download/20/PhotoReport_0.3.24_universal.dmg",
|
||||
});
|
||||
});
|
||||
|
||||
it("answers with the newest desktop release for the platform, through the API, and nothing when up to date", async () => {
|
||||
const releases = [
|
||||
{ id: 7, tag_name: "desktop-v0.3.0", draft: false, prerelease: false, body: "Catálogo local", published_at: "2026-10-13T09:00:00Z", assets: [asset(1, "update-darwin-universal.json"), asset(2, "PhotoReport_universal.app.tar.gz"), asset(4, "PhotoReport_0.3.0_universal.dmg")] },
|
||||
@@ -70,4 +116,16 @@ describe("desktop updates", () => {
|
||||
expect(await r.updateFor("darwin", "aarch64", "0.3.2")).toMatchObject({ version: "0.3.4", url: "/v1/desktop/download/11/PhotoReport.app.tar.gz" });
|
||||
expect(await r.file(11, "PhotoReport.app.tar.gz")).not.toBeNull();
|
||||
});
|
||||
|
||||
it("answers 503 instead of crashing the route when Gitea is unreachable (BIT-31961)", async () => {
|
||||
const releases = new DesktopReleases({ api: API, token: "t" }, async () => {
|
||||
throw new TypeError("fetch failed");
|
||||
});
|
||||
const app = Fastify({ logger: false });
|
||||
await registerDesktopRoutes(app, { releases, publicApiUrl: "https://app.example" });
|
||||
|
||||
const res = await app.inject({ method: "GET", url: "/v1/desktop/download/7/PhotoReport_universal.app.tar.gz" });
|
||||
expect(res.statusCode).toBe(503);
|
||||
expect(res.json()).toEqual({ error: "download_unavailable" });
|
||||
});
|
||||
});
|
||||
@@ -3,6 +3,7 @@ import { hashPassword } from "../src/auth/passwords.js";
|
||||
import { buildApp } from "../src/app.js";
|
||||
import { loadConfig, type Config } from "../src/config.js";
|
||||
import { createDb, type Db } from "../src/db.js";
|
||||
import type { FaceEngine } from "../src/faces/process.js";
|
||||
import type { Role } from "../src/generated/prisma/client.js";
|
||||
import type { Broadcaster } from "../src/realtime.js";
|
||||
import { assertTestDatabase } from "./guard.js";
|
||||
@@ -13,7 +14,13 @@ export interface TestContext {
|
||||
config: Config;
|
||||
}
|
||||
|
||||
export async function createTestApp(overrides: Record<string, string> = {}, realtime?: Broadcaster, fetchImpl?: typeof fetch, engineOnline?: () => boolean): Promise<TestContext> {
|
||||
export async function createTestApp(
|
||||
overrides: Record<string, string> = {},
|
||||
realtime?: Broadcaster,
|
||||
fetchImpl?: typeof fetch,
|
||||
engineOnline?: () => boolean,
|
||||
faceEngine?: FaceEngine,
|
||||
): Promise<TestContext> {
|
||||
const config = loadConfig({
|
||||
NODE_ENV: "test",
|
||||
DATABASE_URL: assertTestDatabase(process.env.DATABASE_URL_TEST),
|
||||
@@ -23,7 +30,14 @@ export async function createTestApp(overrides: Record<string, string> = {}, real
|
||||
...overrides,
|
||||
});
|
||||
const db = createDb(config.DATABASE_URL);
|
||||
const app = await buildApp({ config, db, ...(realtime && { realtime }), ...(fetchImpl && { fetchImpl }), ...(engineOnline && { engineOnline }) });
|
||||
const app = await buildApp({
|
||||
config,
|
||||
db,
|
||||
...(realtime && { realtime }),
|
||||
...(fetchImpl && { fetchImpl }),
|
||||
...(engineOnline && { engineOnline }),
|
||||
...(faceEngine && { faceEngine }),
|
||||
});
|
||||
return { app, db, config };
|
||||
}
|
||||
|
||||
|
||||
@@ -160,10 +160,10 @@ describe("library", () => {
|
||||
expect(forged.statusCode).toBe(404);
|
||||
});
|
||||
|
||||
it("sends a login's photos to the event chosen by hand, whatever the camera's clock, until switched off", async () => {
|
||||
it("FTP pin keeps shots inside its window; shots from another event's time still follow the clock", async () => {
|
||||
const { orgId, admin, foto, other, event } = await setup();
|
||||
const until = new Date(Date.now() + 3600_000).toISOString();
|
||||
const press = (await ctx.app.inject({ method: "POST", url: `/v1/orgs/${orgId}/events`, headers: bearer(admin), payload: { home: "Conferência de imprensa", startsAt: new Date().toISOString(), photographerIds: [] } })).json() as { id: string };
|
||||
const press = (await ctx.app.inject({ method: "POST", url: `/v1/orgs/${orgId}/events`, headers: bearer(admin), payload: { home: "Conferência de imprensa", startsAt: "2026-10-14T10:00:00Z", photographerIds: [] } })).json() as { id: string };
|
||||
await ctx.app.inject({ method: "POST", url: `/v1/orgs/${orgId}/ftp-accounts`, headers: bearer(admin), payload: { userId: other.id, login: "outro.r1" } });
|
||||
// The photographer sees only their own login; the editor sees all.
|
||||
let res = await ctx.app.inject({ method: "GET", url: `/v1/events/${event.id}/ftp-target`, headers: bearer(foto) });
|
||||
@@ -178,8 +178,10 @@ describe("library", () => {
|
||||
res = await ctx.app.inject({ method: "PUT", url: `/v1/events/${press.id}/ftp-target`, headers: bearer(admin), payload: { accountIds: [mine[0]!.id], until } });
|
||||
expect(res.json()).toMatchObject({ ftpTargets: [{ login: "foto.r1", until }] });
|
||||
expect(((await ctx.app.inject({ method: "GET", url: `/v1/events/${event.id}/ftp-target`, headers: bearer(foto) })).json() as { accounts: { elsewhere: { id: string } | null }[] }).accounts[0]!.elsewhere).toMatchObject({ id: press.id });
|
||||
// Taken during the game, but sent while the login points at the press conference: it goes there.
|
||||
expect(await service.ingestFile(await drop("foto.r1", "a.jpg", await jpeg({ color: "#123456" })))).toMatchObject({ status: "ingested", eventId: press.id });
|
||||
// Taken during the press (pin window): press gets it.
|
||||
expect(await service.ingestFile(await drop("foto.r1", "a.jpg", await jpeg({ color: "#123456", taken: "2026:10:14 10:15:00" })))).toMatchObject({ status: "ingested", eventId: press.id });
|
||||
// Taken during the game, pin still on press: clock wins — pin must not swallow another session.
|
||||
expect(await service.ingestFile(await drop("foto.r1", "game.jpg", await jpeg({ color: "#abcdef" })))).toMatchObject({ status: "ingested", eventId: event.id });
|
||||
|
||||
// Switched off: by the time again.
|
||||
await ctx.app.inject({ method: "PUT", url: `/v1/events/${press.id}/ftp-target`, headers: bearer(admin), payload: { accountIds: [] } });
|
||||
@@ -189,6 +191,41 @@ describe("library", () => {
|
||||
expect(await service.ingestFile(await drop("foto.r1", "c.jpg", await jpeg({ color: "#665544" })))).toMatchObject({ status: "ingested", eventId: event.id });
|
||||
});
|
||||
|
||||
it("when two ingest windows overlap, files the photo in the event whose start is closest to the capture", async () => {
|
||||
const { orgId, admin, photographer } = await setup();
|
||||
const miguel = (
|
||||
await ctx.app.inject({
|
||||
method: "POST",
|
||||
url: `/v1/orgs/${orgId}/events`,
|
||||
headers: bearer(admin),
|
||||
payload: { home: "Miguel em estúdio", startsAt: "2026-11-03T14:00:00Z", photographerIds: [photographer.id] },
|
||||
})
|
||||
).json() as { id: string };
|
||||
const sub21 = (
|
||||
await ctx.app.inject({
|
||||
method: "POST",
|
||||
url: `/v1/orgs/${orgId}/events`,
|
||||
headers: bearer(admin),
|
||||
payload: { home: "Treino Sub-21", startsAt: "2026-11-03T16:30:00Z", photographerIds: [photographer.id] },
|
||||
})
|
||||
).json() as { id: string };
|
||||
// Widen windows so they overlap (default is −2h/+4h: Miguel until 18:00, Sub-21 from 14:30).
|
||||
await ctx.db.event.update({ where: { id: miguel.id }, data: { ingestFrom: new Date("2026-11-03T12:00:00Z"), ingestUntil: new Date("2026-11-03T18:00:00Z") } });
|
||||
await ctx.db.event.update({ where: { id: sub21.id }, data: { ingestFrom: new Date("2026-11-03T14:30:00Z"), ingestUntil: new Date("2026-11-03T20:30:00Z") } });
|
||||
|
||||
const send = async (name: string, taken: string, pin?: string) => {
|
||||
const file = path.join(dir, name);
|
||||
await writeFile(file, await jpeg({ color: "#778899", taken }));
|
||||
return service.ingest(file, { organizationId: orgId, userId: photographer.id, source: "DESKTOP", originalName: name, eventId: pin });
|
||||
};
|
||||
// 14:20: only Miguel — Sub-21 pin must not take it.
|
||||
expect(await send("studio.jpg", "2026:11:03 14:20:00", sub21.id)).toMatchObject({ status: "ingested", eventId: miguel.id });
|
||||
// 15:00 overlap, no pin: closest start is Miguel.
|
||||
expect(await send("overlap.jpg", "2026:11:03 15:00:00")).toMatchObject({ status: "ingested", eventId: miguel.id });
|
||||
// 16:40: Sub-21.
|
||||
expect(await send("treino.jpg", "2026:11:03 16:40:00")).toMatchObject({ status: "ingested", eventId: sub21.id });
|
||||
});
|
||||
|
||||
it("a pin left on a game already put away does not take photos shot for the next event", async () => {
|
||||
const { orgId, admin, photographer, event } = await setup();
|
||||
await ctx.db.event.update({ where: { id: event.id }, data: { archivedAt: new Date("2026-10-19T10:40:00Z") } });
|
||||
@@ -210,6 +247,21 @@ describe("library", () => {
|
||||
expect(await send("today.jpg", "2026:10:19 12:05:00")).toMatchObject({ status: "ingested", eventId: press.id });
|
||||
});
|
||||
|
||||
it("a pin does not keep photos after a one-hour shooting pause (open ingest window)", async () => {
|
||||
const { orgId, photographer, event } = await setup();
|
||||
// Window still open for both bursts — only the gap must end the session.
|
||||
await ctx.db.event.update({ where: { id: event.id }, data: { ingestUntil: new Date("2026-09-24T06:00:00Z") } });
|
||||
const send = async (name: string, taken: string) => {
|
||||
const file = path.join(dir, name);
|
||||
await writeFile(file, await jpeg({ color: "#445566", taken }));
|
||||
return service.ingest(file, { organizationId: orgId, userId: photographer.id, source: "DESKTOP", originalName: name, eventId: event.id });
|
||||
};
|
||||
expect(await send("a.jpg", "2026:09:23 20:00:00")).toMatchObject({ status: "ingested", eventId: event.id });
|
||||
expect(await send("b.jpg", "2026:09:23 20:45:00")).toMatchObject({ status: "ingested", eventId: event.id });
|
||||
// >1 h after the last shot: not the same session → Sem evento (no other event fits).
|
||||
expect(await send("c.jpg", "2026:09:23 22:00:00")).toMatchObject({ status: "ingested", eventId: null });
|
||||
});
|
||||
|
||||
it("an archive import stays in its put-away event when the photo was taken outside that window", async () => {
|
||||
const { orgId, admin, photographer, event } = await setup();
|
||||
await ctx.db.event.update({ where: { id: event.id }, data: { archivedAt: new Date("2026-09-24T00:00:00Z") } });
|
||||
@@ -388,6 +440,27 @@ describe("library", () => {
|
||||
expect((await ctx.db.photo.findUnique({ where: { id: photoId } }))?.eventId).toBe(otherId);
|
||||
});
|
||||
|
||||
it("takes a delivered file back when the photo is rejected or un-picked", async () => {
|
||||
const { orgId, admin, event } = await setup();
|
||||
const a = (await service.ingestFile(await drop("foto.r1", "a.jpg", await jpeg({ color: "#111111" })))) as { photoId: string };
|
||||
const b = (await service.ingestFile(await drop("foto.r1", "b.jpg", await jpeg({ color: "#222222" })))) as { photoId: string };
|
||||
await ctx.db.photo.updateMany({ where: { id: { in: [a.photoId, b.photoId] } }, data: { eventId: event.id, flag: "PICK" } });
|
||||
const target = await ctx.db.deliveryTarget.create({
|
||||
data: { organizationId: orgId, name: "FPA", kind: "NEXTCLOUD", baseUrl: "https://cloud.photoreport.pt", username: "fpa", secretEnc: "sealed", folderTemplate: "/{event}/", fileNameTemplate: "{n}.jpg" },
|
||||
});
|
||||
const [itemA, itemB] = await Promise.all(
|
||||
[a.photoId, b.photoId].map((photoId, i) =>
|
||||
ctx.db.deliveryItem.create({
|
||||
data: { organizationId: orgId, targetId: target.id, photoId, eventId: event.id, sequence: i + 1, status: "DONE", remotePath: `/${i + 1}.jpg` },
|
||||
}),
|
||||
),
|
||||
);
|
||||
expect((await ctx.app.inject({ method: "PATCH", url: `/v1/orgs/${orgId}/photos`, headers: bearer(admin), payload: { ids: [a.photoId], patch: { flag: "REJECT" } } })).statusCode).toBe(200);
|
||||
expect(await ctx.db.deliveryItem.findUnique({ where: { id: itemA.id } })).toMatchObject({ status: "QUEUED", retract: true });
|
||||
expect((await ctx.app.inject({ method: "PATCH", url: `/v1/orgs/${orgId}/photos`, headers: bearer(admin), payload: { ids: [b.photoId], patch: { flag: "NONE" } } })).statusCode).toBe(200);
|
||||
expect(await ctx.db.deliveryItem.findUnique({ where: { id: itemB.id } })).toMatchObject({ status: "QUEUED", retract: true });
|
||||
});
|
||||
|
||||
it("previews the IPTC a delivery will write, with codes and identified players", async () => {
|
||||
const { orgId, admin } = await setup();
|
||||
const saved = await ctx.app.inject({ method: "PUT", url: `/v1/orgs/${orgId}/code-list`, headers: bearer(admin), payload: { content: "v7\tMiguel Silva (VSC)\nbad\n" } });
|
||||
|
||||
@@ -5,7 +5,7 @@ import { CodeGeneratorSettings } from "@photoreport/contracts";
|
||||
import sharp from "sharp";
|
||||
import { afterAll, beforeAll, beforeEach, describe, expect, it } from "vitest";
|
||||
import { BLOCK_START, buildCodeLines, mergeGenerated, teamPrefix, toTsv } from "../src/sports/codegen.js";
|
||||
import { type Fetch, fpaProva, fpaShortName, fpfDate, lisbonTime, parseFpaBoletim, parseFpaClubTerms, parseFpaMatchPage, parseFpaReferees, parseFpfLineups, seasonOf } from "../src/sports/providers.js";
|
||||
import { type Fetch, fpaEpochFor, fpaProva, fpaShortName, fpfDate, lisbonTime, parseFpaBoletim, parseFpaClubTerms, parseFpaMatchPage, parseFpaReferees, parseFpfLineups, seasonOf } from "../src/sports/providers.js";
|
||||
import { SportsService } from "../src/sports/service.js";
|
||||
import { LocalStorage } from "../src/storage/storage.js";
|
||||
import { bearer, createTestApp, login, resetDb, seedUser, type TestContext } from "./helpers.js";
|
||||
@@ -56,6 +56,8 @@ describe("federation data", () => {
|
||||
expect(lisbonTime("2026-12-01").timeKnown).toBe(false);
|
||||
expect(seasonOf(new Date("2026-10-13"))).toBe("20262027");
|
||||
expect(seasonOf(new Date("2027-03-01"))).toBe("20262027");
|
||||
expect(fpaEpochFor(new Date("2026-10-27T12:00:00Z"))).toBe("374");
|
||||
expect(fpaEpochFor(new Date("2026-03-01T12:00:00Z"))).toBe("373");
|
||||
});
|
||||
|
||||
it("reads the FPA match report: numbers and licences, the officials' letters, the referees", () => {
|
||||
@@ -243,6 +245,15 @@ const fakeSites = (state: { benfica: { shirtNumber: number; name: string; photos
|
||||
"utf8",
|
||||
),
|
||||
);
|
||||
if (state.handball && u.host === "portal.fpa.pt" && u.pathname === "/associado/198159/") return bytes(Buffer.from(MEMBER_PAGE, "utf8"));
|
||||
if (state.handball && u.host === "ws.fpa.pt" && u.pathname === "/index.php/getCipaInscricoes/203445") return json(MEMBER_REGISTRATIONS);
|
||||
// Full club register (every associate, not only the match sheet): Vitória club 140, season 374.
|
||||
if (state.handball && u.host === "ws.fpa.pt" && u.pathname === "/index.php/getCipClubeEpoca/140/374")
|
||||
return json([
|
||||
{ CIP_NUMERO: "100001", CIP_NOME: "Rui Manuel Sousa Lopes", ID_CIPA: "370001", ATLETA: "S", TECNICO: null, OFICIAL: null, ARBITRO: null, URL_FOTO: "https://si.fpa.pt/blob/obj_anexo/FOTO_CIPA/1_370001.JPG" },
|
||||
{ CIP_NUMERO: "250001", CIP_NOME: "Ana Filipa Mendes Costa", ID_CIPA: "370999", ATLETA: null, TECNICO: "S", OFICIAL: null, ARBITRO: null, URL_FOTO: "https://si.fpa.pt/blob/obj_anexo/FOTO_CIPA/2_370999.JPG" },
|
||||
]);
|
||||
if (state.handball && u.host === "ws.fpa.pt" && u.pathname.includes("getCipClubeEpoca")) return json([]);
|
||||
const licence = /^\/associado\/(100001|185283)\/$/.exec(u.pathname)?.[1];
|
||||
if (state.handball && u.host === "portal.fpa.pt" && licence)
|
||||
return bytes(Buffer.from(`<html><body><img src="https://si.fpa.pt/blob/obj_anexo/FOTO_CIPA/555_${licence}.JPG"></body></html>`, "utf8"));
|
||||
@@ -341,6 +352,7 @@ describe("sports data service", () => {
|
||||
});
|
||||
beforeEach(async () => {
|
||||
await resetDb(ctx.db);
|
||||
sports.resetFpaClocks();
|
||||
state.handball = false;
|
||||
state.benfica = [
|
||||
{ shirtNumber: 14, name: "Vangelis Pavlidis", photos: "https://www.ligaportugal.pt/p/pavlidis.png" },
|
||||
@@ -479,6 +491,55 @@ describe("sports data service", () => {
|
||||
expect((await ctx.app.inject({ method: "POST", url: `/v1/orgs/${org!.id}/events`, headers: bearer(token), payload: { home: "a", away: "b", startsAt: fixture.startsAt, homeTeamId: org!.id } })).statusCode).toBe(400);
|
||||
});
|
||||
|
||||
it("FPA: a person from their licence number (name, latest role, licence photo), the same one on match reports", async () => {
|
||||
state.handball = true;
|
||||
const { org } = await seedUser(ctx.db, "[email protected]", { org: "fpa", role: "OWNER" });
|
||||
await ctx.db.organization.update({ where: { id: org!.id }, data: { biometricsEnabled: true } });
|
||||
const member = await sports.fpa.member("198159");
|
||||
expect(member).toMatchObject({ name: "Maria Ema Bastos Silva", internalId: "203445", photo: "https://si.fpa.pt/blob/obj_anexo/FOTO_CIPA/636722_203445.JPG" });
|
||||
expect(member!.registrations.map((r) => [r.season, r.kind, r.club])).toEqual([
|
||||
["2010/11", "athlete", "ADA CANELAS"],
|
||||
["2024/25", "coach", "ESTARREJA AC"],
|
||||
["2025/26", "official", "Sel.Nac.M"],
|
||||
]);
|
||||
expect(await sports.fpa.member("99999999")).toBeNull();
|
||||
const first = await sports.personFromFpaLicence(org!.id, "198159");
|
||||
expect(first).toMatchObject({ created: true, reference: true, person: { name: "Maria Silva", club: "Seleção Nacional Masculina" } });
|
||||
const again = await sports.personFromFpaLicence(org!.id, "198159");
|
||||
expect(again).toMatchObject({ created: false, person: { id: first.person.id } });
|
||||
expect((await ctx.db.person.findUniqueOrThrow({ where: { id: first.person.id } })).licence).toBe("198159");
|
||||
});
|
||||
|
||||
it("FPA: the whole club register (getCipClubeEpoca) becomes people with licence photos, not only match-sheet names", async () => {
|
||||
state.handball = true;
|
||||
const { org } = await seedUser(ctx.db, "[email protected]", { org: "fpa-reg", role: "OWNER" });
|
||||
await ctx.db.organization.update({ where: { id: org!.id }, data: { biometricsEnabled: true } });
|
||||
const list = await sports.fpa.clubAssociates("140", "374");
|
||||
expect(list).toEqual([
|
||||
{ licence: "100001", internalId: "370001", name: "Rui Manuel Sousa Lopes", photo: "https://si.fpa.pt/blob/obj_anexo/FOTO_CIPA/1_370001.JPG", kind: "athlete" },
|
||||
{ licence: "250001", internalId: "370999", name: "Ana Filipa Mendes Costa", photo: "https://si.fpa.pt/blob/obj_anexo/FOTO_CIPA/2_370999.JPG", kind: "coach" },
|
||||
]);
|
||||
const r = await sports.refreshFpa(now);
|
||||
expect(r.errors).toEqual([]);
|
||||
const coach = await ctx.db.person.findUnique({ where: { organizationId_licence: { organizationId: org!.id, licence: "250001" } } });
|
||||
expect(coach).toMatchObject({ name: "Ana Costa", licence: "250001" });
|
||||
expect(coach!.referenceKey).toBeTruthy();
|
||||
});
|
||||
|
||||
it("FPA: two associates with the exact same name get told apart by licence, instead of a person_name_taken error", async () => {
|
||||
const { org } = await seedUser(ctx.db, "[email protected]", { org: "fpa-homonimos", role: "OWNER" });
|
||||
const first = await sports.personFromFpaAssociate(org!.id, { licence: "900001", internalId: null, name: "Maria Silva", photo: null, kind: "athlete" });
|
||||
expect(first).toMatchObject({ created: true, person: { name: "Maria Silva" } });
|
||||
const second = await sports.personFromFpaAssociate(org!.id, { licence: "900002", internalId: null, name: "Maria Silva", photo: null, kind: "athlete" });
|
||||
expect(second).toMatchObject({ created: true, person: { name: "Maria Silva (900002)" } });
|
||||
expect(second.person.id).not.toBe(first.person.id);
|
||||
const people = await ctx.db.person.findMany({ where: { organizationId: org!.id }, orderBy: { licence: "asc" } });
|
||||
expect(people.map((p) => [p.name, p.licence])).toEqual([
|
||||
["Maria Silva", "900001"],
|
||||
["Maria Silva (900002)", "900002"],
|
||||
]);
|
||||
});
|
||||
|
||||
it("keeps sports data to members and FPF links to admins", async () => {
|
||||
const { user } = await seedUser(ctx.db, "[email protected]", { org: "abola", role: "PHOTOGRAPHER" });
|
||||
const token = (await login(ctx.app, user.email)).body.accessToken;
|
||||
@@ -528,7 +589,9 @@ describe("sports data service", () => {
|
||||
expect(created.statusCode).toBe(201);
|
||||
expect((await ctx.app.inject({ method: "POST", url: `/v1/events/${created.json().id}/squads/sync`, headers: bearer(token) })).statusCode).toBe(200);
|
||||
const people = await ctx.db.person.findMany({ where: { organizationId: org!.id }, orderBy: { name: "asc" } });
|
||||
// Ana Costa comes from the club register (getCipClubeEpoca), not the match sheet — coaches and the rest of the club.
|
||||
expect(people.map((p) => [p.name, p.club, p.number, !!p.referenceKey])).toEqual([
|
||||
["Ana Costa", null, null, true],
|
||||
["Bruno Costa", "Arbitragem", null, false],
|
||||
["Carlos Mesa", "Arbitragem", null, false],
|
||||
["Duarte Sá", "Arbitragem", null, true],
|
||||
@@ -628,3 +691,12 @@ describe("sports data service", () => {
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
const MEMBER_PAGE = `<html><body><div class="association-detail"><div class="association-detail__image"><img src="https://si.fpa.pt/blob/obj_anexo/FOTO_CIPA/636722_203445.JPG"></div>
|
||||
<div class="association-detail__content"><h3>Maria Ema Bastos Silva</h3><table><tr><td>CIPA</td><td>198159</td></tr><tr><td>Inscrito como</td><td>Oficial, Técnico, Atleta</td></tr></table></div></div>
|
||||
<script>var TABLE_CONTENT_1 = {"title":"Hist\\u00f3rico","tabs":[],"cipa":"203445"};</script></body></html>`;
|
||||
const MEMBER_REGISTRATIONS = [
|
||||
{ EPO_DESCRICAO: "2010/11", GCI_TIP_INSCRICAO_TI013: "AT01", CLU_ABREV: "ADA CANELAS", CLU_NOME: "Associacao Desportiva Arsenal Canelas", ESC_DESCRICAO: "Iniciados F" },
|
||||
{ EPO_DESCRICAO: "2024/25", GCI_TIP_INSCRICAO_TI013: "TEC", CLU_ABREV: "ESTARREJA AC", CLU_NOME: "Estarreja Andebol Clube" },
|
||||
{ EPO_DESCRICAO: "2025/26", GCI_TIP_INSCRICAO_TI013: "OFI", CLU_ABREV: "Sel.Nac.M", CLU_NOME: "Selecções Nacionais Masculinas", FOF_ABREV: "DELEGADO TECNICO" },
|
||||
];
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import { t } from "../i18n.js";
|
||||
import { API_URL } from "../api.js";
|
||||
import { desktopInvoke, type Invoke, isDesktop, openExternal } from "../platform.js";
|
||||
@@ -16,35 +16,55 @@ type Listen = (event: string, handler: () => void) => Promise<() => void>;
|
||||
const tauriListen: Listen = async (event, handler) => (await import("@tauri-apps/api/event")).listen(event, handler);
|
||||
|
||||
/**
|
||||
* Desktop only: a newer interface was downloaded in the background (apps/desktop/src-tauri/src/ui.rs). It is used
|
||||
* from the next start; reloading now switches straight away (nothing is lost: edits wait in the local queue).
|
||||
* Desktop only: a newer interface was downloaded onto this computer (`ui.rs`). This is a local app — switch into
|
||||
* it at once (reload). Edits wait in the offline queue; nothing is lost. Also asks `ui_check` on open so a
|
||||
* deploy that landed while the app was closed is applied without waiting for the background timer.
|
||||
*/
|
||||
export function UiReadyNotice({ listen = tauriListen, enabled = isDesktop(), reload = () => window.location.reload() }: { listen?: Listen; enabled?: boolean; reload?: () => void }) {
|
||||
const [ready, setReady] = useState(false);
|
||||
const [dismissed, setDismissed] = useState(false);
|
||||
export function UiReadyNotice({
|
||||
listen = tauriListen,
|
||||
invoke = desktopInvoke,
|
||||
enabled = isDesktop(),
|
||||
reload = () => window.location.reload(),
|
||||
}: {
|
||||
listen?: Listen;
|
||||
invoke?: Invoke;
|
||||
enabled?: boolean;
|
||||
reload?: () => void;
|
||||
}) {
|
||||
const [applying, setApplying] = useState(false);
|
||||
const applied = useRef(false);
|
||||
|
||||
useEffect(() => {
|
||||
if (!enabled) return;
|
||||
let stop: (() => void) | undefined;
|
||||
let alive = true;
|
||||
listen("ui-ready", () => setReady(true)).then(
|
||||
const apply = () => {
|
||||
if (!alive || applied.current) return;
|
||||
applied.current = true;
|
||||
setApplying(true);
|
||||
// Let the asset provider finish switching folders before the webview asks for index.html again.
|
||||
window.setTimeout(() => reload(), 150);
|
||||
};
|
||||
listen("ui-ready", apply).then(
|
||||
(unlisten) => (alive ? (stop = unlisten) : unlisten()),
|
||||
() => {},
|
||||
);
|
||||
// Launch: pull the published interface now if this copy is behind (app-first, not "refresh the browser").
|
||||
invoke<boolean>("ui_check")
|
||||
.then((updated) => {
|
||||
if (alive && updated) apply();
|
||||
})
|
||||
.catch(() => {});
|
||||
return () => {
|
||||
alive = false;
|
||||
stop?.();
|
||||
};
|
||||
}, [enabled, listen]);
|
||||
if (!ready || dismissed) return null;
|
||||
}, [enabled, listen, invoke, reload]);
|
||||
|
||||
if (!applying) return null;
|
||||
return (
|
||||
<div role="status" className="flex flex-wrap items-center gap-3 border-b border-black bg-[#1d2a3a] px-4 py-1.5 text-[12px] text-ink">
|
||||
<span>{t.update.uiReady}</span>
|
||||
<button className="ml-auto h-7 bg-accent px-3 text-[12px] font-semibold text-white hover:bg-accent-strong" onClick={reload}>
|
||||
{t.update.reload}
|
||||
</button>
|
||||
<button className="text-faint hover:text-ink" onClick={() => setDismissed(true)} aria-label={t.update.later}>
|
||||
{t.update.later}
|
||||
</button>
|
||||
<span>{t.update.uiApplying}</span>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -38,18 +38,28 @@ describe("local catalogue", () => {
|
||||
});
|
||||
|
||||
describe("interface update notice", () => {
|
||||
it("says when a newer interface is ready and reloads into it", async () => {
|
||||
it("reloads into a newer interface as soon as it is ready (local app, not a browser tab)", async () => {
|
||||
let fire: () => void = () => {};
|
||||
const listen = vi.fn(async (_event: string, handler: () => void) => {
|
||||
fire = handler;
|
||||
return () => {};
|
||||
});
|
||||
const invoke = vi.fn(async () => false) as unknown as Invoke;
|
||||
const reload = vi.fn();
|
||||
render(<UiReadyNotice listen={listen} enabled reload={reload} />);
|
||||
render(<UiReadyNotice listen={listen} invoke={invoke} enabled reload={reload} />);
|
||||
await waitFor(() => expect(listen).toHaveBeenCalledWith("ui-ready", expect.any(Function)));
|
||||
act(() => fire());
|
||||
fireEvent.click(await screen.findByText("Recarregar agora"));
|
||||
expect(reload).toHaveBeenCalled();
|
||||
expect(await screen.findByText("A actualizar a interface da app…")).toBeTruthy();
|
||||
await waitFor(() => expect(reload).toHaveBeenCalled(), { timeout: 1000 });
|
||||
});
|
||||
|
||||
it("checks for a newer interface on launch and reloads when one was downloaded", async () => {
|
||||
const listen = vi.fn(async () => () => {});
|
||||
const invoke = vi.fn(async (cmd: string) => (cmd === "ui_check" ? true : null)) as unknown as Invoke;
|
||||
const reload = vi.fn();
|
||||
render(<UiReadyNotice listen={listen} invoke={invoke} enabled reload={reload} />);
|
||||
await waitFor(() => expect(invoke).toHaveBeenCalledWith("ui_check"));
|
||||
await waitFor(() => expect(reload).toHaveBeenCalled(), { timeout: 1000 });
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -17,6 +17,48 @@ function renderWorker(): Worker | undefined {
|
||||
}
|
||||
|
||||
let autoIds = 0;
|
||||
let exportIds = 0;
|
||||
|
||||
/** Decodes one file into the render worker. A new key replaces whatever was open. */
|
||||
export function openFrame(key: string, bytes: ArrayBuffer, maxEdge: number): Promise<void> {
|
||||
const w = renderWorker();
|
||||
if (!w) return Promise.reject(new Error("no worker"));
|
||||
return new Promise((resolve, reject) => {
|
||||
const onMessage = (e: MessageEvent<WorkerReply>) => {
|
||||
const msg = e.data;
|
||||
if (msg.type === "opened" && msg.key === key) {
|
||||
w.removeEventListener("message", onMessage);
|
||||
resolve();
|
||||
return;
|
||||
}
|
||||
if (msg.type === "error" && msg.key === key && msg.ticket === undefined) {
|
||||
w.removeEventListener("message", onMessage);
|
||||
reject(new Error(msg.message));
|
||||
}
|
||||
};
|
||||
w.addEventListener("message", onMessage);
|
||||
w.postMessage({ type: "open", key, url: "", bytes, maxEdge } satisfies WorkerRequest, [bytes]);
|
||||
});
|
||||
}
|
||||
|
||||
/** One full-size render of the photo already open in the loupe. The loupe keeps its own frame. */
|
||||
export function exportFrame(key: string, settings: string, maxW: number, maxH: number): Promise<{ width: number; height: number; pixels: Uint8ClampedArray }> {
|
||||
const w = renderWorker();
|
||||
if (!w) return Promise.reject(new Error("no worker"));
|
||||
const id = ++exportIds;
|
||||
return new Promise((resolve, reject) => {
|
||||
const onMessage = (e: MessageEvent<WorkerReply>) => {
|
||||
const msg = e.data;
|
||||
if (msg.type !== "exported" && msg.type !== "exportError") return;
|
||||
if (msg.id !== id) return;
|
||||
w.removeEventListener("message", onMessage);
|
||||
if (msg.type === "exported") resolve({ width: msg.width, height: msg.height, pixels: msg.pixels });
|
||||
else reject(new Error(msg.message));
|
||||
};
|
||||
w.addEventListener("message", onMessage);
|
||||
w.postMessage({ type: "export", id, key, settings, maxW, maxH } satisfies WorkerRequest);
|
||||
});
|
||||
}
|
||||
/**
|
||||
* Asks the render worker for automatic values computed from the open photo (tone, white balance, or the
|
||||
* eyedropper at a point of the uncropped frame). Resolves with control id -> value, ready for `develop.set`.
|
||||
@@ -59,11 +101,18 @@ interface ViewerProps {
|
||||
onError?: (message: string) => void;
|
||||
/** The original from this computer, when the desktop app has it (no download); null to use `sourceUrl`. */
|
||||
localSource?: () => Promise<ArrayBuffer | null>;
|
||||
/** Longest side to decode, when this is not the 1:1 view. The loupe still draws only what fits the screen. */
|
||||
decodeEdge?: number;
|
||||
/** 1:1 (Lightroom's Z): the photo at its own pixels, scrolled to look around, from the full-resolution original. */
|
||||
actualPixels?: boolean;
|
||||
/** Eyedropper on: a click reports where (0..1 in the shown frame). */
|
||||
picking?: boolean;
|
||||
onPick?: (u: number, v: number) => void;
|
||||
/** Remove / heal tool: a click reports where (0..1 in the shown frame). */
|
||||
spotting?: boolean;
|
||||
onSpot?: (u: number, v: number) => void;
|
||||
/** Spot pins to draw over the loupe (normalized in the shown / cropped frame). */
|
||||
spotMarks?: { u: number; v: number; size: number }[];
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -111,7 +160,7 @@ export function Viewer(props: ViewerProps) {
|
||||
if (!w) return;
|
||||
const onMessage = (e: MessageEvent<WorkerReply>) => {
|
||||
const msg = e.data;
|
||||
if (msg.type === "auto") return;
|
||||
if (msg.type === "auto" || msg.type === "exported" || msg.type === "exportError") return;
|
||||
if (msg.type === "opened") {
|
||||
if (msg.key === photoKey) {
|
||||
setOpened(msg.key);
|
||||
@@ -144,14 +193,15 @@ export function Viewer(props: ViewerProps) {
|
||||
void (async () => {
|
||||
const bytes = await (callbacks.current.localSource?.() ?? Promise.resolve(null)).catch(() => null);
|
||||
if (cancelled) return;
|
||||
const msg: WorkerRequest = { type: "open", key: photoKey, url: sourceUrl, ...(bytes && { bytes }), ...(callbacks.current.actualPixels && { maxEdge: FULL_EDGE }) };
|
||||
const edge = callbacks.current.actualPixels ? FULL_EDGE : callbacks.current.decodeEdge;
|
||||
const msg: WorkerRequest = { type: "open", key: photoKey, url: sourceUrl, ...(bytes && { bytes }), ...(edge ? { maxEdge: edge } : {}) };
|
||||
w.postMessage(msg, bytes ? [bytes] : []);
|
||||
})();
|
||||
return () => {
|
||||
cancelled = true;
|
||||
w.removeEventListener("message", onMessage);
|
||||
};
|
||||
}, [photoKey, sourceUrl, send]);
|
||||
}, [photoKey, sourceUrl, send, props.decodeEdge]);
|
||||
|
||||
useEffect(() => {
|
||||
if (opened !== photoKey || !size.w || !size.h) return;
|
||||
@@ -179,7 +229,7 @@ export function Viewer(props: ViewerProps) {
|
||||
|
||||
// 1:1: click and drag moves the photo (the hand tool), like Lightroom.
|
||||
const pan = useRef<{ x: number; y: number; left: number; top: number; id: number } | null>(null);
|
||||
const panning = !!props.actualPixels && !props.picking && !cropping;
|
||||
const panning = !!props.actualPixels && !props.picking && !props.spotting && !cropping;
|
||||
const panHandlers = panning
|
||||
? {
|
||||
onPointerDown: (e: React.PointerEvent<HTMLDivElement>) => {
|
||||
@@ -220,14 +270,34 @@ export function Viewer(props: ViewerProps) {
|
||||
// While cropping the photo turns under an upright crop, as in Lightroom: the engine renders it unturned
|
||||
// (the whole frame), and the straighten angle is shown here so a drag follows the pointer at once.
|
||||
style={cropping && props.crop.angle ? { transform: `rotate(${props.crop.angle}deg)` } : undefined}
|
||||
className={`block h-full w-full shadow-[0_2px_12px_rgba(0,0,0,0.7)] ${props.picking ? "cursor-crosshair" : ""}`}
|
||||
className={`block h-full w-full shadow-[0_2px_12px_rgba(0,0,0,0.7)] ${props.picking || props.spotting ? "cursor-crosshair" : ""}`}
|
||||
aria-label="Foto em revelação"
|
||||
onClick={(e) => {
|
||||
if (!props.picking) return;
|
||||
if (!props.picking && !props.spotting) return;
|
||||
const r = e.currentTarget.getBoundingClientRect();
|
||||
callbacks.current.onPick?.((e.clientX - r.left) / r.width, (e.clientY - r.top) / r.height);
|
||||
const u = (e.clientX - r.left) / r.width;
|
||||
const v = (e.clientY - r.top) / r.height;
|
||||
if (props.picking) callbacks.current.onPick?.(u, v);
|
||||
else callbacks.current.onSpot?.(u, v);
|
||||
}}
|
||||
/>
|
||||
{props.spotMarks && props.spotMarks.length > 0 && (
|
||||
<div className="pointer-events-none absolute inset-0" aria-hidden="true">
|
||||
{props.spotMarks.map((m, i) => (
|
||||
<span
|
||||
key={i}
|
||||
className="absolute rounded-full border border-white/90 bg-black/30"
|
||||
style={{
|
||||
left: `${m.u * 100}%`,
|
||||
top: `${m.v * 100}%`,
|
||||
width: `${Math.max(8, m.size * 100)}%`,
|
||||
height: `${Math.max(8, m.size * 100)}%`,
|
||||
transform: "translate(-50%, -50%)",
|
||||
}}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
{cropping && frame && (
|
||||
<CropFrame
|
||||
crop={props.crop}
|
||||
|
||||
@@ -89,10 +89,14 @@ export type WorkerRequest =
|
||||
| { type: "open"; key: string; url: string; bytes?: ArrayBuffer; maxEdge?: number }
|
||||
| { type: "render"; ticket: number; key: string; settings: string; maxW: number; maxH: number; draft: boolean; applyCrop: boolean }
|
||||
/** Auto values from the photo itself: tone (under `settings`), white balance, or the eyedropper at x, y. */
|
||||
| { type: "auto"; id: number; key: string; kind: "tone" | "wb" | "pick" | "level"; settings?: string; x?: number; y?: number };
|
||||
| { type: "auto"; id: number; key: string; kind: "tone" | "wb" | "pick" | "level"; settings?: string; x?: number; y?: number }
|
||||
/** One full render of the open photo, for a JPEG saved from Revelar. Does not replace the loupe frame. */
|
||||
| { type: "export"; id: number; key: string; settings: string; maxW: number; maxH: number };
|
||||
|
||||
export type WorkerReply =
|
||||
| { type: "opened"; key: string; sourceWidth: number; sourceHeight: number }
|
||||
| { type: "frame"; ticket: number; key: string; width: number; height: number; pixels: Uint8ClampedArray }
|
||||
| { type: "error"; key: string; ticket?: number; message: string }
|
||||
| { type: "auto"; id: number; values?: Record<string, number>; message?: string };
|
||||
| { type: "auto"; id: number; values?: Record<string, number>; message?: string }
|
||||
| { type: "exported"; id: number; width: number; height: number; pixels: Uint8ClampedArray }
|
||||
| { type: "exportError"; id: number; message: string };
|
||||
@@ -36,6 +36,18 @@ async function open(key: string, url: string, bytes?: ArrayBuffer, maxEdge = 204
|
||||
|
||||
self.onmessage = async (e: MessageEvent<WorkerRequest>) => {
|
||||
const msg = e.data;
|
||||
if (msg.type === "export") {
|
||||
try {
|
||||
const photo = current?.key === msg.key ? current.photo : await opening.get(msg.key);
|
||||
if (!photo) throw new Error("photo not open");
|
||||
photo.render(msg.settings, msg.maxW, msg.maxH, false, true);
|
||||
const pixels = new Uint8ClampedArray(photo.pixels().buffer);
|
||||
post({ type: "exported", id: msg.id, width: photo.width, height: photo.height, pixels }, [pixels.buffer]);
|
||||
} catch (err) {
|
||||
post({ type: "exportError", id: msg.id, message: err instanceof Error ? err.message : String(err) });
|
||||
}
|
||||
return;
|
||||
}
|
||||
try {
|
||||
if (msg.type === "open") {
|
||||
const photo = await open(msg.key, msg.url, msg.bytes, msg.maxEdge);
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { addSpot, removeSpotAt, spotsOf, spotsPartial } from "./spots.js";
|
||||
|
||||
describe("spots", () => {
|
||||
it("adds a fill spot and round-trips through merge partial", () => {
|
||||
const settings = "{}";
|
||||
const next = addSpot(settings, { mode: "fill", x: 0.4, y: 0.6, size: 0.03, feather: 40, opacity: 100 });
|
||||
expect(next).toHaveLength(1);
|
||||
expect(next[0]?.mode).toBe("fill");
|
||||
expect(next[0]?.points[0]).toEqual({ x: 0.4, y: 0.6 });
|
||||
const merged = JSON.stringify({ ...JSON.parse(settings), ...spotsPartial(next) });
|
||||
expect(spotsOf(merged)).toEqual(next);
|
||||
});
|
||||
|
||||
it("removes by index", () => {
|
||||
let spots = addSpot("{}", { mode: "remove", x: 0.1, y: 0.1, size: 0.02, feather: 50, opacity: 100 });
|
||||
spots = addSpot(JSON.stringify({ spots }), { mode: "heal", x: 0.2, y: 0.2, size: 0.02, feather: 50, opacity: 100 });
|
||||
expect(removeSpotAt(JSON.stringify({ spots }), 0)).toHaveLength(1);
|
||||
expect(removeSpotAt(JSON.stringify({ spots }), 0)[0]?.mode).toBe("heal");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,78 @@
|
||||
/** Spot / heal / clone / content-aware fill — LightCraft `DevelopSettings.spots` (snake_case JSON). */
|
||||
|
||||
export type SpotMode = "remove" | "heal" | "clone" | "fill";
|
||||
|
||||
export interface SpotPoint {
|
||||
x: number;
|
||||
y: number;
|
||||
}
|
||||
|
||||
export interface Spot {
|
||||
mode: SpotMode;
|
||||
points: SpotPoint[];
|
||||
/** Radius as a fraction of the long edge (LightCraft default ~0.02). */
|
||||
size: number;
|
||||
feather: number;
|
||||
opacity: number;
|
||||
source_offset?: SpotPoint | null;
|
||||
}
|
||||
|
||||
export const SPOT_MODES: { id: SpotMode; labelKey: "spotRemove" | "spotHeal" | "spotClone" | "spotFill" }[] = [
|
||||
{ id: "remove", labelKey: "spotRemove" },
|
||||
{ id: "heal", labelKey: "spotHeal" },
|
||||
{ id: "clone", labelKey: "spotClone" },
|
||||
{ id: "fill", labelKey: "spotFill" },
|
||||
];
|
||||
|
||||
export const DEFAULT_SPOT_SIZE = 0.025;
|
||||
export const DEFAULT_SPOT_FEATHER = 50;
|
||||
export const DEFAULT_SPOT_OPACITY = 100;
|
||||
|
||||
export function spotsOf(settings: string): Spot[] {
|
||||
try {
|
||||
const s = JSON.parse(settings) as { spots?: Spot[] };
|
||||
return Array.isArray(s.spots) ? s.spots : [];
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
/** Partial for `develop.merge`: replace the spots list. */
|
||||
export function spotsPartial(spots: Spot[]): Record<string, unknown> {
|
||||
return { spots };
|
||||
}
|
||||
|
||||
export function addSpot(
|
||||
settings: string,
|
||||
spot: {
|
||||
mode: SpotMode;
|
||||
x: number;
|
||||
y: number;
|
||||
size: number;
|
||||
feather: number;
|
||||
opacity: number;
|
||||
sourceOffset?: SpotPoint | null;
|
||||
},
|
||||
): Spot[] {
|
||||
const next: Spot = {
|
||||
mode: spot.mode,
|
||||
points: [{ x: clamp01(spot.x), y: clamp01(spot.y) }],
|
||||
size: clamp(spot.size, 0.002, 0.25),
|
||||
feather: clamp(spot.feather, 0, 100),
|
||||
opacity: clamp(spot.opacity, 0, 100),
|
||||
source_offset: spot.sourceOffset ?? null,
|
||||
};
|
||||
return [...spotsOf(settings), next];
|
||||
}
|
||||
|
||||
export function removeSpotAt(settings: string, index: number): Spot[] {
|
||||
return spotsOf(settings).filter((_, i) => i !== index);
|
||||
}
|
||||
|
||||
function clamp01(v: number): number {
|
||||
return Math.min(1, Math.max(0, v));
|
||||
}
|
||||
|
||||
function clamp(v: number, lo: number, hi: number): number {
|
||||
return Math.min(hi, Math.max(lo, v));
|
||||
}
|
||||
+99
-3
@@ -55,11 +55,33 @@ export const t = {
|
||||
folderSheet: {
|
||||
opening: "A abrir a pasta…",
|
||||
close: "Fechar",
|
||||
hint: "Folha de contacto desta pasta, neste computador. Não cria um evento nem envia fotografias. Estrelas e marcas ficam só nesta sessão.",
|
||||
hint: "Folha de contacto desta pasta, neste computador. Não cria um evento nem envia fotografias. D abre o Revelar. Estrelas e marcas ficam só nesta sessão.",
|
||||
develop: "Revelar",
|
||||
developTitle: "Abre esta fotografia no Revelar, neste computador. Não envia o ficheiro.",
|
||||
mergeTitle: "Funde as exposições desta pasta num DNG ao lado delas. As originais ficam. Não envia fotografias.",
|
||||
alsoJpeg: "e o JPEG editado",
|
||||
alsoJpegTitle: "No mesmo clique funde, grava o DNG, o JPEG revelado e o XMP com esses ajustes. Desmarca para gravar só o DNG.",
|
||||
workingJpeg: (n: number, total: number) => `A revelar e a gravar o JPEG ${n} de ${total}…`,
|
||||
merged: (n: number) => (n === 1 ? "1 DNG ficou nesta pasta." : `${n} DNG ficaram nesta pasta.`),
|
||||
mergedBoth: (n: number) => (n === 1 ? "1 DNG e o JPEG editado ficaram nesta pasta." : `${n} DNG e os JPEG editados ficaram nesta pasta.`),
|
||||
mergedDownload: (n: number) => (n === 1 ? "O DNG ficou nesta pasta. O JPEG foi descarregado." : "Os DNG ficaram nesta pasta. Os JPEG foram descarregados."),
|
||||
empty: "Esta pasta não tem fotografias.",
|
||||
failed: "Não foi possível abrir esta pasta.",
|
||||
count: (n: number) => (n === 1 ? "1 foto" : `${n} fotos`),
|
||||
},
|
||||
folderDevelop: {
|
||||
back: "Pasta",
|
||||
preset: "Interior",
|
||||
presetHelp: "Luz de dia, sombras abertas e janelas contidas. O XMP ao lado do DNG guarda estes ajustes para os mudares aqui.",
|
||||
dressing: "A acertar brancos, luz e cor…",
|
||||
save: "Guardar JPEG",
|
||||
saving: "A gravar o JPEG…",
|
||||
savedBeside: (name: string) => `${name} ficou nesta pasta.`,
|
||||
savedDownload: (name: string) => `${name} foi descarregado.`,
|
||||
saveFailed: "Não gravei o JPEG.",
|
||||
openFailed: "Não abri esta fotografia no Revelar.",
|
||||
adjustFailed: "Não apliquei este acerto.",
|
||||
},
|
||||
newEvent: "Novo evento",
|
||||
noEvents: "Sem eventos. Cria o primeiro.",
|
||||
noPhotos: "Sem fotografias neste filtro.",
|
||||
@@ -76,6 +98,10 @@ export const t = {
|
||||
clearFilter: "Limpar filtro",
|
||||
clearPlayers: "Limpar jogadores",
|
||||
sendN: (n: number) => (n ? `Enviar ${n}` : "Enviar"),
|
||||
sendOriginals: "Enviar originais",
|
||||
sendOriginalsHelp: "O ficheiro da câmara (sem redimensionar), com IPTC e o nome do destino. Para casos como as fotos do Francisco Tavares.",
|
||||
waitForFaces: "Esperar pelas caras",
|
||||
waitForFacesHelp: "Só neste destino: se o pad usa nomes de jogadores, espera um pouco pelas caras antes de enviar. Por defeito envia já; quando os nomes chegarem, o ficheiro é actualizado e reenviado.",
|
||||
outputSelection: "As selecionadas",
|
||||
outputBest: "As melhores",
|
||||
outputRest: "O resto",
|
||||
@@ -112,7 +138,11 @@ export const t = {
|
||||
stop: "Desligar",
|
||||
help: "A câmara envia por FTP para este computador (mesma rede). Cada foto que chega sobe logo para o evento abaixo e o original passa para a pasta de trabalho do evento.",
|
||||
camera: "Na câmara",
|
||||
edit: "Configurar",
|
||||
edit: "Ligações",
|
||||
connections: "Máquinas",
|
||||
connectionsHelp: "Uma ligação por corpo. No menu FTP da câmara escreves o servidor, a porta, o utilizador e a palavra-passe. O cabo USB não usa isto: liga sozinho.",
|
||||
machine: "Máquina",
|
||||
addMachine: "+ Outra máquina",
|
||||
server: "Servidor",
|
||||
port: "Porta",
|
||||
user: "Utilizador",
|
||||
@@ -164,6 +194,47 @@ export const t = {
|
||||
},
|
||||
outdated: "Esta versão da app de computador ainda não tem FTP local. Instala a versão nova (0.2 ou mais recente).",
|
||||
},
|
||||
usbCamera: {
|
||||
button: "USB",
|
||||
title: "Câmara por USB",
|
||||
help: "Carrega em «Ligar cabo» com a câmara ligada. A app lê o cartão em pulsos curtos e larga a sessão PTP para poderes disparar (sem ecrã «computador»). A primeira leitura dum cartão cheio demora; depois só entram disparos novos. Nada sobe sozinho: escolhes o que descarregar, ou marca «Puxar automaticamente».",
|
||||
none: "Nenhuma câmara ligada por cabo.",
|
||||
tetherOn: "Cabo ligado",
|
||||
tetherOff: "Cabo desligado",
|
||||
turnOn: "Ligar cabo",
|
||||
turnOff: "Desligar cabo",
|
||||
opening: "A ligar à câmara…",
|
||||
tethered: "Câmara livre para disparar — a app lê o cartão em segundo plano",
|
||||
busy: "A câmara está ocupada por outra app (o EOS Utility, por exemplo). Fecha-a: o cabo só pode estar com uma de cada vez. A tentar outra vez sozinho.",
|
||||
idle: "Cabo desligado",
|
||||
listing: "A ler o cartão…",
|
||||
rawKept: "O RAW fica na pasta de trabalho, ao lado do JPEG.",
|
||||
outdated: "Esta versão da app de computador ainda não lê a câmara por USB. Instala a versão nova.",
|
||||
received: (n: number) => (n === 1 ? "1 foto recebida" : `${n} fotos recebidas`),
|
||||
sent: (n: number) => `${n} enviadas`,
|
||||
failed: (n: number) => (n === 1 ? "1 falhou" : `${n} falharam`),
|
||||
clockOk: "Relógio acertado com este computador.",
|
||||
clockAhead: (n: number) => `A câmara estava ${n} s adiantada. O relógio ficou igual ao deste computador.`,
|
||||
clockBehind: (n: number) => `A câmara estava ${n} s atrasada. O relógio ficou igual ao deste computador.`,
|
||||
clockUnsupported: "Esta câmara não deixa acertar o relógio pelo cabo.",
|
||||
clockSync: "Acertar relógio outra vez",
|
||||
card: "Cartão",
|
||||
files: (n: number) => (n === 1 ? "1 ficheiro" : `${n} ficheiros`),
|
||||
newShot: "nova",
|
||||
imported: "já puxada",
|
||||
selectNew: "Seleccionar novas",
|
||||
selectEvent: "Do evento",
|
||||
selectAll: "Todas",
|
||||
selectNone: "Nenhuma",
|
||||
refresh: "Actualizar lista",
|
||||
download: (n: number) => (n === 1 ? "Descarregar 1" : `Descarregar ${n}`),
|
||||
emptyCard: "O cartão ainda não tem fotos listadas.",
|
||||
outsideEvent: "fora do evento",
|
||||
windowHint: (inWin: number, total: number) => `${inWin} de ${total} na janela do evento`,
|
||||
autoIngest: "Puxar automaticamente (só na janela do evento)",
|
||||
autoIngestHelp: "Só fotos novas cuja hora da câmara cai entre o início e o fim de ingestão do evento. O resto do cartão fica por escolher.",
|
||||
autoNeedsEvent: "Escolhe um evento com janela de ingestão para o automático.",
|
||||
},
|
||||
squad: {
|
||||
title: "Pessoas",
|
||||
help: "Quem pode ser identificado nas fotos, por clube. Os plantéis das competições que segues entram sozinhos; aqui juntas outras pessoas e as fotos oficiais (com a foto, a pessoa é sugerida logo no primeiro jogo).",
|
||||
@@ -297,6 +368,9 @@ export const t = {
|
||||
missing: "Falta o ficheiro original de alguma exposição.",
|
||||
engine: "O motor ainda não grava o DNG. Quando a cópia do cartão acabar, atualiza a página.",
|
||||
failed: "Não fundi. Tenta outra vez.",
|
||||
raw: "Não consegui ler estes RAW para os fundir.",
|
||||
write: "Não consegui gravar o DNG nesta pasta.",
|
||||
failedDetail: (reason: string) => `Não fundi. ${reason}`,
|
||||
},
|
||||
},
|
||||
card: {
|
||||
@@ -349,6 +423,7 @@ export const t = {
|
||||
},
|
||||
uploading: (done: number, total: number) => `A enviar ${done} de ${total}`,
|
||||
uploaded: (n: number) => (n === 1 ? "1 foto enviada" : `${n} fotos enviadas`),
|
||||
sendingOriginals: (n: number) => (n === 1 ? "A enviar 1 original desta máquina" : `A enviar ${n} originais desta máquina`),
|
||||
uploadFailed: (n: number) => `${n} com erro`,
|
||||
dismiss: "Fechar",
|
||||
useEmbeddedTitle: "Usar o Title como jogadores",
|
||||
@@ -531,6 +606,7 @@ export const t = {
|
||||
copied: "Copiado",
|
||||
deliveryErrors: {
|
||||
waiting_for_original: "À espera do original (está no computador do fotógrafo; abre a app PhotoReport nesse computador)",
|
||||
waiting_for_original_here: "A pedir o original desta máquina…",
|
||||
original_not_here: "O original nunca chegou do computador do fotógrafo",
|
||||
},
|
||||
deliveryStatus: { QUEUED: "Na fila", RUNNING: "A enviar", WAITING: "À espera do computador", DONE: "Entregue", FAILED: "Falhou", RETRACTED: "Retirada" },
|
||||
@@ -606,6 +682,8 @@ export const t = {
|
||||
pause: "Pausar",
|
||||
look: "Aspeto do site",
|
||||
looks: { none: "PhotoReport", liga: "Liga Portugal", fpa: "Federação de Andebol" } as Record<string, string>,
|
||||
photoFind: "Procura por foto",
|
||||
photoFindHelp: "Quem edita pastas na cloud (como a Federação) pode carregar uma foto e procurar essa cara no arquivo. A foto de pesquisa não fica guardada. Requer reconhecimento de caras ligado.",
|
||||
hostname: "Endereço próprio",
|
||||
hostnamePlaceholder: "arquivo.ligaportugal.pt",
|
||||
hostnameHelp: "Opcional. Aponta esse endereço (DNS, CNAME) para o mesmo servidor do arquivo: o arquivo abre na raiz e o certificado é pedido sozinho.",
|
||||
@@ -776,6 +854,12 @@ export const t = {
|
||||
download: "Descarregar instalador",
|
||||
later: "Mais tarde",
|
||||
uiReady: "Nova versão da interface descarregada. Fica ativa ao recarregar (ou no próximo arranque).",
|
||||
uiApplying: "A actualizar a interface da app…",
|
||||
uiSection: "Interface da app",
|
||||
uiSectionHelp: "A PhotoReport é uma app neste computador. Novas funções descarregam-se sozinhas; podes forçar a verificação aqui.",
|
||||
uiCheckNow: "Actualizar interface agora",
|
||||
uiChecking: "A verificar…",
|
||||
uiCurrent: "Já tens a interface mais recente.",
|
||||
reload: "Recarregar agora",
|
||||
},
|
||||
editorPanelsHelp: "Escolhe os painéis que queres ver ao editar. A escolha acompanha-te no web e no desktop.",
|
||||
@@ -1161,6 +1245,18 @@ export const t = {
|
||||
saved: "Guardado",
|
||||
crop: "Recortar",
|
||||
cropDone: "Concluir",
|
||||
spot: "Apagar",
|
||||
spotDone: "Concluir",
|
||||
spotHelp: "Clica na zona a limpar (softbox, cabo, pó). Q liga a ferramenta.",
|
||||
spotNow: "Clica na foto onde queres apagar. Esc cancela.",
|
||||
spotRemove: "Remover",
|
||||
spotHeal: "Corrigir",
|
||||
spotClone: "Clonar",
|
||||
spotFill: "Preencher",
|
||||
spotSize: "Tamanho",
|
||||
spotFeather: "Suavizar",
|
||||
spotOpacity: "Opacidade",
|
||||
spotDelete: "Tirar",
|
||||
aspect: "Proporção",
|
||||
aspectFree: "Livre",
|
||||
aspectOriginal: "Original",
|
||||
@@ -1194,7 +1290,7 @@ export const t = {
|
||||
syncApply: "Aplicar",
|
||||
synced: (n: number) => `Ajustes sincronizados em ${n} ${n === 1 ? "foto" : "fotos"}`,
|
||||
noAccess: "Só podes revelar fotos que enviaste.",
|
||||
shortcuts: "← → foto · Ctrl/Cmd+A todas · P escolher · X rejeitar · U limpar · 0–5 estrelas · 6–9 cor · G grelha · I informação · Shift+A automático · \\ antes/depois · R recortar · W conta-gotas · Z 1:1 (arrastar move) · E lupa · Ctrl+Alt+1 biblioteca · Ctrl+Z anular",
|
||||
shortcuts: "← → foto · Ctrl/Cmd+A todas · P escolher · X rejeitar · U limpar · 0–5 estrelas · 6–9 cor · G grelha · I informação · Shift+A automático · \\ antes/depois · R recortar · Q apagar · W conta-gotas · Z 1:1 (arrastar move) · E lupa · Ctrl+Alt+1 biblioteca · Ctrl+Z anular",
|
||||
groups: { wb: "Equilíbrio de brancos", tone: "Tom", presence: "Presença", profile: "Perfil" },
|
||||
labels: {
|
||||
"profile.amount": "Intensidade",
|
||||
|
||||
@@ -0,0 +1,330 @@
|
||||
import type { Module } from "@photoreport/contracts";
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import { engineAuto, exportFrame, Viewer } from "../develop/Viewer.js";
|
||||
import { loadEngine, type EngineModule } from "../develop/engine.js";
|
||||
import { DevelopPanels } from "../develop/Panels.js";
|
||||
import type { Crop } from "../develop/session.js";
|
||||
import { t } from "../i18n.js";
|
||||
import { jpegFromRgba } from "./finishMergedJpeg.js";
|
||||
import { folderRead, saveDevelopedJpeg, saveDevelopedXmp } from "./folderDrop.js";
|
||||
import type { FolderFile } from "./folderDrop.js";
|
||||
import { developedJpegName, developedXmpName, developXmp, dirOf, FOLDER_DEVELOP_EDGE, interiorCommand, interiorPartial, partialFromSettings, partialFromXmp } from "./interiorPreset.js";
|
||||
|
||||
const MODULES: readonly Module[] = ["basic", "detail"];
|
||||
const FULL: Crop = { rect: { x0: 0, y0: 0, x1: 1, y1: 1 }, angle: 0, aspect: null };
|
||||
|
||||
const isTyping = (target: EventTarget | null) =>
|
||||
target instanceof HTMLElement && (target.isContentEditable || ["INPUT", "TEXTAREA", "SELECT"].includes(target.tagName));
|
||||
|
||||
function setCommand(values: Record<string, number>): string {
|
||||
return JSON.stringify({ command: "develop.set", params: { values } });
|
||||
}
|
||||
|
||||
/** Temperature and tint only take effect once the white balance is no longer As Shot. */
|
||||
function applyValues(mod: EngineModule, settings: string, values: Record<string, number>): string {
|
||||
let next = mod.apply(settings, setCommand(values));
|
||||
if ("wb.temp" in values || "wb.tint" in values) {
|
||||
next = mod.apply(next, JSON.stringify({ command: "develop.merge", params: { partial: { wb: { mode: "custom", scale: "kelvin" } } } }));
|
||||
}
|
||||
return next;
|
||||
}
|
||||
|
||||
/**
|
||||
* Revelar for one file from a folder dropped on this computer. Settings stay in this window.
|
||||
* Opening the photo applies the interior look (neutral whites, recovered windows, colour). Nothing is uploaded.
|
||||
*/
|
||||
export function FolderDevelop(props: {
|
||||
files: readonly FolderFile[];
|
||||
path: string;
|
||||
onPath: (path: string) => void;
|
||||
onClose: () => void;
|
||||
}) {
|
||||
const { files, path, onPath, onClose } = props;
|
||||
const file = files.find((item) => item.path === path) ?? null;
|
||||
const engineRef = useRef<EngineModule | null>(null);
|
||||
const pathRef = useRef(path);
|
||||
pathRef.current = path;
|
||||
const remembered = useRef(new Map<string, string>());
|
||||
const dressing = useRef<string | null>(null);
|
||||
const [engine, setEngine] = useState<EngineModule | null>(null);
|
||||
const [missing, setMissing] = useState(false);
|
||||
const [settings, setSettings] = useState<string | null>(null);
|
||||
const [opened, setOpened] = useState(false);
|
||||
const [before, setBefore] = useState(false);
|
||||
const [picking, setPicking] = useState(false);
|
||||
const [dragging, setDragging] = useState(false);
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [note, setNote] = useState<string | null>(null);
|
||||
const strip = useRef<HTMLDivElement>(null);
|
||||
|
||||
useEffect(() => {
|
||||
let dead = false;
|
||||
loadEngine().then(
|
||||
(mod) => {
|
||||
if (dead) return;
|
||||
engineRef.current = mod;
|
||||
setEngine(mod);
|
||||
},
|
||||
() => {
|
||||
if (!dead) setMissing(true);
|
||||
},
|
||||
);
|
||||
return () => {
|
||||
dead = true;
|
||||
};
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
if (!engine) return;
|
||||
setSettings(remembered.current.get(path) ?? engine.defaultSettings());
|
||||
setOpened(false);
|
||||
setBefore(false);
|
||||
setPicking(false);
|
||||
}, [engine, path]);
|
||||
|
||||
useEffect(() => {
|
||||
strip.current?.querySelector("[data-current='true']")?.scrollIntoView({ inline: "center", block: "nearest" });
|
||||
}, [path]);
|
||||
|
||||
const applyInterior = async (forPath: string, fromSidecar: boolean) => {
|
||||
const mod = engineRef.current;
|
||||
if (!mod || dressing.current === forPath) return;
|
||||
dressing.current = forPath;
|
||||
setNote(t.folderDevelop.dressing);
|
||||
try {
|
||||
let next = mod.defaultSettings();
|
||||
let loaded = false;
|
||||
if (fromSidecar) {
|
||||
const slash = Math.max(forPath.lastIndexOf("/"), forPath.lastIndexOf("\\"));
|
||||
const fileName = slash >= 0 ? forPath.slice(slash + 1) : forPath;
|
||||
const xmpPath = `${dirOf(forPath)}/${developedXmpName(fileName)}`;
|
||||
try {
|
||||
const bytes = await folderRead(xmpPath);
|
||||
const partial = partialFromXmp(new TextDecoder().decode(bytes));
|
||||
if (partial) {
|
||||
next = mod.apply(next, interiorCommand(partial));
|
||||
loaded = true;
|
||||
}
|
||||
} catch {
|
||||
// No sidecar yet: the interior finish below is the first edit.
|
||||
}
|
||||
}
|
||||
if (!loaded) {
|
||||
let exposure: number | undefined;
|
||||
try {
|
||||
const tone = await engineAuto(forPath, "tone");
|
||||
exposure = tone["light.exposure"];
|
||||
} catch {
|
||||
// The finish still opens the room when the photo has nothing to measure.
|
||||
}
|
||||
next = mod.apply(mod.defaultSettings(), interiorCommand(interiorPartial(exposure)));
|
||||
}
|
||||
if (pathRef.current !== forPath) return;
|
||||
remembered.current.set(forPath, next);
|
||||
setSettings(next);
|
||||
setNote(null);
|
||||
} catch {
|
||||
if (pathRef.current !== forPath) return;
|
||||
const next = mod.apply(mod.defaultSettings(), interiorCommand(interiorPartial(undefined)));
|
||||
remembered.current.set(forPath, next);
|
||||
setSettings(next);
|
||||
setNote(null);
|
||||
} finally {
|
||||
if (dressing.current === forPath) dressing.current = null;
|
||||
}
|
||||
};
|
||||
|
||||
const index = files.findIndex((item) => item.path === path);
|
||||
const go = (delta: number) => {
|
||||
const next = files[index + delta];
|
||||
if (next) onPath(next.path);
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
const onKey = (e: KeyboardEvent) => {
|
||||
if (isTyping(e.target)) return;
|
||||
e.stopPropagation();
|
||||
if (e.key === "Escape") {
|
||||
e.preventDefault();
|
||||
if (picking) setPicking(false);
|
||||
else onClose();
|
||||
return;
|
||||
}
|
||||
if (e.metaKey || e.ctrlKey || e.altKey) return;
|
||||
if (e.key === "ArrowRight") {
|
||||
e.preventDefault();
|
||||
go(1);
|
||||
} else if (e.key === "ArrowLeft") {
|
||||
e.preventDefault();
|
||||
go(-1);
|
||||
} else if (e.key === "\\") setBefore((value) => !value);
|
||||
else if (e.key.toLowerCase() === "w") setPicking((value) => !value);
|
||||
};
|
||||
window.addEventListener("keydown", onKey, true);
|
||||
return () => window.removeEventListener("keydown", onKey, true);
|
||||
}, [go, onClose, picking]);
|
||||
|
||||
const setValue = (id: string, value: number) => {
|
||||
const mod = engineRef.current;
|
||||
if (!mod || !settings) return;
|
||||
setDragging(true);
|
||||
const next = applyValues(mod, settings, { [id]: value });
|
||||
remembered.current.set(path, next);
|
||||
setSettings(next);
|
||||
};
|
||||
|
||||
const save = async () => {
|
||||
const mod = engineRef.current;
|
||||
if (!mod || !settings || !file || saving) return;
|
||||
setSaving(true);
|
||||
setNote(t.folderDevelop.saving);
|
||||
try {
|
||||
const frame = await exportFrame(path, settings, FOLDER_DEVELOP_EDGE, FOLDER_DEVELOP_EDGE);
|
||||
const blob = await jpegFromRgba(frame.pixels, frame.width, frame.height);
|
||||
const bytes = new Uint8Array(await blob.arrayBuffer());
|
||||
const name = developedJpegName(file.name);
|
||||
const dir = dirOf(file.path);
|
||||
const where = await saveDevelopedJpeg(dir, name, bytes);
|
||||
const partial = partialFromSettings(settings);
|
||||
if (partial) await saveDevelopedXmp(dir, developedXmpName(file.name), new TextEncoder().encode(developXmp(partial)));
|
||||
setNote(where === "beside" ? t.folderDevelop.savedBeside(name) : t.folderDevelop.savedDownload(name));
|
||||
} catch {
|
||||
setNote(t.folderDevelop.saveFailed);
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
};
|
||||
|
||||
if (!file) return null;
|
||||
|
||||
const shown = settings && before && engine ? engine.defaultSettings() : settings;
|
||||
|
||||
return (
|
||||
<div className="flex min-h-0 flex-1 flex-col">
|
||||
<div className="flex flex-wrap items-center gap-2 border-b border-line bg-raised px-3 py-1.5 text-[12px]">
|
||||
<button type="button" onClick={onClose} className="h-6 border border-black bg-cell px-2.5 text-[12px] text-ink hover:bg-cell-on">
|
||||
{t.folderDevelop.back}
|
||||
</button>
|
||||
<span className="min-w-0 flex-1 truncate text-ink" title={file.path}>
|
||||
{file.name}
|
||||
</span>
|
||||
<button
|
||||
type="button"
|
||||
title={t.folderDevelop.presetHelp}
|
||||
disabled={!opened || !engine || saving}
|
||||
onClick={() => void applyInterior(path, false)}
|
||||
className="h-6 border border-black bg-cell px-2.5 text-[12px] text-ink hover:bg-cell-on disabled:opacity-40"
|
||||
>
|
||||
{t.folderDevelop.preset}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
disabled={!opened || !settings || saving}
|
||||
onClick={() => void save()}
|
||||
className="h-6 border border-black bg-accent px-2.5 text-[12px] text-white disabled:opacity-40"
|
||||
>
|
||||
{t.folderDevelop.save}
|
||||
</button>
|
||||
{note && (
|
||||
<span role="status" className="max-w-sm truncate text-[12px] text-muted" title={note}>
|
||||
{note}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
{missing ? (
|
||||
<p className="p-8 text-center text-[13px] text-faint">{t.dev.engineMissing}</p>
|
||||
) : (
|
||||
<div className="flex min-h-0 flex-1">
|
||||
<div className="min-w-0 flex-1 bg-black">
|
||||
{engine && shown ? (
|
||||
<Viewer
|
||||
photoKey={path}
|
||||
sourceUrl=""
|
||||
settings={shown}
|
||||
dragging={dragging}
|
||||
cropping={false}
|
||||
crop={FULL}
|
||||
decodeEdge={FOLDER_DEVELOP_EDGE}
|
||||
localSource={() => folderRead(path).catch(() => null)}
|
||||
picking={picking}
|
||||
onSourceSize={() => {
|
||||
setOpened(true);
|
||||
if (!remembered.current.has(path)) void applyInterior(path, true);
|
||||
}}
|
||||
onPick={(u, v) => {
|
||||
setPicking(false);
|
||||
void (async () => {
|
||||
const mod = engineRef.current;
|
||||
if (!mod || !settings) return;
|
||||
try {
|
||||
const values = await engineAuto(path, "pick", { x: u, y: v });
|
||||
const next = applyValues(mod, settings, values);
|
||||
remembered.current.set(path, next);
|
||||
setSettings(next);
|
||||
} catch {
|
||||
setNote(t.folderDevelop.adjustFailed);
|
||||
}
|
||||
})();
|
||||
}}
|
||||
onError={() => setNote(t.folderDevelop.openFailed)}
|
||||
/>
|
||||
) : (
|
||||
<p className="p-8 text-center font-mono text-[12px] text-faint">{t.dev.loading}</p>
|
||||
)}
|
||||
</div>
|
||||
<aside className="w-80 shrink-0 overflow-y-auto border-l border-line bg-panel">
|
||||
<DevelopPanels
|
||||
modules={MODULES}
|
||||
value={(id) => (engine && settings ? engine.value(settings, id) : Number.NaN)}
|
||||
disabled={!opened || !engine}
|
||||
onChange={setValue}
|
||||
onEnd={() => setDragging(false)}
|
||||
onSet={(values) => {
|
||||
const mod = engineRef.current;
|
||||
if (!mod || !settings) return;
|
||||
const next = applyValues(mod, settings, values);
|
||||
remembered.current.set(path, next);
|
||||
setSettings(next);
|
||||
}}
|
||||
picking={picking}
|
||||
onAuto={(kind) => {
|
||||
if (kind === "pick") {
|
||||
setPicking((value) => !value);
|
||||
return;
|
||||
}
|
||||
void (async () => {
|
||||
const mod = engineRef.current;
|
||||
if (!mod || !settings) return;
|
||||
try {
|
||||
const values = await engineAuto(path, kind, kind === "tone" ? { settings } : {});
|
||||
const next = applyValues(mod, settings, values);
|
||||
remembered.current.set(path, next);
|
||||
setSettings(next);
|
||||
} catch {
|
||||
setNote(t.folderDevelop.adjustFailed);
|
||||
}
|
||||
})();
|
||||
}}
|
||||
/>
|
||||
<div className="px-3 py-2 text-[11px] text-faint">{t.folderDevelop.presetHelp}</div>
|
||||
</aside>
|
||||
</div>
|
||||
)}
|
||||
<div ref={strip} className="flex h-10 shrink-0 items-center gap-1 overflow-x-auto border-t border-line bg-chrome px-2">
|
||||
{files.map((item) => (
|
||||
<button
|
||||
key={item.path}
|
||||
type="button"
|
||||
data-current={item.path === path ? "true" : "false"}
|
||||
onClick={() => onPath(item.path)}
|
||||
className={`h-6 max-w-40 shrink-0 truncate border px-2 font-mono text-[10px] ${
|
||||
item.path === path ? "border-white/70 bg-cell-on text-ink" : "border-transparent text-muted hover:text-ink"
|
||||
}`}
|
||||
>
|
||||
{item.name}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,9 +1,12 @@
|
||||
import type { ColorLabel, PhotoFlag, PhotoPatch } from "@photoreport/contracts";
|
||||
import { useEffect, useRef, useState, type CSSProperties } from "react";
|
||||
import { t } from "../i18n.js";
|
||||
import { prefs } from "../platform.js";
|
||||
import { LABEL_COLOR } from "./Grid.js";
|
||||
import { FOLDER_CELL_H, FOLDER_CELL_W, FOLDER_GAP, folderCols, folderWindow } from "./folder-layout.js";
|
||||
import type { FolderListing } from "./folderDrop.js";
|
||||
import { mergeFailureText } from "./folderMerge.js";
|
||||
import { MergeError } from "./mergeExposures.js";
|
||||
import { isMac, patchForKey, pmPatchForKey } from "./store.js";
|
||||
|
||||
interface Mark {
|
||||
@@ -66,8 +69,20 @@ export function FolderSheet(props: {
|
||||
folder: FolderListing;
|
||||
onClose: () => void;
|
||||
thumb: (path: string, edge: number) => Promise<ArrayBuffer | null>;
|
||||
/**
|
||||
* Merges the photos on this sheet and returns how many DNG files were written beside them.
|
||||
* Absent in a view that cannot edit. The library's own merge stays on the event underneath.
|
||||
*/
|
||||
merge?: (input: {
|
||||
files: FolderListing["files"];
|
||||
selectedIds: readonly string[];
|
||||
jpeg: boolean;
|
||||
onStatus: (stack: number, total: number, phase?: "merge" | "jpeg") => void;
|
||||
}) => Promise<{ made: number; jpeg: "beside" | "download" | "none" }>;
|
||||
/** Opens the focused file in Revelar. Absent where the sheet cannot edit. */
|
||||
onDevelop?: (path: string) => void;
|
||||
}) {
|
||||
const { folder, onClose, thumb } = props;
|
||||
const { folder, onClose, thumb, merge, onDevelop } = props;
|
||||
const files = folder.files;
|
||||
const scroller = useRef<HTMLDivElement>(null);
|
||||
const [width, setWidth] = useState(800);
|
||||
@@ -78,6 +93,37 @@ export function FolderSheet(props: {
|
||||
const [selected, setSelected] = useState<ReadonlySet<string>>(() => new Set(files[0] ? [files[0].path] : []));
|
||||
const [marks, setMarks] = useState<ReadonlyMap<string, Mark>>(() => new Map());
|
||||
const [loupe, setLoupe] = useState(false);
|
||||
const [mergeStatus, setMergeStatus] = useState<string | null>(null);
|
||||
const [mergeFailed, setMergeFailed] = useState(false);
|
||||
const [merging, setMerging] = useState(false);
|
||||
const [alsoJpeg, setAlsoJpeg] = useState(() => prefs.get("folder.alsoJpeg") !== "0");
|
||||
const mergePending = useRef(false);
|
||||
|
||||
const runMerge = () => {
|
||||
if (!merge || mergePending.current) return;
|
||||
const withJpeg = alsoJpeg;
|
||||
mergePending.current = true;
|
||||
setMerging(true);
|
||||
setMergeFailed(false);
|
||||
setMergeStatus(t.merge.reading);
|
||||
void merge({
|
||||
files,
|
||||
selectedIds: [...selected],
|
||||
jpeg: withJpeg,
|
||||
onStatus: (stack, total, phase) => setMergeStatus(phase === "jpeg" ? t.folderSheet.workingJpeg(stack, total) : t.merge.working(stack, total)),
|
||||
}).then(
|
||||
(result) => setMergeStatus(result.jpeg === "beside" ? t.folderSheet.mergedBoth(result.made) : result.jpeg === "download" ? t.folderSheet.mergedDownload(result.made) : t.folderSheet.merged(result.made)),
|
||||
(err: unknown) => {
|
||||
const code = err instanceof MergeError ? err.code : "failed";
|
||||
const detail = err instanceof MergeError ? err.detail : undefined;
|
||||
setMergeStatus(mergeFailureText(code, detail));
|
||||
setMergeFailed(true);
|
||||
},
|
||||
).finally(() => {
|
||||
mergePending.current = false;
|
||||
setMerging(false);
|
||||
});
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
const el = scroller.current;
|
||||
@@ -178,11 +224,16 @@ export function FolderSheet(props: {
|
||||
setLoupe(true);
|
||||
return;
|
||||
}
|
||||
if (e.key.toLowerCase() === "d" && focus && onDevelop) {
|
||||
e.preventDefault();
|
||||
onDevelop(focus);
|
||||
return;
|
||||
}
|
||||
if (e.key.toLowerCase() === "g") setLoupe(false);
|
||||
};
|
||||
window.addEventListener("keydown", onKey, true);
|
||||
return () => window.removeEventListener("keydown", onKey, true);
|
||||
}, [anchor, cols, files, focus, loupe, marks, onClose, selected]);
|
||||
}, [anchor, cols, files, focus, loupe, marks, onClose, onDevelop, selected]);
|
||||
|
||||
const pick = (path: string, e: React.MouseEvent) => {
|
||||
const paths = files.map((file) => file.path);
|
||||
@@ -221,6 +272,46 @@ export function FolderSheet(props: {
|
||||
</span>
|
||||
<span className="font-mono text-[11px] text-faint">{t.folderSheet.count(files.length)}</span>
|
||||
<span className="hidden text-[11px] text-faint sm:inline">{t.folderSheet.hint}</span>
|
||||
{onDevelop && focus && (
|
||||
<button
|
||||
type="button"
|
||||
title={t.folderSheet.developTitle}
|
||||
onClick={() => onDevelop(focus)}
|
||||
className="h-6 border border-black bg-cell px-2.5 text-[12px] text-ink hover:bg-cell-on"
|
||||
>
|
||||
{t.folderSheet.develop}
|
||||
</button>
|
||||
)}
|
||||
{merge && files.length > 0 && (
|
||||
<span className="inline-flex items-center gap-2">
|
||||
<button
|
||||
type="button"
|
||||
title={t.folderSheet.mergeTitle}
|
||||
disabled={merging}
|
||||
onClick={runMerge}
|
||||
className="h-6 border border-black bg-cell px-2.5 text-[12px] text-ink hover:bg-cell-on disabled:opacity-40"
|
||||
>
|
||||
{t.merge.button}
|
||||
</button>
|
||||
<label title={t.folderSheet.alsoJpegTitle} className="inline-flex items-center gap-1.5 text-[12px] text-ink">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={alsoJpeg}
|
||||
disabled={merging}
|
||||
onChange={(e) => {
|
||||
setAlsoJpeg(e.target.checked);
|
||||
prefs.set("folder.alsoJpeg", e.target.checked ? "1" : "0");
|
||||
}}
|
||||
/>
|
||||
{t.folderSheet.alsoJpeg}
|
||||
</label>
|
||||
{mergeStatus && (
|
||||
<span role="status" title={mergeStatus} className={`max-w-xl text-[12px] ${mergeFailed ? "text-danger" : "text-muted"}`}>
|
||||
{mergeStatus}
|
||||
</span>
|
||||
)}
|
||||
</span>
|
||||
)}
|
||||
<button type="button" onClick={onClose} className="ml-auto h-6 border border-black bg-cell px-2.5 text-[12px] text-ink hover:bg-cell-on">
|
||||
{t.folderSheet.close}
|
||||
</button>
|
||||
|
||||
@@ -9,6 +9,13 @@ import { localPhotos } from "../offline/local.js";
|
||||
// the target has no organization, so a bare client is enough.
|
||||
vi.mock("../auth.js", () => ({ useAuth: () => ({ api: {} }) }));
|
||||
|
||||
const autopilot = vi.hoisted(() => ({
|
||||
run: (_args: unknown): Promise<void> => Promise.resolve(),
|
||||
}));
|
||||
vi.mock("../offline/autopilot.js", () => ({
|
||||
planLocalAutopilot: (args: unknown) => autopilot.run(args),
|
||||
}));
|
||||
|
||||
const status = (running: boolean): FtpStatus => ({
|
||||
running,
|
||||
settings: { port: 2121, users: [{ name: "1dx", password: "1dx" }], ingest: "~/Desktop/ingest", workFolder: "~/Desktop/{year}/{date} - {event}", autoStart: false, uploadOriginals: false },
|
||||
@@ -17,22 +24,26 @@ const status = (running: boolean): FtpStatus => ({
|
||||
error: null,
|
||||
});
|
||||
|
||||
function fakeShell(files: IncomingFile[]) {
|
||||
function fakeShell(files: IncomingFile[], originals = false) {
|
||||
let running = false;
|
||||
const calls: string[] = [];
|
||||
const sent: unknown[] = [];
|
||||
const asStatus = (runningNow: boolean): FtpStatus => ({
|
||||
...status(runningNow),
|
||||
settings: { ...status(runningNow).settings, uploadOriginals: originals },
|
||||
});
|
||||
const invoke = vi.fn(async (cmd: string, args?: Record<string, unknown>) => {
|
||||
calls.push(cmd);
|
||||
switch (cmd) {
|
||||
case "ftp_status":
|
||||
return status(running);
|
||||
return asStatus(running);
|
||||
case "ftp_start":
|
||||
running = true;
|
||||
return status(true);
|
||||
return asStatus(true);
|
||||
case "ftp_take":
|
||||
return files.splice(0);
|
||||
case "ftp_read":
|
||||
return new TextEncoder().encode(`bytes of ${String(args?.path)}`).buffer;
|
||||
return [...new TextEncoder().encode(`bytes of ${String(args?.path)}`)];
|
||||
case "ftp_preview":
|
||||
// Over the JSON bridge (page loaded from the server) binary answers arrive as arrays of numbers.
|
||||
return [...new TextEncoder().encode(`preview of ${String(args?.path)}`)];
|
||||
@@ -70,6 +81,7 @@ describe("local FTP feed", () => {
|
||||
// Each shows as soon as it arrives. The one the server has leaves; the failed one stays so it can be edited.
|
||||
await waitFor(() => expect(localPhotos.list().map((p) => p.name)).toEqual(["B.JPG"]));
|
||||
// Working locally (the default): previews go up, each with the fingerprint of its original.
|
||||
// Stub previews have no EXIF: the open pin still names the event (same as the server).
|
||||
expect(added).toEqual([
|
||||
{ name: "A.JPG", eventId: "ev1", size: "preview of /x/FTP/A.JPG".length, sha: "sha-/x/FTP/A.JPG" },
|
||||
{ name: "B.JPG", eventId: "ev1", size: "preview of /x/FTP/B.JPG".length, sha: "sha-/x/FTP/B.JPG" },
|
||||
@@ -80,6 +92,30 @@ describe("local FTP feed", () => {
|
||||
for (const photo of localPhotos.list()) localPhotos.remove(photo.id);
|
||||
});
|
||||
|
||||
it("sends the original while detection is still running", async () => {
|
||||
let release: (() => void) | undefined;
|
||||
autopilot.run = () =>
|
||||
new Promise((resolve) => {
|
||||
release = resolve;
|
||||
});
|
||||
const shell = fakeShell([{ path: "/x/FTP/C.JPG", name: "C.JPG", size: 10, modifiedMs: 3 }], true);
|
||||
const added: { name: string; kind: string }[] = [];
|
||||
const add = (files: Iterable<File>, _eventId?: string, onSettled?: (f: File, s: UploadStatus) => void, original?: { sha256: string } | "original") => {
|
||||
for (const f of files) {
|
||||
added.push({ name: f.name, kind: original === "original" ? "original" : "preview" });
|
||||
onSettled?.(f, "done");
|
||||
}
|
||||
};
|
||||
const { result } = renderHook(() => useLocalFtp(add, true, shell.invoke));
|
||||
await waitFor(() => expect(result.current.status).not.toBeNull());
|
||||
act(() => result.current.setTarget({ id: "ev1", title: "ABC x Benfica", home: "ABC", away: "Benfica", startsAt: "2026-10-12T18:00:00Z" } as EventSummary));
|
||||
await act(() => result.current.start());
|
||||
await waitFor(() => expect(added).toEqual([{ name: "C.JPG", kind: "original" }]));
|
||||
release?.();
|
||||
autopilot.run = () => Promise.resolve();
|
||||
for (const photo of localPhotos.list()) localPhotos.remove(photo.id);
|
||||
});
|
||||
|
||||
it("does nothing outside the desktop app", async () => {
|
||||
const shell = fakeShell([]);
|
||||
renderHook(() => useLocalFtp(() => {}, false, shell.invoke));
|
||||
|
||||
@@ -15,7 +15,7 @@ import type { DesktopOrigin, PreviewOf, UploadStatus } from "./uploads.js";
|
||||
export interface FtpSettings {
|
||||
port: number;
|
||||
/** `enabled` missing (older desktop app): on. */
|
||||
users: { name: string; password: string; enabled?: boolean }[];
|
||||
users: { name: string; password: string; enabled?: boolean; label?: string }[];
|
||||
ingest: string;
|
||||
workFolder: string;
|
||||
autoStart: boolean;
|
||||
@@ -47,6 +47,9 @@ export interface FtpTarget {
|
||||
id: string;
|
||||
title: string;
|
||||
date: string;
|
||||
/** Event ingest window (ISO). USB auto-ingest only pulls shots inside this range. */
|
||||
ingestFrom?: string;
|
||||
ingestUntil?: string;
|
||||
}
|
||||
|
||||
export type Invoke = <T>(cmd: string, args?: Record<string, unknown>) => Promise<T>;
|
||||
@@ -59,7 +62,13 @@ const IN_FLIGHT = 6;
|
||||
* Full originals are read through the webview as well. Several at once freeze it, a chunk sits until the access
|
||||
* token expires, and the server answers 401. Two leaves room for the upload to leave.
|
||||
*/
|
||||
const IN_FLIGHT_ORIGINALS = 2;
|
||||
const IN_FLIGHT_ORIGINALS = 3;
|
||||
/**
|
||||
* Originals on the wire at once. One waits out each detection and each server reply, so a full card sits in
|
||||
* ingest while the link is idle. This matches the upload queue. The slot stays held until that file has left,
|
||||
* so the queue cannot pull the whole folder into memory.
|
||||
*/
|
||||
const ORIGINAL_UPLOADS = 4;
|
||||
const POLL_MS = 1000;
|
||||
|
||||
/** The shell put the file back on the queue because the camera has not finished sending it. */
|
||||
@@ -103,23 +112,33 @@ export function useLocalFtp(add: Add, enabled: boolean, invoke: Invoke = tauriIn
|
||||
const [checkState, setCheckState] = useState<null | "busy" | "done" | "unsupported">(null);
|
||||
const backlog = useRef<IncomingFile[]>([]);
|
||||
const inFlight = useRef(0);
|
||||
/** One full original at a time. Several at once freeze the window, and the preview must not wait for that. */
|
||||
/** Originals being read or uploaded. The preview is already on screen and does not wait for these. */
|
||||
const reading = useRef(0);
|
||||
const readQueue = useRef<(() => void)[]>([]);
|
||||
/** Local detection, one photo at a time, off the upload path. */
|
||||
const autopilotChain = useRef(Promise.resolve());
|
||||
const targetRef = useRef(target);
|
||||
targetRef.current = target;
|
||||
const originalsRef = useRef(false);
|
||||
originalsRef.current = !!status?.settings.uploadOriginals;
|
||||
|
||||
const setTarget = useCallback((e: EventSummary | null) => {
|
||||
const next = e ? { id: e.id, title: eventLabel(e), date: e.startsAt.slice(0, 10) } : null;
|
||||
const next = e
|
||||
? {
|
||||
id: e.id,
|
||||
title: eventLabel(e),
|
||||
date: e.startsAt.slice(0, 10),
|
||||
ingestFrom: e.ingestFrom,
|
||||
ingestUntil: e.ingestUntil,
|
||||
}
|
||||
: null;
|
||||
setTargetState(next);
|
||||
prefs.set("ftp.target", JSON.stringify(next));
|
||||
}, []);
|
||||
|
||||
const pump = useCallback(() => {
|
||||
const takeOriginal = () => {
|
||||
if (reading.current < 1) {
|
||||
if (reading.current < ORIGINAL_UPLOADS) {
|
||||
reading.current++;
|
||||
return Promise.resolve();
|
||||
}
|
||||
@@ -146,9 +165,8 @@ export function useLocalFtp(add: Add, enabled: boolean, invoke: Invoke = tauriIn
|
||||
const cached = orgId ? await cache.events(orgId) : null;
|
||||
const events = cached?.events ?? [];
|
||||
const capturedAt = lisbonInstant(exifDateTime(preview));
|
||||
// A pin on a game already put away, or left over from the previous match, does not take the next photos.
|
||||
const pinnedId = to && (!cached || events.some((e) => e.id === to.id && !e.archivedAt)) ? to.id : null;
|
||||
const eventId = eventForArrival(pinnedId, events, capturedAt);
|
||||
// Open FTP target always; eventForArrival drops an archived leftover and keeps shots inside the window.
|
||||
const eventId = eventForArrival(to?.id ?? null, events, capturedAt);
|
||||
const filed = events.find((e) => e.id === eventId);
|
||||
if (!localPhotos.bySha(info.sha256)) {
|
||||
let url = "";
|
||||
@@ -194,13 +212,19 @@ export function useLocalFtp(add: Add, enabled: boolean, invoke: Invoke = tauriIn
|
||||
}
|
||||
};
|
||||
const event = events.find((e) => e.id === eventId);
|
||||
await planLocalAutopilot({ api, orgId, event, sha256: info.sha256, preview, width: info.width, height: info.height }).catch(() => {});
|
||||
// The cloud must not wait for detection. One at a time, or a full card freezes the window.
|
||||
const plan = autopilotChain.current.then(() =>
|
||||
planLocalAutopilot({ api, orgId, event, sha256: info.sha256, preview, width: info.width, height: info.height }).catch(() => {}),
|
||||
);
|
||||
autopilotChain.current = plan.then(
|
||||
() => undefined,
|
||||
() => undefined,
|
||||
);
|
||||
if (!full) {
|
||||
const file = new File([preview], f.name, { type: "image/jpeg", lastModified: f.modifiedMs });
|
||||
add([file], eventId ?? undefined, (_file, result, photo) => settle(_file, result, photo), info);
|
||||
return;
|
||||
}
|
||||
// One original at a time, and only when it is this file's turn to go up. Several at once freeze the window.
|
||||
await takeOriginal();
|
||||
let held = true;
|
||||
const drop = () => {
|
||||
@@ -368,21 +392,25 @@ function SettingsForm({ ftp, initial, onDone }: { ftp: LocalFtpState; initial: F
|
||||
<input className={field} type="number" min={1024} max={65535} value={s.port} onChange={(e) => setS({ ...s, port: Number(e.target.value) })} />
|
||||
</label>
|
||||
<div>
|
||||
<span className="text-[11px] uppercase tracking-wide text-faint">{L.logins}</span>
|
||||
<span className="text-[11px] uppercase tracking-wide text-faint">{L.connections}</span>
|
||||
<p className="mb-1 text-[11px] text-faint">{L.connectionsHelp}</p>
|
||||
{s.users.map((u, i) => (
|
||||
<div key={i} className="mt-1 flex items-center gap-1">
|
||||
<input type="checkbox" aria-label={`${L.loginOn}: ${u.name || L.user}`} title={L.loginOn} checked={u.enabled !== false} onChange={(e) => setUser(i, { enabled: e.target.checked })} />
|
||||
<input className={field} aria-label={L.user} placeholder={L.user} value={u.name} onChange={(e) => setUser(i, { name: e.target.value })} autoComplete="off" />
|
||||
<input className={field} aria-label={L.password} placeholder={L.password} value={u.password} onChange={(e) => setUser(i, { password: e.target.value })} autoComplete="off" />
|
||||
{s.users.length > 1 && (
|
||||
<button type="button" aria-label={L.removeLogin} onClick={() => setS({ ...s, users: s.users.filter((_, j) => j !== i) })} className="px-1 text-faint hover:text-ink">
|
||||
×
|
||||
</button>
|
||||
)}
|
||||
<div key={i} className="mb-2 border border-line bg-[#161617] p-2">
|
||||
<input className={field} aria-label={L.machine} placeholder={L.machine} value={u.label ?? ""} onChange={(e) => setUser(i, { label: e.target.value })} autoComplete="off" />
|
||||
<div className="mt-1 flex items-center gap-1">
|
||||
<input type="checkbox" aria-label={`${L.loginOn}: ${u.name || L.user}`} title={L.loginOn} checked={u.enabled !== false} onChange={(e) => setUser(i, { enabled: e.target.checked })} />
|
||||
<input className={field} aria-label={L.user} placeholder={L.user} value={u.name} onChange={(e) => setUser(i, { name: e.target.value })} autoComplete="off" />
|
||||
<input className={field} aria-label={L.password} placeholder={L.password} value={u.password} onChange={(e) => setUser(i, { password: e.target.value })} autoComplete="off" />
|
||||
{s.users.length > 1 && (
|
||||
<button type="button" aria-label={L.removeLogin} onClick={() => setS({ ...s, users: s.users.filter((_, j) => j !== i) })} className="px-1 text-faint hover:text-ink">
|
||||
×
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
<button type="button" onClick={() => setS({ ...s, users: [...s.users, { name: "", password: "", enabled: true }] })} className="mt-1 text-accent underline">
|
||||
{L.addLogin}
|
||||
<button type="button" onClick={() => setS({ ...s, users: [...s.users, { name: "", password: "", enabled: true, label: "" }] })} className="text-accent underline">
|
||||
{L.addMachine}
|
||||
</button>
|
||||
</div>
|
||||
<label className="block">
|
||||
@@ -478,8 +506,10 @@ export function LocalFtpButton({ ftp, events, openEventId }: { ftp: LocalFtpStat
|
||||
<dd className="select-all text-ink">{status.settings.port}</dd>
|
||||
{status.settings.users.map((u) => (
|
||||
<div key={u.name} className="contents">
|
||||
<dt className="text-faint">{L.user}</dt>
|
||||
<dt className="text-faint">{u.label || L.machine}</dt>
|
||||
<dd className={`select-all ${u.enabled === false ? "text-faint line-through" : "text-ink"}`}>
|
||||
<span className="font-sans">{u.label || u.name}</span>
|
||||
<span className="text-faint"> · </span>
|
||||
{u.name} <span className="text-faint">/</span> {u.password}
|
||||
{u.enabled === false && <span className="ml-1 font-sans no-underline">({L.loginOff})</span>}
|
||||
</dd>
|
||||
|
||||
@@ -66,6 +66,8 @@ export function SendButton(props: { api: ApiClient; orgId: string; selection: Ph
|
||||
const [pickOpen, setPickOpen] = useState(false);
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [note, setNote] = useState<string | null>(null);
|
||||
/** Camera original for this send (overrides the destination's resize). */
|
||||
const [sendOriginals, setSendOriginals] = useState(false);
|
||||
|
||||
/** Remember the chosen destinations across tabs and restarts (persisted on every change, not only on send). */
|
||||
const remember = (ids: string[]) => {
|
||||
@@ -122,7 +124,7 @@ export function SendButton(props: { api: ApiClient; orgId: string; selection: Ph
|
||||
try {
|
||||
// Without a network (or photos still uploading) each request waits on this computer and goes when it can.
|
||||
const results: Awaited<ReturnType<typeof deliver>>[] = [];
|
||||
for (const target of selected) results.push(await deliver(api, orgId, target.id, ids, again));
|
||||
for (const target of selected) results.push(await deliver(api, orgId, target.id, ids, again, sendOriginals));
|
||||
const queued = results.flatMap((r) => r.queued);
|
||||
const skipped = results.flatMap((r) => r.skipped);
|
||||
const waiting = results.some((r) => r.waiting);
|
||||
@@ -142,7 +144,7 @@ export function SendButton(props: { api: ApiClient; orgId: string; selection: Ph
|
||||
setBusy(true);
|
||||
try {
|
||||
const results: Awaited<ReturnType<ApiClient["deliverBest"]>>[] = [];
|
||||
for (const target of selected) results.push(await api.deliverBest(orgId, { targetId: target.id, eventId, count: bestCount, again: bestAgain }));
|
||||
for (const target of selected) results.push(await api.deliverBest(orgId, { targetId: target.id, eventId, count: bestCount, again: bestAgain, originals: sendOriginals }));
|
||||
prefs.set(BEST_COUNT, String(bestCount));
|
||||
const queued = results.flatMap((r) => r.queued);
|
||||
const skipped = results.flatMap((r) => r.skipped);
|
||||
@@ -184,7 +186,7 @@ export function SendButton(props: { api: ApiClient; orgId: string; selection: Ph
|
||||
const results: Awaited<ReturnType<typeof deliver>>[] = [];
|
||||
for (const batch of idsByTarget(choices, photos.map((p) => p.id), bestByCount, [...restIds])) {
|
||||
for (let i = 0; i < batch.ids.length; i += DELIVER_CHUNK) {
|
||||
results.push(await deliver(api, orgId, batch.targetId, batch.ids.slice(i, i + DELIVER_CHUNK)));
|
||||
results.push(await deliver(api, orgId, batch.targetId, batch.ids.slice(i, i + DELIVER_CHUNK), false, sendOriginals));
|
||||
}
|
||||
}
|
||||
const queued = results.flatMap((r) => r.queued);
|
||||
@@ -255,10 +257,25 @@ export function SendButton(props: { api: ApiClient; orgId: string; selection: Ph
|
||||
);
|
||||
})}
|
||||
{planned && <p className="text-faint">{t.outputRestHelp}</p>}
|
||||
<label className="flex items-start gap-2 border-t border-line pt-2 text-ink" title={t.sendOriginalsHelp}>
|
||||
<input type="checkbox" className="mt-0.5" checked={sendOriginals} onChange={(e) => setSendOriginals(e.target.checked)} disabled={busy} />
|
||||
<span>
|
||||
<span className="font-semibold">{t.sendOriginals}</span>
|
||||
<span className="block text-[11px] text-faint">{t.sendOriginalsHelp}</span>
|
||||
</span>
|
||||
</label>
|
||||
</div>
|
||||
)}
|
||||
</span>
|
||||
)}
|
||||
{/* Always visible next to Enviar — desktop may still be on a cached UI until reload. */}
|
||||
<label
|
||||
className={`flex h-6 shrink-0 items-center gap-1 border px-2 text-[11px] ${sendOriginals ? "border-accent bg-accent/20 text-ink" : "border-black bg-cell text-ink"}`}
|
||||
title={t.sendOriginalsHelp}
|
||||
>
|
||||
<input type="checkbox" checked={sendOriginals} onChange={(e) => setSendOriginals(e.target.checked)} disabled={busy} />
|
||||
{t.sendOriginals}
|
||||
</label>
|
||||
<button
|
||||
onClick={() => void (planned ? sendSplit() : send())}
|
||||
disabled={busy || !selected.length || (!planned && !photos.length)}
|
||||
|
||||
@@ -176,6 +176,7 @@ export function TargetForm({
|
||||
keepExif: target?.keepExif ?? true,
|
||||
srgb: target?.srgb ?? false,
|
||||
originals: target?.originals ?? false,
|
||||
waitForFaces: target?.waitForFaces ?? false,
|
||||
onArrival: target?.onArrival ?? false,
|
||||
arrivalLogins: target?.arrivalLogins ?? ([] as string[]),
|
||||
untouched: target?.untouched ?? false,
|
||||
@@ -481,6 +482,17 @@ export function TargetForm({
|
||||
</span>
|
||||
</label>
|
||||
)}
|
||||
<label className="flex items-start gap-2">
|
||||
<input
|
||||
type="checkbox"
|
||||
className="mt-0.5"
|
||||
checked={v.waitForFaces}
|
||||
onChange={(e) => setV({ ...v, waitForFaces: e.target.checked })}
|
||||
/>
|
||||
<span>
|
||||
<span className="text-ink">{t.waitForFaces}</span> — {t.waitForFacesHelp}
|
||||
</span>
|
||||
</label>
|
||||
<label className="flex items-start gap-2">
|
||||
<input
|
||||
type="checkbox"
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
import { useSyncExternalStore } from "react";
|
||||
import { t } from "../i18n.js";
|
||||
import { useIngest } from "./ingest.js";
|
||||
|
||||
/**
|
||||
* Thin transfer strip (Photo Mechanic–style): always at the bottom of the workspace while JPEGs or
|
||||
* originals are leaving this computer — not only on the library page.
|
||||
*/
|
||||
export function TransferBar() {
|
||||
const { uploads, originals } = useIngest();
|
||||
const originalFlight = useSyncExternalStore(
|
||||
(fn) => originals?.subscribe(fn) ?? (() => {}),
|
||||
() => originals?.inFlight.size ?? 0,
|
||||
() => 0,
|
||||
);
|
||||
const sending = uploads.items.filter((i) => i.status === "queued" || i.status === "uploading");
|
||||
const failed = uploads.items.filter((i) => i.status === "failed");
|
||||
const sentCount = uploads.items.filter((i) => i.status === "done" || i.status === "duplicate").length;
|
||||
const overall = uploads.items.length ? uploads.items.reduce((sum, i) => sum + (i.status === "failed" ? 1 : i.progress), 0) / uploads.items.length : 0;
|
||||
const busy = sending.length > 0 || originalFlight > 0;
|
||||
if (!busy && uploads.items.length === 0) return null;
|
||||
|
||||
const label = (() => {
|
||||
if (sending.length) return t.uploading(sentCount, uploads.items.length);
|
||||
if (originalFlight > 0) return t.sendingOriginals(originalFlight);
|
||||
return t.uploaded(sentCount);
|
||||
})();
|
||||
|
||||
const pct = sending.length || uploads.items.length ? Math.round(overall * 100) : originalFlight > 0 ? 50 : 100;
|
||||
|
||||
return (
|
||||
<div className="flex shrink-0 flex-wrap items-center gap-3 border-t border-line bg-panel px-3 py-1 text-[11px]" role="status" aria-live="polite">
|
||||
<span className="font-mono text-faint">
|
||||
{label}
|
||||
{failed.length > 0 && <span className="text-[#f0a35a]"> · {t.uploadFailed(failed.length)}</span>}
|
||||
{originalFlight > 0 && sending.length > 0 && <span className="text-faint"> · {t.sendingOriginals(originalFlight)}</span>}
|
||||
</span>
|
||||
<span className="h-1 min-w-[7rem] flex-1 bg-black" role="progressbar" aria-valuenow={pct} aria-valuemin={0} aria-valuemax={100}>
|
||||
<span className={`block h-full bg-accent transition-[width] ${originalFlight > 0 && !sending.length ? "animate-pulse" : ""}`} style={{ width: `${pct}%` }} />
|
||||
</span>
|
||||
{failed.length > 0 && (
|
||||
<span className="max-w-[14rem] truncate text-faint" title={failed.map((f) => `${f.name}: ${f.error}`).join("\n")}>
|
||||
{failed[0]?.name}: {failed[0]?.error}
|
||||
</span>
|
||||
)}
|
||||
{!sending.length && uploads.items.length > 0 && (
|
||||
<button type="button" onClick={uploads.clear} className="text-faint underline hover:text-muted">
|
||||
{t.dismiss}
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,128 @@
|
||||
import { render, renderHook, screen, waitFor } from "@testing-library/react";
|
||||
import type { EventSummary } from "@photoreport/sdk";
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import type { Invoke } from "./LocalFtp.js";
|
||||
import { prefs } from "../platform.js";
|
||||
import type { UploadStatus } from "./uploads.js";
|
||||
import { UsbCameraButton, type UsbStatus, inEventWindow, useUsbCamera, withSidecars } from "./UsbCamera.js";
|
||||
|
||||
const camera: UsbStatus = {
|
||||
supported: true,
|
||||
tether: true,
|
||||
devices: [{ id: "abc", name: "Canon Digital Camera", vendorId: 1193, productId: 13075, state: "tethered", error: null, catalogReady: true }],
|
||||
files: [
|
||||
{ name: "IMG_0001.JPG", size: 10, isNew: true, imported: false },
|
||||
{ name: "IMG_0001.CR3", size: 20, isNew: true, imported: false },
|
||||
{ name: "IMG_0002.JPG", size: 10, isNew: false, imported: false },
|
||||
],
|
||||
catalogGen: 1,
|
||||
};
|
||||
|
||||
function shell(files: { path: string; name: string; size: number; modifiedMs: number }[]) {
|
||||
const sent: unknown[] = [];
|
||||
const invoke = vi.fn(async (cmd: string, args?: Record<string, unknown>) => {
|
||||
if (cmd === "camera_status") {
|
||||
const since = args?.sinceGen;
|
||||
if (since === camera.catalogGen) return { ...camera, files: [] };
|
||||
return camera;
|
||||
}
|
||||
if (cmd === "camera_take") return files.splice(0);
|
||||
if (cmd === "ftp_preview") return [...new TextEncoder().encode(`preview of ${String(args?.path)}`)];
|
||||
if (cmd === "ftp_info") return { sha256: "sha", size: 5_000_000, width: 6000, height: 4000 };
|
||||
if (cmd === "ftp_sent") {
|
||||
sent.push(args);
|
||||
return null;
|
||||
}
|
||||
return null;
|
||||
}) as unknown as Invoke;
|
||||
return { invoke, sent };
|
||||
}
|
||||
|
||||
const event = { id: "ev1", title: "", home: "Portugal", away: "Suíça", startsAt: "2026-11-04T19:00:00Z" } as EventSummary;
|
||||
|
||||
const usbStub = {
|
||||
status: camera,
|
||||
outdated: false,
|
||||
counts: { received: 0, sent: 0, failed: 0 },
|
||||
setTether: vi.fn(),
|
||||
syncClock: vi.fn(),
|
||||
importFiles: vi.fn(),
|
||||
refresh: vi.fn(),
|
||||
autoIngest: false,
|
||||
setAutoIngest: vi.fn(),
|
||||
};
|
||||
|
||||
describe("usb tether", () => {
|
||||
it("pulls only files the shell already downloaded (chosen on the camera panel)", async () => {
|
||||
const { invoke, sent } = shell([{ path: "/ingest/.usb/IMG_0001.JPG", name: "IMG_0001.JPG", size: 10, modifiedMs: 1 }]);
|
||||
const added: { name: string; eventId: string | undefined }[] = [];
|
||||
const add = (files: Iterable<File>, eventId?: string, onSettled?: (f: File, s: UploadStatus) => void) => {
|
||||
for (const f of files) {
|
||||
added.push({ name: f.name, eventId });
|
||||
onSettled?.(f, "done");
|
||||
}
|
||||
};
|
||||
renderHook(() => useUsbCamera(add, true, { id: "ev1", title: "Portugal x Suíça", date: "2026-11-04" }, invoke));
|
||||
// Preview has no EXIF: keep the open pin (auto-pull already used the card clock for the window).
|
||||
await waitFor(() => expect(added).toEqual([{ name: "IMG_0001.JPG", eventId: "ev1" }]));
|
||||
await waitFor(() => expect(sent).toEqual([{ path: "/ingest/.usb/IMG_0001.JPG", event: "Portugal x Suíça", date: "2026-11-04" }]));
|
||||
});
|
||||
|
||||
it("uses the open event when a camera is plugged in and none is chosen", async () => {
|
||||
const setTarget = vi.fn();
|
||||
render(<UsbCameraButton usb={usbStub} target={null} setTarget={setTarget} openEvent={event} />);
|
||||
await waitFor(() => expect(setTarget).toHaveBeenCalledWith(event));
|
||||
expect(screen.getByRole("button", { name: /USB/ })).toBeTruthy();
|
||||
});
|
||||
|
||||
it("leaves a chosen event alone", () => {
|
||||
const setTarget = vi.fn();
|
||||
render(
|
||||
<UsbCameraButton
|
||||
usb={usbStub}
|
||||
target={{ id: "other", title: "ABC x Benfica", date: "2026-10-12" }}
|
||||
setTarget={setTarget}
|
||||
openEvent={event}
|
||||
/>,
|
||||
);
|
||||
expect(setTarget).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("adds the RAW sidecar when a JPEG is selected for download", () => {
|
||||
expect(withSidecars(["IMG_0001.JPG"], camera.files).sort()).toEqual(["IMG_0001.CR3", "IMG_0001.JPG"]);
|
||||
expect(withSidecars(["IMG_0002.JPG"], camera.files)).toEqual(["IMG_0002.JPG"]);
|
||||
});
|
||||
|
||||
it("does not crash auto-ingest when the shell status omits files", async () => {
|
||||
vi.spyOn(prefs, "get").mockReturnValue("1");
|
||||
const invoke = vi.fn(async (cmd: string) => {
|
||||
if (cmd === "camera_status") return { supported: true, tether: true, devices: [] } as unknown as UsbStatus;
|
||||
if (cmd === "camera_take") return [];
|
||||
return null;
|
||||
}) as unknown as Invoke;
|
||||
const add = () => {};
|
||||
const { result } = renderHook(() =>
|
||||
useUsbCamera(add, true, { id: "ev1", title: "Portugal x Suíça", date: "2026-11-04", ingestFrom: "2026-11-04T18:00:00Z", ingestUntil: "2026-11-04T23:00:00Z" }, invoke),
|
||||
);
|
||||
await waitFor(() => expect(result.current.status?.tether).toBe(true));
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
it("only treats shots inside the event ingest window as auto-eligible", () => {
|
||||
const from = "2026-11-03T18:00:00.000Z";
|
||||
const until = "2026-11-03T23:00:00.000Z";
|
||||
expect(inEventWindow({ createdMs: Date.parse("2026-11-03T19:30:00Z") }, from, until)).toBe(true);
|
||||
expect(inEventWindow({ createdMs: Date.parse("2026-11-02T19:30:00Z") }, from, until)).toBe(false);
|
||||
expect(inEventWindow({ createdMs: null }, from, until)).toBe(false);
|
||||
expect(inEventWindow({ createdMs: Date.parse("2026-11-03T19:30:00Z") }, undefined, until)).toBe(false);
|
||||
});
|
||||
|
||||
it("keeps the last file list when the shell omits files for an unchanged catalogGen", async () => {
|
||||
window.localStorage.removeItem("pr.usb.tether");
|
||||
const { invoke } = shell([]);
|
||||
const { result } = renderHook(() => useUsbCamera(() => {}, true, null, invoke));
|
||||
await waitFor(() => expect(result.current.status?.files).toHaveLength(3));
|
||||
await waitFor(() => expect(invoke).toHaveBeenCalledWith("camera_status", { sinceGen: 1 }));
|
||||
await waitFor(() => expect(result.current.status?.files).toHaveLength(3));
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,477 @@
|
||||
import type { EventSummary } from "@photoreport/sdk";
|
||||
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 { asArrayBuffer, prefs } from "../platform.js";
|
||||
import { type FtpTarget, type IncomingFile, type Invoke, eventLabel } from "./LocalFtp.js";
|
||||
import type { PreviewOf, UploadStatus } from "./uploads.js";
|
||||
|
||||
/** What the desktop shell reports for a PTP body on the USB cable (`camera.rs`). */
|
||||
export interface UsbCamera {
|
||||
id: string;
|
||||
name: string;
|
||||
vendorId: number;
|
||||
productId: number;
|
||||
/** opening: session starting; tethered: ready to pick files; busy: another app holds the cable; idle: off. */
|
||||
state: "opening" | "tethered" | "busy" | "idle";
|
||||
error: string | null;
|
||||
/** synced: clock set to this Mac; unsupported: the body refuses; null: not tried yet. */
|
||||
clock?: "synced" | "unsupported" | null;
|
||||
/** Seconds the camera was ahead of the Mac before the sync. */
|
||||
clockOffset?: number | null;
|
||||
/** True once the card listing is available. */
|
||||
catalogReady?: boolean;
|
||||
}
|
||||
|
||||
export interface UsbFile {
|
||||
name: string;
|
||||
size: number;
|
||||
createdMs?: number | null;
|
||||
isNew?: boolean;
|
||||
imported?: boolean;
|
||||
}
|
||||
|
||||
export interface UsbStatus {
|
||||
supported: boolean;
|
||||
tether: boolean;
|
||||
devices: UsbCamera[];
|
||||
files: UsbFile[];
|
||||
/** Bumps when the shell's file list changes; poll with the last value to skip a repeat payload. */
|
||||
catalogGen?: number;
|
||||
}
|
||||
|
||||
const tauriInvoke: Invoke = async (cmd, args) => (await import("@tauri-apps/api/core")).invoke(cmd, args);
|
||||
|
||||
const IN_FLIGHT = 6;
|
||||
const POLL_MS = 1000;
|
||||
|
||||
type Add = (files: Iterable<File>, eventId?: string, onSettled?: (file: File, status: UploadStatus) => void, original?: PreviewOf) => void;
|
||||
|
||||
/**
|
||||
* USB camera: the shell lists the card (and each new shot). Chosen files are downloaded into the
|
||||
* ingest folder; this hook then uploads them to the target event like local FTP.
|
||||
*/
|
||||
function savedTetherOn(): boolean {
|
||||
return prefs.get("usb.tether") === "1";
|
||||
}
|
||||
|
||||
export function useUsbCamera(add: Add, enabled: boolean, target: FtpTarget | null, invoke: Invoke = tauriInvoke, orgId = "") {
|
||||
const [status, setStatus] = useState<UsbStatus | null>(null);
|
||||
const [outdated, setOutdated] = useState(false);
|
||||
const [counts, setCounts] = useState({ received: 0, sent: 0, failed: 0 });
|
||||
/** Auto-pull only new shots whose camera time sits inside the event's ingest window. */
|
||||
const [autoIngest, setAutoIngestState] = useState(savedAutoIngest);
|
||||
const backlog = useRef<IncomingFile[]>([]);
|
||||
const inFlight = useRef(0);
|
||||
const autoAsked = useRef<Set<string>>(new Set());
|
||||
const catalogGen = useRef(0);
|
||||
const filesRef = useRef<UsbFile[]>([]);
|
||||
const tetherRestored = useRef(false);
|
||||
const targetRef = useRef(target);
|
||||
targetRef.current = target;
|
||||
const orgIdRef = useRef(orgId);
|
||||
orgIdRef.current = orgId;
|
||||
const autoIngestRef = useRef(autoIngest);
|
||||
autoIngestRef.current = autoIngest;
|
||||
|
||||
const applyStatus = useCallback((s: UsbStatus) => {
|
||||
// Same generation → shell omitted `files` on purpose; keep the list we already have.
|
||||
if (typeof s.catalogGen === "number" && s.catalogGen === catalogGen.current) {
|
||||
setStatus({ ...s, files: filesRef.current });
|
||||
return;
|
||||
}
|
||||
if (typeof s.catalogGen === "number") catalogGen.current = s.catalogGen;
|
||||
filesRef.current = s.files;
|
||||
setStatus(s);
|
||||
}, []);
|
||||
|
||||
const pump = useCallback(() => {
|
||||
while (inFlight.current < IN_FLIGHT && backlog.current.length) {
|
||||
const f = backlog.current.shift()!;
|
||||
const to = targetRef.current;
|
||||
inFlight.current++;
|
||||
void (async () => {
|
||||
try {
|
||||
const [bytes, original] = await Promise.all([
|
||||
invoke<unknown>("ftp_preview", { path: f.path }).then(asArrayBuffer),
|
||||
invoke<PreviewOf>("ftp_info", { path: f.path }),
|
||||
]);
|
||||
const file = new File([bytes], f.name, { type: "image/jpeg", lastModified: f.modifiedMs });
|
||||
const cached = orgIdRef.current ? await cache.events(orgIdRef.current) : null;
|
||||
const events = cached?.events ?? [];
|
||||
const capturedAt = lisbonInstant(exifDateTime(bytes));
|
||||
// Always the open USB target — never drop a live pull into Sem evento because the agenda cache is stale.
|
||||
const eventId = eventForArrival(to?.id ?? null, events, capturedAt);
|
||||
const filed = events.find((e) => e.id === eventId);
|
||||
add([file], eventId ?? undefined, (_file, result) => {
|
||||
inFlight.current--;
|
||||
if (result === "done" || result === "duplicate") {
|
||||
setCounts((c) => ({ ...c, sent: c.sent + 1 }));
|
||||
invoke("ftp_sent", {
|
||||
path: f.path,
|
||||
event: filed ? eventLabel(filed) : (to?.title ?? ""),
|
||||
date: filed ? filed.startsAt.slice(0, 10) : (to?.date ?? ""),
|
||||
}).catch(() => {});
|
||||
} else {
|
||||
setCounts((c) => ({ ...c, failed: c.failed + 1 }));
|
||||
}
|
||||
pump();
|
||||
}, original);
|
||||
} catch {
|
||||
inFlight.current--;
|
||||
setCounts((c) => ({ ...c, failed: c.failed + 1 }));
|
||||
pump();
|
||||
}
|
||||
})();
|
||||
}
|
||||
}, [add, invoke]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!enabled) return;
|
||||
let alive = true;
|
||||
const tick = async () => {
|
||||
try {
|
||||
const s = await invoke<UsbStatus>("camera_status", { sinceGen: catalogGen.current });
|
||||
if (!alive) return;
|
||||
applyStatus(s);
|
||||
if (!s.supported || !s.tether) return;
|
||||
const files = await invoke<IncomingFile[]>("camera_take");
|
||||
if (!alive || !files.length) return;
|
||||
const to = targetRef.current;
|
||||
const photos = files.filter((f) => /\.jpe?g$/i.test(f.name));
|
||||
for (const raw of files) {
|
||||
if (/\.jpe?g$/i.test(raw.name)) continue;
|
||||
void invoke("ftp_sent", { path: raw.path, event: to?.title ?? "", date: to?.date ?? "" }).catch(() => {});
|
||||
}
|
||||
if (!photos.length) return;
|
||||
backlog.current.push(...photos);
|
||||
setCounts((c) => ({ ...c, received: c.received + photos.length }));
|
||||
pump();
|
||||
} catch {
|
||||
if (alive) setOutdated(true);
|
||||
}
|
||||
};
|
||||
void tick();
|
||||
const timer = setInterval(() => void tick(), POLL_MS);
|
||||
return () => {
|
||||
alive = false;
|
||||
clearInterval(timer);
|
||||
};
|
||||
}, [enabled, invoke, pump, applyStatus]);
|
||||
|
||||
const syncClock = useCallback(async () => {
|
||||
try {
|
||||
applyStatus(await invoke<UsbStatus>("camera_sync"));
|
||||
} catch {
|
||||
setOutdated(true);
|
||||
}
|
||||
}, [invoke, applyStatus]);
|
||||
|
||||
const setTether = useCallback(
|
||||
async (on: boolean) => {
|
||||
prefs.set("usb.tether", on ? "1" : "0");
|
||||
try {
|
||||
// Full list after a tether change (gen may bump when clearing).
|
||||
catalogGen.current = 0;
|
||||
applyStatus(await invoke<UsbStatus>("camera_tether", { enabled: on }));
|
||||
} catch {
|
||||
setOutdated(true);
|
||||
}
|
||||
},
|
||||
[invoke, applyStatus],
|
||||
);
|
||||
|
||||
// Cable stays off at launch so a full card is not listed until asked; restore the last choice once.
|
||||
useEffect(() => {
|
||||
if (!enabled || tetherRestored.current || !savedTetherOn()) return;
|
||||
tetherRestored.current = true;
|
||||
void setTether(true);
|
||||
}, [enabled, setTether]);
|
||||
|
||||
const importFiles = useCallback(
|
||||
async (names: string[]) => {
|
||||
if (!names.length) return;
|
||||
try {
|
||||
catalogGen.current = 0;
|
||||
applyStatus(await invoke<UsbStatus>("camera_import", { names }));
|
||||
} catch {
|
||||
setOutdated(true);
|
||||
}
|
||||
},
|
||||
[invoke, applyStatus],
|
||||
);
|
||||
|
||||
const refresh = useCallback(async () => {
|
||||
try {
|
||||
catalogGen.current = 0;
|
||||
applyStatus(await invoke<UsbStatus>("camera_refresh"));
|
||||
} catch {
|
||||
setOutdated(true);
|
||||
}
|
||||
}, [invoke, applyStatus]);
|
||||
|
||||
const setAutoIngest = useCallback((on: boolean) => {
|
||||
setAutoIngestState(on);
|
||||
prefs.set("usb.autoIngest", on ? "1" : "0");
|
||||
if (!on) autoAsked.current.clear();
|
||||
}, []);
|
||||
|
||||
// New tethered shots inside the event window only — never the rest of the card / other days.
|
||||
useEffect(() => {
|
||||
if (!autoIngest || !status?.tether || !target?.ingestFrom || !target.ingestUntil) return;
|
||||
const files = status.files ?? [];
|
||||
const due = files.filter(
|
||||
(f) => /\.jpe?g$/i.test(f.name) && f.isNew && !f.imported && inEventWindow(f, target.ingestFrom, target.ingestUntil) && !autoAsked.current.has(f.name),
|
||||
);
|
||||
if (!due.length) return;
|
||||
for (const f of due) autoAsked.current.add(f.name);
|
||||
void importFiles(withSidecars(due.map((f) => f.name), files));
|
||||
}, [autoIngest, status, target, importFiles]);
|
||||
|
||||
return { status, outdated, counts, setTether, syncClock, importFiles, refresh, autoIngest, setAutoIngest };
|
||||
}
|
||||
|
||||
export type UsbCameraState = ReturnType<typeof useUsbCamera>;
|
||||
|
||||
const live = (d: UsbCamera) => d.state === "tethered" || d.state === "opening" || d.state === "busy";
|
||||
|
||||
function stemOf(name: string) {
|
||||
return name.replace(/\.[^.]+$/, "").toLowerCase();
|
||||
}
|
||||
|
||||
/** JPEG names plus any RAW that shares the same stem (Canon CR3 beside the JPG, etc.). */
|
||||
export function withSidecars(selected: Iterable<string>, files: UsbFile[]): string[] {
|
||||
const want = new Set([...selected].map(stemOf));
|
||||
return files.filter((f) => want.has(stemOf(f.name))).map((f) => f.name);
|
||||
}
|
||||
|
||||
/**
|
||||
* True when the shot's camera time falls inside the event ingest window. No capture time → not auto-eligible
|
||||
* (a full card without dates must not flood the event; the photographer picks those by hand).
|
||||
*/
|
||||
export function inEventWindow(file: Pick<UsbFile, "createdMs">, fromIso: string | undefined, untilIso: string | undefined): boolean {
|
||||
if (!fromIso || !untilIso) return false;
|
||||
if (file.createdMs == null || !Number.isFinite(file.createdMs)) return false;
|
||||
const from = Date.parse(fromIso);
|
||||
const until = Date.parse(untilIso);
|
||||
if (!Number.isFinite(from) || !Number.isFinite(until)) return false;
|
||||
return file.createdMs >= from && file.createdMs <= until;
|
||||
}
|
||||
|
||||
function savedAutoIngest(): boolean {
|
||||
return prefs.get("usb.autoIngest") === "1";
|
||||
}
|
||||
|
||||
/** Button + panel in the Library toolbar. Hidden where the shell has no USB cameras (Windows, Linux). */
|
||||
export function UsbCameraButton({
|
||||
usb,
|
||||
target,
|
||||
setTarget,
|
||||
openEvent,
|
||||
}: {
|
||||
usb: UsbCameraState;
|
||||
target: FtpTarget | null;
|
||||
setTarget: (e: EventSummary | null) => void;
|
||||
openEvent: EventSummary | undefined;
|
||||
}) {
|
||||
const [open, setOpen] = useState(false);
|
||||
const [picked, setPicked] = useState<Set<string>>(() => new Set());
|
||||
const { status, counts, autoIngest, setAutoIngest } = usb;
|
||||
const L = t.usbCamera;
|
||||
const devices = status?.devices ?? [];
|
||||
const files = status?.files ?? [];
|
||||
const connected = devices.filter(live);
|
||||
const on = connected.some((d) => d.state === "tethered" || d.state === "opening");
|
||||
const catalogReady = devices.some((d) => d.catalogReady);
|
||||
const jpegs = useMemo(() => files.filter((f) => /\.jpe?g$/i.test(f.name)), [files]);
|
||||
const inWindow = useMemo(
|
||||
() => jpegs.filter((f) => inEventWindow(f, target?.ingestFrom, target?.ingestUntil)),
|
||||
[jpegs, target?.ingestFrom, target?.ingestUntil],
|
||||
);
|
||||
const hasWindow = !!(target?.ingestFrom && target.ingestUntil);
|
||||
|
||||
useEffect(() => {
|
||||
if (connected.length && !target && openEvent) setTarget(openEvent);
|
||||
}, [connected.length, target, openEvent, setTarget]);
|
||||
|
||||
// Drop selections that left the catalog (unplug / refresh).
|
||||
useEffect(() => {
|
||||
const names = new Set(files.map((f) => f.name));
|
||||
setPicked((prev) => {
|
||||
let changed = false;
|
||||
const next = new Set<string>();
|
||||
for (const n of prev) {
|
||||
if (names.has(n)) next.add(n);
|
||||
else changed = true;
|
||||
}
|
||||
return changed ? next : prev;
|
||||
});
|
||||
}, [files]);
|
||||
|
||||
if (status && !status.supported && !usb.outdated) return null;
|
||||
|
||||
const toggle = (name: string) => {
|
||||
setPicked((prev) => {
|
||||
const next = new Set(prev);
|
||||
if (next.has(name)) next.delete(name);
|
||||
else next.add(name);
|
||||
return next;
|
||||
});
|
||||
};
|
||||
|
||||
const download = () => {
|
||||
const names = withSidecars(picked, files);
|
||||
void usb.importFiles(names);
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="relative">
|
||||
<button
|
||||
onClick={() => setOpen((o) => !o)}
|
||||
aria-expanded={open}
|
||||
className="flex h-6 items-center gap-1.5 border border-black bg-cell px-2.5 text-[12px] text-ink hover:bg-cell-on"
|
||||
>
|
||||
<span className={`inline-block h-1.5 w-1.5 rounded-full ${on ? "bg-[#4cc38a]" : connected.some((d) => d.state === "busy") ? "bg-[#f0a35a]" : "bg-faint"}`} />
|
||||
{L.button}
|
||||
{connected.length > 0 && <span className="max-w-40 truncate font-mono text-[11px] text-muted">{connected[0]?.name}</span>}
|
||||
{jpegs.length > 0 && <span className="font-mono text-[11px] text-muted">{jpegs.length}</span>}
|
||||
</button>
|
||||
{open && (
|
||||
<div className="absolute left-0 top-7 z-30 w-[420px] border border-black bg-panel p-3 text-[12px] shadow-xl" role="dialog" aria-label={L.title}>
|
||||
<div className="mb-2 flex items-center justify-between">
|
||||
<span className="font-semibold uppercase tracking-wide text-ink">{L.title}</span>
|
||||
<span className={on ? "text-[#4cc38a]" : "text-faint"}>{status?.tether ? L.tetherOn : L.tetherOff}</span>
|
||||
</div>
|
||||
{usb.outdated && <p className="text-[#f0a35a]">{L.outdated}</p>}
|
||||
{!usb.outdated && (
|
||||
<>
|
||||
<p className="mb-3 text-faint">{L.help}</p>
|
||||
<div className="mb-3">
|
||||
<div className="mb-1 text-[11px] uppercase tracking-wide text-faint">{t.localFtp.target}</div>
|
||||
<div className="text-ink">{target ? `${target.date} · ${target.title}` : t.localFtp.noTarget}</div>
|
||||
{hasWindow && (
|
||||
<div className="mt-1 font-mono text-[11px] text-muted">
|
||||
{L.windowHint(inWindow.length, jpegs.length)}
|
||||
</div>
|
||||
)}
|
||||
{openEvent && openEvent.id !== target?.id && (
|
||||
<button onClick={() => setTarget(openEvent)} className="mt-1 text-left text-accent underline">
|
||||
{t.localFtp.useOpen(eventLabel(openEvent))}
|
||||
</button>
|
||||
)}
|
||||
{on && hasWindow && (
|
||||
<label className="mt-2 flex cursor-pointer items-center gap-2 text-ink">
|
||||
<input type="checkbox" checked={autoIngest} onChange={(e) => setAutoIngest(e.target.checked)} className="accent-accent" />
|
||||
{L.autoIngest}
|
||||
</label>
|
||||
)}
|
||||
{autoIngest && !hasWindow && <p className="mt-1 text-[#f0a35a]">{L.autoNeedsEvent}</p>}
|
||||
{autoIngest && hasWindow && <p className="mt-1 text-[11px] text-faint">{L.autoIngestHelp}</p>}
|
||||
</div>
|
||||
{devices.length === 0 && <p className="text-faint">{L.none}</p>}
|
||||
{devices.map((d) => (
|
||||
<div key={d.id} className="mb-2 border border-line bg-[#161617] p-2">
|
||||
<div className="font-mono text-ink">{d.name}</div>
|
||||
<div className={d.state === "busy" ? "text-[#f0a35a]" : "text-muted"}>
|
||||
{d.state === "opening" && L.opening}
|
||||
{d.state === "tethered" && (d.catalogReady ? L.tethered : L.listing)}
|
||||
{d.state === "idle" && L.idle}
|
||||
{d.state === "busy" && L.busy}
|
||||
</div>
|
||||
{d.error && d.state === "busy" && <div className="mt-1 font-mono text-[11px] text-faint">{d.error}</div>}
|
||||
{d.clock === "unsupported" && <div className="mt-1 text-[#f0a35a]">{L.clockUnsupported}</div>}
|
||||
{d.clock === "synced" && (
|
||||
<div className="mt-1 text-[#4cc38a]">
|
||||
{d.clockOffset == null || Math.abs(d.clockOffset) < 2
|
||||
? L.clockOk
|
||||
: d.clockOffset > 0
|
||||
? L.clockAhead(Math.round(d.clockOffset))
|
||||
: L.clockBehind(Math.round(Math.abs(d.clockOffset)))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
|
||||
{on && (
|
||||
<div className="mb-3 border border-line bg-[#161617] p-2">
|
||||
<div className="mb-2 flex items-center justify-between gap-2">
|
||||
<span className="text-[11px] uppercase tracking-wide text-faint">
|
||||
{L.card}
|
||||
{jpegs.length > 0 && <span className="ml-2 font-mono normal-case text-muted">{L.files(jpegs.length)}</span>}
|
||||
</span>
|
||||
<div className="flex flex-wrap gap-2">
|
||||
{hasWindow && (
|
||||
<button type="button" className="text-accent underline" onClick={() => setPicked(new Set(inWindow.filter((f) => !f.imported).map((f) => f.name)))}>
|
||||
{L.selectEvent}
|
||||
</button>
|
||||
)}
|
||||
<button type="button" className="text-accent underline" onClick={() => setPicked(new Set(jpegs.filter((f) => f.isNew && !f.imported).map((f) => f.name)))}>
|
||||
{L.selectNew}
|
||||
</button>
|
||||
<button type="button" className="text-accent underline" onClick={() => setPicked(new Set(jpegs.filter((f) => !f.imported).map((f) => f.name)))}>
|
||||
{L.selectAll}
|
||||
</button>
|
||||
<button type="button" className="text-accent underline" onClick={() => setPicked(new Set())}>
|
||||
{L.selectNone}
|
||||
</button>
|
||||
<button type="button" className="text-accent underline" onClick={() => void usb.refresh()}>
|
||||
{L.refresh}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
{!catalogReady && <p className="text-faint">{L.listing}</p>}
|
||||
{catalogReady && jpegs.length === 0 && <p className="text-faint">{L.emptyCard}</p>}
|
||||
{jpegs.length > 0 && (
|
||||
<ul className="max-h-48 overflow-auto border border-line">
|
||||
{jpegs.map((f) => {
|
||||
const checked = picked.has(f.name);
|
||||
const matches = inEventWindow(f, target?.ingestFrom, target?.ingestUntil);
|
||||
return (
|
||||
<li key={f.name} className="flex items-center gap-2 border-b border-line px-2 py-1 last:border-b-0 hover:bg-cell">
|
||||
<input type="checkbox" checked={checked} disabled={!!f.imported} onChange={() => toggle(f.name)} className="accent-accent" />
|
||||
<button type="button" className="min-w-0 flex-1 truncate text-left font-mono text-ink disabled:text-faint" disabled={!!f.imported} onClick={() => toggle(f.name)}>
|
||||
{f.name}
|
||||
</button>
|
||||
{f.isNew && !f.imported && <span className="text-[10px] uppercase text-[#4cc38a]">{L.newShot}</span>}
|
||||
{f.imported && <span className="text-[10px] uppercase text-faint">{L.imported}</span>}
|
||||
{hasWindow && !matches && !f.imported && <span className="text-[10px] uppercase text-[#f0a35a]">{L.outsideEvent}</span>}
|
||||
</li>
|
||||
);
|
||||
})}
|
||||
</ul>
|
||||
)}
|
||||
{picked.size > 0 && (
|
||||
<button type="button" onClick={download} className="mt-2 h-7 w-full border border-black bg-cell px-3 text-ink hover:bg-cell-on">
|
||||
{L.download(picked.size)}
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{counts.received > 0 && (
|
||||
<div className="mb-3 font-mono text-[11px] text-muted">
|
||||
{L.received(counts.received)} · {L.sent(counts.sent)}
|
||||
{counts.failed > 0 && <span className="text-[#f0a35a]"> · {L.failed(counts.failed)}</span>}
|
||||
</div>
|
||||
)}
|
||||
<p className="mb-3 text-[11px] text-faint">{L.rawKept}</p>
|
||||
{status && (
|
||||
<div className="flex gap-2">
|
||||
<button onClick={() => void usb.setTether(!status.tether)} className="h-7 border border-black bg-cell px-3 text-ink hover:bg-cell-on">
|
||||
{status.tether ? L.turnOff : L.turnOn}
|
||||
</button>
|
||||
{on && (
|
||||
<button onClick={() => void usb.syncClock()} className="h-7 border border-black bg-cell px-3 text-ink hover:bg-cell-on">
|
||||
{L.clockSync}
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
import { engineAuto, exportFrame, openFrame } from "../develop/Viewer.js";
|
||||
import { loadEngine } from "../develop/engine.js";
|
||||
import { folderRead, saveDevelopedJpeg, saveDevelopedXmp } from "./folderDrop.js";
|
||||
import { developedJpegName, developedXmpName, developXmp, dirOf, FOLDER_DEVELOP_EDGE, interiorCommand, interiorPartial } from "./interiorPreset.js";
|
||||
|
||||
/** JPEG bytes of one rendered frame. The pixels are already the developed image. */
|
||||
export async function jpegFromRgba(pixels: Uint8ClampedArray, width: number, height: number): Promise<Blob> {
|
||||
const canvas = document.createElement("canvas");
|
||||
canvas.width = width;
|
||||
canvas.height = height;
|
||||
const ctx = canvas.getContext("2d");
|
||||
if (!ctx) throw new Error("canvas");
|
||||
const rgba = new Uint8ClampedArray(pixels.byteLength);
|
||||
rgba.set(pixels);
|
||||
ctx.putImageData(new ImageData(rgba, width, height), 0, 0);
|
||||
const blob = await new Promise<Blob | null>((resolve) => canvas.toBlob(resolve, "image/jpeg", 0.92));
|
||||
if (!blob) throw new Error("jpeg");
|
||||
return blob;
|
||||
}
|
||||
|
||||
/**
|
||||
* The merged DNG, revealed for an interior (neutral whites, held windows, colour) and written beside it.
|
||||
* `download` means this shell cannot write into the folder yet, so the file went to Downloads.
|
||||
*/
|
||||
export async function finishMergedJpeg(dngPath: string): Promise<"beside" | "download"> {
|
||||
const engine = await loadEngine();
|
||||
const bytes = await folderRead(dngPath);
|
||||
const key = `${dngPath}#${Date.now()}`;
|
||||
await openFrame(key, bytes.slice(0), FOLDER_DEVELOP_EDGE);
|
||||
let exposure: number | undefined;
|
||||
try {
|
||||
const tone = await engineAuto(key, "tone");
|
||||
exposure = tone["light.exposure"];
|
||||
} catch {
|
||||
// The finish still opens the room when the photo has nothing to measure.
|
||||
}
|
||||
const partial = interiorPartial(exposure);
|
||||
const settings = engine.apply(engine.defaultSettings(), interiorCommand(partial));
|
||||
const frame = await exportFrame(key, settings, FOLDER_DEVELOP_EDGE, FOLDER_DEVELOP_EDGE);
|
||||
const blob = await jpegFromRgba(frame.pixels, frame.width, frame.height);
|
||||
const jpeg = new Uint8Array(await blob.arrayBuffer());
|
||||
const slash = Math.max(dngPath.lastIndexOf("/"), dngPath.lastIndexOf("\\"));
|
||||
const fileName = slash >= 0 ? dngPath.slice(slash + 1) : dngPath;
|
||||
const dir = dirOf(dngPath);
|
||||
const where = await saveDevelopedJpeg(dir, developedJpegName(fileName), jpeg);
|
||||
await saveDevelopedXmp(dir, developedXmpName(fileName), new TextEncoder().encode(developXmp(partial)));
|
||||
return where;
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { beginDropWait, htmlDropIsFolder, nativePaths, resetDropGate } from "./folderDrop.js";
|
||||
import { beginDropWait, htmlDropIsFolder, nativePaths, resetDropGate, saveDevelopedJpeg } from "./folderDrop.js";
|
||||
|
||||
describe("folder drop", () => {
|
||||
beforeEach(() => resetDropGate());
|
||||
@@ -31,6 +31,18 @@ describe("folder drop", () => {
|
||||
await expect(wait).resolves.toBe("files");
|
||||
});
|
||||
|
||||
it("writes a developed jpeg beside the photo", async () => {
|
||||
const writes: string[] = [];
|
||||
const where = await saveDevelopedJpeg("/job", "a.jpg", new Uint8Array([1, 2]), async (dir, name) => {
|
||||
writes.push(`${dir}/${name}`);
|
||||
});
|
||||
expect(where).toBe("beside");
|
||||
expect(writes).toEqual(["/job/a.jpg"]);
|
||||
await expect(saveDevelopedJpeg("/job", "a.jpg", new Uint8Array([1]), async () => {
|
||||
throw new Error("permission denied");
|
||||
})).rejects.toThrow(/permission/);
|
||||
});
|
||||
|
||||
it("sees a directory item as a folder", () => {
|
||||
expect(htmlDropIsFolder([{ webkitGetAsEntry: () => ({ isDirectory: true }) }])).toBe(true);
|
||||
expect(htmlDropIsFolder([{ webkitGetAsEntry: () => ({ isDirectory: false }) }])).toBe(false);
|
||||
|
||||
@@ -116,6 +116,90 @@ export async function openFolder(path: string, invoke: Invoke = desktopInvoke):
|
||||
}
|
||||
}
|
||||
|
||||
/** Capture metadata of one photo on the open sheet, read in the desktop process. */
|
||||
export function folderMeta(path: string, invoke: Invoke = desktopInvoke): Promise<string> {
|
||||
return invoke<string>("folder_meta", { path });
|
||||
}
|
||||
|
||||
/**
|
||||
* Merges these photos in the desktop process and writes the DNG beside the middle one.
|
||||
* The raws never cross into the page: a folder of CR3 does not fit in the browser engine.
|
||||
*/
|
||||
export function mergeFolderDng(paths: readonly string[], maxEdge: number, invoke: Invoke = desktopInvoke): Promise<string> {
|
||||
return invoke<string>("folder_merge_dng", { paths, maxEdge });
|
||||
}
|
||||
|
||||
/** The original of one photo on the open sheet, so Revelar can decode it here. */
|
||||
export async function folderRead(path: string, invoke: Invoke = desktopInvoke): Promise<ArrayBuffer> {
|
||||
return asArrayBuffer(await invoke<unknown>("folder_read", { path }));
|
||||
}
|
||||
|
||||
/** The file is the raw body. `dir` and `name` ride in headers, the same way a merged DNG is written. */
|
||||
async function writeJpegInShell(dir: string, name: string, bytes: Uint8Array): Promise<void> {
|
||||
const { invoke } = await import("@tauri-apps/api/core");
|
||||
await invoke<string>("folder_save_jpeg", bytes, {
|
||||
headers: { dir: encodeURIComponent(dir), name: encodeURIComponent(name) },
|
||||
});
|
||||
}
|
||||
|
||||
async function writeXmpInShell(dir: string, name: string, bytes: Uint8Array): Promise<void> {
|
||||
const { invoke } = await import("@tauri-apps/api/core");
|
||||
await invoke<string>("folder_save_xmp", bytes, {
|
||||
headers: { dir: encodeURIComponent(dir), name: encodeURIComponent(name) },
|
||||
});
|
||||
}
|
||||
|
||||
/** Writes the edit sidecar beside the DNG. A shell without the command leaves the JPEG as the only file. */
|
||||
export async function saveDevelopedXmp(dir: string, name: string, bytes: Uint8Array, write?: (dir: string, name: string, bytes: Uint8Array) => Promise<void>): Promise<"beside" | "missing"> {
|
||||
if (!dir) return "missing";
|
||||
if (!write && !isDesktop()) return "missing";
|
||||
try {
|
||||
await (write ?? writeXmpInShell)(dir, name, bytes);
|
||||
return "beside";
|
||||
} catch (err) {
|
||||
const message = err instanceof Error ? err.message : String(err);
|
||||
if (!write && /not found|unknown command/i.test(message)) return "missing";
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
function downloadJpeg(name: string, bytes: Uint8Array): void {
|
||||
const copy = new Uint8Array(bytes.byteLength);
|
||||
copy.set(bytes);
|
||||
const blob = new Blob([copy], { type: "image/jpeg" });
|
||||
const url = URL.createObjectURL(blob);
|
||||
const link = document.createElement("a");
|
||||
link.href = url;
|
||||
link.download = name;
|
||||
link.click();
|
||||
setTimeout(() => URL.revokeObjectURL(url), 1500);
|
||||
}
|
||||
|
||||
/**
|
||||
* Writes a developed JPEG into the opened folder. A shell from before this command downloads the file instead.
|
||||
* `write` replaces the shell call in tests.
|
||||
*/
|
||||
export async function saveDevelopedJpeg(
|
||||
dir: string,
|
||||
name: string,
|
||||
bytes: Uint8Array,
|
||||
write?: (dir: string, name: string, bytes: Uint8Array) => Promise<void>,
|
||||
): Promise<"beside" | "download"> {
|
||||
if (!dir) throw new Error("not_a_folder");
|
||||
if (write || isDesktop()) {
|
||||
try {
|
||||
await (write ?? writeJpegInShell)(dir, name, bytes);
|
||||
return "beside";
|
||||
} catch (err) {
|
||||
const message = err instanceof Error ? err.message : String(err);
|
||||
const missing = !write && /not found|unknown command/i.test(message);
|
||||
if (!missing) throw err;
|
||||
}
|
||||
}
|
||||
downloadJpeg(name, bytes);
|
||||
return "download";
|
||||
}
|
||||
|
||||
export async function folderThumb(path: string, edge: number, invoke?: Invoke): Promise<ArrayBuffer | null> {
|
||||
if (!invoke && !isDesktop()) return null;
|
||||
try {
|
||||
|
||||
@@ -0,0 +1,123 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { mergeFailureText, mergeFolderExposures, mergeFolderNative } from "./folderMerge.js";
|
||||
import { MergeError } from "./mergeExposures.js";
|
||||
|
||||
const at = (ms: number) => new Date(Date.parse("2026-10-21T10:00:00.000Z") + ms).toISOString();
|
||||
|
||||
function tags(bias: number, ms: number, exposureTime = 1 / 125): string {
|
||||
return JSON.stringify({
|
||||
capturedAt: at(ms),
|
||||
cameraModel: "EOS R5",
|
||||
focalLength: 16,
|
||||
aperture: 8,
|
||||
iso: 100,
|
||||
width: 4000,
|
||||
height: 3000,
|
||||
exposureBias: bias,
|
||||
exposureTime,
|
||||
});
|
||||
}
|
||||
|
||||
function files() {
|
||||
return [
|
||||
{ path: "/job/sala/dark.cr3", name: "dark.cr3" },
|
||||
{ path: "/job/sala/mid.cr3", name: "mid.cr3" },
|
||||
{ path: "/job/sala/bright.cr3", name: "bright.cr3" },
|
||||
{ path: "/job/sala/mid-fundido.dng", name: "mid-fundido.dng" },
|
||||
];
|
||||
}
|
||||
|
||||
const meta = new Map([
|
||||
["/job/sala/dark.cr3", tags(-2, 0)],
|
||||
["/job/sala/mid.cr3", tags(0, 200)],
|
||||
["/job/sala/bright.cr3", tags(2, 400)],
|
||||
]);
|
||||
|
||||
describe("merge a contact sheet", () => {
|
||||
it("writes one DNG beside the bracket when only the focused photo is selected", async () => {
|
||||
const saved: { dir: string; name: string; bytes: Uint8Array }[] = [];
|
||||
const made = await mergeFolderExposures({
|
||||
files: files(),
|
||||
selectedIds: ["/job/sala/dark.cr3"],
|
||||
readFile: async (path) => new TextEncoder().encode(path),
|
||||
readMeta: (bytes) => meta.get(new TextDecoder().decode(bytes)) ?? "{}",
|
||||
mergeDng: () => new Uint8Array([1, 2, 3]),
|
||||
saveDng: async (dir, name, bytes) => {
|
||||
saved.push({ dir, name, bytes });
|
||||
},
|
||||
});
|
||||
expect(made).toBe(1);
|
||||
expect(saved).toEqual([{ dir: "/job/sala", name: "mid-fundido.dng", bytes: new Uint8Array([1, 2, 3]) }]);
|
||||
});
|
||||
|
||||
it("merges the photos the user selected even when they are not a detected bracket", async () => {
|
||||
const saved: string[] = [];
|
||||
const made = await mergeFolderExposures({
|
||||
files: files(),
|
||||
selectedIds: ["/job/sala/dark.cr3", "/job/sala/mid.cr3"],
|
||||
readFile: async (path) => new TextEncoder().encode(path),
|
||||
readMeta: () => tags(0, 0, 1 / 125),
|
||||
mergeDng: (frames) => new Uint8Array([frames.length]),
|
||||
saveDng: async (_dir, name) => {
|
||||
saved.push(name);
|
||||
},
|
||||
});
|
||||
expect(made).toBe(1);
|
||||
expect(saved).toEqual(["dark-fundido.dng"]);
|
||||
});
|
||||
|
||||
it("says there is no set when a single photo is not part of a bracket", async () => {
|
||||
const run = mergeFolderExposures({
|
||||
files: [{ path: "/job/a.cr3", name: "a.cr3" }, { path: "/job/b.cr3", name: "b.cr3" }],
|
||||
selectedIds: ["/job/a.cr3"],
|
||||
readFile: async (path) => new TextEncoder().encode(path),
|
||||
readMeta: () => tags(0, 0),
|
||||
mergeDng: () => new Uint8Array([1]),
|
||||
saveDng: async () => {},
|
||||
});
|
||||
await expect(run).rejects.toBeInstanceOf(MergeError);
|
||||
await expect(run).rejects.toMatchObject({ code: "none" });
|
||||
});
|
||||
});
|
||||
|
||||
describe("merge a contact sheet on this computer", () => {
|
||||
const pair = [
|
||||
{ path: "/job/dark.cr3", name: "dark.cr3" },
|
||||
{ path: "/job/mid.cr3", name: "mid.cr3" },
|
||||
];
|
||||
|
||||
it("asks the desktop to merge the stack and keeps its reason when that fails", async () => {
|
||||
const stacks: string[][] = [];
|
||||
const run = mergeFolderNative({
|
||||
files: pair,
|
||||
selectedIds: pair.map((file) => file.path),
|
||||
metaOf: async () => tags(0, 0),
|
||||
mergePaths: async (paths) => {
|
||||
stacks.push([...paths]);
|
||||
throw new Error("cannot read the photo: cr3");
|
||||
},
|
||||
});
|
||||
await expect(run).rejects.toMatchObject({ code: "failed", detail: "cannot read the photo: cr3" });
|
||||
expect(stacks).toEqual([["/job/dark.cr3", "/job/mid.cr3"]]);
|
||||
expect(mergeFailureText("failed", "cannot read the photo: cr3")).toBe("Não consegui ler estes RAW para os fundir.");
|
||||
});
|
||||
|
||||
it("reveals each merged file when a jpeg was asked for", async () => {
|
||||
const finished: string[] = [];
|
||||
const phases: string[] = [];
|
||||
const result = await mergeFolderNative({
|
||||
files: pair,
|
||||
selectedIds: pair.map((file) => file.path),
|
||||
metaOf: async () => tags(0, 0),
|
||||
onStatus: (stack, total, phase) => phases.push(`${phase ?? "merge"} ${stack}/${total}`),
|
||||
mergePaths: async () => "/job/mid-fundido.dng",
|
||||
finishJpeg: async (path) => {
|
||||
finished.push(path);
|
||||
return "beside";
|
||||
},
|
||||
});
|
||||
expect(result).toEqual({ made: 1, jpeg: "beside" });
|
||||
expect(finished).toEqual(["/job/mid-fundido.dng"]);
|
||||
expect(phases).toEqual(["merge 1/1", "jpeg 1/1"]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,222 @@
|
||||
import { loadEngine, type EngineModule } from "../develop/engine.js";
|
||||
import { t } from "../i18n.js";
|
||||
import { frameFromCapture } from "../realestate/readFrame.js";
|
||||
import { MergeError } from "./mergeExposures.js";
|
||||
import { MERGE_EDGE, isMergedName, stacksOfFrames } from "./mergeStacks.js";
|
||||
|
||||
export interface FolderExposure {
|
||||
path: string;
|
||||
name: string;
|
||||
}
|
||||
|
||||
function parentDir(path: string): string {
|
||||
const slash = Math.max(path.lastIndexOf("/"), path.lastIndexOf("\\"));
|
||||
if (slash <= 0) throw new MergeError("failed");
|
||||
return path.slice(0, slash);
|
||||
}
|
||||
|
||||
function stemOf(name: string): string {
|
||||
const dot = name.lastIndexOf(".");
|
||||
return dot > 0 ? name.slice(0, dot) : name;
|
||||
}
|
||||
|
||||
/**
|
||||
* Merges the contact sheet on this computer. A selection of two or more is that set; otherwise every
|
||||
* bracket in the folder. The DNG is written beside the middle frame. Nothing is uploaded.
|
||||
* Metadata is read first and the bytes dropped, then each stack is read again to merge: a folder of
|
||||
* raws must not all sit in memory at once.
|
||||
*/
|
||||
export async function mergeFolderExposures(opts: {
|
||||
files: readonly FolderExposure[];
|
||||
selectedIds: readonly string[];
|
||||
readFile: (path: string) => Promise<Uint8Array>;
|
||||
readMeta: (bytes: Uint8Array) => string | Promise<string>;
|
||||
mergeDng: (files: Uint8Array[]) => Uint8Array;
|
||||
saveDng: (dir: string, name: string, bytes: Uint8Array) => Promise<void>;
|
||||
onStatus?: (stack: number, total: number) => void;
|
||||
}): Promise<number> {
|
||||
const candidates = opts.files.filter((file) => !isMergedName(file.name));
|
||||
const selected = new Set(opts.selectedIds);
|
||||
const chosen = selected.size >= 2;
|
||||
const pool = chosen ? candidates.filter((file) => selected.has(file.path)) : candidates;
|
||||
if (pool.length < 2) throw new MergeError("none");
|
||||
|
||||
const frames = [];
|
||||
for (const file of pool) {
|
||||
const bytes = await readOrMissing(opts.readFile, file.path);
|
||||
frames.push(await frameOfFile(file, bytes, opts.readMeta));
|
||||
}
|
||||
|
||||
const stacks = stacksOfFrames(frames, opts.selectedIds);
|
||||
if (stacks.length === 0) throw new MergeError("none");
|
||||
|
||||
const byPath = new Map(pool.map((file) => [file.path, file]));
|
||||
let made = 0;
|
||||
for (let index = 0; index < stacks.length; index++) {
|
||||
opts.onStatus?.(index + 1, stacks.length);
|
||||
const members = (stacks[index] ?? []).map((id) => byPath.get(id)).filter((file): file is FolderExposure => !!file);
|
||||
if (members.length < 2) throw new MergeError("none");
|
||||
const files: Uint8Array[] = [];
|
||||
for (const member of members) files.push(await readOrMissing(opts.readFile, member.path));
|
||||
const dng = mergedOrFailed(opts.mergeDng, files);
|
||||
const mid = members[Math.floor((members.length - 1) / 2)]!;
|
||||
try {
|
||||
await opts.saveDng(parentDir(mid.path), `${stemOf(mid.name)}-fundido.dng`, dng);
|
||||
} catch (err) {
|
||||
if (err instanceof MergeError) throw err;
|
||||
throw new MergeError("failed");
|
||||
}
|
||||
made += 1;
|
||||
}
|
||||
return made;
|
||||
}
|
||||
|
||||
async function readOrMissing(readFile: (path: string) => Promise<Uint8Array>, path: string): Promise<Uint8Array> {
|
||||
try {
|
||||
const bytes = await readFile(path);
|
||||
if (bytes.byteLength === 0) throw new MergeError("missing");
|
||||
return bytes;
|
||||
} catch (err) {
|
||||
if (err instanceof MergeError) throw err;
|
||||
throw new MergeError("missing");
|
||||
}
|
||||
}
|
||||
|
||||
async function frameOfFile(
|
||||
file: FolderExposure,
|
||||
bytes: Uint8Array,
|
||||
readMeta: (bytes: Uint8Array) => string | Promise<string>,
|
||||
) {
|
||||
try {
|
||||
const tags = JSON.parse(await readMeta(bytes)) as Record<string, unknown>;
|
||||
return frameFromCapture(file.path, file.name, tags);
|
||||
} catch {
|
||||
return { id: file.path, fileName: file.name };
|
||||
}
|
||||
}
|
||||
|
||||
function mergedOrFailed(mergeDng: (files: Uint8Array[]) => Uint8Array, files: Uint8Array[]): Uint8Array {
|
||||
try {
|
||||
const dng = mergeDng(files);
|
||||
if (dng.byteLength === 0) throw new MergeError("failed");
|
||||
return dng;
|
||||
} catch (err) {
|
||||
if (err instanceof MergeError) throw err;
|
||||
throw new MergeError("failed");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Merges the contact sheet in the desktop process. Metadata and the DNG stay there: sending every
|
||||
* raw into the browser engine is what made a folder of CR3 fail with no reason.
|
||||
*/
|
||||
export async function mergeFolderNative(opts: {
|
||||
files: readonly FolderExposure[];
|
||||
selectedIds: readonly string[];
|
||||
metaOf: (path: string) => Promise<string>;
|
||||
/** Merges one stack and returns the DNG path written beside the middle frame. */
|
||||
mergePaths: (paths: readonly string[]) => Promise<string>;
|
||||
/** When set, each DNG is also revealed and saved as a JPEG before the next stack. */
|
||||
finishJpeg?: (dngPath: string) => Promise<"beside" | "download">;
|
||||
onStatus?: (stack: number, total: number, phase?: "merge" | "jpeg") => void;
|
||||
}): Promise<{ made: number; jpeg: "beside" | "download" | "none" }> {
|
||||
const candidates = opts.files.filter((file) => !isMergedName(file.name));
|
||||
const selected = new Set(opts.selectedIds);
|
||||
const chosen = selected.size >= 2;
|
||||
const pool = chosen ? candidates.filter((file) => selected.has(file.path)) : candidates;
|
||||
if (pool.length < 2) throw new MergeError("none");
|
||||
|
||||
const frames = [];
|
||||
for (const file of pool) {
|
||||
try {
|
||||
const tags = JSON.parse(await opts.metaOf(file.path)) as Record<string, unknown>;
|
||||
frames.push(frameFromCapture(file.path, file.name, tags));
|
||||
} catch (err) {
|
||||
if (err instanceof MergeError) throw err;
|
||||
frames.push({ id: file.path, fileName: file.name });
|
||||
}
|
||||
}
|
||||
|
||||
const stacks = stacksOfFrames(frames, opts.selectedIds);
|
||||
if (stacks.length === 0) throw new MergeError("none");
|
||||
|
||||
let made = 0;
|
||||
let jpeg: "beside" | "download" | "none" = opts.finishJpeg ? "beside" : "none";
|
||||
for (let index = 0; index < stacks.length; index++) {
|
||||
const ids = stacks[index] ?? [];
|
||||
if (ids.length < 2) throw new MergeError("none");
|
||||
opts.onStatus?.(index + 1, stacks.length, "merge");
|
||||
let dngPath = "";
|
||||
try {
|
||||
dngPath = await opts.mergePaths(ids);
|
||||
} catch (err) {
|
||||
if (err instanceof MergeError) throw err;
|
||||
const detail = err instanceof Error ? err.message : String(err);
|
||||
throw new MergeError("failed", detail);
|
||||
}
|
||||
if (opts.finishJpeg) {
|
||||
opts.onStatus?.(index + 1, stacks.length, "jpeg");
|
||||
try {
|
||||
const where = await opts.finishJpeg(dngPath);
|
||||
if (where === "download") jpeg = "download";
|
||||
} catch (err) {
|
||||
if (err instanceof MergeError) throw err;
|
||||
const detail = err instanceof Error ? err.message : String(err);
|
||||
throw new MergeError("failed", detail);
|
||||
}
|
||||
}
|
||||
made += 1;
|
||||
}
|
||||
return { made, jpeg };
|
||||
}
|
||||
|
||||
/** The sentence under the button. An unknown failure keeps the desktop's reason, so the next try is not a guess. */
|
||||
export function mergeFailureText(code: MergeError["code"], detail?: string): string {
|
||||
if (code !== "failed" || !detail) return t.merge.errors[code];
|
||||
const lower = detail.toLowerCase();
|
||||
if (lower.includes("permission") || lower.includes("read-only") || lower.includes("operation not permitted")) {
|
||||
return t.merge.errors.write;
|
||||
}
|
||||
if (lower.includes("cannot read the photo") || lower.includes("cannot be reduced")) {
|
||||
return t.merge.errors.raw;
|
||||
}
|
||||
return t.merge.errors.failedDetail(detail);
|
||||
}
|
||||
|
||||
/** The desktop merge: capture metadata and the linear DNG come from the develop engine. */
|
||||
export async function mergeFolderOnDisk(opts: {
|
||||
files: readonly FolderExposure[];
|
||||
selectedIds: readonly string[];
|
||||
readFile: (path: string) => Promise<Uint8Array>;
|
||||
saveDng: (dir: string, name: string, bytes: Uint8Array) => Promise<void>;
|
||||
onStatus?: (stack: number, total: number) => void;
|
||||
}): Promise<number> {
|
||||
let engine: EngineModule;
|
||||
try {
|
||||
engine = await loadEngine();
|
||||
} catch {
|
||||
throw new MergeError("engine");
|
||||
}
|
||||
return mergeFolderExposures({
|
||||
...opts,
|
||||
readMeta: (bytes) => engine.readCaptureMeta(bytes),
|
||||
mergeDng: (files) => dngOf(engine, files),
|
||||
});
|
||||
}
|
||||
|
||||
function dngOf(engine: EngineModule, files: Uint8Array[]): Uint8Array {
|
||||
const job = new engine.BracketJob();
|
||||
try {
|
||||
for (const file of files) job.push(file);
|
||||
if (!job.mergeDng) throw new MergeError("engine");
|
||||
const dng = job.mergeDng(MERGE_EDGE);
|
||||
const copy = new Uint8Array(dng.byteLength);
|
||||
copy.set(dng);
|
||||
return copy;
|
||||
} catch (err) {
|
||||
if (err instanceof MergeError) throw err;
|
||||
throw new MergeError("failed");
|
||||
} finally {
|
||||
job.free();
|
||||
}
|
||||
}
|
||||
@@ -37,6 +37,59 @@ describe("contact sheet", () => {
|
||||
expect(onClose).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it("merges the photos on the sheet", async () => {
|
||||
const user = userEvent.setup();
|
||||
const merge = vi.fn(
|
||||
async (_input: {
|
||||
files: { path: string; name: string }[];
|
||||
selectedIds: readonly string[];
|
||||
jpeg: boolean;
|
||||
onStatus: (stack: number, total: number, phase?: "merge" | "jpeg") => void;
|
||||
}) => ({ made: 1, jpeg: "none" as const }),
|
||||
);
|
||||
render(
|
||||
<FolderSheet
|
||||
folder={{
|
||||
path: "/job",
|
||||
name: "Sala",
|
||||
files: [
|
||||
{ path: "/job/a.jpg", name: "a.jpg" },
|
||||
{ path: "/job/b.jpg", name: "b.jpg" },
|
||||
{ path: "/job/c.jpg", name: "c.jpg" },
|
||||
],
|
||||
}}
|
||||
onClose={() => {}}
|
||||
thumb={thumb}
|
||||
merge={merge}
|
||||
/>,
|
||||
);
|
||||
await user.click(screen.getByRole("button", { name: "Fundir exposições" }));
|
||||
expect(merge).toHaveBeenCalledOnce();
|
||||
const input = merge.mock.calls[0]![0];
|
||||
expect(input.files.map((file) => file.name)).toEqual(["a.jpg", "b.jpg", "c.jpg"]);
|
||||
expect(input.selectedIds).toEqual(["/job/a.jpg"]);
|
||||
expect(input.jpeg).toBe(true);
|
||||
expect((await screen.findByRole("status")).textContent).toBe("1 DNG ficou nesta pasta.");
|
||||
});
|
||||
|
||||
it("opens the focused photo in develop", async () => {
|
||||
const user = userEvent.setup();
|
||||
const onDevelop = vi.fn();
|
||||
render(
|
||||
<FolderSheet
|
||||
folder={{ path: "/job", name: "Sala", files: [{ path: "/job/a.jpg", name: "a.jpg" }, { path: "/job/b.jpg", name: "b.jpg" }] }}
|
||||
onClose={() => {}}
|
||||
thumb={thumb}
|
||||
onDevelop={onDevelop}
|
||||
/>,
|
||||
);
|
||||
await user.click(screen.getByRole("button", { name: "Revelar" }));
|
||||
expect(onDevelop).toHaveBeenCalledWith("/job/a.jpg");
|
||||
onDevelop.mockClear();
|
||||
await user.keyboard("d");
|
||||
expect(onDevelop).toHaveBeenCalledWith("/job/a.jpg");
|
||||
});
|
||||
|
||||
it("does not mount a thumbnail button for every file", () => {
|
||||
const files = Array.from({ length: 200 }, (_, i) => ({ path: `/job/${i}.jpg`, name: `${i}.jpg` }));
|
||||
render(<FolderSheet folder={{ path: "/job", name: "job", files }} onClose={() => {}} thumb={thumb} />);
|
||||
|
||||
@@ -1,14 +1,22 @@
|
||||
import type { LibraryMessage } from "@photoreport/contracts";
|
||||
import type { PhotoSummary } from "@photoreport/contracts";
|
||||
import { createContext, type ReactNode, useCallback, useContext, useEffect, useRef } from "react";
|
||||
import { createContext, type ReactNode, useContext, useEffect, useMemo } from "react";
|
||||
import { useAuth } from "../auth.js";
|
||||
import { isDesktop, localOriginal, localOriginalChanged } from "../platform.js";
|
||||
import { isDesktop, localOriginal } from "../platform.js";
|
||||
import { useLocalFtp } from "./LocalFtp.js";
|
||||
import { OriginalSender } from "./originals.js";
|
||||
import { useLibraryLive } from "./realtime.js";
|
||||
import { useUploadQueue } from "./uploads.js";
|
||||
import { useOfflineSync } from "../offline/sync.js";
|
||||
import { useUsbCamera } from "./UsbCamera.js";
|
||||
|
||||
type Ingest = { uploads: ReturnType<typeof useUploadQueue>; localFtp: ReturnType<typeof useLocalFtp>; desktop: boolean };
|
||||
type Ingest = {
|
||||
uploads: ReturnType<typeof useUploadQueue>;
|
||||
localFtp: ReturnType<typeof useLocalFtp>;
|
||||
usb: ReturnType<typeof useUsbCamera>;
|
||||
desktop: boolean;
|
||||
/** Desktop only: pushes full originals for delivery / 100% zoom, off the JPEG upload queue. */
|
||||
originals: OriginalSender | null;
|
||||
};
|
||||
|
||||
const IngestContext = createContext<Ingest | null>(null);
|
||||
|
||||
@@ -29,89 +37,37 @@ function IngestState({ api, orgId, children }: { api: ReturnType<typeof useAuth>
|
||||
const desktop = isDesktop();
|
||||
const uploads = useUploadQueue(api, orgId);
|
||||
const localFtp = useLocalFtp(uploads.add, desktop && !!orgId, undefined, orgId);
|
||||
const usb = useUsbCamera(uploads.add, desktop && !!orgId, localFtp.target, undefined, orgId);
|
||||
const originals = useMemo(() => (desktop && orgId ? new OriginalSender(api) : null), [api, desktop, orgId]);
|
||||
useOfflineSync(api, orgId);
|
||||
return (
|
||||
<IngestContext.Provider value={{ uploads, localFtp, desktop }}>
|
||||
{desktop && !!orgId && <OriginalResponder api={api} add={uploads.add} />}
|
||||
<IngestContext.Provider value={{ uploads, localFtp, usb, desktop, originals }}>
|
||||
{desktop && !!orgId && originals && <OriginalResponder api={api} orgId={orgId} sender={originals} />}
|
||||
{desktop && !!orgId && <FailedRepair api={api} orgId={orgId} add={uploads.add} />}
|
||||
{children}
|
||||
</IngestContext.Provider>
|
||||
);
|
||||
}
|
||||
|
||||
/** Several megabytes through IPC. Dozens at once freeze the webview on "A enviar…" and the send never finishes. */
|
||||
const ORIGINAL_IPC_MS = 45_000;
|
||||
/** A few at a time: one is slow, all of them freeze the bar. */
|
||||
const MAX_PARALLEL_ORIGINALS = 3;
|
||||
|
||||
function withTimeout<T>(work: Promise<T>, ms: number): Promise<T | "timeout" | null> {
|
||||
return new Promise((resolve) => {
|
||||
let settled = false;
|
||||
const finish = (value: T | "timeout" | null) => {
|
||||
if (settled) return;
|
||||
settled = true;
|
||||
clearTimeout(timer);
|
||||
resolve(value);
|
||||
};
|
||||
const timer = setTimeout(() => finish("timeout"), ms);
|
||||
work.then(
|
||||
(value) => finish(value),
|
||||
() => finish(null),
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Desktop app: when someone needs the full original of a photo this computer keeps (100% zoom on the web, an export
|
||||
* made on the server, delivery to ZeroZero), the server asks over the live channel and this sends it.
|
||||
* Up to three at a time, so the webview stays responsive and the next ask can run.
|
||||
* Desktop: when delivery (or 100% zoom) needs a full original kept here, send it on its own track — never
|
||||
* through the JPEG upload queue, so new shots keep leaving and one stuck file does not block the rest.
|
||||
*/
|
||||
function OriginalResponder({ api, add }: { api: ReturnType<typeof useAuth>["api"]; add: ReturnType<typeof useUploadQueue>["add"] }) {
|
||||
const sending = useRef(new Set<string>());
|
||||
const queue = useRef<{ sha256: string; photoId: string }[]>([]);
|
||||
const active = useRef(0);
|
||||
|
||||
const pump = useCallback(() => {
|
||||
while (active.current < MAX_PARALLEL_ORIGINALS) {
|
||||
const next = queue.current.shift();
|
||||
if (!next) return;
|
||||
active.current += 1;
|
||||
const release = () => {
|
||||
sending.current.delete(next.sha256);
|
||||
active.current -= 1;
|
||||
pump();
|
||||
};
|
||||
void (async () => {
|
||||
const bytes = await withTimeout(localOriginal(next.sha256), ORIGINAL_IPC_MS);
|
||||
if (bytes && bytes !== "timeout") {
|
||||
add([new File([bytes], `${next.sha256}.jpg`, { type: "image/jpeg" })], undefined, () => release());
|
||||
return;
|
||||
}
|
||||
if (bytes !== "timeout") {
|
||||
// The file is still here but changed since it arrived (Photo Mechanic wrote captions into it): sent as this
|
||||
// photo's original, which the server checks is the same photo.
|
||||
try {
|
||||
const changed = await withTimeout(localOriginalChanged(next.sha256), ORIGINAL_IPC_MS);
|
||||
if (changed && changed !== "timeout") await api.sendOriginal(next.photoId, new Blob([changed], { type: "image/jpeg" }), `${next.sha256}.jpg`);
|
||||
} catch {
|
||||
/* not the same photo, or offline: asked again later */
|
||||
}
|
||||
}
|
||||
release();
|
||||
})();
|
||||
}
|
||||
}, [add, api]);
|
||||
|
||||
const onMessage = useCallback(
|
||||
(m: LibraryMessage) => {
|
||||
if (m.type !== "original.requested" || sending.current.has(m.sha256)) return;
|
||||
sending.current.add(m.sha256);
|
||||
queue.current.push({ sha256: m.sha256, photoId: m.photoId });
|
||||
pump();
|
||||
},
|
||||
[pump],
|
||||
);
|
||||
useLibraryLive(api, onMessage);
|
||||
function OriginalResponder({
|
||||
api,
|
||||
orgId,
|
||||
sender,
|
||||
}: {
|
||||
api: ReturnType<typeof useAuth>["api"];
|
||||
orgId: string;
|
||||
sender: OriginalSender;
|
||||
}) {
|
||||
useLibraryLive(api, (m) => sender.onMessage(m));
|
||||
useEffect(() => {
|
||||
void sender.flushWaiting(orgId);
|
||||
const timer = setInterval(() => void sender.flushWaiting(orgId), 45_000);
|
||||
return () => clearInterval(timer);
|
||||
}, [sender, orgId]);
|
||||
return null;
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,66 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { developedJpegName, developedXmpName, developXmp, dirOf, interiorPartial, partialFromSettings, partialFromXmp } from "./interiorPreset.js";
|
||||
|
||||
describe("interior finish", () => {
|
||||
it("opens the room from the photo's exposure and holds the windows", () => {
|
||||
const next = interiorPartial(0.31);
|
||||
expect(next.wb.mode).toBe("daylight");
|
||||
expect(next.wb.temp).toBe(5500);
|
||||
expect(next.wb.tint).toBe(10);
|
||||
expect(next.light.exposure).toBe(0.71);
|
||||
expect(next.light.contrast).toBe(12);
|
||||
expect(next.light.highlights).toBe(-100);
|
||||
expect(next.light.shadows).toBe(100);
|
||||
expect(next.light.whites).toBe(-15);
|
||||
expect(next.detail.sharpen_amount).toBe(40);
|
||||
expect(next.detail.nr_color).toBe(25);
|
||||
});
|
||||
|
||||
it("does not let a bright or dark measurement throw the exposure away", () => {
|
||||
expect(interiorPartial(2).light.exposure).toBe(1.15);
|
||||
expect(interiorPartial(-2).light.exposure).toBe(0.35);
|
||||
expect(interiorPartial(undefined).light.exposure).toBe(0.7);
|
||||
});
|
||||
});
|
||||
|
||||
describe("develop sidecar", () => {
|
||||
it("writes the edit and reads the same sliders back", () => {
|
||||
const partial = interiorPartial(0.31);
|
||||
const back = partialFromXmp(developXmp(partial));
|
||||
expect(back).toEqual(partial);
|
||||
});
|
||||
|
||||
it("reads a sidecar another editor saved", () => {
|
||||
const xml = `<rdf:Description crs:WhiteBalance="Custom" crs:Temperature="5200" crs:Tint="+4" crs:Exposure2012="+0.40" crs:Shadows2012="+80" crs:Highlights2012="-60"/>`;
|
||||
const back = partialFromXmp(xml);
|
||||
expect(back?.wb.mode).toBe("custom");
|
||||
expect(back?.wb.temp).toBe(5200);
|
||||
expect(back?.light.exposure).toBe(0.4);
|
||||
expect(back?.light.shadows).toBe(80);
|
||||
expect(back?.light.highlights).toBe(-60);
|
||||
});
|
||||
|
||||
it("takes the edit off the settings document", () => {
|
||||
const partial = partialFromSettings(
|
||||
JSON.stringify({
|
||||
wb: { mode: "daylight", temp: 5500, tint: 10 },
|
||||
light: { exposure: 0.71, contrast: 12, highlights: -100, shadows: 90, whites: -15, blacks: 4 },
|
||||
color: { vibrance: 12, saturation: 0 },
|
||||
effects: { clarity: 8, dehaze: 6 },
|
||||
detail: { sharpen_amount: 40, nr_color: 25 },
|
||||
}),
|
||||
);
|
||||
expect(partial?.light.shadows).toBe(90);
|
||||
expect(partial?.wb.mode).toBe("daylight");
|
||||
});
|
||||
});
|
||||
|
||||
describe("developed jpeg name", () => {
|
||||
it("uses the file's own stem beside it", () => {
|
||||
expect(developedJpegName("PSR10172-fundido.dng")).toBe("PSR10172-fundido.jpg");
|
||||
expect(developedXmpName("PSR10172-fundido.dng")).toBe("PSR10172-fundido.xmp");
|
||||
expect(developedJpegName("PSR10172.CR3")).toBe("PSR10172.jpg");
|
||||
expect(developedJpegName("sala")).toBe("sala.jpg");
|
||||
expect(dirOf("/Users/cyclop/Desktop/RAW/PSR10172-fundido.dng")).toBe("/Users/cyclop/Desktop/RAW");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,239 @@
|
||||
/** Longest side decoded for a folder photo in Revelar, and for the JPEG saved from it. */
|
||||
export const FOLDER_DEVELOP_EDGE = 4096;
|
||||
|
||||
/**
|
||||
* Daylight interior. Auto contrast (a high fixed value) was crushing the shadows it had just
|
||||
* lifted, and a grey-world white balance on wood stayed warmer than the daylight the camera used.
|
||||
* Exposure still follows the photo, a little brighter, and is kept inside a range that opens the
|
||||
* room without throwing the windows away. The other sliders are the finish, not a nudge.
|
||||
*/
|
||||
export type InteriorPartial = {
|
||||
wb: { mode: string; temp: number; tint: number; scale: "kelvin" };
|
||||
light: { exposure: number; contrast: number; highlights: number; shadows: number; whites: number; blacks: number };
|
||||
color: { vibrance: number; saturation: number };
|
||||
effects: { clarity: number; dehaze: number };
|
||||
detail: { sharpen_amount: number; nr_color: number };
|
||||
};
|
||||
|
||||
const FINISH = {
|
||||
contrast: 12,
|
||||
highlights: -100,
|
||||
shadows: 100,
|
||||
whites: -15,
|
||||
blacks: 4,
|
||||
vibrance: 12,
|
||||
saturation: 0,
|
||||
clarity: 8,
|
||||
dehaze: 6,
|
||||
sharpen: 40,
|
||||
nrColor: 25,
|
||||
temp: 5500,
|
||||
tint: 10,
|
||||
} as const;
|
||||
|
||||
export function interiorPartial(autoExposure: number | undefined): InteriorPartial {
|
||||
const base = Number.isFinite(autoExposure) ? (autoExposure as number) : 0.3;
|
||||
const exposure = Math.round(Math.min(1.15, Math.max(0.35, base + 0.4)) * 100) / 100;
|
||||
return {
|
||||
wb: { mode: "daylight", temp: FINISH.temp, tint: FINISH.tint, scale: "kelvin" },
|
||||
light: {
|
||||
exposure,
|
||||
contrast: FINISH.contrast,
|
||||
highlights: FINISH.highlights,
|
||||
shadows: FINISH.shadows,
|
||||
whites: FINISH.whites,
|
||||
blacks: FINISH.blacks,
|
||||
},
|
||||
color: { vibrance: FINISH.vibrance, saturation: FINISH.saturation },
|
||||
effects: { clarity: FINISH.clarity, dehaze: FINISH.dehaze },
|
||||
detail: { sharpen_amount: FINISH.sharpen, nr_color: FINISH.nrColor },
|
||||
};
|
||||
}
|
||||
|
||||
/** One develop.merge of the interior finish, including the daylight white balance. */
|
||||
export function interiorCommand(partial: InteriorPartial): string {
|
||||
return JSON.stringify({ command: "develop.merge", params: { partial } });
|
||||
}
|
||||
|
||||
/** JPEG written beside the file being developed: `PSR10172-fundido.dng` becomes `PSR10172-fundido.jpg`. */
|
||||
export function developedJpegName(fileName: string): string {
|
||||
const slash = Math.max(fileName.lastIndexOf("/"), fileName.lastIndexOf("\\"));
|
||||
const base = slash >= 0 ? fileName.slice(slash + 1) : fileName;
|
||||
const dot = base.lastIndexOf(".");
|
||||
const stem = dot > 0 ? base.slice(0, dot) : base;
|
||||
return `${stem || "foto"}.jpg`;
|
||||
}
|
||||
|
||||
/** Sidecar with the same stem, so the edit can be opened and changed again. */
|
||||
export function developedXmpName(fileName: string): string {
|
||||
return developedJpegName(fileName).replace(/\.jpg$/i, ".xmp");
|
||||
}
|
||||
|
||||
export function dirOf(path: string): string {
|
||||
const slash = Math.max(path.lastIndexOf("/"), path.lastIndexOf("\\"));
|
||||
if (slash <= 0) return "";
|
||||
return path.slice(0, slash);
|
||||
}
|
||||
|
||||
type SettingsDoc = {
|
||||
wb?: { mode?: string; temp?: number; tint?: number };
|
||||
light?: Partial<InteriorPartial["light"]>;
|
||||
color?: Partial<InteriorPartial["color"]>;
|
||||
effects?: Partial<InteriorPartial["effects"]>;
|
||||
detail?: { sharpen_amount?: number; nr_color?: number };
|
||||
};
|
||||
|
||||
/** The edit currently on the photo, in the shape a sidecar stores. */
|
||||
export function partialFromSettings(settings: string): InteriorPartial | null {
|
||||
let doc: SettingsDoc;
|
||||
try {
|
||||
doc = JSON.parse(settings) as SettingsDoc;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
if (!doc || typeof doc !== "object") return null;
|
||||
const fallback = interiorPartial(0.3);
|
||||
const num = (value: number | undefined, instead: number) => (typeof value === "number" && Number.isFinite(value) ? value : instead);
|
||||
const mode = typeof doc.wb?.mode === "string" && doc.wb.mode ? doc.wb.mode : fallback.wb.mode;
|
||||
return {
|
||||
wb: {
|
||||
mode,
|
||||
temp: num(doc.wb?.temp, fallback.wb.temp),
|
||||
tint: num(doc.wb?.tint, fallback.wb.tint),
|
||||
scale: "kelvin",
|
||||
},
|
||||
light: {
|
||||
exposure: num(doc.light?.exposure, fallback.light.exposure),
|
||||
contrast: num(doc.light?.contrast, fallback.light.contrast),
|
||||
highlights: num(doc.light?.highlights, fallback.light.highlights),
|
||||
shadows: num(doc.light?.shadows, fallback.light.shadows),
|
||||
whites: num(doc.light?.whites, fallback.light.whites),
|
||||
blacks: num(doc.light?.blacks, fallback.light.blacks),
|
||||
},
|
||||
color: {
|
||||
vibrance: num(doc.color?.vibrance, fallback.color.vibrance),
|
||||
saturation: num(doc.color?.saturation, fallback.color.saturation),
|
||||
},
|
||||
effects: {
|
||||
clarity: num(doc.effects?.clarity, fallback.effects.clarity),
|
||||
dehaze: num(doc.effects?.dehaze, fallback.effects.dehaze),
|
||||
},
|
||||
detail: {
|
||||
sharpen_amount: num(doc.detail?.sharpen_amount, fallback.detail.sharpen_amount),
|
||||
nr_color: num(doc.detail?.nr_color, fallback.detail.nr_color),
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
const WB_LABEL: Record<string, string> = {
|
||||
asShot: "As Shot",
|
||||
auto: "Auto",
|
||||
daylight: "Daylight",
|
||||
cloudy: "Cloudy",
|
||||
shade: "Shade",
|
||||
tungsten: "Tungsten",
|
||||
fluorescent: "Fluorescent",
|
||||
flash: "Flash",
|
||||
custom: "Custom",
|
||||
};
|
||||
|
||||
function crsNumber(value: number, digits: number): string {
|
||||
const text = digits === 0 ? String(Math.round(value)) : value.toFixed(digits);
|
||||
return value > 0 ? `+${text}` : text;
|
||||
}
|
||||
|
||||
function xmlAttr(value: string): string {
|
||||
return value.replace(/&/g, "&").replace(/"/g, """).replace(/</g, "<");
|
||||
}
|
||||
|
||||
/**
|
||||
* Sidecar in the camera-raw vocabulary: temperature, tint and the same sliders, so the edit can be
|
||||
* read back here and by another raw editor that understands those names.
|
||||
*/
|
||||
export function developXmp(partial: InteriorPartial): string {
|
||||
const wb = WB_LABEL[partial.wb.mode] ?? "Custom";
|
||||
const attrs = [
|
||||
`crs:Version="15.4"`,
|
||||
`crs:ProcessVersion="11.0"`,
|
||||
`crs:WhiteBalance="${xmlAttr(wb)}"`,
|
||||
`crs:Temperature="${crsNumber(partial.wb.temp, 0)}"`,
|
||||
`crs:Tint="${crsNumber(partial.wb.tint, 0)}"`,
|
||||
`crs:Exposure2012="${crsNumber(partial.light.exposure, 2)}"`,
|
||||
`crs:Contrast2012="${crsNumber(partial.light.contrast, 0)}"`,
|
||||
`crs:Highlights2012="${crsNumber(partial.light.highlights, 0)}"`,
|
||||
`crs:Shadows2012="${crsNumber(partial.light.shadows, 0)}"`,
|
||||
`crs:Whites2012="${crsNumber(partial.light.whites, 0)}"`,
|
||||
`crs:Blacks2012="${crsNumber(partial.light.blacks, 0)}"`,
|
||||
`crs:Clarity2012="${crsNumber(partial.effects.clarity, 0)}"`,
|
||||
`crs:Dehaze="${crsNumber(partial.effects.dehaze, 0)}"`,
|
||||
`crs:Vibrance="${crsNumber(partial.color.vibrance, 0)}"`,
|
||||
`crs:Saturation="${crsNumber(partial.color.saturation, 0)}"`,
|
||||
`crs:Sharpness="${crsNumber(partial.detail.sharpen_amount, 0)}"`,
|
||||
`crs:ColorNoiseReduction="${crsNumber(partial.detail.nr_color, 0)}"`,
|
||||
].join(" ");
|
||||
return `<?xml version="1.0" encoding="UTF-8"?>\n<x:xmpmeta xmlns:x="adobe:ns:meta/">\n <rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">\n <rdf:Description rdf:about="" xmlns:crs="http://ns.adobe.com/camera-raw-settings/1.0/" ${attrs}/>\n </rdf:RDF>\n</x:xmpmeta>\n`;
|
||||
}
|
||||
|
||||
function crsAttr(xml: string, name: string): string | undefined {
|
||||
const match = new RegExp(`crs:${name}="([^"]*)"`).exec(xml);
|
||||
return match?.[1];
|
||||
}
|
||||
|
||||
function crsFloat(xml: string, name: string): number | undefined {
|
||||
const text = crsAttr(xml, name);
|
||||
if (text === undefined) return undefined;
|
||||
const value = Number(text);
|
||||
return Number.isFinite(value) ? value : undefined;
|
||||
}
|
||||
|
||||
const WB_MODE: Record<string, string> = {
|
||||
"as shot": "asShot",
|
||||
auto: "auto",
|
||||
daylight: "daylight",
|
||||
cloudy: "cloudy",
|
||||
shade: "shade",
|
||||
tungsten: "tungsten",
|
||||
fluorescent: "fluorescent",
|
||||
flash: "flash",
|
||||
custom: "custom",
|
||||
};
|
||||
|
||||
/** The edit stored in a sidecar. Null when the packet has none of the sliders. */
|
||||
export function partialFromXmp(xml: string): InteriorPartial | null {
|
||||
const exposure = crsFloat(xml, "Exposure2012");
|
||||
const shadows = crsFloat(xml, "Shadows2012");
|
||||
const highlights = crsFloat(xml, "Highlights2012");
|
||||
const temp = crsFloat(xml, "Temperature");
|
||||
if (exposure === undefined && shadows === undefined && highlights === undefined && temp === undefined) return null;
|
||||
const fallback = interiorPartial(exposure);
|
||||
const label = (crsAttr(xml, "WhiteBalance") ?? "").toLowerCase().replace(/\s+/g, " ");
|
||||
const mode = WB_MODE[label] ?? (temp === undefined ? fallback.wb.mode : "custom");
|
||||
return {
|
||||
wb: {
|
||||
mode,
|
||||
temp: temp ?? fallback.wb.temp,
|
||||
tint: crsFloat(xml, "Tint") ?? fallback.wb.tint,
|
||||
scale: "kelvin",
|
||||
},
|
||||
light: {
|
||||
exposure: exposure ?? fallback.light.exposure,
|
||||
contrast: crsFloat(xml, "Contrast2012") ?? fallback.light.contrast,
|
||||
highlights: highlights ?? fallback.light.highlights,
|
||||
shadows: shadows ?? fallback.light.shadows,
|
||||
whites: crsFloat(xml, "Whites2012") ?? fallback.light.whites,
|
||||
blacks: crsFloat(xml, "Blacks2012") ?? fallback.light.blacks,
|
||||
},
|
||||
color: {
|
||||
vibrance: crsFloat(xml, "Vibrance") ?? fallback.color.vibrance,
|
||||
saturation: crsFloat(xml, "Saturation") ?? fallback.color.saturation,
|
||||
},
|
||||
effects: {
|
||||
clarity: crsFloat(xml, "Clarity2012") ?? fallback.effects.clarity,
|
||||
dehaze: crsFloat(xml, "Dehaze") ?? fallback.effects.dehaze,
|
||||
},
|
||||
detail: {
|
||||
sharpen_amount: crsFloat(xml, "Sharpness") ?? fallback.detail.sharpen_amount,
|
||||
nr_color: crsFloat(xml, "ColorNoiseReduction") ?? fallback.detail.nr_color,
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import { localPhotos } from "../offline/local.js";
|
||||
import { showLocalJpeg } from "./localIngest.js";
|
||||
|
||||
describe("showLocalJpeg", () => {
|
||||
it("puts a desktop preview into the library before upload", async () => {
|
||||
for (const p of localPhotos.list()) localPhotos.remove(p.id);
|
||||
const bytes = new Uint8Array([0xff, 0xd8, 0xff, 0xd9]);
|
||||
const file = new File([bytes], "IMG_1.JPG", { type: "image/jpeg" });
|
||||
// createImageBitmap may be missing in jsdom — stub size via origin.
|
||||
const sha = await showLocalJpeg({
|
||||
file,
|
||||
eventId: "ev1",
|
||||
origin: { sha256: "abc123", size: 4, width: 100, height: 80 },
|
||||
});
|
||||
expect(sha?.sha256).toBe("abc123");
|
||||
expect(localPhotos.bySha("abc123")?.eventId).toBe("ev1");
|
||||
expect(localPhotos.bySha("abc123")?.originalName).toBe("IMG_1.JPG");
|
||||
for (const p of localPhotos.list()) localPhotos.remove(p.id);
|
||||
});
|
||||
|
||||
it("skips a second put for the same sha", async () => {
|
||||
for (const p of localPhotos.list()) localPhotos.remove(p.id);
|
||||
const file = new File([new Uint8Array([1, 2, 3])], "A.JPG", { type: "image/jpeg" });
|
||||
const origin = { sha256: "same", size: 3, width: 10, height: 10 };
|
||||
await showLocalJpeg({ file, origin });
|
||||
const spy = vi.spyOn(localPhotos, "put");
|
||||
await showLocalJpeg({ file, origin });
|
||||
expect(spy).not.toHaveBeenCalled();
|
||||
spy.mockRestore();
|
||||
for (const p of localPhotos.list()) localPhotos.remove(p.id);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,106 @@
|
||||
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 type { DesktopOrigin } from "./uploads.js";
|
||||
|
||||
/** SHA-256 hex of the bytes (same fingerprint the desktop shell uses for the original). */
|
||||
export async function sha256Hex(bytes: ArrayBuffer): Promise<string> {
|
||||
const hash = await crypto.subtle.digest("SHA-256", bytes);
|
||||
return [...new Uint8Array(hash)].map((b) => b.toString(16).padStart(2, "0")).join("");
|
||||
}
|
||||
|
||||
async function imageSize(blob: Blob): Promise<{ width: number; height: number }> {
|
||||
if (typeof createImageBitmap === "function") {
|
||||
const bmp = await createImageBitmap(blob);
|
||||
const size = { width: bmp.width, height: bmp.height };
|
||||
bmp.close();
|
||||
return size;
|
||||
}
|
||||
return await new Promise((resolve, reject) => {
|
||||
const img = new Image();
|
||||
const url = URL.createObjectURL(blob);
|
||||
img.onload = () => {
|
||||
resolve({ width: img.naturalWidth, height: img.naturalHeight });
|
||||
URL.revokeObjectURL(url);
|
||||
};
|
||||
img.onerror = () => {
|
||||
URL.revokeObjectURL(url);
|
||||
reject(new Error("decode"));
|
||||
};
|
||||
img.src = url;
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Puts a JPEG into the library at once from bytes already on this computer. Upload can finish later;
|
||||
* `photo.added` (same sha) replaces this row. Returns the sha (and the event chosen from EXIF) when on screen.
|
||||
*/
|
||||
export async function showLocalJpeg(args: {
|
||||
file: File;
|
||||
eventId?: string | undefined;
|
||||
origin?: DesktopOrigin | undefined;
|
||||
orgId?: string | undefined;
|
||||
events?: Pick<EventSummary, "id" | "startsAt" | "ingestFrom" | "ingestUntil" | "archivedAt">[] | undefined;
|
||||
}): Promise<{ sha256: string; eventId: string | null } | null> {
|
||||
const { file, origin, orgId, events } = args;
|
||||
try {
|
||||
let sha256: string;
|
||||
let width: number;
|
||||
let height: number;
|
||||
// Always read EXIF from the JPEG bytes when we can — desktop previews keep DateTimeOriginal, and that
|
||||
// clock (not the open event pin) decides which folder the photo appears in.
|
||||
const previewBytes = await file.arrayBuffer();
|
||||
if (origin && origin !== "original") {
|
||||
sha256 = origin.sha256;
|
||||
width = origin.width;
|
||||
height = origin.height;
|
||||
} else {
|
||||
sha256 = await sha256Hex(previewBytes);
|
||||
const size = await imageSize(new Blob([previewBytes], { type: "image/jpeg" }));
|
||||
width = size.width;
|
||||
height = size.height;
|
||||
}
|
||||
if (localPhotos.bySha(sha256)) return { sha256, eventId: localPhotos.bySha(sha256)?.eventId ?? null };
|
||||
let url = "";
|
||||
try {
|
||||
url = URL.createObjectURL(new Blob([previewBytes], { type: "image/jpeg" }));
|
||||
} catch {
|
||||
try {
|
||||
url = URL.createObjectURL(file);
|
||||
} catch {
|
||||
/* tests / no blob URLs */
|
||||
}
|
||||
}
|
||||
const capturedAt = lisbonInstant(exifDateTime(previewBytes));
|
||||
const eventId = events ? eventForArrival(args.eventId ?? null, events, capturedAt) : (args.eventId ?? null);
|
||||
localPhotos.put(
|
||||
localPhoto({
|
||||
sha256,
|
||||
name: file.name,
|
||||
width,
|
||||
height,
|
||||
capturedAt,
|
||||
eventId,
|
||||
url,
|
||||
}),
|
||||
);
|
||||
if (orgId) {
|
||||
for (const op of offlineQueue(orgId).pending) {
|
||||
if (op.kind === "patch" && op.ids.includes(localId(sha256))) {
|
||||
localPhotos.patch(localId(sha256), op.patch as Partial<PhotoSummary>);
|
||||
}
|
||||
}
|
||||
}
|
||||
return { sha256, eventId };
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/** After the server has the photo: map offline edits and drop the local stand-in. */
|
||||
export function settleLocalUpload(orgId: string, sha256: string | null | undefined, photo: PhotoSummary | undefined): void {
|
||||
if (!sha256) return;
|
||||
if (photo) offlineQueue(orgId).uploaded(sha256, photo.id);
|
||||
localPhotos.remove(localId(sha256));
|
||||
}
|
||||
@@ -5,8 +5,11 @@ import { localOriginal } from "../platform.js";
|
||||
import { MERGE_EDGE, stacksToMerge } from "./mergeStacks.js";
|
||||
|
||||
export class MergeError extends Error {
|
||||
constructor(readonly code: "none" | "missing" | "engine" | "failed") {
|
||||
super(code);
|
||||
constructor(
|
||||
readonly code: "none" | "missing" | "engine" | "failed",
|
||||
readonly detail?: string,
|
||||
) {
|
||||
super(detail ? `${code}: ${detail}` : code);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -4,12 +4,14 @@ import { groupBrackets, type BracketFrame } from "@photoreport/metadata";
|
||||
/** The engine's long-side cap for a merge. The DNG is this photo, not the full sensor. */
|
||||
export const MERGE_EDGE = 4096;
|
||||
|
||||
/** A DNG this merge already wrote is not another exposure. */
|
||||
export function isMergedName(name: string): boolean {
|
||||
const lower = name.toLowerCase();
|
||||
return lower.endsWith(".dng") || lower.includes("-fundido");
|
||||
}
|
||||
|
||||
function isMergedFile(photo: PhotoSummary): boolean {
|
||||
const names = [photo.originalName, photo.name];
|
||||
return names.some((name) => {
|
||||
const lower = name.toLowerCase();
|
||||
return lower.endsWith(".dng") || lower.includes("-fundido");
|
||||
});
|
||||
return isMergedName(photo.originalName) || isMergedName(photo.name);
|
||||
}
|
||||
|
||||
export function frameOf(photo: PhotoSummary): BracketFrame {
|
||||
@@ -27,25 +29,31 @@ export function frameOf(photo: PhotoSummary): BracketFrame {
|
||||
};
|
||||
}
|
||||
|
||||
function byCapture(a: PhotoSummary, b: PhotoSummary): number {
|
||||
function byFrame(a: BracketFrame, b: BracketFrame): number {
|
||||
const time = (a.capturedAt ?? "").localeCompare(b.capturedAt ?? "");
|
||||
if (time !== 0) return time;
|
||||
return (a.originalName || a.name).localeCompare(b.originalName || b.name, undefined, { numeric: true, sensitivity: "base" });
|
||||
return (a.fileName ?? a.id).localeCompare(b.fileName ?? b.id, undefined, { numeric: true, sensitivity: "base" });
|
||||
}
|
||||
|
||||
/**
|
||||
* Stacks to merge. A selection of two or more is that set (detected into angles when they are brackets,
|
||||
* otherwise one stack in capture order). With nothing selected, every bracket in the folder is a stack.
|
||||
* A DNG already produced here is not an exposure.
|
||||
* otherwise one stack in capture order). With fewer than two selected, every bracket in the folder is a stack.
|
||||
*/
|
||||
export function stacksOfFrames(frames: readonly BracketFrame[], selectedIds: readonly string[]): string[][] {
|
||||
const selected = new Set(selectedIds);
|
||||
const chosen = selected.size >= 2;
|
||||
const pool = chosen ? frames.filter((frame) => selected.has(frame.id)) : [...frames];
|
||||
if (pool.length < 2) return [];
|
||||
const grouped = groupBrackets(pool);
|
||||
if (grouped.stacks.length > 0) return grouped.stacks.map((stack) => stack.frameIds);
|
||||
if (!chosen) return [];
|
||||
return [[...pool].sort(byFrame).map((frame) => frame.id)];
|
||||
}
|
||||
|
||||
/**
|
||||
* Stacks in a library collection. A DNG already produced here is not an exposure.
|
||||
*/
|
||||
export function stacksToMerge(photos: readonly PhotoSummary[], selectedIds: readonly string[]): string[][] {
|
||||
const ready = photos.filter((photo) => photo.status === "READY" && !isMergedFile(photo));
|
||||
const selected = new Set(selectedIds);
|
||||
const chosen = selected.size >= 2;
|
||||
const pool = chosen ? ready.filter((photo) => selected.has(photo.id)) : ready;
|
||||
if (pool.length < 2) return [];
|
||||
const grouped = groupBrackets(pool.map(frameOf));
|
||||
if (grouped.stacks.length > 0) return grouped.stacks.map((stack) => stack.frameIds);
|
||||
if (!chosen) return [];
|
||||
return [[...pool].sort(byCapture).map((photo) => photo.id)];
|
||||
return stacksOfFrames(ready.map(frameOf), selectedIds);
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import { OriginalSender } from "./originals.js";
|
||||
|
||||
describe("OriginalSender", () => {
|
||||
it("does not put the same sha on the queue twice", () => {
|
||||
const api = {
|
||||
sendOriginal: vi.fn(async () => ({ stored: true })),
|
||||
requestOriginal: vi.fn(async () => ({ stored: false })),
|
||||
listDeliveries: vi.fn(async () => ({ items: [] })),
|
||||
};
|
||||
const sender = new OriginalSender(api as never);
|
||||
sender.enqueue({ photoId: "p1", sha256: "abc" });
|
||||
sender.enqueue({ photoId: "p1", sha256: "abc" });
|
||||
expect(sender.inFlight.size).toBeLessThanOrEqual(1);
|
||||
});
|
||||
|
||||
it("asks the server for originals when a delivery is waiting", () => {
|
||||
const api = {
|
||||
sendOriginal: vi.fn(async () => ({ stored: true })),
|
||||
requestOriginal: vi.fn(async () => ({ stored: false })),
|
||||
listDeliveries: vi.fn(async () => ({ items: [] })),
|
||||
};
|
||||
const sender = new OriginalSender(api as never);
|
||||
sender.onMessage({
|
||||
type: "delivery.updated",
|
||||
item: {
|
||||
id: "i1",
|
||||
targetId: "t1",
|
||||
photoId: "p1",
|
||||
eventId: "e1",
|
||||
sequence: 1,
|
||||
status: "QUEUED",
|
||||
attempts: 0,
|
||||
lastError: "waiting_for_original",
|
||||
remotePath: null,
|
||||
byteSize: null,
|
||||
updatedAt: "",
|
||||
},
|
||||
});
|
||||
expect(api.requestOriginal).toHaveBeenCalledWith("p1");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,126 @@
|
||||
import type { LibraryMessage } from "@photoreport/contracts";
|
||||
import type { ApiClient } from "@photoreport/sdk";
|
||||
import { localOriginal, localOriginalChanged, prefs } from "../platform.js";
|
||||
|
||||
/** Several megabytes through IPC. Dozens at once freeze the webview; one slow disk must not kill the rest. */
|
||||
const ORIGINAL_IPC_MS = 90_000;
|
||||
|
||||
const PREF_PARALLEL = "originals.parallel";
|
||||
|
||||
/** How many full originals leave this computer at once (delivery / 100% zoom). Default 4, clamp 2..8. */
|
||||
export function originalsParallel(): number {
|
||||
const n = Number(prefs.get(PREF_PARALLEL));
|
||||
if (Number.isFinite(n) && n >= 2 && n <= 8) return Math.floor(n);
|
||||
return 4;
|
||||
}
|
||||
|
||||
function withTimeout<T>(work: Promise<T>, ms: number): Promise<T | "timeout" | null> {
|
||||
return new Promise((resolve) => {
|
||||
let settled = false;
|
||||
const finish = (value: T | "timeout" | null) => {
|
||||
if (settled) return;
|
||||
settled = true;
|
||||
clearTimeout(timer);
|
||||
resolve(value);
|
||||
};
|
||||
const timer = setTimeout(() => finish("timeout"), ms);
|
||||
work.then(
|
||||
(value) => finish(value),
|
||||
() => finish(null),
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
export type OriginalNeed = { photoId: string; sha256: string };
|
||||
|
||||
/**
|
||||
* Sends originals this computer still has, on their own path (`POST /original`), never through the JPEG
|
||||
* upload queue. New shots keep uploading in parallel; one stuck original does not block the others.
|
||||
*/
|
||||
export class OriginalSender {
|
||||
private readonly sending = new Set<string>();
|
||||
private readonly queue: OriginalNeed[] = [];
|
||||
private active = 0;
|
||||
/** photoIds this machine is currently pushing — Destinos shows "a enviar…" instead of "abre a app". */
|
||||
readonly inFlight = new Set<string>();
|
||||
private readonly listeners = new Set<() => void>();
|
||||
|
||||
constructor(private readonly api: ApiClient) {}
|
||||
|
||||
subscribe(fn: () => void): () => void {
|
||||
this.listeners.add(fn);
|
||||
return () => this.listeners.delete(fn);
|
||||
}
|
||||
|
||||
private changed(): void {
|
||||
for (const fn of this.listeners) fn();
|
||||
}
|
||||
|
||||
/** From the live channel, or a Destinos row that is waiting for the file on this Mac. */
|
||||
enqueue(need: OriginalNeed): void {
|
||||
if (this.sending.has(need.sha256)) return;
|
||||
this.sending.add(need.sha256);
|
||||
this.queue.push(need);
|
||||
this.pump();
|
||||
}
|
||||
|
||||
onMessage(m: LibraryMessage): void {
|
||||
if (m.type === "original.requested") {
|
||||
this.enqueue({ photoId: m.photoId, sha256: m.sha256 });
|
||||
return;
|
||||
}
|
||||
// Delivery is blocked on the original we keep: push it at once (do not wait for the next 60 s ask).
|
||||
if (m.type === "delivery.updated" && m.item.lastError === "waiting_for_original") {
|
||||
void this.api.requestOriginal(m.item.photoId).catch(() => {});
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Destinos / start: every queued row still waiting for an original — ask the server (it broadcasts sha256)
|
||||
* so we send what we have without the photographer clicking Retry.
|
||||
*/
|
||||
async flushWaiting(orgId: string): Promise<void> {
|
||||
try {
|
||||
const { items } = await this.api.listDeliveries(orgId, { status: "QUEUED" });
|
||||
for (const item of items) {
|
||||
if (item.lastError !== "waiting_for_original") continue;
|
||||
void this.api.requestOriginal(item.photoId).catch(() => {});
|
||||
}
|
||||
} catch {
|
||||
/* offline: live channel will ask again */
|
||||
}
|
||||
}
|
||||
|
||||
private pump(): void {
|
||||
const room = originalsParallel();
|
||||
while (this.active < room) {
|
||||
const next = this.queue.shift();
|
||||
if (!next) return;
|
||||
this.active += 1;
|
||||
this.inFlight.add(next.photoId);
|
||||
this.changed();
|
||||
void this.sendOne(next).finally(() => {
|
||||
this.sending.delete(next.sha256);
|
||||
this.inFlight.delete(next.photoId);
|
||||
this.active -= 1;
|
||||
this.changed();
|
||||
this.pump();
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
private async sendOne(need: OriginalNeed): Promise<void> {
|
||||
const exact = await withTimeout(localOriginal(need.sha256), ORIGINAL_IPC_MS);
|
||||
let bytes: ArrayBuffer | null = exact && exact !== "timeout" ? exact : null;
|
||||
if (!bytes) {
|
||||
const changed = await withTimeout(localOriginalChanged(need.sha256), ORIGINAL_IPC_MS);
|
||||
bytes = changed && changed !== "timeout" ? changed : null;
|
||||
}
|
||||
if (!bytes) return;
|
||||
try {
|
||||
await this.api.sendOriginal(need.photoId, new Blob([bytes], { type: "image/jpeg" }), `${need.sha256}.jpg`);
|
||||
} catch {
|
||||
/* offline / not the same photo: server asks again */
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,10 @@
|
||||
import type { PhotoSummary } from "@photoreport/contracts";
|
||||
import { ApiError, type ApiClient } from "@photoreport/sdk";
|
||||
import { isNetworkError } from "../offline/queue.js";
|
||||
import { cache } from "../offline/cache.js";
|
||||
import { isNetworkError, offlineQueue } from "../offline/queue.js";
|
||||
import { useCallback, useRef, useState } from "react";
|
||||
import { prefs } from "../platform.js";
|
||||
import { settleLocalUpload, showLocalJpeg } from "./localIngest.js";
|
||||
|
||||
export type UploadStatus = "queued" | "uploading" | "done" | "duplicate" | "failed";
|
||||
|
||||
@@ -14,7 +17,12 @@ export interface UploadItem {
|
||||
error?: string | undefined;
|
||||
}
|
||||
|
||||
const CONCURRENCY = 4;
|
||||
/** Parallel JPEG uploads. Pref `upload.concurrency` (3–8); default 4. One failure never holds the others. */
|
||||
function uploadConcurrency(): number {
|
||||
const n = Number(prefs.get("upload.concurrency"));
|
||||
if (Number.isFinite(n) && n >= 3 && n <= 8) return Math.floor(n);
|
||||
return 4;
|
||||
}
|
||||
const ACCEPTED = /\.jpe?g$/i;
|
||||
|
||||
const CHUNK = 4 * 1024 * 1024;
|
||||
@@ -146,12 +154,21 @@ export async function sendResumable(
|
||||
}
|
||||
|
||||
/**
|
||||
* Parallel upload queue (4 at a time). New photos show up in the grid through the live channel, so the queue
|
||||
* only tracks progress. Non-JPEG files are refused before sending.
|
||||
* Parallel upload queue (4 at a time). Each JPEG is shown in the library from a local preview at once;
|
||||
* the live channel replaces it when the server has the photo. Non-JPEG files are refused before sending.
|
||||
*/
|
||||
export function useUploadQueue(api: ApiClient, orgId: string) {
|
||||
const [items, setItems] = useState<UploadItem[]>([]);
|
||||
const queue = useRef<{ item: UploadItem; file: File; eventId: string | undefined; original?: DesktopOrigin; onSettled?: (status: UploadStatus, photo?: PhotoSummary) => void }[]>([]);
|
||||
const queue = useRef<
|
||||
{
|
||||
item: UploadItem;
|
||||
file: File;
|
||||
eventId: string | undefined;
|
||||
original?: DesktopOrigin;
|
||||
sha256?: string | null;
|
||||
onSettled?: (status: UploadStatus, photo?: PhotoSummary) => void;
|
||||
}[]
|
||||
>([]);
|
||||
const running = useRef(0);
|
||||
/** No network: the queue waits (nothing fails) and carries on when the connection is back. */
|
||||
const paused = useRef(false);
|
||||
@@ -162,28 +179,29 @@ export function useUploadQueue(api: ApiClient, orgId: string) {
|
||||
}, []);
|
||||
|
||||
const pump = useCallback(() => {
|
||||
while (!paused.current && running.current < CONCURRENCY && queue.current.length) {
|
||||
while (!paused.current && running.current < uploadConcurrency() && queue.current.length) {
|
||||
const next = queue.current.shift()!;
|
||||
running.current++;
|
||||
void (async () => {
|
||||
const { item, file, eventId, original, onSettled } = next;
|
||||
const { item, file, original, onSettled } = next;
|
||||
let final: UploadStatus = "failed";
|
||||
let filed: PhotoSummary | undefined;
|
||||
let waiting = false;
|
||||
update(item.id, { status: "uploading", error: undefined });
|
||||
try {
|
||||
let lastTick = 0;
|
||||
// Read eventId/sha at send time so a late EXIF route on `next` still wins if it finished first.
|
||||
const res = await sendResumable(
|
||||
api,
|
||||
orgId,
|
||||
file,
|
||||
eventId,
|
||||
next.eventId,
|
||||
(p) => {
|
||||
const now = Date.now();
|
||||
if (now - lastTick > 150 || p === 1) {
|
||||
lastTick = now;
|
||||
update(item.id, { progress: p });
|
||||
}
|
||||
const now = Date.now();
|
||||
if (now - lastTick > 150 || p === 1) {
|
||||
lastTick = now;
|
||||
update(item.id, { progress: p });
|
||||
}
|
||||
},
|
||||
original,
|
||||
);
|
||||
@@ -215,7 +233,13 @@ export function useUploadQueue(api: ApiClient, orgId: string) {
|
||||
}
|
||||
} else update(item.id, { status: "failed", error: (err as Error).message });
|
||||
} finally {
|
||||
if (!waiting) onSettled?.(final, filed);
|
||||
if (!waiting) {
|
||||
if (final === "done" || final === "duplicate") {
|
||||
settleLocalUpload(orgId, next.sha256, filed);
|
||||
void offlineQueue(orgId).flush(api);
|
||||
}
|
||||
onSettled?.(final, filed);
|
||||
}
|
||||
running.current--;
|
||||
pump();
|
||||
}
|
||||
@@ -227,6 +251,10 @@ export function useUploadQueue(api: ApiClient, orgId: string) {
|
||||
const add = useCallback(
|
||||
/** `onSettled` is called once per accepted file, after it is sent (or definitely failed). */
|
||||
(files: Iterable<File>, eventId?: string, onSettled?: (file: File, status: UploadStatus, photo?: PhotoSummary) => void, original?: DesktopOrigin) => {
|
||||
// A previous offline pause must not leave new shots stuck on "queued" after the VPN is back.
|
||||
if (paused.current) {
|
||||
paused.current = false;
|
||||
}
|
||||
const added: UploadItem[] = [];
|
||||
for (const file of files) {
|
||||
const item: UploadItem = { id: crypto.randomUUID(), name: file.name, size: file.size, status: "queued", progress: 0 };
|
||||
@@ -236,14 +264,53 @@ export function useUploadQueue(api: ApiClient, orgId: string) {
|
||||
continue;
|
||||
}
|
||||
added.push(item);
|
||||
queue.current.push({ item, file, eventId, ...(original && { original }), ...(onSettled && { onSettled: (status: UploadStatus, photo?: PhotoSummary) => onSettled(file, status, photo) }) });
|
||||
// Preview / EXIF routing must not block the wire: a hung IndexedDB cache left the bar at "queued" forever.
|
||||
// Enqueue at once with the open pin; enrich sha + routed event while the queue runs (or before the first byte).
|
||||
const entry: {
|
||||
item: UploadItem;
|
||||
file: File;
|
||||
eventId: string | undefined;
|
||||
original?: DesktopOrigin;
|
||||
sha256?: string | null;
|
||||
onSettled?: (status: UploadStatus, photo?: PhotoSummary) => void;
|
||||
} = {
|
||||
item,
|
||||
file,
|
||||
eventId,
|
||||
...(original && { original }),
|
||||
sha256: null,
|
||||
...(onSettled && { onSettled: (status: UploadStatus, photo?: PhotoSummary) => onSettled(file, status, photo) }),
|
||||
};
|
||||
queue.current.push(entry);
|
||||
void (async () => {
|
||||
try {
|
||||
const cached = orgId
|
||||
? await Promise.race([
|
||||
cache.events(orgId),
|
||||
new Promise<null>((resolve) => setTimeout(() => resolve(null), 800)),
|
||||
])
|
||||
: null;
|
||||
const shown = await showLocalJpeg({
|
||||
file,
|
||||
eventId,
|
||||
origin: original,
|
||||
orgId,
|
||||
events: cached?.events,
|
||||
});
|
||||
if (!shown) return;
|
||||
entry.sha256 = shown.sha256;
|
||||
// Prefer EXIF routing when it names an event; otherwise keep the open pin already on the entry.
|
||||
if (shown.eventId) entry.eventId = shown.eventId;
|
||||
} catch {
|
||||
/* preview optional — upload already queued */
|
||||
}
|
||||
})();
|
||||
}
|
||||
setItems((list) => [...list.filter((i) => i.status !== "done" && i.status !== "duplicate"), ...added]);
|
||||
setItems((list) => list.filter((i) => i.status !== "done" && i.status !== "duplicate").concat(added));
|
||||
pump();
|
||||
},
|
||||
[pump],
|
||||
[orgId, pump],
|
||||
);
|
||||
|
||||
const clear = useCallback(() => setItems((list) => list.filter((i) => i.status === "queued" || i.status === "uploading")), []);
|
||||
|
||||
return { items, add, clear };
|
||||
|
||||
@@ -75,29 +75,44 @@ export function lisbonInstant(exif: string | null): string | null {
|
||||
|
||||
type RoutedEvent = Pick<EventSummary, "id" | "ingestFrom" | "ingestUntil" | "archivedAt" | "startsAt">;
|
||||
|
||||
/**
|
||||
* Among open events whose ingest window covers `at`, the one whose start is closest to the capture.
|
||||
* "Latest start wins" wrongly pulled a 14:00 studio session into a 16:30 training when windows overlapped.
|
||||
*/
|
||||
export function bestEventForCapture(events: RoutedEvent[], at: string): RoutedEvent | null {
|
||||
const t = Date.parse(at);
|
||||
if (!Number.isFinite(t)) return null;
|
||||
const open = events.filter((e) => !e.archivedAt && Date.parse(e.ingestFrom) <= t && t <= Date.parse(e.ingestUntil));
|
||||
if (!open.length) return null;
|
||||
open.sort((a, b) => Math.abs(Date.parse(a.startsAt) - t) - Math.abs(Date.parse(b.startsAt) - t));
|
||||
return open[0] ?? null;
|
||||
}
|
||||
|
||||
/** The event a photo taken at `at` belongs to, as the server would route it (offline guess; the server decides). */
|
||||
export function routeLocally(events: RoutedEvent[], at: string | null): string | null {
|
||||
if (!at) return null;
|
||||
const t = Date.parse(at);
|
||||
const open = events.filter((e) => !e.archivedAt && Date.parse(e.ingestFrom) <= t && t <= Date.parse(e.ingestUntil));
|
||||
open.sort((a, b) => Date.parse(b.startsAt) - Date.parse(a.startsAt));
|
||||
return open[0]?.id ?? null;
|
||||
return bestEventForCapture(events, at)?.id ?? null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Where a local-FTP photo goes. The event the photographer pinned receives it only while the capture falls in that
|
||||
* event's window. Outside it (the pin left over from yesterday's match), the photo goes to the event of the time
|
||||
* it was taken. A pin whose window isn't in the list, or a photo with no capture time, keeps the pin.
|
||||
* Where a photo arrives on this computer. With a capture time, the pin (FTP target / open event) wins only
|
||||
* inside that event's window — leftover pins from the morning studio must not swallow the afternoon training.
|
||||
* Without a capture time, keep the pin (same as the server): USB auto-pull already filtered by the window via
|
||||
* the card clock, and inventing "now" is what we must not do.
|
||||
*/
|
||||
export function eventForArrival(pinnedId: string | null, events: RoutedEvent[], at: string | null): string | null {
|
||||
if (!at) return pinnedId;
|
||||
if (!pinnedId) return routeLocally(events, at);
|
||||
const pinned = events.find((e) => e.id === pinnedId);
|
||||
if (!pinned || !at) return pinnedId;
|
||||
if (!pinned) {
|
||||
// Agenda cache miss: keep the open pin so USB/FTP does not dump live shots into Sem evento.
|
||||
return pinnedId;
|
||||
}
|
||||
if (pinned.archivedAt) return routeLocally(events, at);
|
||||
const t = Date.parse(at);
|
||||
if (Date.parse(pinned.ingestFrom) <= t && t <= Date.parse(pinned.ingestUntil)) return pinnedId;
|
||||
return routeLocally(events, at);
|
||||
}
|
||||
|
||||
export function localPhoto(p: { sha256: string; name: string; width: number; height: number; capturedAt: string | null; eventId: string | null; url: string }): PhotoSummary {
|
||||
return {
|
||||
id: localId(p.sha256),
|
||||
|
||||
@@ -123,8 +123,26 @@ describe("photos arriving on this computer", () => {
|
||||
// Yesterday's pin only holds photos taken inside it. The next morning goes to that morning's event.
|
||||
expect(eventForArrival("braga", events, at)).toBe("braga");
|
||||
expect(eventForArrival("braga", events, "2026-10-10T15:30:00Z")).toBe("other");
|
||||
// No capture time: keep the pin (USB already filtered by the card clock; server keeps the named folder too).
|
||||
expect(eventForArrival("braga", events, null)).toBe("braga");
|
||||
expect(eventForArrival(null, events, null)).toBeNull();
|
||||
// Cache miss for the pin id: keep it (do not dump into Sem evento); archived pins fall through to the clock.
|
||||
expect(eventForArrival("missing", events, "2026-10-10T15:30:00Z")).toBe("missing");
|
||||
expect(eventForArrival("braga", [{ ...events[0]!, archivedAt: "2026-10-10T00:00:00Z" }, events[1]!], "2026-10-10T15:30:00Z")).toBe("other");
|
||||
});
|
||||
|
||||
it("when two ingest windows overlap, files the photo in the event whose start is closest to the capture", () => {
|
||||
const events = [
|
||||
{ id: "miguel", startsAt: "2026-11-03T14:00:00Z", ingestFrom: "2026-11-03T12:00:00Z", ingestUntil: "2026-11-03T18:00:00Z", archivedAt: null },
|
||||
{ id: "sub21", startsAt: "2026-11-03T16:30:00Z", ingestFrom: "2026-11-03T14:30:00Z", ingestUntil: "2026-11-03T20:30:00Z", archivedAt: null },
|
||||
];
|
||||
// Studio at 14:20: only Miguel's window.
|
||||
expect(eventForArrival("sub21", events, "2026-11-03T14:20:00Z")).toBe("miguel");
|
||||
// Overlap at 15:00 with Sub-21 pinned: pin wins while capture is inside its window.
|
||||
expect(eventForArrival("sub21", events, "2026-11-03T15:00:00Z")).toBe("sub21");
|
||||
// Overlap without a pin: closest start (Miguel at 14:00 beats Sub-21 at 16:30 for a 15:00 capture).
|
||||
expect(eventForArrival(null, events, "2026-11-03T15:00:00Z")).toBe("miguel");
|
||||
expect(eventForArrival(null, events, "2026-11-03T16:40:00Z")).toBe("sub21");
|
||||
});
|
||||
|
||||
it("show in the library at once and give way to the server's copy, keeping what was done to them", () => {
|
||||
|
||||
@@ -11,7 +11,7 @@ import { ApiError, type ApiClient } from "@photoreport/sdk";
|
||||
export type QueuedOp =
|
||||
| { id: string; kind: "patch"; ids: string[]; patch: PhotoPatch }
|
||||
| { id: string; kind: "iptc"; ids: string[]; set: Record<string, string | string[] | null> }
|
||||
| { id: string; kind: "deliver"; targetId: string; ids: string[]; again: boolean };
|
||||
| { id: string; kind: "deliver"; targetId: string; ids: string[]; again: boolean; originals?: boolean };
|
||||
|
||||
export type NewOp = QueuedOp extends infer O ? (O extends QueuedOp ? Omit<O, "id"> : never) : never;
|
||||
|
||||
@@ -189,7 +189,7 @@ export class OfflineQueue {
|
||||
try {
|
||||
if (op.kind === "patch") await api.updatePhotos(this.orgId, resolved, op.patch);
|
||||
else if (op.kind === "iptc") await api.setPhotosIptc(this.orgId, resolved, op.set);
|
||||
else await api.deliver(this.orgId, op.targetId, resolved, op.again);
|
||||
else await api.deliver(this.orgId, op.targetId, resolved, op.again, op.originals ?? false);
|
||||
} catch (err) {
|
||||
if (isNetworkError(err) || (err instanceof ApiError && (err.status === 401 || err.status === 429))) return;
|
||||
// Refused for good (photo deleted, no permission): nothing to retry.
|
||||
|
||||
@@ -71,16 +71,16 @@ export function setIptc(api: ApiClient, orgId: string, ids: string[], set: Recor
|
||||
}
|
||||
|
||||
/** "Send to": with no network (or photos still uploading) the request waits here and goes when it can. */
|
||||
export async function deliver(api: ApiClient, orgId: string, targetId: string, ids: string[], again = false) {
|
||||
export async function deliver(api: ApiClient, orgId: string, targetId: string, ids: string[], again = false, originals = false) {
|
||||
const queue = offlineQueue(orgId);
|
||||
let answer: Awaited<ReturnType<ApiClient["deliver"]>> | null = null;
|
||||
const result = await attempt(
|
||||
queue,
|
||||
ids,
|
||||
async (x) => {
|
||||
answer = await api.deliver(orgId, targetId, x, again);
|
||||
answer = await api.deliver(orgId, targetId, x, again, originals);
|
||||
},
|
||||
() => queue.add({ kind: "deliver", targetId, ids, again }),
|
||||
() => queue.add({ kind: "deliver", targetId, ids, again, originals }),
|
||||
);
|
||||
return result === "sent" && answer ? { ...(answer as Awaited<ReturnType<ApiClient["deliver"]>>), waiting: false } : { queued: [], skipped: [], waiting: true };
|
||||
}
|
||||
@@ -223,6 +223,18 @@ function SourceCard({ api, source, isAdmin, active, onSelect, onChange, onRemove
|
||||
</select>
|
||||
</label>
|
||||
)}
|
||||
{isAdmin && (
|
||||
<label className="flex w-full flex-wrap items-center gap-2">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={!!source.photoFindEnabled}
|
||||
disabled={busy}
|
||||
onChange={(e) => void run(() => api.updateCloudSource(source.id, { photoFindEnabled: e.target.checked }))}
|
||||
/>
|
||||
<span className="text-[12px] text-ink">{A.photoFind}</span>
|
||||
<span className="w-full text-faint">{A.photoFindHelp}</span>
|
||||
</label>
|
||||
)}
|
||||
{isAdmin && (
|
||||
<form
|
||||
className="flex w-full flex-wrap items-center gap-2"
|
||||
|
||||
@@ -122,7 +122,13 @@ export function DeliveryPage() {
|
||||
<td className="border-b border-line px-3 py-1.5 font-mono text-[11px] text-faint">{i.sequence}</td>
|
||||
<td className="border-b border-line px-3 py-1.5 font-mono text-[11px] break-all">
|
||||
{i.remotePath ?? <span className="text-faint">—</span>}
|
||||
{i.lastError && <span className="block text-[10px] text-[#f0a35a]">{t.deliveryErrors[i.lastError as keyof typeof t.deliveryErrors] ?? i.lastError}</span>}
|
||||
{i.lastError && (
|
||||
<span className="block text-[10px] text-[#f0a35a]">
|
||||
{i.lastError === "waiting_for_original" && isDesktop()
|
||||
? t.deliveryErrors.waiting_for_original_here
|
||||
: (t.deliveryErrors[i.lastError as keyof typeof t.deliveryErrors] ?? i.lastError)}
|
||||
</span>
|
||||
)}
|
||||
</td>
|
||||
<td className={`border-b border-line px-3 py-1.5 font-mono text-[11px] ${STATUS_COLOR[i.status]}`}>
|
||||
{t.deliveryStatus[i.status]}
|
||||
|
||||
@@ -12,6 +12,17 @@ import { type Crop, cropOf, DevelopSession, localOutbox } from "../develop/sessi
|
||||
import { SyncSettingsButton } from "../develop/SyncSettings.js";
|
||||
import { commandsFrom, queueSync } from "../develop/copySettings.js";
|
||||
import { clampUnit, constrainRotated, fitAspect, GUIDES, type Guide, rotateAspect } from "../develop/crop.js";
|
||||
import {
|
||||
addSpot,
|
||||
DEFAULT_SPOT_FEATHER,
|
||||
DEFAULT_SPOT_OPACITY,
|
||||
DEFAULT_SPOT_SIZE,
|
||||
removeSpotAt,
|
||||
SPOT_MODES,
|
||||
spotsOf,
|
||||
spotsPartial,
|
||||
type SpotMode,
|
||||
} from "../develop/spots.js";
|
||||
import { engineAuto, Viewer } from "../develop/Viewer.js";
|
||||
import { IptcInfo } from "../library/IptcInfo.js";
|
||||
import { activePhoto, savedFilter, saveFilter, setActivePhoto } from "../library/active.js";
|
||||
@@ -342,12 +353,21 @@ export function DevelopPage() {
|
||||
e.preventDefault();
|
||||
flagCurrent(patchForKey(e.key)!);
|
||||
}
|
||||
else if (e.key.toLowerCase() === "r" && canEdit) setCropping((c) => !c);
|
||||
else if (e.key.toLowerCase() === "w" && canEdit) setPicking((p) => !p);
|
||||
else if (e.key.toLowerCase() === "z") setOneToOne((z) => !z);
|
||||
else if (e.key.toLowerCase() === "r" && canEdit) {
|
||||
setSpotting(false);
|
||||
setCropping((c) => !c);
|
||||
} else if (e.key.toLowerCase() === "q" && canEdit) {
|
||||
setCropping(false);
|
||||
setPicking(false);
|
||||
setSpotting((s) => !s);
|
||||
} else if (e.key.toLowerCase() === "w" && canEdit) {
|
||||
setSpotting(false);
|
||||
setPicking((p) => !p);
|
||||
} else if (e.key.toLowerCase() === "z") setOneToOne((z) => !z);
|
||||
else if (e.key === "Escape") {
|
||||
setCropping(false);
|
||||
setPicking(false);
|
||||
setSpotting(false);
|
||||
}
|
||||
};
|
||||
window.addEventListener("keydown", onKey);
|
||||
@@ -356,6 +376,7 @@ export function DevelopPage() {
|
||||
|
||||
const settings = session?.loaded ? session.settings : null;
|
||||
const crop = useMemo(() => (settings ? cropOf(settings) : { rect: { x0: 0, y0: 0, x1: 1, y1: 1 }, angle: 0, aspect: null }), [settings]);
|
||||
const spots = useMemo(() => (settings ? spotsOf(settings) : []), [settings]);
|
||||
const shown = settings && before && typeof engine === "object" ? engine.defaultSettings() : settings;
|
||||
|
||||
const setValue = useCallback(
|
||||
@@ -366,9 +387,57 @@ export function DevelopPage() {
|
||||
[session],
|
||||
);
|
||||
const [picking, setPicking] = useState(false);
|
||||
const [spotting, setSpotting] = useState(false);
|
||||
const [spotMode, setSpotMode] = useState<SpotMode>("remove");
|
||||
const [spotSize, setSpotSize] = useState(DEFAULT_SPOT_SIZE);
|
||||
const [spotFeather, setSpotFeather] = useState(DEFAULT_SPOT_FEATHER);
|
||||
const [spotOpacity, setSpotOpacity] = useState(DEFAULT_SPOT_OPACITY);
|
||||
|
||||
const placeSpot = useCallback(
|
||||
(u: number, v: number) => {
|
||||
if (!session?.loaded || !canEdit) return;
|
||||
const r = crop.rect;
|
||||
const x = r.x0 + u * (r.x1 - r.x0);
|
||||
const y = r.y0 + v * (r.y1 - r.y0);
|
||||
const next = addSpot(session.settings, {
|
||||
mode: spotMode,
|
||||
x,
|
||||
y,
|
||||
size: spotSize,
|
||||
feather: spotFeather,
|
||||
opacity: spotOpacity,
|
||||
});
|
||||
session.edit({ command: "develop.merge", params: { partial: spotsPartial(next) } });
|
||||
session.endGesture();
|
||||
},
|
||||
[session, canEdit, crop.rect, spotMode, spotSize, spotFeather, spotOpacity],
|
||||
);
|
||||
|
||||
const deleteSpot = useCallback(
|
||||
(index: number) => {
|
||||
if (!session?.loaded || !canEdit) return;
|
||||
session.edit({ command: "develop.merge", params: { partial: spotsPartial(removeSpotAt(session.settings, index)) } });
|
||||
session.endGesture();
|
||||
},
|
||||
[session, canEdit],
|
||||
);
|
||||
|
||||
const spotMarks = useMemo(() => {
|
||||
if (!spotting || !spots.length) return [];
|
||||
const r = crop.rect;
|
||||
const rw = r.x1 - r.x0 || 1;
|
||||
const rh = r.y1 - r.y0 || 1;
|
||||
return spots
|
||||
.map((s) => {
|
||||
const p = s.points[0];
|
||||
if (!p) return null;
|
||||
return { u: (p.x - r.x0) / rw, v: (p.y - r.y0) / rh, size: s.size / Math.max(rw, rh) };
|
||||
})
|
||||
.filter((m): m is { u: number; v: number; size: number } => !!m && m.u >= -0.05 && m.u <= 1.05 && m.v >= -0.05 && m.v <= 1.05);
|
||||
}, [spotting, spots, crop.rect]);
|
||||
|
||||
/** 1:1 view, and where its full-resolution original stands. */
|
||||
const [oneToOne, setOneToOne] = useState(false);
|
||||
const [fullState, setFullState] = useState<"idle" | "waiting" | "ready" | "missing">("idle");
|
||||
const [oneToOne, setOneToOne] = useState(false); const [fullState, setFullState] = useState<"idle" | "waiting" | "ready" | "missing">("idle");
|
||||
useEffect(() => {
|
||||
setOneToOne(false);
|
||||
setFullState("idle");
|
||||
@@ -625,13 +694,16 @@ export function DevelopPage() {
|
||||
{...(oneToOne || current.originalName.toLowerCase().endsWith(".dng") || current.name.toLowerCase().endsWith(".dng")
|
||||
? { localSource: fullSource }
|
||||
: isDesktop() && { localSource: () => localOriginalToView(current.sha256) })}
|
||||
picking={picking && !cropping && !before}
|
||||
picking={picking && !cropping && !spotting && !before}
|
||||
onPick={(u, v) => {
|
||||
setPicking(false);
|
||||
// The view shows the cropped frame: map back to the whole frame (straighten angle ignored).
|
||||
const r = crop.rect;
|
||||
void autoValues("pick", { x: r.x0 + u * (r.x1 - r.x0), y: r.y0 + v * (r.y1 - r.y0) });
|
||||
}}
|
||||
spotting={spotting && !cropping && !before}
|
||||
onSpot={placeSpot}
|
||||
spotMarks={spotMarks}
|
||||
onCrop={(rect, final) => {
|
||||
setDragging(!final);
|
||||
session?.edit({ command: "crop.set", params: { rect: clampUnit(rect), angle: crop.angle, aspect: crop.aspect } }, "crop");
|
||||
@@ -651,13 +723,103 @@ export function DevelopPage() {
|
||||
{oneToOne && fullState === "waiting" && <p className="border-b border-line bg-accent/20 px-3 py-2 text-[12px] text-ink">{t.dev.fullWaiting}</p>}
|
||||
{oneToOne && fullState === "missing" && <p className="border-b border-line px-3 py-2 text-[12px] text-[#f0a35a]">{t.dev.fullMissing}</p>}
|
||||
{picking && <p className="border-b border-line bg-accent/20 px-3 py-2 text-[12px] text-ink">{t.dev.pickWbNow}</p>}
|
||||
{spotting && <p className="border-b border-line bg-accent/20 px-3 py-2 text-[12px] text-ink">{t.dev.spotNow}</p>}
|
||||
{!canEdit && current && <p className="border-b border-line px-3 py-2 text-[12px] text-faint">{t.dev.noAccess}</p>}
|
||||
<Section title={t.dev.spot}>
|
||||
<div className="mb-2 flex flex-wrap items-center gap-2">
|
||||
<button
|
||||
disabled={!canEdit}
|
||||
onClick={() => {
|
||||
setCropping(false);
|
||||
setPicking(false);
|
||||
setSpotting((s) => !s);
|
||||
}}
|
||||
aria-pressed={spotting}
|
||||
className={`h-7 border border-black px-3 text-[12px] disabled:opacity-40 ${spotting ? "bg-accent text-white" : "bg-cell"}`}
|
||||
>
|
||||
{spotting ? t.dev.spotDone : t.dev.spot}
|
||||
</button>
|
||||
<span className="text-[11px] text-faint">{t.dev.spotHelp}</span>
|
||||
</div>
|
||||
<div className="mb-2 flex flex-wrap gap-1">
|
||||
{SPOT_MODES.map((m) => (
|
||||
<button
|
||||
key={m.id}
|
||||
disabled={!canEdit}
|
||||
onClick={() => setSpotMode(m.id)}
|
||||
aria-pressed={spotMode === m.id}
|
||||
className={`h-6 border border-black px-2 text-[11px] disabled:opacity-40 ${spotMode === m.id ? "bg-cell-on text-ink" : "bg-cell text-muted"}`}
|
||||
>
|
||||
{t.dev[m.labelKey]}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
<label className="mb-2 block text-[11px] text-faint">
|
||||
{t.dev.spotSize}
|
||||
<input
|
||||
type="range"
|
||||
min={0.005}
|
||||
max={0.12}
|
||||
step={0.001}
|
||||
value={spotSize}
|
||||
disabled={!canEdit}
|
||||
onChange={(e) => setSpotSize(Number(e.target.value))}
|
||||
className="mt-1 w-full"
|
||||
/>
|
||||
</label>
|
||||
<label className="mb-2 block text-[11px] text-faint">
|
||||
{t.dev.spotFeather}
|
||||
<input
|
||||
type="range"
|
||||
min={0}
|
||||
max={100}
|
||||
step={1}
|
||||
value={spotFeather}
|
||||
disabled={!canEdit}
|
||||
onChange={(e) => setSpotFeather(Number(e.target.value))}
|
||||
className="mt-1 w-full"
|
||||
/>
|
||||
</label>
|
||||
<label className="mb-2 block text-[11px] text-faint">
|
||||
{t.dev.spotOpacity}
|
||||
<input
|
||||
type="range"
|
||||
min={0}
|
||||
max={100}
|
||||
step={1}
|
||||
value={spotOpacity}
|
||||
disabled={!canEdit}
|
||||
onChange={(e) => setSpotOpacity(Number(e.target.value))}
|
||||
className="mt-1 w-full"
|
||||
/>
|
||||
</label>
|
||||
{spots.length > 0 && (
|
||||
<ul className="mt-1 max-h-28 space-y-1 overflow-y-auto text-[11px]">
|
||||
{spots.map((s, i) => {
|
||||
const label = SPOT_MODES.find((m) => m.id === s.mode);
|
||||
return (
|
||||
<li key={i} className="flex items-center justify-between gap-2 border border-line bg-cell px-2 py-1">
|
||||
<span className="truncate text-muted">
|
||||
{label ? t.dev[label.labelKey] : s.mode} · {i + 1}
|
||||
</span>
|
||||
<button type="button" disabled={!canEdit} className="text-ink underline disabled:opacity-40" onClick={() => deleteSpot(i)}>
|
||||
{t.dev.spotDelete}
|
||||
</button>
|
||||
</li>
|
||||
);
|
||||
})}
|
||||
</ul>
|
||||
)}
|
||||
</Section>
|
||||
{modules.includes("crop") && (
|
||||
<Section title={t.modules.crop}>
|
||||
<div className="mb-2 flex items-center gap-2">
|
||||
<button
|
||||
disabled={!canEdit}
|
||||
onClick={() => setCropping(!cropping)}
|
||||
onClick={() => {
|
||||
setSpotting(false);
|
||||
setCropping(!cropping);
|
||||
}}
|
||||
aria-pressed={cropping}
|
||||
className={`h-7 border border-black px-3 text-[12px] disabled:opacity-40 ${cropping ? "bg-accent text-white" : "bg-cell"}`}
|
||||
>
|
||||
|
||||
@@ -12,14 +12,19 @@ import { EventSettingsButton } from "../library/EventSettings.js";
|
||||
import { useFolderScan } from "../library/folderScan.js";
|
||||
import { FacesView } from "../library/FacesView.js";
|
||||
import { LookupBanner } from "../library/PhotoLookup.js";
|
||||
import { FolderDevelop } from "../library/FolderDevelop.js";
|
||||
import { FolderSheet } from "../library/FolderSheet.js";
|
||||
import { beginDropWait, folderDropPath, htmlDropIsFolder, nativePaths, openFolder, folderThumb, type FolderListing } from "../library/folderDrop.js";
|
||||
import { beginDropWait, folderDropPath, folderMeta, htmlDropIsFolder, mergeFolderDng, nativePaths, openFolder, folderThumb, type FolderListing } from "../library/folderDrop.js";
|
||||
import { finishMergedJpeg } from "../library/finishMergedJpeg.js";
|
||||
import { mergeFolderNative } from "../library/folderMerge.js";
|
||||
import { MERGE_EDGE } from "../library/mergeStacks.js";
|
||||
import { Grid, Loupe, type LoupeFace } from "../library/Grid.js";
|
||||
import { InfoPanel } from "../library/InfoPanel.js";
|
||||
import { IptcInfo } from "../library/IptcInfo.js";
|
||||
import { useLibraryLive } from "../library/realtime.js";
|
||||
import { useIngest } from "../library/ingest.js";
|
||||
import { LocalFtpButton } from "../library/LocalFtp.js";
|
||||
import { UsbCameraButton } from "../library/UsbCamera.js";
|
||||
import { CardIngestButton, CardOverallStatus } from "../library/CardIngest.js";
|
||||
import { MergeButton } from "../library/MergeButton.js";
|
||||
import { AutopilotButton } from "../library/Autopilot.js";
|
||||
@@ -265,10 +270,11 @@ export function LibraryPage() {
|
||||
dispatch({ type: "local", photos: localPhotos.list() });
|
||||
}, [localVersion]);
|
||||
const waitingChanges = useQueueSize(orgId);
|
||||
const { uploads, localFtp, desktop } = useIngest();
|
||||
const { uploads, localFtp, usb, desktop } = useIngest();
|
||||
const fileInput = useRef<HTMLInputElement>(null);
|
||||
const [dragging, setDragging] = useState(false);
|
||||
const [sheet, setSheet] = useState<FolderListing | null>(null);
|
||||
const [developPath, setDevelopPath] = useState<string | null>(null);
|
||||
const [openingFolder, setOpeningFolder] = useState(false);
|
||||
const [removeOpen, setRemoveOpen] = useState(false);
|
||||
useEffect(() => {
|
||||
@@ -288,6 +294,7 @@ export function LibraryPage() {
|
||||
(listing) => {
|
||||
if (dead) return;
|
||||
setOpeningFolder(false);
|
||||
setDevelopPath(null);
|
||||
setSheet(listing);
|
||||
},
|
||||
() => {
|
||||
@@ -314,11 +321,6 @@ export function LibraryPage() {
|
||||
const games = openEvent && !events.some((event) => event.id === openEvent.id) ? [openEvent, ...events] : events;
|
||||
syncGames(games);
|
||||
}, [events, openEvent, syncGames]);
|
||||
const sending = uploads.items.filter((i) => i.status === "queued" || i.status === "uploading");
|
||||
const failed = uploads.items.filter((i) => i.status === "failed");
|
||||
const sentCount = uploads.items.filter((i) => i.status === "done" || i.status === "duplicate").length;
|
||||
const overall = uploads.items.length ? uploads.items.reduce((sum, i) => sum + (i.status === "failed" ? 1 : i.progress), 0) / uploads.items.length : 0;
|
||||
|
||||
const playerIds = useMemo(() => photoIdsOf(players), [players]);
|
||||
const visible = useMemo(() => state.photos.filter((p) => matchesFilter(p, filter) && (playerIds === null || playerIds.has(p.id))), [state.photos, filter, playerIds]);
|
||||
const selectedPlayerIds = useMemo(() => players.map((p) => p.id), [players]);
|
||||
@@ -523,6 +525,7 @@ export function LibraryPage() {
|
||||
{t.cardScan.button}
|
||||
</button>
|
||||
)}
|
||||
{desktop && <UsbCameraButton usb={usb} target={localFtp.target} setTarget={localFtp.setTarget} openEvent={openEvent} />}
|
||||
{desktop && <LocalFtpButton ftp={localFtp} events={events} openEventId={uploadInto} />}
|
||||
{desktop && <CardIngestButton />}
|
||||
{openEvent && (
|
||||
@@ -577,7 +580,7 @@ export function LibraryPage() {
|
||||
))}
|
||||
</select>
|
||||
)}
|
||||
{canCull && state.scope && !state.scope.startsWith("search:") && !state.scope.startsWith("face:") && (
|
||||
{canCull && !sheet && state.scope && !state.scope.startsWith("search:") && !state.scope.startsWith("face:") && (
|
||||
<MergeButton api={api} orgId={orgId} eventId={state.scope === "inbox" ? null : state.scope} photos={state.photos} selectedIds={[...state.selected]} />
|
||||
)}
|
||||
{canCull && (
|
||||
@@ -706,8 +709,45 @@ export function LibraryPage() {
|
||||
onClose={() => void open(lookup.from ?? "inbox")}
|
||||
/>
|
||||
)}
|
||||
{sheet ? (
|
||||
<FolderSheet folder={sheet} onClose={() => setSheet(null)} thumb={folderThumb} />
|
||||
{sheet && developPath && sheet.files.some((file) => file.path === developPath) ? (
|
||||
<FolderDevelop files={sheet.files} path={developPath} onPath={setDevelopPath} onClose={() => setDevelopPath(null)} />
|
||||
) : sheet ? (
|
||||
<FolderSheet
|
||||
folder={sheet}
|
||||
onClose={() => {
|
||||
setDevelopPath(null);
|
||||
setSheet(null);
|
||||
}}
|
||||
onDevelop={setDevelopPath}
|
||||
thumb={folderThumb}
|
||||
{...(canCull
|
||||
? {
|
||||
merge: async (input: {
|
||||
files: FolderListing["files"];
|
||||
selectedIds: readonly string[];
|
||||
jpeg: boolean;
|
||||
onStatus: (stack: number, total: number, phase?: "merge" | "jpeg") => void;
|
||||
}) => {
|
||||
const result = await mergeFolderNative({
|
||||
files: input.files,
|
||||
selectedIds: input.selectedIds,
|
||||
onStatus: input.onStatus,
|
||||
metaOf: folderMeta,
|
||||
mergePaths: (paths) => mergeFolderDng(paths, MERGE_EDGE),
|
||||
...(input.jpeg ? { finishJpeg: finishMergedJpeg } : {}),
|
||||
});
|
||||
const folderPath = sheet.path;
|
||||
try {
|
||||
const listing = await openFolder(folderPath);
|
||||
setSheet((current) => (current?.path === folderPath ? listing : current));
|
||||
} catch {
|
||||
// The DNG is already beside the frames. Reopening the folder shows it.
|
||||
}
|
||||
return result;
|
||||
},
|
||||
}
|
||||
: {})}
|
||||
/>
|
||||
) : openingFolder ? (
|
||||
<p className="p-8 text-center text-[13px] text-faint">{t.folderSheet.opening}</p>
|
||||
) : view === "faces" && state.scope && state.scope !== "inbox" && !state.scope.startsWith("search:") && !state.scope.startsWith("face:") ? (
|
||||
@@ -729,23 +769,6 @@ export function LibraryPage() {
|
||||
)}
|
||||
</div>
|
||||
|
||||
{uploads.items.length > 0 && (
|
||||
<div className="flex flex-wrap items-center gap-3 border-t border-line bg-panel px-3 py-1.5 text-[12px]" role="status">
|
||||
<span className="font-mono text-[11px]">
|
||||
{sending.length ? t.uploading(sentCount, uploads.items.length) : t.uploaded(sentCount)}
|
||||
{failed.length > 0 && <span className="text-[#f0a35a]"> · {t.uploadFailed(failed.length)}</span>}
|
||||
</span>
|
||||
<span className="h-1 min-w-24 flex-1 bg-black">
|
||||
<span className="block h-full bg-accent transition-[width]" style={{ width: `${Math.round(overall * 100)}%` }} />
|
||||
</span>
|
||||
{failed.length > 0 && <span className="truncate text-[11px] text-faint" title={failed.map((f) => `${f.name}: ${f.error}`).join("\n")}>{failed[0]?.name}: {failed[0]?.error}</span>}
|
||||
{!sending.length && (
|
||||
<button onClick={uploads.clear} className="text-[11px] text-faint underline hover:text-muted">
|
||||
{t.dismiss}
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
{desktop && <CardOverallStatus />}
|
||||
<div className="border-t border-line bg-raised px-3 py-1.5 text-[11px] text-faint">{t.shortcuts}</div>
|
||||
</div>
|
||||
|
||||
@@ -4,7 +4,7 @@ import { useAuth } from "../auth.js";
|
||||
import { Alert } from "../components/ui.js";
|
||||
import { LocalCatalog } from "../desktop/LocalCatalog.js";
|
||||
import { t } from "../i18n.js";
|
||||
import { isDesktop } from "../platform.js";
|
||||
import { desktopInvoke, isDesktop } from "../platform.js";
|
||||
import { PageHeader } from "./Shell.js";
|
||||
|
||||
// "advanced" is an internal bucket for controls a future engine version adds before we name a panel.
|
||||
@@ -14,6 +14,7 @@ export function PreferencesPage() {
|
||||
const { api, me, reload } = useAuth();
|
||||
const [selected, setSelected] = useState<Module[]>(me?.preferences.editorModules ?? [...DEFAULT_MODULES]);
|
||||
const [status, setStatus] = useState<"idle" | "saved" | "error">("idle");
|
||||
const [uiStatus, setUiStatus] = useState<"idle" | "checking" | "current" | "error">("idle");
|
||||
|
||||
const toggle = async (module: Module) => {
|
||||
const next = selected.includes(module) ? selected.filter((m) => m !== module) : [...selected, module];
|
||||
@@ -52,6 +53,30 @@ export function PreferencesPage() {
|
||||
))}
|
||||
</ul>
|
||||
</section>
|
||||
{isDesktop() && (
|
||||
<section className="max-w-2xl space-y-3 border-t border-line p-6">
|
||||
<h2 className="text-sm font-semibold">{t.update.uiSection}</h2>
|
||||
<p className="text-sm text-muted">{t.update.uiSectionHelp}</p>
|
||||
<button
|
||||
type="button"
|
||||
disabled={uiStatus === "checking"}
|
||||
className="h-8 border border-black bg-cell px-3 text-[12px] text-ink hover:bg-cell-on disabled:opacity-50"
|
||||
onClick={() => {
|
||||
setUiStatus("checking");
|
||||
desktopInvoke<boolean>("ui_check")
|
||||
.then((updated) => {
|
||||
if (updated) window.location.reload();
|
||||
else setUiStatus("current");
|
||||
})
|
||||
.catch(() => setUiStatus("error"));
|
||||
}}
|
||||
>
|
||||
{uiStatus === "checking" ? t.update.uiChecking : t.update.uiCheckNow}
|
||||
</button>
|
||||
{uiStatus === "current" && <p className="text-xs text-ok">{t.update.uiCurrent}</p>}
|
||||
{uiStatus === "error" && <Alert>{t.unexpectedError}</Alert>}
|
||||
</section>
|
||||
)}
|
||||
{isDesktop() && <LocalCatalog />}
|
||||
</>
|
||||
);
|
||||
|
||||
@@ -8,6 +8,7 @@ import { LocalDeliveries } from "../desktop/localDeliveries.js";
|
||||
import { UiReadyNotice, UpdateNotice } from "../desktop/UpdateNotice.js";
|
||||
import { FolderScanProvider } from "../library/folderScan.js";
|
||||
import { IngestProvider } from "../library/ingest.js";
|
||||
import { TransferBar } from "../library/TransferBar.js";
|
||||
|
||||
const moduleClass = ({ isActive }: { isActive: boolean }) =>
|
||||
`px-3 py-1 font-display text-[19px] max-sm:px-2 max-sm:text-[15px] font-semibold uppercase tracking-wide transition-colors ${
|
||||
@@ -141,13 +142,14 @@ export function Shell() {
|
||||
<UpdateNotice />
|
||||
<UiReadyNotice />
|
||||
<LocalDeliveries />
|
||||
<main className="min-h-0 flex-1 overflow-auto">
|
||||
<IngestProvider>
|
||||
<IngestProvider>
|
||||
<main className="min-h-0 flex-1 overflow-auto">
|
||||
<FolderScanProvider>
|
||||
<Outlet />
|
||||
</FolderScanProvider>
|
||||
</IngestProvider>
|
||||
</main>
|
||||
</main>
|
||||
<TransferBar />
|
||||
</IngestProvider>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -12,6 +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.
|
||||
- Local catalogue (`src/catalog.rs`, Preferências → **Catálogo local**). See below.
|
||||
- Works without network: when the server can't be reached at start-up, the window opens the copy of the web app
|
||||
bundled in the installer (photo engine included), so the catalogue, local FTP and editing originals on disk go on;
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@photoreport/desktop",
|
||||
"version": "0.3.22",
|
||||
"version": "0.3.27",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "photoreport-desktop"
|
||||
version = "0.3.22"
|
||||
version = "0.3.27"
|
||||
edition = "2024"
|
||||
publish = false
|
||||
description = "PhotoReport desktop: the web app in a native shell, with keychain sign-in and (later) local FTP and the native engine."
|
||||
@@ -11,6 +11,7 @@ crate-type = ["staticlib", "cdylib", "rlib"]
|
||||
|
||||
[build-dependencies]
|
||||
tauri-build = { version = "2", features = [] }
|
||||
cc = "1"
|
||||
|
||||
[dependencies]
|
||||
tauri = { version = "2", features = [] }
|
||||
@@ -31,7 +32,7 @@ sha2 = "0.10"
|
||||
libc = "0.2"
|
||||
image = { version = "0.25", default-features = false, features = ["jpeg"] }
|
||||
# Capture time and filmstrip thumbnails. The embedded-preview feature reads the camera JPEG; the browser build leaves it off.
|
||||
photoreport-engine = { path = "../../../engine/core", features = ["embedded-preview"] }
|
||||
photoreport-engine = { path = "../../../engine/core", features = ["embedded-preview", "photo-merge"] }
|
||||
photoreport-faces = { path = "../../../workers/faces" }
|
||||
tauri-plugin-dialog = "2"
|
||||
tauri-plugin-updater = "2"
|
||||
|
||||
@@ -1,6 +1,18 @@
|
||||
fn main() {
|
||||
// The keychain and local FTP commands get ACL permissions, so the web app loaded from the server (a remote origin) can be
|
||||
// granted them explicitly in capabilities/default.json.
|
||||
let target = std::env::var("CARGO_CFG_TARGET_OS").unwrap_or_default();
|
||||
if target == "macos" {
|
||||
// ImageCaptureCore: PTP cameras (they never mount as a volume).
|
||||
cc::Build::new()
|
||||
.file("src/camera_mac.m")
|
||||
.flag("-fobjc-arc")
|
||||
.compile("camera_mac");
|
||||
println!("cargo:rustc-link-lib=framework=Foundation");
|
||||
println!("cargo:rustc-link-lib=framework=ImageCaptureCore");
|
||||
println!("cargo:rustc-link-lib=framework=IOKit");
|
||||
println!("cargo:rerun-if-changed=src/camera_mac.m");
|
||||
}
|
||||
// The keychain, local FTP and USB camera commands get ACL permissions, so the web app loaded from the server
|
||||
// (a remote origin) can be granted them explicitly in capabilities/default.json.
|
||||
tauri_build::try_build(tauri_build::Attributes::new().app_manifest(
|
||||
tauri_build::AppManifest::new().commands(&[
|
||||
"refresh_token_get",
|
||||
@@ -22,6 +34,12 @@ fn main() {
|
||||
"folder_drop",
|
||||
"folder_open",
|
||||
"folder_thumb",
|
||||
"folder_read",
|
||||
"folder_meta",
|
||||
"folder_merge_dng",
|
||||
"folder_save_dng",
|
||||
"folder_save_jpeg",
|
||||
"folder_save_xmp",
|
||||
"ftp_preview",
|
||||
"ftp_info",
|
||||
"catalog_folders",
|
||||
@@ -49,6 +67,12 @@ fn main() {
|
||||
"delivery_folder_pick",
|
||||
"delivery_write",
|
||||
"import_upload_profiles",
|
||||
"camera_status",
|
||||
"camera_take",
|
||||
"camera_tether",
|
||||
"camera_sync",
|
||||
"camera_import",
|
||||
"camera_refresh",
|
||||
]),
|
||||
))
|
||||
.expect("failed to run tauri-build");
|
||||
|
||||
@@ -37,6 +37,12 @@
|
||||
"allow-folder-drop",
|
||||
"allow-folder-open",
|
||||
"allow-folder-thumb",
|
||||
"allow-folder-read",
|
||||
"allow-folder-meta",
|
||||
"allow-folder-merge-dng",
|
||||
"allow-folder-save-dng",
|
||||
"allow-folder-save-jpeg",
|
||||
"allow-folder-save-xmp",
|
||||
"allow-ftp-preview",
|
||||
"allow-ftp-info",
|
||||
"allow-catalog-folders",
|
||||
@@ -63,7 +69,13 @@
|
||||
"allow-delivery-folders",
|
||||
"allow-delivery-folder-pick",
|
||||
"allow-delivery-write",
|
||||
"allow-import-upload-profiles"
|
||||
"allow-import-upload-profiles",
|
||||
"allow-camera-status",
|
||||
"allow-camera-take",
|
||||
"allow-camera-tether",
|
||||
"allow-camera-sync",
|
||||
"allow-camera-import",
|
||||
"allow-camera-refresh"
|
||||
],
|
||||
"remote": {
|
||||
"urls": [
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
# Automatically generated - DO NOT EDIT!
|
||||
|
||||
[[permission]]
|
||||
identifier = "allow-camera-import"
|
||||
description = "Enables the camera_import command without any pre-configured scope."
|
||||
commands.allow = ["camera_import"]
|
||||
|
||||
[[permission]]
|
||||
identifier = "deny-camera-import"
|
||||
description = "Denies the camera_import command without any pre-configured scope."
|
||||
commands.deny = ["camera_import"]
|
||||
@@ -0,0 +1,11 @@
|
||||
# Automatically generated - DO NOT EDIT!
|
||||
|
||||
[[permission]]
|
||||
identifier = "allow-camera-refresh"
|
||||
description = "Enables the camera_refresh command without any pre-configured scope."
|
||||
commands.allow = ["camera_refresh"]
|
||||
|
||||
[[permission]]
|
||||
identifier = "deny-camera-refresh"
|
||||
description = "Denies the camera_refresh command without any pre-configured scope."
|
||||
commands.deny = ["camera_refresh"]
|
||||
@@ -0,0 +1,11 @@
|
||||
# Automatically generated - DO NOT EDIT!
|
||||
|
||||
[[permission]]
|
||||
identifier = "allow-camera-status"
|
||||
description = "Enables the camera_status command without any pre-configured scope."
|
||||
commands.allow = ["camera_status"]
|
||||
|
||||
[[permission]]
|
||||
identifier = "deny-camera-status"
|
||||
description = "Denies the camera_status command without any pre-configured scope."
|
||||
commands.deny = ["camera_status"]
|
||||
@@ -0,0 +1,11 @@
|
||||
# Automatically generated - DO NOT EDIT!
|
||||
|
||||
[[permission]]
|
||||
identifier = "allow-camera-sync"
|
||||
description = "Enables the camera_sync command without any pre-configured scope."
|
||||
commands.allow = ["camera_sync"]
|
||||
|
||||
[[permission]]
|
||||
identifier = "deny-camera-sync"
|
||||
description = "Denies the camera_sync command without any pre-configured scope."
|
||||
commands.deny = ["camera_sync"]
|
||||
@@ -0,0 +1,11 @@
|
||||
# Automatically generated - DO NOT EDIT!
|
||||
|
||||
[[permission]]
|
||||
identifier = "allow-camera-take"
|
||||
description = "Enables the camera_take command without any pre-configured scope."
|
||||
commands.allow = ["camera_take"]
|
||||
|
||||
[[permission]]
|
||||
identifier = "deny-camera-take"
|
||||
description = "Denies the camera_take command without any pre-configured scope."
|
||||
commands.deny = ["camera_take"]
|
||||
@@ -0,0 +1,11 @@
|
||||
# Automatically generated - DO NOT EDIT!
|
||||
|
||||
[[permission]]
|
||||
identifier = "allow-camera-tether"
|
||||
description = "Enables the camera_tether command without any pre-configured scope."
|
||||
commands.allow = ["camera_tether"]
|
||||
|
||||
[[permission]]
|
||||
identifier = "deny-camera-tether"
|
||||
description = "Denies the camera_tether command without any pre-configured scope."
|
||||
commands.deny = ["camera_tether"]
|
||||
@@ -0,0 +1,11 @@
|
||||
# Automatically generated - DO NOT EDIT!
|
||||
|
||||
[[permission]]
|
||||
identifier = "allow-folder-merge-dng"
|
||||
description = "Enables the folder_merge_dng command without any pre-configured scope."
|
||||
commands.allow = ["folder_merge_dng"]
|
||||
|
||||
[[permission]]
|
||||
identifier = "deny-folder-merge-dng"
|
||||
description = "Denies the folder_merge_dng command without any pre-configured scope."
|
||||
commands.deny = ["folder_merge_dng"]
|
||||
@@ -0,0 +1,11 @@
|
||||
# Automatically generated - DO NOT EDIT!
|
||||
|
||||
[[permission]]
|
||||
identifier = "allow-folder-meta"
|
||||
description = "Enables the folder_meta command without any pre-configured scope."
|
||||
commands.allow = ["folder_meta"]
|
||||
|
||||
[[permission]]
|
||||
identifier = "deny-folder-meta"
|
||||
description = "Denies the folder_meta command without any pre-configured scope."
|
||||
commands.deny = ["folder_meta"]
|
||||
@@ -0,0 +1,11 @@
|
||||
# Automatically generated - DO NOT EDIT!
|
||||
|
||||
[[permission]]
|
||||
identifier = "allow-folder-read"
|
||||
description = "Enables the folder_read command without any pre-configured scope."
|
||||
commands.allow = ["folder_read"]
|
||||
|
||||
[[permission]]
|
||||
identifier = "deny-folder-read"
|
||||
description = "Denies the folder_read command without any pre-configured scope."
|
||||
commands.deny = ["folder_read"]
|
||||
@@ -0,0 +1,11 @@
|
||||
# Automatically generated - DO NOT EDIT!
|
||||
|
||||
[[permission]]
|
||||
identifier = "allow-folder-save-dng"
|
||||
description = "Enables the folder_save_dng command without any pre-configured scope."
|
||||
commands.allow = ["folder_save_dng"]
|
||||
|
||||
[[permission]]
|
||||
identifier = "deny-folder-save-dng"
|
||||
description = "Denies the folder_save_dng command without any pre-configured scope."
|
||||
commands.deny = ["folder_save_dng"]
|
||||
@@ -0,0 +1,11 @@
|
||||
# Automatically generated - DO NOT EDIT!
|
||||
|
||||
[[permission]]
|
||||
identifier = "allow-folder-save-jpeg"
|
||||
description = "Enables the folder_save_jpeg command without any pre-configured scope."
|
||||
commands.allow = ["folder_save_jpeg"]
|
||||
|
||||
[[permission]]
|
||||
identifier = "deny-folder-save-jpeg"
|
||||
description = "Denies the folder_save_jpeg command without any pre-configured scope."
|
||||
commands.deny = ["folder_save_jpeg"]
|
||||
@@ -0,0 +1,11 @@
|
||||
# Automatically generated - DO NOT EDIT!
|
||||
|
||||
[[permission]]
|
||||
identifier = "allow-folder-save-xmp"
|
||||
description = "Enables the folder_save_xmp command without any pre-configured scope."
|
||||
commands.allow = ["folder_save_xmp"]
|
||||
|
||||
[[permission]]
|
||||
identifier = "deny-folder-save-xmp"
|
||||
description = "Denies the folder_save_xmp command without any pre-configured scope."
|
||||
commands.deny = ["folder_save_xmp"]
|
||||
Loaded 100 of 133 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user