Compare commits
8
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
dc433d0bdf | ||
|
|
af1e0ca2cc | ||
|
|
9ff98530d9 | ||
|
|
6a91d3fa30 | ||
|
|
8ecfec231f | ||
|
|
c51ab4b010 | ||
|
|
01cb66fe23 | ||
|
|
8af78f18b2 |
No files matched your search
@@ -0,0 +1,10 @@
|
||||
-- A non-local export can also keep a copy in a folder on one computer.
|
||||
ALTER TABLE "delivery_targets" ADD COLUMN "local_folder" TEXT;
|
||||
ALTER TABLE "delivery_targets" ADD COLUMN "local_machine" TEXT;
|
||||
ALTER TABLE "delivery_targets" ADD COLUMN "local_folder_template" TEXT;
|
||||
-- The hidden LOCAL target that receives those copies.
|
||||
ALTER TABLE "delivery_targets" ADD COLUMN "mirror_of_id" UUID;
|
||||
|
||||
CREATE UNIQUE INDEX "delivery_targets_mirror_of_id_key" ON "delivery_targets"("mirror_of_id");
|
||||
|
||||
ALTER TABLE "delivery_targets" ADD CONSTRAINT "delivery_targets_mirror_of_id_fkey" FOREIGN KEY ("mirror_of_id") REFERENCES "delivery_targets"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
@@ -0,0 +1,24 @@
|
||||
-- Face search compares a group with every other group. The centroids stay float arrays for the
|
||||
-- worker; this copy is what the archive searches, kept in step by the trigger.
|
||||
CREATE EXTENSION IF NOT EXISTS vector;
|
||||
|
||||
ALTER TABLE "face_groups" ADD COLUMN "centroid_vec" vector(512);
|
||||
|
||||
CREATE OR REPLACE FUNCTION face_groups_set_centroid_vec() RETURNS trigger AS $$
|
||||
BEGIN
|
||||
IF NEW.centroid IS NULL OR cardinality(NEW.centroid) IS DISTINCT FROM 512 THEN
|
||||
NEW.centroid_vec := NULL;
|
||||
ELSE
|
||||
NEW.centroid_vec := NEW.centroid::vector(512);
|
||||
END IF;
|
||||
RETURN NEW;
|
||||
END;
|
||||
$$ LANGUAGE plpgsql;
|
||||
|
||||
CREATE TRIGGER face_groups_centroid_vec
|
||||
BEFORE INSERT OR UPDATE OF centroid ON face_groups
|
||||
FOR EACH ROW EXECUTE FUNCTION face_groups_set_centroid_vec();
|
||||
|
||||
UPDATE face_groups SET centroid_vec = centroid::vector(512) WHERE cardinality(centroid) = 512;
|
||||
|
||||
CREATE INDEX face_groups_centroid_vec_hnsw ON face_groups USING hnsw (centroid_vec vector_cosine_ops);
|
||||
@@ -564,12 +564,23 @@ model DeliveryTarget {
|
||||
/// Everything sent here is also sent to this target (usually a folder on a computer), with this target's IPTC:
|
||||
/// a local copy of what a client got. Same organization; null: none.
|
||||
copyTargetId String? @map("copy_target_id") @db.Uuid
|
||||
/// A folder on one computer that also receives every file this destination exports (FTP and the rest stay as
|
||||
/// they are). Not for a LOCAL target. The desktop app of `localMachine` writes under this path.
|
||||
localFolder String? @map("local_folder")
|
||||
/// That computer's id (`delivery_machine`).
|
||||
localMachine String? @map("local_machine")
|
||||
/// Subfolders under `localFolder`. `{destination}` is this target's name.
|
||||
localFolderTemplate String? @map("local_folder_template")
|
||||
/// Set only on the hidden LOCAL target that holds those copies; points at the export it mirrors.
|
||||
mirrorOfId String? @unique @map("mirror_of_id") @db.Uuid
|
||||
createdAt DateTime @default(now()) @map("created_at")
|
||||
updatedAt DateTime @updatedAt @map("updated_at")
|
||||
disabledAt DateTime? @map("disabled_at")
|
||||
|
||||
organization Organization @relation(fields: [organizationId], references: [id], onDelete: Cascade)
|
||||
organization Organization @relation(fields: [organizationId], references: [id], onDelete: Cascade)
|
||||
items DeliveryItem[]
|
||||
mirrorOf DeliveryTarget? @relation("LocalMirror", fields: [mirrorOfId], references: [id], onDelete: Cascade)
|
||||
localMirror DeliveryTarget? @relation("LocalMirror")
|
||||
|
||||
@@unique([organizationId, name])
|
||||
@@map("delivery_targets")
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { sameTeam } from "../delivery/zerozero.js";
|
||||
import { officialSigla } from "../sports/fpa-siglas.js";
|
||||
|
||||
/**
|
||||
* What a gallery folder's place and name say about its game. The archives are organised by season, competition
|
||||
@@ -377,6 +378,10 @@ export function isTeam(name: string, team: { name: string; abbreviation: string
|
||||
if (team.abbreviation && fold(team.abbreviation) === n) return true;
|
||||
if (fold(team.slug) === n || fold(team.name) === n) return true;
|
||||
if (sameTeam(name, team.name)) return true;
|
||||
// The delivery writes the federation's short code ("AAAS"). That is not the initials of the sponsor name
|
||||
// ("Águas Santas Milaneza" is A, S, M), and these teams have no abbreviation of their own.
|
||||
const sigla = officialSigla(team.name);
|
||||
if (sigla && fold(sigla) === n) return true;
|
||||
return name.trim().length <= 6 && !/\s/.test(name.trim()) && isInitials(name, team.name);
|
||||
}
|
||||
|
||||
|
||||
@@ -120,8 +120,14 @@ export async function registerArchivePeopleRoutes(app: FastifyInstance, deps: De
|
||||
const { sourceId } = SourceParams.parse(req.params);
|
||||
const v = viewerOf(req, sourceId);
|
||||
const query = PeopleQuery.parse(req.query);
|
||||
const scope = await scopeOf(v);
|
||||
if (!scope) return { people: [], clubs: [] };
|
||||
const visible = await visibleFolders(v);
|
||||
if (visible !== "all" && !visible.length) return { people: [], clubs: [] };
|
||||
const scope = visible === "all"
|
||||
? Prisma.sql`cf.source_id = ${v.s}::uuid AND cf.status = 'DONE' AND cf.photo_id IS NOT NULL`
|
||||
: 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[])`;
|
||||
const folderLimit = visible === "all"
|
||||
? Prisma.sql`cf.source_id = ${v.s}::uuid`
|
||||
: Prisma.sql`cf.source_id = ${v.s}::uuid AND cf.id = ANY(${visible}::uuid[])`;
|
||||
const rows = await db.$queryRaw<{ id: string; name: string; club: string | null; number: string | null; reference: boolean; confirmed: bigint; probable: bigint }[]>`
|
||||
SELECT p.id, p.name, p.club, p.number, p.reference_key IS NOT NULL AS reference,
|
||||
count(DISTINCT f.photo_id) FILTER (WHERE g.person_id = p.id) AS confirmed,
|
||||
@@ -154,8 +160,35 @@ export async function registerArchivePeopleRoutes(app: FastifyInstance, deps: De
|
||||
return [f.person_id, { src: signer.url(f.photo_id, "preview", p.renderedSeq), box: faceBox(f, p), aspect: p.width && p.height ? p.width / p.height : 1.5 }];
|
||||
}),
|
||||
);
|
||||
const clubs = new Map<string, number>();
|
||||
for (const r of rows) if (r.club) clubs.set(r.club, (clubs.get(r.club) ?? 0) + 1);
|
||||
// Clubs already recognised on a face, plus every team named by a gallery the viewer may see. A team with no
|
||||
// face named yet is still a team in the cloud: it stays on the list with nobody counted.
|
||||
const teamRows = await db.$queryRaw<{ name: string; games: number }[]>`
|
||||
SELECT btrim(name) AS name, count(DISTINCT event_id)::int AS games
|
||||
FROM (
|
||||
SELECT e.id AS event_id, e.home AS name
|
||||
FROM cloud_folders cf JOIN events e ON e.id = cf.event_id
|
||||
WHERE ${folderLimit} AND cf.photo_count > 0 AND cf.matched_by IS DISTINCT FROM 'FOLDER' AND btrim(e.home) <> ''
|
||||
UNION ALL
|
||||
SELECT e.id, e.away
|
||||
FROM cloud_folders cf JOIN events e ON e.id = cf.event_id
|
||||
WHERE ${folderLimit} AND cf.photo_count > 0 AND cf.matched_by IS DISTINCT FROM 'FOLDER' AND btrim(e.away) <> ''
|
||||
) sides
|
||||
GROUP BY btrim(name)`;
|
||||
const clubs = new Map<string, { name: string; people: number; games: number }>();
|
||||
const clubKey = (s: string) => fold(s).replace(/\s+/g, " ").trim();
|
||||
for (const r of rows) {
|
||||
if (!r.club) continue;
|
||||
const key = clubKey(r.club);
|
||||
const cur = clubs.get(key) ?? { name: r.club, people: 0, games: 0 };
|
||||
cur.people += 1;
|
||||
clubs.set(key, cur);
|
||||
}
|
||||
for (const t of teamRows) {
|
||||
const key = clubKey(t.name);
|
||||
const cur = clubs.get(key) ?? { name: t.name, people: 0, games: 0 };
|
||||
cur.games += Number(t.games);
|
||||
clubs.set(key, cur);
|
||||
}
|
||||
return {
|
||||
people: shown
|
||||
.map((r) => ({
|
||||
@@ -169,7 +202,9 @@ export async function registerArchivePeopleRoutes(app: FastifyInstance, deps: De
|
||||
face: faceOf.get(r.id) ?? null,
|
||||
}))
|
||||
.sort((a, b) => b.photos + b.probable - (a.photos + a.probable) || a.name.localeCompare(b.name)),
|
||||
clubs: [...clubs].map(([name, people]) => ({ name, people })).sort((a, b) => b.people - a.people || a.name.localeCompare(b.name)),
|
||||
clubs: [...clubs.values()]
|
||||
.sort((a, b) => b.people - a.people || b.games - a.games || a.name.localeCompare(b.name))
|
||||
.map(({ name, people }) => ({ name, people })),
|
||||
};
|
||||
});
|
||||
|
||||
@@ -214,34 +249,60 @@ export async function registerArchivePeopleRoutes(app: FastifyInstance, deps: De
|
||||
};
|
||||
});
|
||||
|
||||
/** Face groups in the viewer's galleries like a face: their faces, with how alike, most alike first. */
|
||||
/**
|
||||
* Face groups in the viewer's galleries like a face, most alike first.
|
||||
* A 512-long centroid is the production embedder: the database ranks it (the column kept for that search).
|
||||
* Anything else is a test vector, compared here.
|
||||
*/
|
||||
const similarGroups = async (embedding: number[], model: string, scope: Prisma.Sql, exclude: Set<string>) => {
|
||||
const t = THRESHOLDS[model] ?? { match: 0.5 };
|
||||
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 cardinality(g.centroid) > 0
|
||||
AND g.event_id IN (
|
||||
SELECT ph.event_id FROM photos ph
|
||||
JOIN cloud_files cf ON cf.photo_id = ph.id
|
||||
WHERE ${scope} AND ph.event_id IS NOT NULL
|
||||
)`;
|
||||
const asVector = (v: unknown): number[] => (Array.isArray(v) ? v.map(Number) : typeof v === "string" ? v.replace(/[{}]/g, "").split(",").filter(Boolean).map(Number) : []);
|
||||
const near = groups
|
||||
.filter((g) => !exclude.has(g.id))
|
||||
.map((g) => ({ g, vector: asVector(g.centroid) }))
|
||||
.filter((x) => x.vector.length)
|
||||
.map((x) => ({ g: x.g, score: cosine(embedding, x.vector) }))
|
||||
.filter((x) => x.score >= t.match);
|
||||
const NEAREST = 400;
|
||||
let near: { id: string; person_id: string | null; score: number }[];
|
||||
if (embedding.length === 512) {
|
||||
const literal = `[${embedding.map((n) => (Number.isFinite(n) ? n : 0)).join(",")}]`;
|
||||
const excluded = exclude.size ? Prisma.sql`AND g.id <> ALL(${[...exclude]}::uuid[])` : Prisma.empty;
|
||||
near = 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.event_id IN (
|
||||
SELECT ph.event_id FROM photos ph
|
||||
JOIN cloud_files cf ON cf.photo_id = ph.id
|
||||
WHERE ${scope} AND ph.event_id IS NOT NULL
|
||||
)
|
||||
${excluded}
|
||||
ORDER BY g.centroid_vec <=> ${literal}::vector
|
||||
LIMIT ${NEAREST}
|
||||
) ranked
|
||||
WHERE score >= ${t.match}`;
|
||||
} else {
|
||||
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 cardinality(g.centroid) > 0
|
||||
AND g.event_id IN (
|
||||
SELECT ph.event_id FROM photos ph
|
||||
JOIN cloud_files cf ON cf.photo_id = ph.id
|
||||
WHERE ${scope} AND ph.event_id IS NOT NULL
|
||||
)`;
|
||||
const asVector = (v: unknown): number[] => (Array.isArray(v) ? v.map(Number) : typeof v === "string" ? v.replace(/[{}]/g, "").split(",").filter(Boolean).map(Number) : []);
|
||||
near = groups
|
||||
.filter((g) => !exclude.has(g.id))
|
||||
.map((g) => ({ id: g.id, person_id: g.person_id, score: cosine(embedding, asVector(g.centroid)) }))
|
||||
.filter((x) => x.score >= t.match)
|
||||
.sort((a, b) => b.score - a.score)
|
||||
.slice(0, NEAREST);
|
||||
}
|
||||
if (!near.length) return [];
|
||||
const score = new Map(near.map((x) => [x.g.id, x]));
|
||||
const score = new Map(near.map((x) => [x.id, x]));
|
||||
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
|
||||
WHERE f.group_id = ANY(${[...score.keys()]}::uuid[]) AND ${scope}`;
|
||||
return faces
|
||||
.map((f) => ({ faceId: f.id, photoId: f.photo_id, sharpness: f.sharpness, score: score.get(f.group_id)!.score, personId: score.get(f.group_id)!.g.person_id }))
|
||||
.map((f) => ({ faceId: f.id, photoId: f.photo_id, sharpness: f.sharpness, score: score.get(f.group_id)!.score, personId: score.get(f.group_id)!.person_id }))
|
||||
.sort((a, b) => b.score - a.score);
|
||||
};
|
||||
|
||||
|
||||
@@ -321,7 +321,12 @@ export async function registerArchiveViewerRoutes(
|
||||
...(query.player && { photo: { players: { has: query.player } } }),
|
||||
...(query.person && { photo: { faces: { some: { group: { personId: query.person, ignoredAt: null } } } } }),
|
||||
};
|
||||
const [total, files, named, sharpest] = await Promise.all([
|
||||
// People named anywhere in this game (every part the viewer may see), not only in this folder.
|
||||
const rosterScope =
|
||||
visible === "all"
|
||||
? Prisma.sql`cf.source_id = ${folder.sourceId}::uuid AND cf.status = 'DONE'`
|
||||
: Prisma.sql`cf.source_id = ${folder.sourceId}::uuid AND cf.status = 'DONE' AND cf.folder_id = ANY(${visible}::uuid[])`;
|
||||
const [total, files, named, sharpest, roster] = await Promise.all([
|
||||
db.cloudFile.count({ where }),
|
||||
db.cloudFile.findMany({
|
||||
where,
|
||||
@@ -344,6 +349,19 @@ export async function registerArchiveViewerRoutes(
|
||||
JOIN face_groups g ON g.id = f.group_id AND g.person_id IS NOT NULL AND g.ignored_at IS NULL
|
||||
JOIN cloud_files cf ON cf.photo_id = f.photo_id AND cf.folder_id = ${folderId}::uuid AND cf.status = 'DONE'
|
||||
ORDER BY g.person_id, f.sharpness DESC NULLS LAST, f.score DESC`,
|
||||
folder.eventId
|
||||
? db.$queryRaw<{ id: string; name: string; club: string | null; number: string | null; here: number; in_game: number }[]>`
|
||||
SELECT p.id, p.name, p.club, p.number,
|
||||
count(DISTINCT cf.photo_id) FILTER (WHERE cf.folder_id = ${folderId}::uuid)::int AS here,
|
||||
count(DISTINCT cf.photo_id)::int AS in_game
|
||||
FROM faces f
|
||||
JOIN face_groups g ON g.id = f.group_id AND g.person_id IS NOT NULL AND g.ignored_at IS NULL
|
||||
JOIN people p ON p.id = g.person_id
|
||||
JOIN cloud_files cf ON cf.photo_id = f.photo_id AND ${rosterScope}
|
||||
JOIN photos ph ON ph.id = cf.photo_id AND ph.event_id = ${folder.eventId}::uuid
|
||||
GROUP BY p.id, p.name, p.club, p.number
|
||||
ORDER BY p.name`
|
||||
: Promise.resolve([]),
|
||||
]);
|
||||
const facePhotos = await db.photo.findMany({
|
||||
where: { id: { in: sharpest.map((f) => f.photo_id) } },
|
||||
@@ -368,6 +386,8 @@ export async function registerArchiveViewerRoutes(
|
||||
cloudUrl: `${base}/f/${folder.fileId}`,
|
||||
total,
|
||||
people: named.map((p) => ({ id: p.id, name: p.name, count: Number(p.count), face: faceOf.get(p.id) ?? null })),
|
||||
/** Everyone named in this game, so a gallery can offer them even when this part has only some. */
|
||||
roster: roster.map((p) => ({ id: p.id, name: p.name, club: p.club, number: p.number, here: Number(p.here), inGame: Number(p.in_game) })),
|
||||
photos: files.map((f) => ({
|
||||
id: f.photo!.id,
|
||||
name: f.path.split("/").pop(),
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { createReadStream, existsSync } from "node:fs";
|
||||
import { DeliveryBestRequest, DeliveryRequest } from "@photoreport/contracts";
|
||||
import { bestOfEvent } from "../autopilot/best.js";
|
||||
import { IptcTemplate, PathTemplateError, renderFileName, renderFolder, buildVars } from "@photoreport/metadata";
|
||||
import { IptcTemplate, LOCAL_COPY_FOLDER, PathTemplateError, renderFileName, renderFolder, buildVars } from "@photoreport/metadata";
|
||||
import type { FastifyInstance } from "fastify";
|
||||
import { z } from "zod";
|
||||
import { currentUserId, requireAuth, requireMembership } from "../auth/guard.js";
|
||||
@@ -10,7 +10,7 @@ import type { Db } from "../db.js";
|
||||
import { type DeliveryTarget, Prisma } from "../generated/prisma/client.js";
|
||||
import { compact } from "../lib/compact.js";
|
||||
import { AppError, badRequest, conflict, notFound } from "../lib/errors.js";
|
||||
import { DeliveryRejected, type DeliveryService, toItemSummary } from "./service.js";
|
||||
import { DeliveryRejected, syncLocalMirror, type DeliveryService, toItemSummary } from "./service.js";
|
||||
import { NextcloudError } from "./nextcloud.js";
|
||||
import { TransportError } from "./transports.js";
|
||||
import type { SecretBox } from "./secrets.js";
|
||||
@@ -59,6 +59,12 @@ const TargetBase = z.object({
|
||||
iptcOverrides: IptcTemplate.partial().nullable(),
|
||||
/** Everything sent here also goes to this target (a folder on a computer), with this target's IPTC; null: none. */
|
||||
copyTargetId: z.uuid().nullable(),
|
||||
/** Also save each exported file under this folder on one computer. Null: the export only. Not for LOCAL. */
|
||||
localFolder: z.string().trim().min(1).max(300).nullable(),
|
||||
/** That computer's id. Required when `localFolder` is set. */
|
||||
localMachine: z.string().trim().min(8).max(120).nullable(),
|
||||
/** Subfolders under `localFolder`. `{destination}` is this target's name. Null with a folder: the default. */
|
||||
localFolderTemplate: z.string().trim().min(1).max(400).nullable(),
|
||||
});
|
||||
const checkAddress = (kind: z.infer<typeof KIND>, baseUrl: string, username: string) => {
|
||||
if (!ADDRESS[kind].test(baseUrl)) throw badRequest("invalid_address", `address for ${kind} must look like ${ADDRESS[kind].source}`);
|
||||
@@ -79,6 +85,9 @@ const TargetFields = TargetBase.extend({
|
||||
untouched: TargetBase.shape.untouched.default(false),
|
||||
iptcOverrides: TargetBase.shape.iptcOverrides.default(null),
|
||||
copyTargetId: TargetBase.shape.copyTargetId.default(null),
|
||||
localFolder: TargetBase.shape.localFolder.default(null),
|
||||
localMachine: TargetBase.shape.localMachine.default(null),
|
||||
localFolderTemplate: TargetBase.shape.localFolderTemplate.default(null),
|
||||
});
|
||||
const UpdateTarget = TargetBase.partial().extend({ disabled: z.boolean().optional(), resetHostKey: z.boolean().optional() });
|
||||
const ListQuery = z.object({
|
||||
@@ -100,17 +109,35 @@ function overridesValue(o: unknown): Prisma.InputJsonValue | typeof Prisma.DbNul
|
||||
}
|
||||
|
||||
function publicTarget(t: DeliveryTarget) {
|
||||
const { secretEnc: _secret, ...rest } = t;
|
||||
const { secretEnc: _secret, mirrorOfId: _mirror, ...rest } = t;
|
||||
return { ...rest, shareLinks: t.kind === "NEXTCLOUD" || t.kind === "DROPBOX" };
|
||||
}
|
||||
|
||||
/** The local copy of an export: a real folder on a computer. A destination that is already a folder has none. */
|
||||
function localCopyOf(
|
||||
kind: z.infer<typeof KIND>,
|
||||
fields: { localFolder: string | null; localMachine: string | null; localFolderTemplate: string | null },
|
||||
): { localFolder: string | null; localMachine: string | null; localFolderTemplate: string | null } {
|
||||
if (kind === "LOCAL" || !fields.localFolder) {
|
||||
return { localFolder: null, localMachine: null, localFolderTemplate: null };
|
||||
}
|
||||
if (!ADDRESS.LOCAL.test(fields.localFolder)) throw badRequest("invalid_address", "the local folder must be an absolute path");
|
||||
if (!fields.localMachine) throw badRequest("username_required");
|
||||
const localFolderTemplate = fields.localFolderTemplate || LOCAL_COPY_FOLDER;
|
||||
checkTemplates(localFolderTemplate, "{originalName}", { destination: "Cliente" });
|
||||
return { localFolder: fields.localFolder, localMachine: fields.localMachine, localFolderTemplate };
|
||||
}
|
||||
|
||||
/** Renders the templates against a sample event so a broken template is refused when saved, not at delivery. */
|
||||
function checkTemplates(folderTemplate: string, fileNameTemplate: string) {
|
||||
const sample = buildVars(
|
||||
{ home: "Casa", away: "Fora", venue: "Pavilhão", city: "Cidade", sport: "andebol", competition: "Competição", competitionCode: "C01", round: "1", matchNumber: "1", startsAt: new Date("2026-09-23T19:00:00Z") },
|
||||
{ capturedAt: new Date("2026-09-23T19:30:00Z"), players: ["Jogador"], sequence: 1 },
|
||||
"Fotógrafo",
|
||||
);
|
||||
function checkTemplates(folderTemplate: string, fileNameTemplate: string, extra: Record<string, string> = {}) {
|
||||
const sample = {
|
||||
...buildVars(
|
||||
{ home: "Casa", away: "Fora", venue: "Pavilhão", city: "Cidade", sport: "andebol", competition: "Competição", competitionCode: "C01", round: "1", matchNumber: "1", startsAt: new Date("2026-09-23T19:00:00Z") },
|
||||
{ capturedAt: new Date("2026-09-23T19:30:00Z"), players: ["Jogador"], sequence: 1 },
|
||||
"Fotógrafo",
|
||||
),
|
||||
...extra,
|
||||
};
|
||||
try {
|
||||
return { folder: renderFolder(folderTemplate, sample), fileName: renderFileName(fileNameTemplate, sample, "IMG_0001.JPG") };
|
||||
} catch (err) {
|
||||
@@ -135,7 +162,7 @@ export async function registerDeliveryRoutes(
|
||||
const checkCopy = async (orgId: string, selfId: string | null, copyId: string | null | undefined) => {
|
||||
if (!copyId) return;
|
||||
if (copyId === selfId) throw badRequest("copy_to_itself");
|
||||
if (!(await db.deliveryTarget.count({ where: { id: copyId, organizationId: orgId } }))) throw badRequest("unknown_copy_target");
|
||||
if (!(await db.deliveryTarget.count({ where: { id: copyId, organizationId: orgId, mirrorOfId: null } }))) throw badRequest("unknown_copy_target");
|
||||
};
|
||||
const seal = (password: string) => {
|
||||
if (!secrets) throw new AppError(503, "delivery_not_configured", "DELIVERY_SECRET_KEY is not set");
|
||||
@@ -152,7 +179,7 @@ export async function registerDeliveryRoutes(
|
||||
app.get("/v1/orgs/:orgId/delivery-targets", { preHandler: authenticate }, async (req) => {
|
||||
const { orgId } = OrgParams.parse(req.params);
|
||||
await requireMembership(db, req, orgId, "INGESTER");
|
||||
const targets = await db.deliveryTarget.findMany({ where: { organizationId: orgId }, orderBy: { name: "asc" } });
|
||||
const targets = await db.deliveryTarget.findMany({ where: { organizationId: orgId, mirrorOfId: null }, orderBy: { name: "asc" } });
|
||||
return { targets: targets.map(publicTarget) };
|
||||
});
|
||||
|
||||
@@ -163,11 +190,13 @@ export async function registerDeliveryRoutes(
|
||||
checkAddress(body.kind, body.baseUrl, body.username);
|
||||
const example = checkTemplates(body.folderTemplate, body.fileNameTemplate);
|
||||
if (await db.deliveryTarget.findUnique({ where: { organizationId_name: { organizationId: orgId, name: body.name } } })) throw conflict("name_taken");
|
||||
const { password, iptcOverrides, ...fields } = body;
|
||||
const { password, iptcOverrides, localFolder: _lf, localMachine: _lm, localFolderTemplate: _lt, ...fields } = body;
|
||||
const local = localCopyOf(body.kind, body);
|
||||
if (!password && body.kind !== "LOCAL") throw badRequest("password_required");
|
||||
await checkLogins(orgId, body.arrivalLogins);
|
||||
await checkCopy(orgId, null, body.copyTargetId);
|
||||
const target = await db.deliveryTarget.create({ data: { ...fields, iptcOverrides: overridesValue(iptcOverrides), organizationId: orgId, secretEnc: seal(password ?? "") } });
|
||||
const target = await db.deliveryTarget.create({ data: { ...fields, ...local, iptcOverrides: overridesValue(iptcOverrides), organizationId: orgId, secretEnc: seal(password ?? "") } });
|
||||
await syncLocalMirror(db, secrets, target).catch(fail);
|
||||
return reply.code(201).send({ ...publicTarget(target), example });
|
||||
});
|
||||
|
||||
@@ -184,18 +213,25 @@ export async function registerDeliveryRoutes(
|
||||
// Another server, another key: a changed address forgets the remembered one.
|
||||
const forgetKey = body.resetHostKey === true || kind !== current.kind || baseUrl !== current.baseUrl;
|
||||
const { password, disabled, resetHostKey: _reset, iptcOverrides, ...fields } = body;
|
||||
const local = localCopyOf(kind, {
|
||||
localFolder: fields.localFolder !== undefined ? fields.localFolder : current.localFolder,
|
||||
localMachine: fields.localMachine !== undefined ? fields.localMachine : current.localMachine,
|
||||
localFolderTemplate: fields.localFolderTemplate !== undefined ? fields.localFolderTemplate : current.localFolderTemplate,
|
||||
});
|
||||
if (fields.arrivalLogins) await checkLogins(orgId, fields.arrivalLogins);
|
||||
if (fields.copyTargetId !== undefined) await checkCopy(orgId, targetId, fields.copyTargetId);
|
||||
const target = await db.deliveryTarget.update({
|
||||
where: { id: targetId },
|
||||
data: {
|
||||
...compact(fields),
|
||||
...local,
|
||||
...(iptcOverrides !== undefined && { iptcOverrides: overridesValue(iptcOverrides) }),
|
||||
...(password !== undefined && { secretEnc: seal(password) }),
|
||||
...(forgetKey && { hostFingerprint: null }),
|
||||
...(disabled !== undefined && { disabledAt: disabled ? (current.disabledAt ?? new Date()) : null }),
|
||||
},
|
||||
});
|
||||
await syncLocalMirror(db, secrets, target).catch(fail);
|
||||
return { ...publicTarget(target), example };
|
||||
});
|
||||
|
||||
@@ -209,8 +245,9 @@ export async function registerDeliveryRoutes(
|
||||
if (await db.deliveryTarget.findUnique({ where: { organizationId_name: { organizationId: orgId, name: body.name } } })) throw conflict("name_taken");
|
||||
const folderTemplate = body.folderTemplate ?? source.folderTemplate;
|
||||
const example = checkTemplates(folderTemplate, source.fileNameTemplate);
|
||||
const { id: _id, createdAt: _c, updatedAt: _u, disabledAt: _d, iptcOverrides, ...copy } = source;
|
||||
const { id: _id, createdAt: _c, updatedAt: _u, disabledAt: _d, iptcOverrides, mirrorOfId: _mirror, ...copy } = source;
|
||||
const target = await db.deliveryTarget.create({ data: { ...copy, iptcOverrides: overridesValue(iptcOverrides), name: body.name, folderTemplate } });
|
||||
await syncLocalMirror(db, secrets, target).catch(fail);
|
||||
return reply.code(201).send({ ...publicTarget(target), example });
|
||||
});
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import type { DeliveryItemSummary } from "@photoreport/contracts";
|
||||
import { buildVars, createdStamp, eventName, PathTemplateError, renderFileName, renderFolder } from "@photoreport/metadata";
|
||||
import { buildVars, createdStamp, eventName, LOCAL_COPY_FOLDER, PathTemplateError, renderFileName, renderFolder } from "@photoreport/metadata";
|
||||
import type { Db } from "../db.js";
|
||||
import type { DeliveryItem } from "../generated/prisma/client.js";
|
||||
import type { DeliveryItem, DeliveryTarget } from "../generated/prisma/client.js";
|
||||
import type { IngestLogger } from "../ingest/service.js";
|
||||
import { waitUntil } from "../lib/idle.js";
|
||||
import { eventInfoOf } from "../library/event-info.js";
|
||||
@@ -61,6 +61,45 @@ export function deliveredName(photo: { originalName: string; fileName: string |
|
||||
/** Where a file rendered for a computer's folder waits on the server. */
|
||||
export const localKey = (orgId: string, itemId: string) => `${orgId}/deliveries/${itemId}.jpg`;
|
||||
|
||||
/**
|
||||
* Keeps the hidden LOCAL target that receives one export's local copies in step with that export (same file name
|
||||
* and output). Turning the folder off disables it; the export itself is unchanged.
|
||||
*/
|
||||
export async function syncLocalMirror(db: Db, secrets: { seal(plain: string): string } | undefined, target: DeliveryTarget): Promise<void> {
|
||||
const existing = await db.deliveryTarget.findFirst({ where: { mirrorOfId: target.id } });
|
||||
const off = target.kind === "LOCAL" || !target.localFolder || !target.localMachine;
|
||||
if (off) {
|
||||
if (existing && !existing.disabledAt) await db.deliveryTarget.update({ where: { id: existing.id }, data: { disabledAt: new Date() } });
|
||||
return;
|
||||
}
|
||||
const data = {
|
||||
name: `local-copy:${target.id}`,
|
||||
kind: "LOCAL" as const,
|
||||
baseUrl: target.localFolder!,
|
||||
username: target.localMachine!,
|
||||
folderTemplate: target.localFolderTemplate || LOCAL_COPY_FOLDER,
|
||||
fileNameTemplate: target.fileNameTemplate,
|
||||
longEdge: target.longEdge,
|
||||
jpegQuality: target.jpegQuality,
|
||||
sharpen: target.sharpen,
|
||||
dpi: target.dpi,
|
||||
keepExif: target.keepExif,
|
||||
srgb: target.srgb,
|
||||
originals: target.originals,
|
||||
untouched: target.untouched,
|
||||
onArrival: false,
|
||||
arrivalLogins: [] as string[],
|
||||
disabledAt: null,
|
||||
organizationId: target.organizationId,
|
||||
};
|
||||
if (existing) {
|
||||
await db.deliveryTarget.update({ where: { id: existing.id }, data });
|
||||
return;
|
||||
}
|
||||
if (!secrets) throw new DeliveryRejected("delivery_secret_key_missing");
|
||||
await db.deliveryTarget.create({ data: { ...data, mirrorOfId: target.id, secretEnc: secrets.seal("") } });
|
||||
}
|
||||
|
||||
/**
|
||||
* Marks a photo's deliveries to be taken back (the photo was rejected or un-picked). Already on a destination
|
||||
* (DONE) or waiting for a computer (WAITING): queued for the worker to remove. Not uploaded yet (QUEUED):
|
||||
@@ -148,6 +187,8 @@ export class DeliveryService {
|
||||
requestedById: string | null;
|
||||
/** 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. */
|
||||
sequences?: ReadonlyMap<string, number>;
|
||||
}): Promise<{ queued: DeliveryItem[]; skipped: { photoId: string; reason: string }[] }> {
|
||||
const { db } = this.deps;
|
||||
const target = await db.deliveryTarget.findFirst({ where: { id: input.targetId, organizationId: input.organizationId, disabledAt: null } });
|
||||
@@ -188,9 +229,13 @@ export class DeliveryService {
|
||||
let next = (last._max.sequence ?? 0) + 1;
|
||||
const created: DeliveryItem[] = [];
|
||||
for (const photo of group) {
|
||||
// A local copy of an export keeps that export's number, so the file name is the one that was sent.
|
||||
const fixed = input.sequences?.get(photo.id);
|
||||
const sequence = fixed ?? next;
|
||||
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: next++, 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 },
|
||||
}),
|
||||
);
|
||||
}
|
||||
@@ -199,11 +244,30 @@ export class DeliveryService {
|
||||
queued.push(...items);
|
||||
}
|
||||
for (const item of queued) this.deps.broadcaster.library(item.organizationId, { type: "delivery.updated", item: toItemSummary(item) });
|
||||
// A copy of what this client gets, e.g. in a folder on the photographer's computer (one level: a copy is not copied).
|
||||
if (target.copyTargetId && target.copyTargetId !== target.id && !input.via && queued.length) {
|
||||
await this.enqueue({ ...input, targetId: target.copyTargetId, photoIds: queued.map((q) => q.photoId), via: target.id }).catch((err: unknown) =>
|
||||
this.deps.log.warn({ err, targetId: target.id, copyTargetId: target.copyTargetId }, "delivery: local copy not queued"),
|
||||
);
|
||||
// Copies are not copied again. The export itself is unchanged; these are extra files.
|
||||
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"),
|
||||
);
|
||||
}
|
||||
// The same export, also saved under the computer folder (date, game, destination name).
|
||||
if (target.kind !== "LOCAL" && target.localFolder && target.localMachine) {
|
||||
const mirror = await db.deliveryTarget.findFirst({ where: { mirrorOfId: target.id, disabledAt: null } });
|
||||
if (!mirror) this.deps.log.warn({ targetId: target.id }, "delivery: local folder set but its copy target is missing");
|
||||
else {
|
||||
await this.enqueue({
|
||||
organizationId: input.organizationId,
|
||||
targetId: mirror.id,
|
||||
photoIds,
|
||||
again: input.again,
|
||||
requestedById: input.requestedById,
|
||||
via: target.id,
|
||||
sequences: new Map(queued.map((q) => [q.photoId, q.sequence])),
|
||||
}).catch((err: unknown) => this.deps.log.warn({ err, targetId: target.id }, "delivery: local copy not queued"));
|
||||
}
|
||||
}
|
||||
}
|
||||
return { queued, skipped };
|
||||
}
|
||||
@@ -397,25 +461,29 @@ export class DeliveryService {
|
||||
try {
|
||||
// The IPTC first: Photo Mechanic's {headline}, {caption}... in folder and file names are the photo's pad.
|
||||
// With this client's own fields on top (another agency in Creator, players left to right in Title...).
|
||||
// A local copy of another client's delivery is written with that client's IPTC: the same file it got.
|
||||
const via = item.viaTargetId ? await db.deliveryTarget.findUnique({ where: { id: item.viaTargetId }, select: { iptcOverrides: true } }) : null;
|
||||
const iptc = await iptcForPhoto(db, item.photoId, via ? via.iptcOverrides : item.target.iptcOverrides);
|
||||
// A copy of another client's delivery is written with that client's IPTC. The local folder of an export is
|
||||
// the same file that client got (its size, name and IPTC), filed by day, game and destination.
|
||||
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;
|
||||
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.
|
||||
const exif = item.photo.exif ?? (await readCameraInfo(source).then((c) => c.extra ?? null, () => null));
|
||||
const vars = buildVars(eventInfoOf(item.event), photoInfoOf({ ...item.photo, exif }, { sequence: item.sequence }), item.photo.uploader?.name, { iptc: iptc?.values });
|
||||
let folder = renderFolder(item.target.folderTemplate, vars);
|
||||
if (item.target.kind === "ZEROZERO") folder = `${await this.zerozeroGameId(item.target, item.event)}/`;
|
||||
const named = sameExport && viaTarget ? { ...vars, destination: viaTarget.name } : vars;
|
||||
let folder = renderFolder(sameExport && viaTarget ? viaTarget.localFolderTemplate || LOCAL_COPY_FOLDER : item.target.folderTemplate, named);
|
||||
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(item.target.fileNameTemplate, vars, item.target.originals && item.target.untouched ? item.photo.originalName : deliveredName(item.photo));
|
||||
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 created = item.photo.capturedAt ? createdStamp(item.photo.capturedAt) : undefined;
|
||||
const rendered = item.target.originals
|
||||
? item.target.untouched
|
||||
const rendered = recipe.originals
|
||||
? recipe.untouched
|
||||
? await readFile(source)
|
||||
: await originalWithMetadata(source, iptc?.values ?? {}, created)
|
||||
: await renderDelivery(source, iptc?.values ?? {}, { longEdge: item.target.longEdge, quality: item.target.jpegQuality, sharpen: item.target.sharpen, dpi: item.target.dpi, exif: item.target.keepExif, srgb: item.target.srgb }, created, edit);
|
||||
: 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);
|
||||
const data = rendered;
|
||||
if (item.target.kind === "LOCAL") {
|
||||
// Kept here until the computer's desktop app takes it (localClaim → localFile → localResult).
|
||||
|
||||
@@ -266,6 +266,9 @@ export class FaceService {
|
||||
const people = everyone.filter((p) => !sport || !sports.has(p.id) || sports.get(p.id) === sport);
|
||||
// Numbers as worn in this event's season and competition (another season, a cup, the national team: another).
|
||||
const ctx = await numberContext(db, eventId);
|
||||
// A game linked to its two clubs: only those squads. Another club's player who looks alike is not a guess.
|
||||
const squadIds = ctx?.teamIds.length ? await playerIdsOnSquads(db, ctx.teamIds, ctx.season) : null;
|
||||
const candidates = squadIds ? people.filter((p) => p.sportsPlayerId !== null && squadIds.has(p.sportsPlayerId)) : people;
|
||||
const worn = new Map<string, string | null>();
|
||||
const numberOf = async (ids: string[]): Promise<Map<string, string | null>> => {
|
||||
const missing = ids.filter((id) => !worn.has(id));
|
||||
@@ -277,7 +280,7 @@ export class FaceService {
|
||||
};
|
||||
for (const g of groups) {
|
||||
const { match, margin } = this.thresholds(g.model);
|
||||
const ranked = people
|
||||
const ranked = candidates
|
||||
.filter((p) => p.model === g.model)
|
||||
.map((p) => ({ p, s: cosine(p.centroid, g.centroid) }))
|
||||
.sort((a, b) => b.s - a.s);
|
||||
@@ -577,6 +580,31 @@ export function normSport(s: string | null | undefined): string | null {
|
||||
return v;
|
||||
}
|
||||
|
||||
/**
|
||||
* Squad entries of these teams this season, plus the same player written under another season (the federation id,
|
||||
* or the same name at the same club). Null when this season's squad is not here yet: then a face may still be
|
||||
* matched more widely. An empty set means the squad is known and nobody outside it is a candidate.
|
||||
*/
|
||||
async function playerIdsOnSquads(db: Db, teamIds: string[], season: string): Promise<Set<string> | null> {
|
||||
const squad = await db.sportsPlayer.findMany({
|
||||
where: { teamId: { in: teamIds }, season },
|
||||
select: { id: true, teamId: true, name: true, externalId: true },
|
||||
});
|
||||
if (!squad.length) return null;
|
||||
const externalIds = [...new Set(squad.map((s) => s.externalId).filter((x): x is string => !!x))];
|
||||
const same = await db.sportsPlayer.findMany({
|
||||
where: {
|
||||
OR: [
|
||||
{ id: { in: squad.map((s) => s.id) } },
|
||||
...squad.map((s) => ({ teamId: s.teamId, name: s.name })),
|
||||
...(externalIds.length ? [{ externalId: { in: externalIds } }] : []),
|
||||
],
|
||||
},
|
||||
select: { id: true },
|
||||
});
|
||||
return new Set(same.map((s) => s.id));
|
||||
}
|
||||
|
||||
/** The sport of an event: its own, its official game's, or its archive cloud's (Liga: football, FPA: handball). */
|
||||
export async function eventSport(db: Db, eventId: string): Promise<string | null> {
|
||||
const rows = await db.$queryRaw<{ sport: string | null }[]>`
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
import { mkdtemp, rm, writeFile } from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import path from "node:path";
|
||||
import sharp from "sharp";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { jpegComplete, jpegFileComplete } from "./jpeg.js";
|
||||
|
||||
describe("finished JPEG", () => {
|
||||
it("accepts a file that ends with the end marker and refuses one still arriving", async () => {
|
||||
const full = await sharp({ create: { width: 8, height: 8, channels: 3, background: "#336699" } }).jpeg().toBuffer();
|
||||
expect(jpegComplete(full)).toBe(true);
|
||||
expect(jpegComplete(Buffer.concat([full, Buffer.from([0x00, 0x00])]))).toBe(true);
|
||||
expect(jpegComplete(full.subarray(0, full.length - 20))).toBe(false);
|
||||
expect(jpegComplete(Buffer.from("not really a jpeg"))).toBe(false);
|
||||
expect(jpegComplete(Buffer.from([0xff, 0xd8, 0xff, 0xd9]))).toBe(true);
|
||||
|
||||
const dir = await mkdtemp(path.join(tmpdir(), "pr-jpeg-"));
|
||||
try {
|
||||
const file = path.join(dir, "a.jpg");
|
||||
await writeFile(file, full.subarray(0, full.length - 20));
|
||||
expect(await jpegFileComplete(file)).toBe(false);
|
||||
await writeFile(file, full);
|
||||
expect(await jpegFileComplete(file)).toBe(true);
|
||||
} finally {
|
||||
await rm(dir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,49 @@
|
||||
import { open } from "node:fs/promises";
|
||||
|
||||
const TAIL = 64;
|
||||
|
||||
/**
|
||||
* A JPEG the camera has finished writing: it starts with SOI and the end-of-image marker is at the tail.
|
||||
* A few padding bytes after that marker are normal. Entropy-coded data never contains a raw FFD9
|
||||
* (a 0xFF there is stuffed), so the marker at the end means the transfer of this file is done.
|
||||
*/
|
||||
export function jpegComplete(bytes: Uint8Array): boolean {
|
||||
if (bytes.length < 4 || bytes[0] !== 0xff || bytes[1] !== 0xd8) return false;
|
||||
return eoiAtEnd(bytes);
|
||||
}
|
||||
|
||||
/** Reads the head and the tail only, and checks the size again so a file still growing is not complete. */
|
||||
export async function jpegFileComplete(file: string): Promise<boolean> {
|
||||
const fh = await open(file, "r");
|
||||
try {
|
||||
const size = (await fh.stat()).size;
|
||||
if (size < 4) return false;
|
||||
const head = Buffer.alloc(2);
|
||||
const headRead = await fh.read(head, 0, 2, 0);
|
||||
if (headRead.bytesRead !== 2 || head[0] !== 0xff || head[1] !== 0xd8) return false;
|
||||
const n = Math.min(size, TAIL);
|
||||
const tail = Buffer.alloc(n);
|
||||
const tailRead = await fh.read(tail, 0, n, size - n);
|
||||
if (tailRead.bytesRead !== n) return false;
|
||||
if ((await fh.stat()).size !== size) return false;
|
||||
return eoiAtEnd(tail);
|
||||
} catch {
|
||||
return false;
|
||||
} finally {
|
||||
await fh.close();
|
||||
}
|
||||
}
|
||||
|
||||
function eoiAtEnd(tail: Uint8Array): boolean {
|
||||
if (tail.length < 2) return false;
|
||||
const from = Math.max(0, tail.length - TAIL);
|
||||
for (let i = tail.length - 2; i >= from; i--) {
|
||||
if (tail[i] !== 0xff || tail[i + 1] !== 0xd9) continue;
|
||||
for (let j = i + 2; j < tail.length; j++) {
|
||||
const b = tail[j];
|
||||
if (b !== 0x00 && b !== 0xff) return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
import { readdir, stat } from "node:fs/promises";
|
||||
import path from "node:path";
|
||||
import { waitUntil } from "../lib/idle.js";
|
||||
import { jpegFileComplete } from "./jpeg.js";
|
||||
import type { IngestLogger, IngestService } from "./service.js";
|
||||
|
||||
interface Seen {
|
||||
@@ -9,9 +10,11 @@ interface Seen {
|
||||
}
|
||||
|
||||
/**
|
||||
* Polls the FTP drop folder. A file is processed once its size and modification time stay the same between two
|
||||
* scans (the upload has finished). Folders starting with `_` (set-aside files) and dot files (temporary
|
||||
* uploads) are ignored. The SFTPGo upload hook can push a file earlier; the scanner is the safety net.
|
||||
* Polls the FTP drop folder. A JPEG is processed once two scans see the same size and modification time and the
|
||||
* file ends with the end-of-image marker. A pause while the camera is still sending leaves the file where it is:
|
||||
* moving it then stores the grey fill of the rows that have not arrived. Folders starting with `_` (set-aside
|
||||
* files) and dot files (temporary uploads) are ignored. The SFTPGo upload hook can push a file earlier; the
|
||||
* scanner is the safety net.
|
||||
*/
|
||||
export class IngestScanner {
|
||||
private readonly seen = new Map<string, Seen>();
|
||||
@@ -76,7 +79,10 @@ export class IngestScanner {
|
||||
if (!s) continue;
|
||||
const before = this.seen.get(file);
|
||||
this.seen.set(file, { size: s.size, mtimeMs: s.mtimeMs });
|
||||
if (before && before.size === s.size && before.mtimeMs === s.mtimeMs && s.size > 0) ready.push(file);
|
||||
if (!before || before.size !== s.size || before.mtimeMs !== s.mtimeMs || s.size === 0) continue;
|
||||
const ext = path.extname(file).toLowerCase();
|
||||
// Anything else is set aside by the service. A JPEG also has to be finished, not merely quiet.
|
||||
if ((ext !== ".jpg" && ext !== ".jpeg") || (await jpegFileComplete(file))) ready.push(file);
|
||||
}
|
||||
for (const file of this.seen.keys()) if (!present.has(file)) this.seen.delete(file);
|
||||
|
||||
|
||||
@@ -9,6 +9,7 @@ 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 { jpegFileComplete } from "./jpeg.js";
|
||||
|
||||
export const ACCEPTED_EXTENSIONS = new Set([".jpg", ".jpeg"]);
|
||||
|
||||
@@ -16,7 +17,7 @@ export type IngestOutcome =
|
||||
| { status: "ingested"; photoId: string; eventId: string | null }
|
||||
| { status: "duplicate"; photoId: string }
|
||||
| { status: "failed"; photoId: string; error: string }
|
||||
| { status: "skipped"; reason: "unknown_login" | "unsupported_type" | "outside_root" };
|
||||
| { status: "skipped"; reason: "unknown_login" | "unsupported_type" | "outside_root" | "incomplete" };
|
||||
|
||||
export interface IngestLogger {
|
||||
info(obj: object, msg: string): void;
|
||||
@@ -82,6 +83,12 @@ export class IngestService {
|
||||
log.warn({ file }, "ingest: unsupported file type set aside (JPEG only for now)");
|
||||
return { status: "skipped", reason: "unsupported_type" };
|
||||
}
|
||||
// Still arriving: leave it in the drop folder. Moving it now (and decoding with a lenient JPEG loader)
|
||||
// stores a grey rectangle for the rows the camera has not sent yet.
|
||||
if (!(await jpegFileComplete(file))) {
|
||||
log.info({ file }, "ingest: transfer still in progress, file left in place");
|
||||
return { status: "skipped", reason: "incomplete" };
|
||||
}
|
||||
const account = await db.ftpAccount.findUnique({ where: { login } });
|
||||
if (!account) {
|
||||
await this.setAside(file, "_unclaimed");
|
||||
@@ -268,15 +275,14 @@ export class IngestService {
|
||||
private async makeDerivatives(orgId: string, sha256: string, storageKey: string): Promise<{ width: number; height: number }> {
|
||||
const { storage } = this.deps;
|
||||
const source = storage.resolve(storageKey);
|
||||
// A truncated upload (interrupted FTP) still has a usable image: decode what is there
|
||||
// instead of failing the whole photo, as Photo Mechanic does. Genuinely unreadable
|
||||
// files still throw below (no width/height).
|
||||
const meta = await sharp(source, { failOn: "none" }).metadata();
|
||||
// A cut-off file must fail. libvips otherwise paints the missing rows grey and we store that as the photo.
|
||||
// The failed row is replaced when the same bytes arrive again; a file still transferring never gets here.
|
||||
const meta = await sharp(source, { failOn: "error" }).metadata();
|
||||
if (!meta.width || !meta.height) throw new Error("not a readable image");
|
||||
const rotated = (meta.orientation ?? 1) >= 5;
|
||||
for (const variant of ["thumb", "preview"] as const) {
|
||||
const side = VARIANT_SIZE[variant];
|
||||
const data = await sharp(source, { failOn: "none" })
|
||||
const data = await sharp(source, { failOn: "error" })
|
||||
.rotate()
|
||||
.resize({ width: side, height: side, fit: "inside", withoutEnlargement: true })
|
||||
.jpeg({ quality: variant === "thumb" ? 80 : 88, mozjpeg: true })
|
||||
|
||||
@@ -9,6 +9,7 @@ import { badRequest, notFound } from "../lib/errors.js";
|
||||
import { waitUntil } from "../lib/idle.js";
|
||||
import type { LocalStorage } from "../storage/storage.js";
|
||||
import { type CodeClash, type SquadForCodes, buildCodeLines, hasGeneratedBlock, mergeGenerated, slugify, toTsv } from "./codegen.js";
|
||||
import { tallyOf, tallySquadPhotos } from "./squadPhotos.js";
|
||||
import {
|
||||
type Fetch,
|
||||
type FixtureData,
|
||||
@@ -746,17 +747,8 @@ export class SportsService {
|
||||
JOIN photos ph ON ph.id = f.photo_id
|
||||
WHERE g.event_id = ${eventId}::uuid AND g.ignored_at IS NULL AND ph.event_id = ${eventId}::uuid
|
||||
AND (g.person_id IS NOT NULL OR g.suggested_person_id IS NOT NULL)`;
|
||||
const photosOf = new Map<string, { confirmed: Set<string>; likely: Set<string> }>();
|
||||
for (const r of rows) {
|
||||
const entry = photosOf.get(r.person_id) ?? { confirmed: new Set<string>(), likely: new Set<string>() };
|
||||
(r.confirmed ? entry.confirmed : entry.likely).add(r.photo_id);
|
||||
photosOf.set(r.person_id, entry);
|
||||
}
|
||||
const counts = (personId: string | null) => {
|
||||
const e = personId ? photosOf.get(personId) : undefined;
|
||||
if (!e) return { confirmed: 0, likely: 0 };
|
||||
return { confirmed: e.confirmed.size, likely: [...e.likely].filter((id) => !e.confirmed.has(id)).length };
|
||||
};
|
||||
const photosOf = tallySquadPhotos(rows);
|
||||
const counts = (personId: string | null) => tallyOf(photosOf, personId);
|
||||
for (const [side, team] of [
|
||||
["home", event.homeTeam],
|
||||
["away", event.awayTeam],
|
||||
@@ -771,16 +763,20 @@ export class SportsService {
|
||||
sides.push({
|
||||
side,
|
||||
team: { id: team.id, name: team.name, abbreviation: team.abbreviation, logoUrl: team.logoUrl },
|
||||
players: players.map((p) => ({
|
||||
id: p.id,
|
||||
number: p.number,
|
||||
name: p.name,
|
||||
fullName: p.fullName,
|
||||
position: p.position,
|
||||
hasPhoto: !!p.photoUrl,
|
||||
personId: personOf.get(p.id) ?? null,
|
||||
photos: counts(personOf.get(p.id) ?? null),
|
||||
})),
|
||||
players: players.map((p) => {
|
||||
const tally = counts(personOf.get(p.id) ?? null);
|
||||
return {
|
||||
id: p.id,
|
||||
number: p.number,
|
||||
name: p.name,
|
||||
fullName: p.fullName,
|
||||
position: p.position,
|
||||
hasPhoto: !!p.photoUrl,
|
||||
personId: personOf.get(p.id) ?? null,
|
||||
photos: { confirmed: tally.confirmed, likely: tally.likely },
|
||||
photoIds: tally.photoIds,
|
||||
};
|
||||
}),
|
||||
});
|
||||
}
|
||||
return { eventId, sides };
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { tallyOf, tallySquadPhotos } from "./squadPhotos.js";
|
||||
|
||||
describe("squad photo tallies", () => {
|
||||
it("counts a photo once when it is both confirmed and only suggested", () => {
|
||||
const index = tallySquadPhotos([
|
||||
{ person_id: "rui", photo_id: "p1", confirmed: true },
|
||||
{ person_id: "rui", photo_id: "p2", confirmed: true },
|
||||
{ person_id: "rui", photo_id: "p2", confirmed: false },
|
||||
{ person_id: "rui", photo_id: "p3", confirmed: false },
|
||||
{ person_id: "tiago", photo_id: "p4", confirmed: false },
|
||||
]);
|
||||
expect(tallyOf(index, "rui")).toEqual({ confirmed: 2, likely: 1, photoIds: ["p1", "p2", "p3"] });
|
||||
expect(tallyOf(index, "tiago")).toEqual({ confirmed: 0, likely: 1, photoIds: ["p4"] });
|
||||
expect(tallyOf(index, null)).toEqual({ confirmed: 0, likely: 0, photoIds: [] });
|
||||
expect(tallyOf(index, "missing")).toEqual({ confirmed: 0, likely: 0, photoIds: [] });
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,39 @@
|
||||
/** One face row: the person it names, the photo, and whether that name is confirmed. */
|
||||
export interface SquadPhotoRow {
|
||||
person_id: string;
|
||||
photo_id: string;
|
||||
confirmed: boolean;
|
||||
}
|
||||
|
||||
export interface SquadPhotoTally {
|
||||
confirmed: number;
|
||||
likely: number;
|
||||
/** Confirmed photos, then the ones only suggested. A photo that is both is listed once. */
|
||||
photoIds: string[];
|
||||
}
|
||||
|
||||
/**
|
||||
* Photos of each person in one event. A photo with a confirmed face and a suggestion of the same person
|
||||
* counts once, as confirmed. The id list is what the library shows when that player is picked.
|
||||
*/
|
||||
export function tallySquadPhotos(rows: readonly SquadPhotoRow[]): Map<string, SquadPhotoTally> {
|
||||
const buckets = new Map<string, { confirmed: Set<string>; likely: Set<string> }>();
|
||||
for (const row of rows) {
|
||||
if (!row.person_id || !row.photo_id) continue;
|
||||
const bucket = buckets.get(row.person_id) ?? { confirmed: new Set<string>(), likely: new Set<string>() };
|
||||
if (row.confirmed) bucket.confirmed.add(row.photo_id);
|
||||
else bucket.likely.add(row.photo_id);
|
||||
buckets.set(row.person_id, bucket);
|
||||
}
|
||||
const out = new Map<string, SquadPhotoTally>();
|
||||
for (const [personId, bucket] of buckets) {
|
||||
const likely = [...bucket.likely].filter((id) => !bucket.confirmed.has(id));
|
||||
out.set(personId, { confirmed: bucket.confirmed.size, likely: likely.length, photoIds: [...bucket.confirmed, ...likely] });
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
export function tallyOf(index: Map<string, SquadPhotoTally>, personId: string | null): SquadPhotoTally {
|
||||
if (!personId) return { confirmed: 0, likely: 0, photoIds: [] };
|
||||
return index.get(personId) ?? { confirmed: 0, likely: 0, photoIds: [] };
|
||||
}
|
||||
@@ -169,6 +169,22 @@ describe("archive folder names", () => {
|
||||
expect(isTeam("ABC", { name: "ABC de Braga / Uminho", abbreviation: null, slug: "abc-braga" })).toBe(true);
|
||||
expect(isTeam("SLB", { name: "Sport Lisboa e Benfica", abbreviation: null, slug: "benfica" })).toBe(true);
|
||||
expect(isTeam("SLB", { name: "Sporting Clube de Portugal", abbreviation: null, slug: "sporting" })).toBe(false);
|
||||
// The program writes the federation code. "AAAS" is not the initials of the sponsor name.
|
||||
const aguas = { name: "Águas Santas Milaneza", abbreviation: null, slug: "aguas-santas-milaneza" };
|
||||
const sporting = { name: "Sporting CP", abbreviation: null, slug: "sporting-cp" };
|
||||
expect(isTeam("AAAS", aguas)).toBe(true);
|
||||
expect(isTeam("SCP", sporting)).toBe(true);
|
||||
expect(isTeam("AAAS", { name: "AA Águas Santas 'B'", abbreviation: null, slug: "aa-aguas-santas-b" })).toBe(false);
|
||||
const today: FixtureCandidate = {
|
||||
id: "hoje",
|
||||
startsAt: new Date("2026-10-18T13:00:00Z"),
|
||||
season: "20262027",
|
||||
round: null,
|
||||
competition: { externalId: "PO01" },
|
||||
homeTeam: aguas,
|
||||
awayTeam: sporting,
|
||||
};
|
||||
expect(pickFixture(parseFolder("/FPA/Fotos/2026_2027/Competições Nacionais/PO01 - Campeonato Betclic/20261018 - AAAS x SCP")!, [today])?.id).toBe("hoje");
|
||||
});
|
||||
|
||||
it("takes a game only when both sides are recognised, never with one guessed", () => {
|
||||
@@ -662,7 +678,10 @@ describe("archive from a Nextcloud", () => {
|
||||
|
||||
const owner = await signIn("peter");
|
||||
let res = await get(owner, `/v1/archive/${source.id}/people`);
|
||||
expect(res.json()).toMatchObject({ people: [{ name: "Martim Costa", club: "Sporting CP", photos: 2, face: { box: expect.any(Object) } }], clubs: [{ name: "Sporting CP", people: 1 }] });
|
||||
expect(res.json()).toMatchObject({
|
||||
people: [{ name: "Martim Costa", club: "Sporting CP", photos: 2, face: { box: expect.any(Object) } }],
|
||||
clubs: expect.arrayContaining([{ name: "Sporting CP", people: 1 }]),
|
||||
});
|
||||
|
||||
// Martim: his two named photos, and the gala photo with a face like his.
|
||||
res = await get(owner, `/v1/archive/${source.id}/people/${martim.id}`);
|
||||
@@ -686,6 +705,7 @@ describe("archive from a Nextcloud", () => {
|
||||
expect(res.json().total).toBe(2);
|
||||
expect(res.json().photos[0].faces).toBeUndefined();
|
||||
expect(res.json().people).toEqual([expect.objectContaining({ name: "Martim Costa", count: 2 })]);
|
||||
expect(res.json().roster).toEqual([expect.objectContaining({ name: "Martim Costa", here: 2, inGame: 2 })]);
|
||||
res = await get(owner, `/v1/archive/photos/${p2.id}`);
|
||||
expect((res.json().faces as { person: { name: string } | null }[]).map((f) => f.person?.name ?? null).sort()).toEqual(["Martim Costa", null].sort());
|
||||
|
||||
|
||||
@@ -404,6 +404,56 @@ describe("delivery", () => {
|
||||
expect(copied["IPTC:ObjectName"]).toBe("Rui Costa (AAAS), Miguel Silva (VSC)");
|
||||
});
|
||||
|
||||
it("saves the same export into a computer folder named by the day, the game and the destination", async () => {
|
||||
const { orgId, token, target } = await setup();
|
||||
const saved = await ctx.app.inject({
|
||||
method: "PATCH",
|
||||
url: `/v1/orgs/${orgId}/delivery-targets/${target.id}`,
|
||||
headers: bearer(token),
|
||||
payload: { localFolder: "/Users/cyclop/Desktop/2026", localMachine: "desktop-0000000000000001", localFolderTemplate: "/{iptcdate} - {event} - {destination}/" },
|
||||
});
|
||||
expect(saved.statusCode).toBe(200);
|
||||
expect(saved.json()).toMatchObject({ baseUrl: "https://cloud.test", localFolder: "/Users/cyclop/Desktop/2026", localFolderTemplate: "/{iptcdate} - {event} - {destination}/" });
|
||||
const listed = (await ctx.app.inject({ method: "GET", url: `/v1/orgs/${orgId}/delivery-targets`, headers: bearer(token) })).json() as { targets: { name: string }[] };
|
||||
expect(listed.targets.map((t) => t.name)).toEqual(["FPA"]);
|
||||
|
||||
const id = await photo("a.jpg", "2026:09:23 21:10:00");
|
||||
await ctx.app.inject({ method: "POST", url: `/v1/orgs/${orgId}/deliveries`, headers: bearer(token), payload: { targetId: target.id, photoIds: [id] } });
|
||||
await drain();
|
||||
|
||||
const sentPath = [...nc.files.keys()][0]!;
|
||||
expect(sentPath.endsWith("/PS_VSC x AAAS_1.jpg")).toBe(true);
|
||||
const copy = await ctx.db.deliveryItem.findFirstOrThrow({ where: { viaTargetId: target.id } });
|
||||
expect([copy.status, copy.sequence, copy.remotePath]).toEqual(["WAITING", 1, "20260923 - VSC x AAAS - FPA/PS_VSC x AAAS_1.jpg"]);
|
||||
const mirror = await ctx.db.deliveryTarget.findFirstOrThrow({ where: { mirrorOfId: target.id } });
|
||||
expect(mirror).toMatchObject({ kind: "LOCAL", baseUrl: "/Users/cyclop/Desktop/2026", username: "desktop-0000000000000001", disabledAt: null });
|
||||
|
||||
const cleared = await ctx.app.inject({
|
||||
method: "PATCH",
|
||||
url: `/v1/orgs/${orgId}/delivery-targets/${target.id}`,
|
||||
headers: bearer(token),
|
||||
payload: { localFolder: null },
|
||||
});
|
||||
expect(cleared.statusCode).toBe(200);
|
||||
expect((cleared.json() as { localFolder: null }).localFolder).toBeNull();
|
||||
expect((await ctx.db.deliveryTarget.findFirstOrThrow({ where: { id: mirror.id } })).disabledAt).not.toBeNull();
|
||||
|
||||
const later = await photo("b.jpg", "2026:09:23 21:20:00");
|
||||
await ctx.app.inject({ method: "POST", url: `/v1/orgs/${orgId}/deliveries`, headers: bearer(token), payload: { targetId: target.id, photoIds: [later] } });
|
||||
await drain();
|
||||
expect(await ctx.db.deliveryItem.count({ where: { viaTargetId: target.id } })).toBe(1);
|
||||
|
||||
// A destination that is already a folder does not grow a second copy of itself.
|
||||
const localOnly = await ctx.app.inject({
|
||||
method: "POST",
|
||||
url: `/v1/orgs/${orgId}/delivery-targets`,
|
||||
headers: bearer(token),
|
||||
payload: { name: "Pasta", kind: "LOCAL", baseUrl: "/Users/cyclop/Desktop/2026", username: "desktop-0000000000000001", folderTemplate: "/{event}/", fileNameTemplate: "{originalName}", localFolder: "/tmp/outra", localMachine: "desktop-0000000000000001" },
|
||||
});
|
||||
expect(localOnly.statusCode).toBe(201);
|
||||
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 () => {
|
||||
const { orgId, token, target } = await setup();
|
||||
await ctx.db.organization.update({ where: { id: orgId }, data: { biometricsEnabled: true, biometricsLegalBasis: "test" } });
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { mkdir, mkdtemp, readdir, rm, writeFile } from "node:fs/promises";
|
||||
import { mkdir, mkdtemp, readdir, rm, stat, writeFile } from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import path from "node:path";
|
||||
import sharp from "sharp";
|
||||
@@ -254,7 +254,9 @@ describe("library", () => {
|
||||
|
||||
it("says why a photo failed", async () => {
|
||||
const { orgId, admin } = await setup();
|
||||
await service.ingestFile(await drop("foto.r1", "cut.jpg", Buffer.from("not really a jpeg")));
|
||||
// End marker present, so this is a finished file that cannot be decoded, not one still arriving.
|
||||
const unreadable = Buffer.concat([Buffer.from([0xff, 0xd8]), Buffer.from("not really a jpeg"), Buffer.from([0xff, 0xd9])]);
|
||||
await service.ingestFile(await drop("foto.r1", "cut.jpg", unreadable));
|
||||
const list = await ctx.app.inject({ method: "GET", url: `/v1/orgs/${orgId}/photos?status=FAILED`, headers: bearer(admin) });
|
||||
const [photo] = (list.json() as { photos: { status: string; error?: string }[] }).photos;
|
||||
expect(photo).toMatchObject({ status: "FAILED", error: expect.any(String) });
|
||||
@@ -262,7 +264,8 @@ describe("library", () => {
|
||||
|
||||
it("marks unreadable files as failed instead of losing them", async () => {
|
||||
await setup();
|
||||
const outcome = await service.ingestFile(await drop("foto.r1", "broken.jpg", Buffer.from("not really a jpeg")));
|
||||
const unreadable = Buffer.concat([Buffer.from([0xff, 0xd8]), Buffer.from("not really a jpeg"), Buffer.from([0xff, 0xd9])]);
|
||||
const outcome = await service.ingestFile(await drop("foto.r1", "broken.jpg", unreadable));
|
||||
expect(outcome.status).toBe("failed");
|
||||
const photo = await ctx.db.photo.findFirstOrThrow();
|
||||
expect(photo.status).toBe("FAILED");
|
||||
@@ -277,6 +280,19 @@ describe("library", () => {
|
||||
expect(await ctx.db.photo.count()).toBe(1);
|
||||
});
|
||||
|
||||
it("leaves a jpeg that is still transferring where the camera is writing it", async () => {
|
||||
await setup();
|
||||
const scanner = new IngestScanner(service, ingestRoot, { intervalMs: 10, concurrency: 2, log: quiet });
|
||||
const file = await drop("foto.r1", "part.jpg", Buffer.from([0xff, 0xd8, 0x00, 0x11, 0x22]));
|
||||
expect(await scanner.scanOnce()).toEqual([]);
|
||||
expect(await scanner.scanOnce()).toEqual([]);
|
||||
expect(await ctx.db.photo.count()).toBe(0);
|
||||
expect((await stat(file)).size).toBe(5);
|
||||
const outcome = await service.ingestFile(file);
|
||||
expect(outcome).toEqual({ status: "skipped", reason: "incomplete" });
|
||||
expect((await stat(file)).size).toBe(5);
|
||||
});
|
||||
|
||||
it("culls in batch, live, and keeps photographers to their own photos", async () => {
|
||||
const { orgId, admin, foto } = await setup();
|
||||
const a = await service.ingestFile(await drop("foto.r1", "a.jpg", await jpeg({ color: "#101010" })));
|
||||
|
||||
@@ -546,10 +546,12 @@ describe("sports data service", () => {
|
||||
await face(p3!.id, likely.id);
|
||||
await face(p4!.id, doubtful.id);
|
||||
await face(p1!.id, ignored.id); // "not a person" / ignored: never counted
|
||||
const squads = (await ctx.app.inject({ method: "GET", url: `/v1/events/${eventId}/squads`, headers: bearer(token) })).json() as { sides: { players: { name: string; photos: { confirmed: number; likely: number } }[] }[] };
|
||||
const photosOf = (name: string) => squads.sides.flatMap((s) => s.players).find((p) => p.name === name)!.photos;
|
||||
expect(photosOf("Rui Lopes")).toEqual({ confirmed: 2, likely: 1 });
|
||||
expect(photosOf("Tiago Ferreira")).toEqual({ confirmed: 0, likely: 1 });
|
||||
const squads = (await ctx.app.inject({ method: "GET", url: `/v1/events/${eventId}/squads`, headers: bearer(token) })).json() as { sides: { players: { name: string; photos: { confirmed: number; likely: number }; photoIds: string[] }[] }[] };
|
||||
const player = (name: string) => squads.sides.flatMap((s) => s.players).find((p) => p.name === name)!;
|
||||
expect(player("Rui Lopes").photos).toEqual({ confirmed: 2, likely: 1 });
|
||||
expect(player("Rui Lopes").photoIds.slice().sort()).toEqual([p1!.id, p2!.id, p3!.id].sort());
|
||||
expect(player("Tiago Ferreira").photos).toEqual({ confirmed: 0, likely: 1 });
|
||||
expect(player("Tiago Ferreira").photoIds).toEqual([p4!.id]);
|
||||
});
|
||||
|
||||
it("FPA: a past season, club by club, following every club met (national games only)", async () => {
|
||||
|
||||
@@ -58,6 +58,7 @@ export const t = {
|
||||
deliveryStates: { any: "Todas", unsent: "Por enviar", queued: "A enviar", sent: "Enviadas", failed: "Com erro" },
|
||||
noPlayersFilter: "Sem jogador",
|
||||
clearFilter: "Limpar filtro",
|
||||
clearPlayers: "Limpar jogadores",
|
||||
sendN: (n: number) => (n ? `Enviar ${n}` : "Enviar"),
|
||||
outputSelection: "As selecionadas",
|
||||
outputBest: "As melhores",
|
||||
|
||||
@@ -54,6 +54,11 @@ const tauriInvoke: Invoke = async (cmd, args) => (await import("@tauri-apps/api/
|
||||
const IN_FLIGHT = 6;
|
||||
const POLL_MS = 1000;
|
||||
|
||||
/** The shell put the file back on the queue because the camera has not finished sending it. */
|
||||
function isIncomplete(err: unknown): boolean {
|
||||
return err === "incomplete" || (err instanceof Error && err.message === "incomplete");
|
||||
}
|
||||
|
||||
type Add = (files: Iterable<File>, eventId?: string, onSettled?: (file: File, status: UploadStatus, photo?: PhotoSummary) => void, original?: DesktopOrigin) => void;
|
||||
|
||||
export const eventLabel = (e: Pick<EventSummary, "title" | "home" | "away">) => e.title || [e.home, e.away].filter(Boolean).join(" x ");
|
||||
@@ -141,9 +146,10 @@ export function useLocalFtp(add: Add, enabled: boolean, invoke: Invoke = tauriIn
|
||||
localPhotos.remove(localId(info.sha256));
|
||||
pump();
|
||||
}, full ? "original" : info);
|
||||
} catch {
|
||||
} catch (err) {
|
||||
inFlight.current--;
|
||||
setCounts((c) => ({ ...c, failed: c.failed + 1 }));
|
||||
// A pause mid-transfer is not a failed photo: the shell hands it out again once the file is whole.
|
||||
if (!isIncomplete(err)) setCounts((c) => ({ ...c, failed: c.failed + 1 }));
|
||||
pump();
|
||||
}
|
||||
})();
|
||||
|
||||
@@ -0,0 +1,62 @@
|
||||
import type { ApiClient, EventSquads, EventSummary } from "@photoreport/sdk";
|
||||
import { fireEvent, render, screen, waitFor } from "@testing-library/react";
|
||||
import { useMemo, useState } from "react";
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import { SquadsButton } from "./Squads.js";
|
||||
import { type PlayerPick, samePicks } from "./squadFilter.js";
|
||||
|
||||
const squads: EventSquads = {
|
||||
eventId: "e1",
|
||||
sides: [
|
||||
{
|
||||
side: "home",
|
||||
team: { id: "t1", name: "ÁGUAS SANTAS MILANEZA", abbreviation: "ASM", logoUrl: null },
|
||||
players: [
|
||||
{ id: "pl1", number: "5", name: "Miguel Baptista", fullName: null, position: null, hasPhoto: false, personId: "pe1", photos: { confirmed: 0, likely: 2 }, photoIds: ["a", "b"] },
|
||||
{ id: "pl2", number: "7", name: "Gabriel", fullName: null, position: null, hasPhoto: false, personId: null, photos: { confirmed: 0, likely: 0 }, photoIds: [] },
|
||||
],
|
||||
},
|
||||
{
|
||||
side: "away",
|
||||
team: { id: "t2", name: "SPORTING CP", abbreviation: "SCP", logoUrl: null },
|
||||
players: [
|
||||
{ id: "pl3", number: "2", name: "Edney Oliveira", fullName: null, position: null, hasPhoto: false, personId: "pe3", photos: { confirmed: 1, likely: 0 }, photoIds: ["b", "c"] },
|
||||
],
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
function Harness() {
|
||||
const [picks, setPicks] = useState<PlayerPick[]>([]);
|
||||
const ids = useMemo(() => picks.map((p) => p.id), [picks]);
|
||||
return (
|
||||
<>
|
||||
<SquadsButton
|
||||
api={{ eventSquads: vi.fn().mockResolvedValue(squads) } as unknown as ApiClient}
|
||||
event={{ id: "e1", homeTeamId: "t1", awayTeamId: "t2" } as EventSummary}
|
||||
canEdit={false}
|
||||
onSaved={() => {}}
|
||||
selectedIds={ids}
|
||||
onPlayers={(next) => setPicks((cur) => (samePicks(cur, next) ? cur : next))}
|
||||
/>
|
||||
<p data-testid="picked">{picks.map((p) => p.photoIds.join("+")).join("|")}</p>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
describe("squad panel", () => {
|
||||
it("filters to each player that is clicked, and drops one on a second click", async () => {
|
||||
render(<Harness />);
|
||||
fireEvent.click(screen.getByRole("button", { name: "Plantéis" }));
|
||||
const miguel = await screen.findByRole("button", { name: /Miguel Baptista/ });
|
||||
expect((screen.getByRole("button", { name: /Gabriel/ }) as HTMLButtonElement).disabled).toBe(true);
|
||||
fireEvent.click(miguel);
|
||||
await waitFor(() => expect(screen.getByTestId("picked").textContent).toBe("a+b"));
|
||||
expect(miguel.getAttribute("aria-pressed")).toBe("true");
|
||||
fireEvent.click(screen.getByRole("button", { name: /Edney Oliveira/ }));
|
||||
await waitFor(() => expect(screen.getByTestId("picked").textContent).toBe("a+b|b+c"));
|
||||
fireEvent.click(miguel);
|
||||
await waitFor(() => expect(screen.getByTestId("picked").textContent).toBe("b+c"));
|
||||
expect(miguel.getAttribute("aria-pressed")).toBe("false");
|
||||
});
|
||||
});
|
||||
@@ -2,12 +2,14 @@ import { ApiError, type ApiClient, type EventSquads, type EventSummary } from "@
|
||||
import { useEffect, useState } from "react";
|
||||
import { t } from "../i18n.js";
|
||||
import { FixturePicker } from "./EventForm.js";
|
||||
import { type PlayerPick, picksFrom } from "./squadFilter.js";
|
||||
|
||||
/**
|
||||
* The open event's squads (from the federations): who is who by number, and whether each player is already a person
|
||||
* of the organisation (faces and jersey numbers name people). An older event can be linked to its match here.
|
||||
* Picking players filters the grid to their photos (click again to drop one).
|
||||
*/
|
||||
export function SquadsButton({ api, event, canEdit, onSaved }: { api: ApiClient; event: EventSummary; canEdit: boolean; onSaved: (e: EventSummary) => void }) {
|
||||
export function SquadsButton({ api, event, canEdit, onSaved, facesTick = 0, selectedIds = [], onPlayers }: { api: ApiClient; event: EventSummary; canEdit: boolean; onSaved: (e: EventSummary) => void; facesTick?: number; selectedIds?: readonly string[]; onPlayers?: (picks: PlayerPick[]) => void }) {
|
||||
const [open, setOpen] = useState(false);
|
||||
const [squads, setSquads] = useState<EventSquads | null>(null);
|
||||
const [status, setStatus] = useState<string | null>(null);
|
||||
@@ -15,9 +17,30 @@ export function SquadsButton({ api, event, canEdit, onSaved }: { api: ApiClient;
|
||||
const linked = !!(event.homeTeamId || event.awayTeamId);
|
||||
|
||||
useEffect(() => {
|
||||
if (!open || !linked) return;
|
||||
api.eventSquads(event.id).then(setSquads, () => setSquads(null));
|
||||
}, [api, open, linked, event.id, event.homeTeamId, event.awayTeamId]);
|
||||
if (!linked || (!open && selectedIds.length === 0)) return;
|
||||
let alive = true;
|
||||
api.eventSquads(event.id).then(
|
||||
(s) => alive && setSquads(s),
|
||||
() => alive && setSquads(null),
|
||||
);
|
||||
return () => {
|
||||
alive = false;
|
||||
};
|
||||
// selectedIds.length: a closed panel still reloads while a player filter is on.
|
||||
}, [api, open, linked, event.id, event.homeTeamId, event.awayTeamId, facesTick, selectedIds.length]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!onPlayers || !squads || selectedIds.length === 0) return;
|
||||
onPlayers(picksFrom(squads, selectedIds));
|
||||
// The squad list was reloaded (new face counts). Keep the same players, with their new photos.
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [squads]);
|
||||
|
||||
const toggle = (playerId: string) => {
|
||||
if (!squads || !onPlayers) return;
|
||||
const next = selectedIds.includes(playerId) ? selectedIds.filter((id) => id !== playerId) : [...selectedIds, playerId];
|
||||
onPlayers(picksFrom(squads, next));
|
||||
};
|
||||
|
||||
const fail = (err: unknown) => setStatus(err instanceof ApiError ? err.code : t.unexpectedError);
|
||||
const sync = async () => {
|
||||
@@ -67,24 +90,36 @@ export function SquadsButton({ api, event, canEdit, onSaved }: { api: ApiClient;
|
||||
<div key={s.side}>
|
||||
<p className="mb-1 font-semibold text-ink">{s.team.name}</p>
|
||||
<ul className="max-h-72 overflow-y-auto">
|
||||
{s.players.map((p) => (
|
||||
<li key={p.id} className="flex gap-2">
|
||||
<span className="w-7 shrink-0 text-right font-mono text-accent">{p.number ?? "–"}</span>
|
||||
<span className="truncate text-ink">{p.name}</span>
|
||||
<span className="ml-auto shrink-0 font-mono text-[11px]" title={p.personId ? t.sports.photosHelp(p.photos?.confirmed ?? 0, p.photos?.likely ?? 0) : t.sports.notPerson}>
|
||||
{!p.personId ? (
|
||||
<span className="text-faint">·</span>
|
||||
) : p.photos && p.photos.confirmed + p.photos.likely > 0 ? (
|
||||
<>
|
||||
{p.photos.confirmed > 0 && <span className="text-ink">{p.photos.confirmed}</span>}
|
||||
{p.photos.likely > 0 && <span className="text-faint">{p.photos.confirmed > 0 ? " " : ""}+{p.photos.likely}</span>}
|
||||
</>
|
||||
) : (
|
||||
<span className="text-faint">0</span>
|
||||
)}
|
||||
</span>
|
||||
</li>
|
||||
))}
|
||||
{s.players.map((p) => {
|
||||
const on = selectedIds.includes(p.id);
|
||||
return (
|
||||
<li key={p.id}>
|
||||
<button
|
||||
type="button"
|
||||
disabled={!p.personId}
|
||||
aria-pressed={on}
|
||||
title={p.personId ? t.sports.photosHelp(p.photos?.confirmed ?? 0, p.photos?.likely ?? 0) : t.sports.notPerson}
|
||||
onClick={() => toggle(p.id)}
|
||||
className={`flex w-full gap-2 px-1 py-0.5 text-left ${on ? "bg-cell-on" : "hover:bg-cell"} disabled:cursor-default disabled:hover:bg-transparent`}
|
||||
>
|
||||
<span className="w-7 shrink-0 text-right font-mono text-accent">{p.number ?? "–"}</span>
|
||||
<span className="truncate text-ink">{p.name}</span>
|
||||
<span className="ml-auto shrink-0 font-mono text-[11px]">
|
||||
{!p.personId ? (
|
||||
<span className="text-faint">·</span>
|
||||
) : p.photos && p.photos.confirmed + p.photos.likely > 0 ? (
|
||||
<>
|
||||
{p.photos.confirmed > 0 && <span className="text-ink">{p.photos.confirmed}</span>}
|
||||
{p.photos.likely > 0 && <span className="text-faint">{p.photos.confirmed > 0 ? " " : ""}+{p.photos.likely}</span>}
|
||||
</>
|
||||
) : (
|
||||
<span className="text-faint">0</span>
|
||||
)}
|
||||
</span>
|
||||
</button>
|
||||
</li>
|
||||
);
|
||||
})}
|
||||
</ul>
|
||||
</div>
|
||||
))}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { DESTINATION_EXAMPLES, IPTC_FIELDS } from "@photoreport/metadata";
|
||||
import { DESTINATION_EXAMPLES, IPTC_FIELDS, LOCAL_COPY_FOLDER } from "@photoreport/metadata";
|
||||
import {
|
||||
ApiError,
|
||||
type ApiClient,
|
||||
@@ -180,6 +180,9 @@ export function TargetForm({
|
||||
arrivalLogins: target?.arrivalLogins ?? ([] as string[]),
|
||||
untouched: target?.untouched ?? false,
|
||||
copyTargetId: target?.copyTargetId ?? null,
|
||||
localFolder: target?.localFolder ?? null,
|
||||
localMachine: target?.localMachine ?? null,
|
||||
localFolderTemplate: target?.localFolderTemplate || LOCAL_COPY_FOLDER,
|
||||
});
|
||||
// The other destinations a copy can go to (a folder on this computer, usually).
|
||||
const [others, setOthers] = useState<DeliveryTarget[]>([]);
|
||||
@@ -239,8 +242,12 @@ export function TargetForm({
|
||||
const { password: _pw, ...base } = v;
|
||||
const iptcOverrides = overridesOf(overrides);
|
||||
const password = v.password;
|
||||
const rest = { ...base, iptcOverrides };
|
||||
const all = { ...v, iptcOverrides };
|
||||
const local =
|
||||
v.kind === "LOCAL" || !v.localFolder
|
||||
? { localFolder: null, localMachine: null, localFolderTemplate: null }
|
||||
: { localFolder: v.localFolder, localMachine: v.localMachine, localFolderTemplate: v.localFolderTemplate || LOCAL_COPY_FOLDER };
|
||||
const rest = { ...base, ...local, iptcOverrides };
|
||||
const all = { ...v, ...local, iptcOverrides };
|
||||
if (v.kind === "LOCAL" && !v.baseUrl) {
|
||||
setBusy(false);
|
||||
setError("Escolhe a pasta.");
|
||||
@@ -513,6 +520,75 @@ export function TargetForm({
|
||||
</fieldset>
|
||||
)}
|
||||
</div>
|
||||
{v.kind !== "LOCAL" && (
|
||||
<fieldset className="space-y-2 border border-line p-3 text-[12px]">
|
||||
<legend className="px-1 text-[11px] text-faint">Cópia neste computador</legend>
|
||||
<p className="text-faint">
|
||||
O envio (FTP, cloud, …) fica como está. Cada ficheiro enviado é gravado também numa pasta, para se ver
|
||||
depois o que foi para onde. A app de computador tem de estar aberta nessa máquina.
|
||||
</p>
|
||||
<label className="flex items-start gap-2">
|
||||
<input
|
||||
type="checkbox"
|
||||
className="mt-0.5"
|
||||
checked={!!v.localFolder}
|
||||
onChange={(e) => {
|
||||
if (!e.target.checked) {
|
||||
setV({ ...v, localFolder: null, localMachine: null });
|
||||
return;
|
||||
}
|
||||
if (!isDesktop()) {
|
||||
setError("A pasta escolhe-se na app de computador.");
|
||||
return;
|
||||
}
|
||||
void Promise.all([desktopDeliveryShell.pick(), desktopDeliveryShell.machine()]).then(
|
||||
([folder, machine]) => {
|
||||
if (folder) setV((cur) => ({ ...cur, localFolder: folder, localMachine: machine }));
|
||||
},
|
||||
() => setError("Esta versão da app ainda não sabe guardar em pastas: atualiza a app."),
|
||||
);
|
||||
}}
|
||||
/>
|
||||
<span className="text-ink">Gravar também uma cópia na pasta</span>
|
||||
</label>
|
||||
{v.localFolder && (
|
||||
<>
|
||||
<div className="flex gap-2">
|
||||
<span className={`${input} flex items-center truncate font-mono text-[12px]`}>{v.localFolder}</span>
|
||||
{isDesktop() && (
|
||||
<button
|
||||
type="button"
|
||||
className="h-8 shrink-0 border border-black bg-cell px-3 text-[12px] hover:bg-cell-on"
|
||||
onClick={() =>
|
||||
void Promise.all([desktopDeliveryShell.pick(), desktopDeliveryShell.machine()]).then(
|
||||
([folder, machine]) => {
|
||||
if (folder) setV((cur) => ({ ...cur, localFolder: folder, localMachine: machine }));
|
||||
},
|
||||
() => setError("Esta versão da app ainda não sabe guardar em pastas: atualiza a app."),
|
||||
)
|
||||
}
|
||||
>
|
||||
Escolher pasta…
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
<label className="block">
|
||||
<span className="mb-1 block text-[11px] text-faint">
|
||||
Subpasta ({"{iptcdate}"} = dia da foto, {"{event}"} = jogo, {"{destination}"} = nome deste destino)
|
||||
</span>
|
||||
<input
|
||||
className={`${input} font-mono text-[12px]`}
|
||||
value={v.localFolderTemplate}
|
||||
onChange={(e) => setV({ ...v, localFolderTemplate: e.target.value })}
|
||||
/>
|
||||
</label>
|
||||
<p className="font-mono text-[11px] leading-snug text-faint">
|
||||
{v.localFolder.replace(/\/$/, "")}/20261018 - Águas Santas Milaneza x Sporting CP - {v.name || "Record"}/
|
||||
</p>
|
||||
</>
|
||||
)}
|
||||
</fieldset>
|
||||
)}
|
||||
{others.length > 0 && (
|
||||
<label className="block">
|
||||
<span className="mb-1 block text-[11px] text-faint">
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
import type { EventSquads } from "@photoreport/sdk";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { photoIdsOf, picksFrom } from "./squadFilter.js";
|
||||
|
||||
const squads: EventSquads = {
|
||||
eventId: "e",
|
||||
sides: [
|
||||
{
|
||||
side: "home",
|
||||
team: { id: "t1", name: "Águas Santas", abbreviation: "ASM", logoUrl: null },
|
||||
players: [
|
||||
{ id: "pl1", number: "5", name: "Miguel Baptista", fullName: null, position: null, hasPhoto: false, personId: "pe1", photos: { confirmed: 1, likely: 1 }, photoIds: ["a", "b"] },
|
||||
{ id: "pl2", number: "7", name: "Gabriel", fullName: null, position: null, hasPhoto: false, personId: null, photos: { confirmed: 0, likely: 0 }, photoIds: [] },
|
||||
],
|
||||
},
|
||||
{
|
||||
side: "away",
|
||||
team: { id: "t2", name: "Sporting", abbreviation: "SCP", logoUrl: null },
|
||||
players: [
|
||||
{ id: "pl3", number: "2", name: "Edney Oliveira", fullName: null, position: null, hasPhoto: false, personId: "pe3", photos: { confirmed: 0, likely: 1 }, photoIds: ["b", "c"] },
|
||||
],
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
describe("squad player filter", () => {
|
||||
it("keeps the photos of every picked player, once", () => {
|
||||
const picks = picksFrom(squads, ["pl3", "pl1", "pl2"]);
|
||||
expect(picks.map((p) => p.name)).toEqual(["Miguel Baptista", "Edney Oliveira"]);
|
||||
expect([...(photoIdsOf(picks) ?? [])].sort()).toEqual(["a", "b", "c"]);
|
||||
expect(photoIdsOf([])).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,40 @@
|
||||
import type { EventSquads } from "@photoreport/sdk";
|
||||
|
||||
/** A player picked in the squad panel, and the photos of them in this event. */
|
||||
export interface PlayerPick {
|
||||
id: string;
|
||||
name: string;
|
||||
photoIds: string[];
|
||||
}
|
||||
|
||||
/** The picked players, in squad order. Someone who is not a person yet cannot filter. */
|
||||
export function picksFrom(squads: EventSquads, playerIds: readonly string[]): PlayerPick[] {
|
||||
const want = new Set(playerIds);
|
||||
const picks: PlayerPick[] = [];
|
||||
for (const side of squads.sides) {
|
||||
for (const player of side.players) {
|
||||
if (!want.has(player.id) || !player.personId) continue;
|
||||
picks.push({ id: player.id, name: player.name, photoIds: player.photoIds ?? [] });
|
||||
}
|
||||
}
|
||||
return picks;
|
||||
}
|
||||
|
||||
export function samePicks(a: readonly PlayerPick[], b: readonly PlayerPick[]): boolean {
|
||||
if (a.length !== b.length) return false;
|
||||
for (let i = 0; i < a.length; i++) {
|
||||
const left = a[i]!;
|
||||
const right = b[i]!;
|
||||
if (left.id !== right.id || left.name !== right.name || left.photoIds.length !== right.photoIds.length) return false;
|
||||
for (let j = 0; j < left.photoIds.length; j++) if (left.photoIds[j] !== right.photoIds[j]) return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/** Photos of any of the picked players. Null means the squad filter is off. */
|
||||
export function photoIdsOf(picks: readonly PlayerPick[]): Set<string> | null {
|
||||
if (!picks.length) return null;
|
||||
const ids = new Set<string>();
|
||||
for (const pick of picks) for (const id of pick.photoIds) ids.add(id);
|
||||
return ids;
|
||||
}
|
||||
@@ -156,6 +156,15 @@ export function DeliveryPage() {
|
||||
<dd className="font-mono text-[11px]">
|
||||
{target.longEdge >= 12000 ? "original" : `${target.longEdge} px`} · JPEG {target.jpegQuality}
|
||||
</dd>
|
||||
{target.localFolder && (
|
||||
<>
|
||||
<dt className="text-faint">Cópia no computador</dt>
|
||||
<dd className="break-all font-mono text-[11px]">
|
||||
{target.localFolder}
|
||||
{target.localFolderTemplate ? ` · ${target.localFolderTemplate}` : ""}
|
||||
</dd>
|
||||
</>
|
||||
)}
|
||||
<dt className="text-faint">Ligação</dt>
|
||||
<dd className="break-all font-mono text-[11px]">
|
||||
{target.kind} · {target.kind === "DROPBOX" ? "Dropbox" : target.baseUrl}
|
||||
|
||||
@@ -20,6 +20,7 @@ import { LocalFtpButton } from "../library/LocalFtp.js";
|
||||
import { CardIngestButton } from "../library/CardIngest.js";
|
||||
import { AutopilotButton } from "../library/Autopilot.js";
|
||||
import { SquadsButton } from "../library/Squads.js";
|
||||
import { type PlayerPick, photoIdsOf, samePicks } from "../library/squadFilter.js";
|
||||
import { initialLibrary, isMac, type LibraryFilter, libraryReducer, matchesFilter, patchForKey, pmPatchForKey } from "../library/store.js";
|
||||
import { cache, type CachedEvents } from "../offline/cache.js";
|
||||
import { localPhotos } from "../offline/local.js";
|
||||
@@ -50,6 +51,8 @@ export function LibraryPage() {
|
||||
const { open: openFolderScan, syncGames } = useFolderScan();
|
||||
const [state, dispatch] = useReducer(libraryReducer, initialLibrary);
|
||||
const [filter, setFilterState] = useState<LibraryFilter>(() => savedFilter(orgId));
|
||||
const [players, setPlayers] = useState<PlayerPick[]>([]);
|
||||
const onPlayers = useCallback((next: PlayerPick[]) => setPlayers((cur) => (samePicks(cur, next) ? cur : next)), []);
|
||||
useEffect(() => setFilterState(savedFilter(orgId)), [orgId]);
|
||||
const setFilter = useCallback(
|
||||
(f: LibraryFilter) => {
|
||||
@@ -220,7 +223,22 @@ export function LibraryPage() {
|
||||
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 visible = useMemo(() => state.photos.filter((p) => matchesFilter(p, filter)), [state.photos, filter]);
|
||||
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]);
|
||||
useEffect(() => {
|
||||
setPlayers([]);
|
||||
}, [uploadInto]);
|
||||
useEffect(() => {
|
||||
if (!playerIds) return;
|
||||
if (state.focus && playerIds.has(state.focus)) return;
|
||||
const next = state.photos.filter((p) => playerIds.has(p.id) && matchesFilter(p, filter));
|
||||
const first = next[0];
|
||||
if (!first) return;
|
||||
dispatch({ type: "select", id: first.id, mode: "single", visible: next.map((p) => p.id) });
|
||||
// Only when the picked players change. The photos and the other filters are the ones of this render.
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [playerIds]);
|
||||
const visibleIds = useMemo(() => visible.map((p) => p.id), [visible]);
|
||||
const byId = useMemo(() => new Map(state.photos.map((p) => [p.id, p])), [state.photos]);
|
||||
const focus = (state.focus && byId.get(state.focus)) || null;
|
||||
@@ -367,6 +385,16 @@ export function LibraryPage() {
|
||||
<div className="flex min-h-[70vh] min-w-0 flex-1 flex-col lg:min-h-0">
|
||||
<div className="flex flex-wrap items-center gap-x-4 gap-y-1 border-b border-line bg-raised px-3 py-1.5 text-[12px]">
|
||||
<FilterBar filter={filter} onChange={setFilter} />
|
||||
{players.length > 0 && (
|
||||
<span className="flex min-w-0 items-center gap-2">
|
||||
<span className="max-w-72 truncate text-ink" title={players.map((p) => p.name).join(", ")}>
|
||||
{players.map((p) => p.name).join(", ")}
|
||||
</span>
|
||||
<button type="button" onClick={() => setPlayers([])} className="text-accent hover:underline">
|
||||
{t.clearPlayers}
|
||||
</button>
|
||||
</span>
|
||||
)}
|
||||
{canCull && state.scope && state.scope !== "inbox" && !state.scope.startsWith("search:") && !state.scope.startsWith("face:") && (
|
||||
<button
|
||||
onClick={() => setView(view === "faces" ? "grid" : "faces")}
|
||||
@@ -411,7 +439,7 @@ export function LibraryPage() {
|
||||
/>
|
||||
)}
|
||||
{canCull && openEvent && (
|
||||
<SquadsButton api={api} event={openEvent} canEdit={canCreate} onSaved={(e) => setEvents((list) => list.map((x) => (x.id === e.id ? e : x)))} />
|
||||
<SquadsButton api={api} event={openEvent} canEdit={canCreate} facesTick={facesTick} selectedIds={selectedPlayerIds} onPlayers={onPlayers} onSaved={(e) => setEvents((list) => list.map((x) => (x.id === e.id ? e : x)))} />
|
||||
)}
|
||||
{canCull && openEvent && (
|
||||
<AutopilotButton api={api} event={openEvent} targets={targets} canEdit={canCreate} onSaved={(e) => setEvents((list) => list.map((x) => (x.id === e.id ? e : x)))} />
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@photoreport/desktop",
|
||||
"version": "0.3.18",
|
||||
"version": "0.3.19",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "photoreport-desktop"
|
||||
version = "0.3.18"
|
||||
version = "0.3.19"
|
||||
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."
|
||||
|
||||
@@ -7,8 +7,9 @@
|
||||
//!
|
||||
//! Every finished upload (STOR) is picked up by scanning the ingest folder; the web app polls `ftp_take`, reads the
|
||||
//! bytes with `ftp_read` and, once the server has the photo, calls `ftp_sent`, which moves the original into the
|
||||
//! event's work folder. Anything still in the ingest folder (app closed mid-match, no network) goes again on the
|
||||
//! next start, so nothing is lost: the ingest folder is the queue.
|
||||
//! event's work folder. A file is finished only when it starts with the JPEG marker and ends with the end-of-image
|
||||
//! marker: a pause while the camera is still sending is not enough, and the file stays in the queue. Anything still
|
||||
//! in the ingest folder (app closed mid-match, no network) goes again on the next start, so nothing is lost.
|
||||
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::net::IpAddr;
|
||||
@@ -27,9 +28,8 @@ use unftp_core::auth::{AuthenticationError, Authenticator, Credentials, Principa
|
||||
use unftp_sbe_fs::Filesystem;
|
||||
|
||||
const PASSIVE_PORTS: std::ops::RangeInclusive<u16> = 50000..=50100;
|
||||
/// A file nobody has written to for this long is complete (or abandoned by the camera, which then resends it).
|
||||
const SETTLED_MS: u64 = 10_000;
|
||||
/// Two scans in a row with the same size and time, and this quiet, also count as complete.
|
||||
/// Two scans in a row with the same size and time, and this quiet, may be a finished file. It still has to end
|
||||
/// with the JPEG end marker: a Wi-Fi pause mid-transfer looks the same and must not be moved.
|
||||
const STABLE_MS: u64 = 2_000;
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
|
||||
@@ -154,7 +154,7 @@ pub struct FtpState {
|
||||
/// (file name, bytes) of uploads the FTP session reported as finished. The session only gives the name
|
||||
/// relative to its current folder, so the folder scan matches them up by name and size.
|
||||
finished: Arc<Mutex<HashSet<(String, u64)>>>,
|
||||
/// Size and time of each file at the previous scan: a file that stopped changing is complete.
|
||||
/// Size and time of each file at the previous scan. Quiet is not enough; the end marker has to be there too.
|
||||
seen: Mutex<HashMap<String, (u64, u64)>>,
|
||||
/// Paths already handed to the web app (so the next scan does not send them twice).
|
||||
taken: Mutex<HashSet<String>>,
|
||||
@@ -593,10 +593,12 @@ impl FtpState {
|
||||
continue;
|
||||
}
|
||||
let quiet = now.saturating_sub(f.modified_ms);
|
||||
let done = finished.remove(&(f.name.clone(), f.size))
|
||||
|| quiet >= SETTLED_MS
|
||||
|| (quiet >= STABLE_MS && seen.get(&f.path) == Some(&(f.size, f.modified_ms)));
|
||||
let reported = finished.contains(&(f.name.clone(), f.size));
|
||||
let stable = quiet >= STABLE_MS && seen.get(&f.path) == Some(&(f.size, f.modified_ms));
|
||||
let done = (reported || stable) && jpeg_complete(Path::new(&f.path));
|
||||
if done {
|
||||
let name = f.name.clone();
|
||||
finished.retain(|(n, _)| n != &name);
|
||||
seen.remove(&f.path);
|
||||
taken.insert(f.path.clone());
|
||||
ready.push(f);
|
||||
@@ -609,7 +611,7 @@ impl FtpState {
|
||||
|
||||
/// The server has the photo: move the original into the event's work folder (kept, never deleted).
|
||||
pub fn sent(&self, path: &str, event: &str, date: &str) -> Result<String, String> {
|
||||
let p = self.inside_ingest(path)?;
|
||||
let p = self.finished_jpeg(path)?;
|
||||
let dir = work_folder(&self.settings().work_folder, event, date);
|
||||
std::fs::create_dir_all(&dir).map_err(|e| e.to_string())?;
|
||||
let name = p
|
||||
@@ -631,6 +633,64 @@ impl FtpState {
|
||||
self.taken.lock().unwrap().remove(path);
|
||||
Ok(target.to_string_lossy().into_owned())
|
||||
}
|
||||
|
||||
/// The path is inside the ingest folder and the JPEG is finished. Otherwise it goes back on the queue.
|
||||
fn finished_jpeg(&self, path: &str) -> Result<PathBuf, String> {
|
||||
let p = self.inside_ingest(path)?;
|
||||
if !jpeg_complete(&p) {
|
||||
self.taken.lock().unwrap().remove(path);
|
||||
return Err("incomplete".into());
|
||||
}
|
||||
Ok(p)
|
||||
}
|
||||
}
|
||||
|
||||
/// SOI at the start and the end-of-image marker in the tail. The size is read again afterwards so a file
|
||||
/// that grew while we looked is not treated as finished.
|
||||
fn jpeg_complete(path: &Path) -> bool {
|
||||
let Ok(mut file) = std::fs::File::open(path) else {
|
||||
return false;
|
||||
};
|
||||
let Ok(meta) = file.metadata() else {
|
||||
return false;
|
||||
};
|
||||
let size = meta.len();
|
||||
if size < 4 {
|
||||
return false;
|
||||
}
|
||||
use std::io::{Read, Seek, SeekFrom};
|
||||
let mut head = [0u8; 2];
|
||||
if file.read(&mut head).ok() != Some(2) || head != [0xFF, 0xD8] {
|
||||
return false;
|
||||
}
|
||||
let n = std::cmp::min(64u64, size) as usize;
|
||||
if file.seek(SeekFrom::Start(size - n as u64)).is_err() {
|
||||
return false;
|
||||
}
|
||||
let mut tail = vec![0u8; n];
|
||||
if file.read(&mut tail).ok() != Some(n) {
|
||||
return false;
|
||||
}
|
||||
let Ok(after) = file.metadata() else {
|
||||
return false;
|
||||
};
|
||||
if after.len() != size {
|
||||
return false;
|
||||
}
|
||||
eoi_at_end(&tail)
|
||||
}
|
||||
|
||||
fn eoi_at_end(tail: &[u8]) -> bool {
|
||||
if tail.len() < 2 {
|
||||
return false;
|
||||
}
|
||||
let from = tail.len().saturating_sub(64);
|
||||
for i in (from..tail.len() - 1).rev() {
|
||||
if tail[i] == 0xFF && tail[i + 1] == 0xD9 {
|
||||
return tail[i + 2..].iter().all(|b| *b == 0x00 || *b == 0xFF);
|
||||
}
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
/// rename(), or copy + remove when the work folder is on another disk.
|
||||
@@ -726,7 +786,7 @@ pub async fn ftp_read(
|
||||
state: tauri::State<'_, FtpState>,
|
||||
path: String,
|
||||
) -> Result<tauri::ipc::Response, String> {
|
||||
let p = state.inside_ingest(&path)?;
|
||||
let p = state.finished_jpeg(&path)?;
|
||||
let bytes = tokio::fs::read(&p).await.map_err(|e| e.to_string())?;
|
||||
Ok(tauri::ipc::Response::new(bytes))
|
||||
}
|
||||
@@ -738,7 +798,7 @@ pub async fn ftp_preview(
|
||||
state: tauri::State<'_, FtpState>,
|
||||
path: String,
|
||||
) -> Result<tauri::ipc::Response, String> {
|
||||
let p = state.inside_ingest(&path)?;
|
||||
let p = state.finished_jpeg(&path)?;
|
||||
let bytes = tokio::fs::read(&p).await.map_err(|e| e.to_string())?;
|
||||
let preview =
|
||||
tauri::async_runtime::spawn_blocking(move || crate::preview::make_preview(&bytes))
|
||||
@@ -754,7 +814,7 @@ pub async fn ftp_info(
|
||||
index: tauri::State<'_, crate::local::LocalIndex>,
|
||||
path: String,
|
||||
) -> Result<crate::preview::OriginalInfo, String> {
|
||||
let p = state.inside_ingest(&path)?;
|
||||
let p = state.finished_jpeg(&path)?;
|
||||
let at = p.clone();
|
||||
let info = tauri::async_runtime::spawn_blocking(move || crate::preview::original_info(&p))
|
||||
.await
|
||||
@@ -980,7 +1040,7 @@ mod tests {
|
||||
std::thread::sleep(std::time::Duration::from_millis(300));
|
||||
|
||||
let photo = dir.join("IMG_0001.JPG");
|
||||
std::fs::write(&photo, b"\xff\xd8 not really a jpeg").unwrap();
|
||||
std::fs::write(&photo, b"\xff\xd8\xff\xd9").unwrap();
|
||||
let curl = |user: &str, url: String| {
|
||||
std::process::Command::new("curl")
|
||||
.args(["-s", "--ftp-create-dirs", "-T"])
|
||||
@@ -1033,15 +1093,80 @@ mod tests {
|
||||
assert!(Path::new(&moved).exists());
|
||||
assert!(state.take().is_empty());
|
||||
|
||||
// A fresh file with no "finished" report is handed out once it has stopped changing.
|
||||
// A fresh file with no "finished" report is handed out once it has stopped changing and it is a whole JPEG.
|
||||
state.stop();
|
||||
std::fs::write(dir.join("ingest/late.jpg"), b"x").unwrap();
|
||||
std::fs::write(dir.join("ingest/partial.jpg"), b"\xff\xd8 not yet").unwrap();
|
||||
assert!(state.take().is_empty());
|
||||
std::thread::sleep(std::time::Duration::from_millis(STABLE_MS + 200));
|
||||
assert!(
|
||||
state.take().is_empty(),
|
||||
"a quiet file without the end marker is still transferring"
|
||||
);
|
||||
std::fs::write(dir.join("ingest/late.jpg"), b"\xff\xd8\xff\xd9").unwrap();
|
||||
assert!(state.take().is_empty());
|
||||
std::thread::sleep(std::time::Duration::from_millis(STABLE_MS + 200));
|
||||
assert_eq!(state.take().len(), 1);
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_unfinished_jpeg_is_not_moved_even_when_the_session_says_it_finished() {
|
||||
let dir = std::env::temp_dir().join(format!("pr-ftp-partial-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(dir.join("ingest")).unwrap();
|
||||
let state = FtpState {
|
||||
config_path: Some(dir.join("ftp.json")),
|
||||
..Default::default()
|
||||
};
|
||||
let partial = dir.join("ingest/partial.jpg");
|
||||
let bytes = b"\xff\xd8 still coming";
|
||||
std::fs::write(&partial, bytes).unwrap();
|
||||
state
|
||||
.save(FtpSettings {
|
||||
port: 2121,
|
||||
users: vec![FtpUser {
|
||||
name: "1dx".into(),
|
||||
password: "1dx".into(),
|
||||
enabled: true,
|
||||
}],
|
||||
ingest: dir.join("ingest").to_string_lossy().into_owned(),
|
||||
work_folder: dir
|
||||
.join("{year}/{date} - {event}")
|
||||
.to_string_lossy()
|
||||
.into_owned(),
|
||||
auto_start: false,
|
||||
upload_originals: false,
|
||||
})
|
||||
.unwrap();
|
||||
state
|
||||
.finished
|
||||
.lock()
|
||||
.unwrap()
|
||||
.insert(("partial.jpg".into(), bytes.len() as u64));
|
||||
assert!(state.take().is_empty());
|
||||
assert!(partial.exists());
|
||||
assert_eq!(
|
||||
state
|
||||
.sent(partial.to_str().unwrap(), "Game", "2026-10-18")
|
||||
.unwrap_err(),
|
||||
"incomplete"
|
||||
);
|
||||
assert!(partial.exists());
|
||||
|
||||
std::fs::write(&partial, b"\xff\xd8\xff\xd9").unwrap();
|
||||
state
|
||||
.finished
|
||||
.lock()
|
||||
.unwrap()
|
||||
.insert(("partial.jpg".into(), 4));
|
||||
let got = state.take();
|
||||
assert_eq!(got.len(), 1);
|
||||
let moved = state.sent(&got[0].path, "Game", "2026-10-18").unwrap();
|
||||
assert!(Path::new(&moved).exists());
|
||||
assert!(!partial.exists());
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn date_folder() {
|
||||
assert_eq!(today().len(), 10);
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"$schema": "https://schema.tauri.app/config/2",
|
||||
"productName": "PhotoReport",
|
||||
"version": "0.3.18",
|
||||
"version": "0.3.19",
|
||||
"identifier": "pt.photoreport.desktop",
|
||||
"build": {
|
||||
"devUrl": "http://localhost:5173",
|
||||
|
||||
@@ -68,6 +68,16 @@ interface GalleryPerson {
|
||||
face: { src: string; box: Box | null; aspect: number } | null;
|
||||
}
|
||||
|
||||
/** Someone named in the game, including parts of it other than the folder on screen. */
|
||||
interface GamePerson {
|
||||
id: string;
|
||||
name: string;
|
||||
club: string | null;
|
||||
number: string | null;
|
||||
here: number;
|
||||
inGame: number;
|
||||
}
|
||||
|
||||
interface GalleryDetail {
|
||||
id: string;
|
||||
title: string;
|
||||
@@ -77,6 +87,8 @@ interface GalleryDetail {
|
||||
cloudUrl: string;
|
||||
total?: number;
|
||||
people?: GalleryPerson[];
|
||||
/** People named anywhere in this game. */
|
||||
roster?: GamePerson[];
|
||||
photos: ArchivePhoto[];
|
||||
}
|
||||
|
||||
@@ -398,7 +410,13 @@ function Browse({ info, token, onExpired, start }: { info: ArchiveInfo; token: s
|
||||
if (view.kind === "person" || view.kind === "face")
|
||||
return <PhotosOf key={`${view.kind}${view.id}`} info={info} token={token} view={view} onBack={() => go({ kind: "browse" })} onExpired={onExpired} onFace={(id) => go({ kind: "face", id })} onPerson={(id) => go({ kind: "person", id })} onGallery={(id) => go({ kind: "gallery", id })} />;
|
||||
|
||||
const shownPeople = (people?.people ?? []).filter((p) => (!club || p.club === club) && fold(`${p.name} ${p.club ?? ""} ${p.number ?? ""}`).includes(fold(q.trim())));
|
||||
const shownPeople = (people?.people ?? []).filter((p) => (!club || fold(p.club ?? "") === fold(club)) && fold(`${p.name} ${p.club ?? ""} ${p.number ?? ""}`).includes(fold(q.trim())));
|
||||
let emptyPeople = "";
|
||||
if (people && shownPeople.length === 0) {
|
||||
if (club && !people.people.some((p) => fold(p.club ?? "") === fold(club))) emptyPeople = "Ainda não há pessoas identificadas desta equipa.";
|
||||
else if (people.people.length) emptyPeople = "Ninguém com esse nome.";
|
||||
else emptyPeople = "Ainda não há pessoas identificadas nestas galerias. Abre uma foto e clica numa cara para encontrar mais fotos dela.";
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
@@ -468,13 +486,14 @@ function Browse({ info, token, onExpired, start }: { info: ArchiveInfo; token: s
|
||||
</button>
|
||||
{people.clubs.map((c) => (
|
||||
<button key={c.name} type="button" className={`chip${club === c.name ? " on" : ""}`} onClick={() => setClub(club === c.name ? null : c.name)}>
|
||||
{c.name} <span className="mono">{c.people}</span>
|
||||
{c.name}
|
||||
{c.people > 0 && <span className="mono">{c.people}</span>}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
{!people && <Loading />}
|
||||
{people && shownPeople.length === 0 && <p className="empty">{people.people.length ? "Ninguém com esse nome." : "Ainda não há pessoas identificadas nestas galerias. Abre uma foto e clica numa cara para encontrar mais fotos dela."}</p>}
|
||||
{emptyPeople && <p className="empty">{emptyPeople}</p>}
|
||||
<ul className="people-grid">
|
||||
{shownPeople.map((p) => (
|
||||
<li key={p.id}>
|
||||
@@ -853,8 +872,9 @@ function Gallery({
|
||||
const applyPage = useCallback((offset: number, body: GalleryDetail) => {
|
||||
setG((cur) => {
|
||||
const people = body.people ?? cur?.people;
|
||||
const roster = body.roster ?? cur?.roster;
|
||||
const photos = offset === 0 ? body.photos : [...(cur?.photos ?? []), ...body.photos];
|
||||
return { ...body, people, photos, total: body.total ?? photos.length };
|
||||
return { ...body, people, roster, photos, total: body.total ?? photos.length };
|
||||
});
|
||||
}, []);
|
||||
useEffect(() => {
|
||||
@@ -877,6 +897,8 @@ function Gallery({
|
||||
}, [fetchPage, applyPage, only, onExpired, attempt]);
|
||||
|
||||
const people = g?.people ?? [];
|
||||
const roster = g?.roster ?? [];
|
||||
const picked = roster.find((p) => p.id === only) ?? null;
|
||||
const photos = g?.photos ?? [];
|
||||
const total = g?.total ?? photos.length;
|
||||
const rememberFaces = useCallback((photoId: string, faces: PhotoFace[]) => {
|
||||
@@ -917,6 +939,27 @@ function Gallery({
|
||||
{g.title}
|
||||
{g.section ? <span className="meta"> · {g.section}</span> : null}
|
||||
</h2>
|
||||
{roster.length > 0 && (
|
||||
<label className="game-person">
|
||||
<span>Pessoas do jogo</span>
|
||||
<select value={only ?? ""} onChange={(e) => setOnly(e.target.value || null)} aria-label="Pessoas do jogo">
|
||||
<option value="">Todas</option>
|
||||
{roster.map((p) => (
|
||||
<option key={p.id} value={p.id}>
|
||||
{p.name}
|
||||
{p.number ? ` · ${p.number}` : ""}
|
||||
{p.club ? ` · ${p.club}` : ""}
|
||||
{p.here > 0 ? ` (${p.here} nesta parte)` : " (noutra parte do jogo)"}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
{picked && (
|
||||
<button type="button" className="linkish" onClick={() => onPerson(picked.id)}>
|
||||
Ver todas as fotos de {picked.name}
|
||||
</button>
|
||||
)}
|
||||
</label>
|
||||
)}
|
||||
{people.length > 0 && (
|
||||
<ul className="gallery-people">
|
||||
{people.map((p) => (
|
||||
@@ -936,6 +979,7 @@ function Gallery({
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
{picked && photos.length === 0 && <p className="empty">Sem fotos de {picked.name} nesta parte do jogo.</p>}
|
||||
<div className="grid">
|
||||
{photos.map((p, i) => (
|
||||
<button key={p.id} type="button" className="tile" onClick={() => setIndex(i)} aria-label={p.players.join(", ") || p.name}>
|
||||
|
||||
@@ -879,6 +879,23 @@ button.chip {
|
||||
align-items: center;
|
||||
padding: 8px 0 16px;
|
||||
}
|
||||
.game-person {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
padding: 8px 0 4px;
|
||||
}
|
||||
.game-person span {
|
||||
font-size: 12px;
|
||||
letter-spacing: 0.04em;
|
||||
text-transform: uppercase;
|
||||
color: var(--muted, #666);
|
||||
}
|
||||
.game-person select {
|
||||
min-width: min(100%, 280px);
|
||||
max-width: 100%;
|
||||
}
|
||||
.gallery-people {
|
||||
list-style: none;
|
||||
margin: 0;
|
||||
|
||||
@@ -337,6 +337,11 @@ The same queue also delivers to SFTP, FTP/FTPS and Dropbox (`delivery/transports
|
||||
with the templates' subfolders and name. It only writes inside folders chosen there with the system's folder
|
||||
picker (`src-tauri/src/deliver.rs`), never a path a page passes. For testing a destination's rules, or keeping
|
||||
the finished files to choose from later.
|
||||
- **A local copy of any other export** (`local_folder`, not on a LOCAL target): the FTP, SFTP, Nextcloud, Dropbox
|
||||
or ZeroZero send is unchanged. With the option on, the same file (that destination's size, name and IPTC) is also
|
||||
saved by the desktop app under the chosen folder, in `{iptcdate} - {event} - {destination}`
|
||||
(`/Users/cyclop/Desktop/2026/20261018 - Águas Santas Milaneza x Sporting CP - Record/`). The subfolder template is
|
||||
editable; `{destination}` is the destination's name. A hidden LOCAL target holds the copies and is not listed.
|
||||
- **Originals** (`delivery_targets.originals`, any kind): the original as it arrived, byte for byte in its image
|
||||
(no resizing, no recompression, the camera's EXIF and profile kept), with the IPTC written by exiftool and the
|
||||
name from the templates, like Photo Mechanic's Live Ingest destination (`{iptcdate} - {event}`,
|
||||
|
||||
+2
-1
@@ -132,7 +132,8 @@ or a share of its root or a folder above it, sees all of it.
|
||||
|
||||
A gallery, a person and a face each have a URL (`/arquivo/<source>/g/<folder>`, `/p/<person>`, `/f/<face>`), so a
|
||||
link survives refresh. A gallery page is 48 thumbs; the faces of a photo load when that photo is opened. The row
|
||||
of people in a gallery is one query on that folder. People, similar faces and the player directory join
|
||||
of faces is the people named in that folder. "Pessoas do jogo" lists everyone named in the game (every part
|
||||
the viewer may see); choosing one shows their photos in this part, or all of their photos. People, similar faces and the player directory join
|
||||
`cloud_files` for the source (and the viewer's folders when they do not see everything) instead of loading every
|
||||
photo id. Originals still open on the cloud itself (`/f/<fileid>`).
|
||||
|
||||
|
||||
@@ -65,6 +65,12 @@ export function renderFileName(template: string, vars: TemplateVars, originalFil
|
||||
return /\.[a-z0-9]{2,4}$/i.test(name) ? name : name + (ext === ".jpeg" ? ".jpg" : ext);
|
||||
}
|
||||
|
||||
/**
|
||||
* Subfolders for the local copy of an export: the capture day, the game, and the destination's name
|
||||
* (`20261018 - Águas Santas Milaneza x Sporting CP - Record`). `{destination}` is filled only for that copy.
|
||||
*/
|
||||
export const LOCAL_COPY_FOLDER = "/{iptcdate} - {event} - {destination}/";
|
||||
|
||||
/** Example destination rules taken from today's deliveries. */
|
||||
export const DESTINATION_EXAMPLES = {
|
||||
fpa: {
|
||||
|
||||
@@ -197,6 +197,8 @@ export interface EventSquads {
|
||||
personId: string | null;
|
||||
/** Photos of them in this event: confirmed, and taken for them by the faces (70% or more) not confirmed yet. */
|
||||
photos?: { confirmed: number; likely: number };
|
||||
/** Those photos, confirmed first. The library filter uses this when the player is picked. */
|
||||
photoIds?: string[];
|
||||
}[];
|
||||
}[];
|
||||
}
|
||||
@@ -253,6 +255,12 @@ export interface DeliveryTarget {
|
||||
iptcOverrides?: Record<string, string | string[]> | null;
|
||||
/** Everything sent here also goes to this target (a folder on a computer), with this target's IPTC. */
|
||||
copyTargetId?: string | null;
|
||||
/** Also save each exported file under this folder on one computer. Null: the export only. */
|
||||
localFolder?: string | null;
|
||||
/** That computer's id. */
|
||||
localMachine?: string | null;
|
||||
/** Subfolders under `localFolder`. `{destination}` is this target's name. */
|
||||
localFolderTemplate?: string | null;
|
||||
username: string;
|
||||
folderTemplate: string;
|
||||
fileNameTemplate: string;
|
||||
@@ -319,6 +327,11 @@ export interface DeliveryTargetInput {
|
||||
/** IPTC fields this client gets instead of the event's; null: none. */
|
||||
iptcOverrides?: Record<string, string | string[]> | null;
|
||||
copyTargetId?: string | null;
|
||||
/** Also save each exported file under this folder on one computer. Null: the export only. */
|
||||
localFolder?: string | null;
|
||||
localMachine?: string | null;
|
||||
/** Subfolders under the folder. `{destination}` is this target's name. */
|
||||
localFolderTemplate?: string | null;
|
||||
}
|
||||
|
||||
export interface PersonSummary {
|
||||
|
||||
Reference in new issue
Block a user