Compare commits
19
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f8611ad405 | ||
|
|
cda3885fcd | ||
|
|
b58bc3129e | ||
|
|
c16730f540 | ||
|
|
655ec1bba8 | ||
|
|
b694e93a2b | ||
|
|
aae9ab8d0b | ||
|
|
cceabdef06 | ||
|
|
17784c8b22 | ||
|
|
24ec8095f6 | ||
|
|
82ab4a3888 | ||
|
|
91a88c1aaa | ||
|
|
edf8c21488 | ||
|
|
112cea980f | ||
|
|
4e1d293d06 | ||
|
|
c94772e78e | ||
|
|
e9fcf973c3 | ||
|
|
72d9c17a4d | ||
|
|
ff8488fd93 |
No files matched your search
@@ -1,7 +1,8 @@
|
||||
name: desktop-release
|
||||
# Tag `desktop-vX.Y.Z` builds the desktop installers and attaches them to a Gitea release.
|
||||
# Linux builds on the standard runner. macOS (.dmg) and Windows (.msi) need runners with those labels:
|
||||
# register one on a Mac and one on a Windows machine, then uncomment the matrix entries.
|
||||
# Linux builds on the standard runner. macOS (.dmg) builds on a Mac registered as a runner with the label "macos"
|
||||
# (infra/desktop/macos-runner.sh, once); a release made while that Mac is off waits for it. Windows (.msi) needs a
|
||||
# runner labelled "windows": register one, then uncomment its entry.
|
||||
#
|
||||
# Self-updates (apps/desktop/src-tauri/src/updater.rs): with the secret TAURI_SIGNING_PRIVATE_KEY (and
|
||||
# TAURI_SIGNING_PRIVATE_KEY_PASSWORD) and the variable TAURI_UPDATER_PUBKEY set (`tauri signer generate`), each job
|
||||
@@ -20,10 +21,10 @@ jobs:
|
||||
- runner: ubuntu-latest
|
||||
bundles: deb,appimage
|
||||
platform: linux-x86_64
|
||||
# - runner: macos
|
||||
# bundles: dmg,app
|
||||
# platform: darwin-universal
|
||||
# args: --target universal-apple-darwin
|
||||
- runner: macos
|
||||
bundles: dmg,app
|
||||
platform: darwin-universal
|
||||
args: --target universal-apple-darwin
|
||||
# - runner: windows
|
||||
# bundles: msi
|
||||
# platform: windows-x86_64
|
||||
@@ -46,6 +47,9 @@ jobs:
|
||||
with:
|
||||
node-version: 22
|
||||
- uses: dtolnay/rust-toolchain@stable
|
||||
- name: Both Mac processors (universal app)
|
||||
if: runner.os == 'macOS'
|
||||
run: rustup target add aarch64-apple-darwin x86_64-apple-darwin
|
||||
- name: Photo engine (WebAssembly)
|
||||
run: |
|
||||
rustup target add wasm32-unknown-unknown
|
||||
@@ -68,7 +72,12 @@ jobs:
|
||||
if: env.TAURI_SIGNING_PRIVATE_KEY != ''
|
||||
shell: bash
|
||||
run: |
|
||||
dir=$(ls -d apps/desktop/src-tauri/target/*/release/bundle apps/desktop/src-tauri/target/release/bundle 2>/dev/null | head -1)
|
||||
# The bundle folder: target/<triple>/release/bundle (cross builds) or target/release/bundle. (A plain `ls` of
|
||||
# both exits 2 for the one that doesn't exist, which ended the step under pipefail.)
|
||||
dir=""
|
||||
for d in apps/desktop/src-tauri/target/*/release/bundle apps/desktop/src-tauri/target/release/bundle; do
|
||||
if [[ -d "$d" ]]; then dir="$d"; break; fi
|
||||
done
|
||||
node infra/desktop/update-manifest.mjs "$dir" ${{ matrix.platform }} "${GITHUB_REF_NAME}"
|
||||
- uses: actions/upload-artifact@v3
|
||||
with:
|
||||
|
||||
@@ -0,0 +1,2 @@
|
||||
-- AlterTable
|
||||
ALTER TABLE "print_events" ADD COLUMN "kiosk_token_hash" TEXT;
|
||||
@@ -0,0 +1,14 @@
|
||||
-- CreateTable
|
||||
CREATE TABLE "gallery_views" (
|
||||
"gallery_id" UUID NOT NULL,
|
||||
"day" DATE NOT NULL,
|
||||
"views" INTEGER NOT NULL DEFAULT 0,
|
||||
|
||||
CONSTRAINT "gallery_views_pkey" PRIMARY KEY ("gallery_id","day")
|
||||
);
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "gallery_views_day_idx" ON "gallery_views"("day");
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "gallery_views" ADD CONSTRAINT "gallery_views_gallery_id_fkey" FOREIGN KEY ("gallery_id") REFERENCES "galleries"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
@@ -0,0 +1,2 @@
|
||||
-- AlterTable
|
||||
ALTER TABLE "user_preferences" ADD COLUMN "calendar_url" TEXT;
|
||||
@@ -0,0 +1,2 @@
|
||||
-- AlterTable
|
||||
ALTER TABLE "pending_uploads" ADD COLUMN "from_desktop" BOOLEAN NOT NULL DEFAULT false;
|
||||
@@ -192,6 +192,8 @@ model DeviceAuthorization {
|
||||
model UserPreferences {
|
||||
userId String @id @map("user_id") @db.Uuid
|
||||
editorModules String[] @default(["crop", "basic"]) @map("editor_modules")
|
||||
/// The person's calendar (secret iCal address), sealed with the secret box; the new-event form lists its entries.
|
||||
calendarUrl String? @map("calendar_url")
|
||||
updatedAt DateTime @updatedAt @map("updated_at")
|
||||
|
||||
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
|
||||
@@ -729,6 +731,7 @@ model Gallery {
|
||||
visitors GalleryVisitor[]
|
||||
comments GalleryComment[]
|
||||
bundles Bundle[]
|
||||
views GalleryView[]
|
||||
|
||||
@@unique([organizationId, slug])
|
||||
@@index([organizationId, publishedAt])
|
||||
@@ -751,6 +754,19 @@ model GalleryPhoto {
|
||||
@@map("gallery_photos")
|
||||
}
|
||||
|
||||
/// Visits to a gallery's public page, per day (the site's "Mais vistas"). One per browser session.
|
||||
model GalleryView {
|
||||
galleryId String @map("gallery_id") @db.Uuid
|
||||
day DateTime @db.Date
|
||||
views Int @default(0)
|
||||
|
||||
gallery Gallery @relation(fields: [galleryId], references: [id], onDelete: Cascade)
|
||||
|
||||
@@id([galleryId, day])
|
||||
@@index([day])
|
||||
@@map("gallery_views")
|
||||
}
|
||||
|
||||
/// Photos taken out of a live gallery by hand: the live mode never adds them back.
|
||||
model GalleryExclusion {
|
||||
galleryId String @map("gallery_id") @db.Uuid
|
||||
@@ -966,6 +982,8 @@ model PrintEvent {
|
||||
galleryId String? @map("gallery_id") @db.Uuid
|
||||
/// The printer jobs go to unless an operator moves them.
|
||||
printerId String? @map("printer_id") @db.Uuid
|
||||
/// Kiosk mode (a tablet at the event): SHA-256 of the secret in the kiosk link; null: no kiosk.
|
||||
kioskTokenHash String? @map("kiosk_token_hash")
|
||||
createdAt DateTime @default(now()) @map("created_at")
|
||||
updatedAt DateTime @updatedAt @map("updated_at")
|
||||
|
||||
@@ -1079,6 +1097,8 @@ model PendingUpload {
|
||||
offset Int @default(0)
|
||||
/// Set when this upload is a preview standing in for an original kept on the desktop: {sha256, size, width, height}.
|
||||
original Json?
|
||||
/// An original sent by the desktop app's ingest (its local FTP): edited by the event's autopilot like FTP photos.
|
||||
fromDesktop Boolean @default(false) @map("from_desktop")
|
||||
createdAt DateTime @default(now()) @map("created_at")
|
||||
updatedAt DateTime @updatedAt @map("updated_at")
|
||||
|
||||
|
||||
+4
-1
@@ -9,6 +9,8 @@ import { SessionService } from "./auth/sessions.js";
|
||||
import type { Config } from "./config.js";
|
||||
import type { Db } from "./db.js";
|
||||
import { registerErrorHandler } from "./lib/errors.js";
|
||||
import { CalendarService } from "./calendar/service.js";
|
||||
import { registerCalendarRoutes } from "./calendar/routes.js";
|
||||
import { registerMeRoutes } from "./me/routes.js";
|
||||
import { registerDeliveryRoutes } from "./delivery/routes.js";
|
||||
import { SecretBox } from "./delivery/secrets.js";
|
||||
@@ -103,9 +105,10 @@ export async function buildApp({ config, db, realtime, fetchImpl }: AppDeps): Pr
|
||||
|
||||
await registerAuthRoutes(app, { db, config, sessions });
|
||||
await registerMeRoutes(app, { db, sessions });
|
||||
await registerCalendarRoutes(app, { sessions, calendar: new CalendarService({ db, secrets, ...(fetchImpl && { fetchImpl }) }) });
|
||||
await registerOrgRoutes(app, { db, sessions });
|
||||
const sports = new SportsService({ db, storage, log: app.log, fetch: fetchImpl ?? fetch });
|
||||
await registerEventRoutes(app, { db, sessions, sports });
|
||||
await registerEventRoutes(app, { db, sessions, sports, broadcaster });
|
||||
await registerSportsRoutes(app, { db, sessions, sports });
|
||||
await registerPhotoRoutes(app, { db, sessions, storage, signer, broadcaster });
|
||||
await registerCompositionRoutes(app, { db, sessions, storage, storageRoot: config.STORAGE_ROOT });
|
||||
|
||||
@@ -0,0 +1,215 @@
|
||||
/**
|
||||
* A small iCalendar (RFC 5545) reader for a person's own agenda (Google, iCloud and Outlook "secret iCal address").
|
||||
* Only what the new-event form needs: one-off events with their title, place, notes and times. Repeating events
|
||||
* show their first date only (press conferences and galas don't repeat).
|
||||
*/
|
||||
|
||||
export interface CalendarEvent {
|
||||
uid: string;
|
||||
summary: string;
|
||||
location: string | null;
|
||||
description: string | null;
|
||||
start: Date;
|
||||
end: Date | null;
|
||||
/** A whole-day entry (no time). */
|
||||
allDay: boolean;
|
||||
}
|
||||
|
||||
const DEFAULT_ZONE = "Europe/Lisbon";
|
||||
|
||||
/** Outlook writes Windows zone names; these are the ones a Portuguese agenda meets. */
|
||||
const WINDOWS_ZONES: Record<string, string> = {
|
||||
"GMT Standard Time": "Europe/Lisbon",
|
||||
"W. Europe Standard Time": "Europe/Madrid",
|
||||
"Romance Standard Time": "Europe/Paris",
|
||||
"Azores Standard Time": "Atlantic/Azores",
|
||||
UTC: "UTC",
|
||||
};
|
||||
|
||||
function zoneOf(tzid: string | undefined): string {
|
||||
if (!tzid) return DEFAULT_ZONE;
|
||||
const name = WINDOWS_ZONES[tzid] ?? tzid.replace(/^\/+/, "");
|
||||
try {
|
||||
new Intl.DateTimeFormat("en-US", { timeZone: name });
|
||||
return name;
|
||||
} catch {
|
||||
return DEFAULT_ZONE;
|
||||
}
|
||||
}
|
||||
|
||||
/** Wall-clock time in a zone → the instant. */
|
||||
export function zonedToUtc(y: number, mo: number, d: number, h: number, mi: number, s: number, zone: string): Date {
|
||||
const wall = Date.UTC(y, mo - 1, d, h, mi, s);
|
||||
const offset = (at: number) => {
|
||||
const p = Object.fromEntries(
|
||||
new Intl.DateTimeFormat("en-US", { timeZone: zone, hourCycle: "h23", year: "numeric", month: "2-digit", day: "2-digit", hour: "2-digit", minute: "2-digit", second: "2-digit" })
|
||||
.formatToParts(new Date(at))
|
||||
.map((x) => [x.type, x.value]),
|
||||
);
|
||||
return Date.UTC(Number(p.year), Number(p.month) - 1, Number(p.day), Number(p.hour), Number(p.minute), Number(p.second)) - at;
|
||||
};
|
||||
const guess = wall - offset(wall);
|
||||
return new Date(wall - offset(guess));
|
||||
}
|
||||
|
||||
function unescapeText(v: string): string {
|
||||
return v.replace(/\\([\;,nN])/g, (_, c: string) => (c === "n" || c === "N" ? "\n" : c));
|
||||
}
|
||||
|
||||
interface Prop {
|
||||
name: string;
|
||||
params: Record<string, string>;
|
||||
value: string;
|
||||
}
|
||||
|
||||
function parseLine(line: string): Prop | null {
|
||||
// NAME;PARAM=a;PARAM="b:c":value: the first colon outside quotes ends the name and parameters.
|
||||
let inQuote = false;
|
||||
let cut = -1;
|
||||
for (let i = 0; i < line.length; i++) {
|
||||
const c = line[i];
|
||||
if (c === '"') inQuote = !inQuote;
|
||||
else if (c === ":" && !inQuote) {
|
||||
cut = i;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (cut < 0) return null;
|
||||
const [name, ...rawParams] = line.slice(0, cut).split(";");
|
||||
const params: Record<string, string> = {};
|
||||
for (const p of rawParams) {
|
||||
const eq = p.indexOf("=");
|
||||
if (eq > 0) params[p.slice(0, eq).toUpperCase()] = p.slice(eq + 1).replace(/^"|"$/g, "");
|
||||
}
|
||||
return { name: (name ?? "").toUpperCase(), params, value: line.slice(cut + 1) };
|
||||
}
|
||||
|
||||
function parseTime(p: Prop): { at: Date; allDay: boolean } | null {
|
||||
const v = p.value.trim();
|
||||
const date = /^(\d{4})(\d{2})(\d{2})$/.exec(v);
|
||||
if (date || p.params.VALUE === "DATE") {
|
||||
const m = date ?? /^(\d{4})(\d{2})(\d{2})/.exec(v);
|
||||
if (!m) return null;
|
||||
return { at: zonedToUtc(Number(m[1]), Number(m[2]), Number(m[3]), 0, 0, 0, DEFAULT_ZONE), allDay: true };
|
||||
}
|
||||
const m = /^(\d{4})(\d{2})(\d{2})T(\d{2})(\d{2})(\d{2})(Z?)$/.exec(v);
|
||||
if (!m) return null;
|
||||
const [y, mo, d, h, mi, s] = m.slice(1, 7).map(Number) as [number, number, number, number, number, number];
|
||||
if (m[7] === "Z") return { at: new Date(Date.UTC(y, mo - 1, d, h, mi, s)), allDay: false };
|
||||
return { at: zonedToUtc(y, mo, d, h, mi, s, zoneOf(p.params.TZID)), allDay: false };
|
||||
}
|
||||
|
||||
export function parseIcs(text: string): CalendarEvent[] {
|
||||
// Unfold: a line starting with a space or tab continues the previous one.
|
||||
const lines = text.replace(/\r\n|\r/g, "\n").replace(/\n[ \t]/g, "").split("\n");
|
||||
if (!lines.some((l) => l.trim().toUpperCase() === "BEGIN:VCALENDAR")) throw new Error("not_ics");
|
||||
const out: CalendarEvent[] = [];
|
||||
let cur: Partial<CalendarEvent> | null = null;
|
||||
let depth = 0; // nested components inside a VEVENT (VALARM) are skipped
|
||||
for (const raw of lines) {
|
||||
const line = raw.trimEnd();
|
||||
const upper = line.toUpperCase();
|
||||
if (upper === "BEGIN:VEVENT") {
|
||||
cur = {};
|
||||
depth = 0;
|
||||
continue;
|
||||
}
|
||||
if (!cur) continue;
|
||||
if (upper.startsWith("BEGIN:")) {
|
||||
depth++;
|
||||
continue;
|
||||
}
|
||||
if (upper.startsWith("END:") && depth > 0) {
|
||||
depth--;
|
||||
continue;
|
||||
}
|
||||
if (upper === "END:VEVENT") {
|
||||
if (cur.start && cur.summary !== undefined && (cur as { cancelled?: boolean }).cancelled !== true) {
|
||||
out.push({ uid: cur.uid ?? `${cur.summary}@${cur.start.toISOString()}`, summary: cur.summary, location: cur.location ?? null, description: cur.description ?? null, start: cur.start, end: cur.end ?? null, allDay: cur.allDay ?? false });
|
||||
}
|
||||
cur = null;
|
||||
continue;
|
||||
}
|
||||
if (depth > 0) continue;
|
||||
const p = parseLine(line);
|
||||
if (!p) continue;
|
||||
switch (p.name) {
|
||||
case "UID":
|
||||
cur.uid = p.value.trim();
|
||||
break;
|
||||
case "SUMMARY":
|
||||
cur.summary = unescapeText(p.value).trim();
|
||||
break;
|
||||
case "LOCATION":
|
||||
cur.location = unescapeText(p.value).trim() || null;
|
||||
break;
|
||||
case "DESCRIPTION":
|
||||
cur.description = unescapeText(p.value).trim() || null;
|
||||
break;
|
||||
case "STATUS":
|
||||
if (p.value.trim().toUpperCase() === "CANCELLED") (cur as { cancelled?: boolean }).cancelled = true;
|
||||
break;
|
||||
case "DTSTART": {
|
||||
const t = parseTime(p);
|
||||
if (t) {
|
||||
cur.start = t.at;
|
||||
cur.allDay = t.allDay;
|
||||
}
|
||||
break;
|
||||
}
|
||||
case "DTEND": {
|
||||
const t = parseTime(p);
|
||||
if (t) cur.end = t.at;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
return out.sort((a, b) => a.start.getTime() - b.start.getTime());
|
||||
}
|
||||
|
||||
/** The Lisbon day ("YYYY-MM-DD") an instant falls on. */
|
||||
export function lisbonDay(at: Date): string {
|
||||
return new Intl.DateTimeFormat("en-CA", { timeZone: DEFAULT_ZONE, year: "numeric", month: "2-digit", day: "2-digit" }).format(at);
|
||||
}
|
||||
|
||||
/** Entries that happen on a Lisbon day (a multi-day entry counts on each of its days). */
|
||||
export function eventsOn(events: CalendarEvent[], day: string): CalendarEvent[] {
|
||||
return events.filter((e) => {
|
||||
const first = lisbonDay(e.start);
|
||||
// An all-day DTEND is exclusive (the next day at midnight).
|
||||
const last = e.end ? lisbonDay(new Date(e.end.getTime() - (e.allDay ? 1 : 0))) : first;
|
||||
return first <= day && day <= last;
|
||||
});
|
||||
}
|
||||
|
||||
export interface EventSuggestion {
|
||||
name: string;
|
||||
venue: string | null;
|
||||
city: string | null;
|
||||
/** A caption to start from; the editor changes it. */
|
||||
caption: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* What the form fills from an agenda entry. The place is split as maps write it ("Estádio do Dragão, Via Futebol
|
||||
* Clube do Porto, 4350-415 Porto, Portugal"): the first part is the venue, the city comes after the postal code.
|
||||
*/
|
||||
export function suggestionFor(e: CalendarEvent): EventSuggestion {
|
||||
const parts = (e.location ?? "")
|
||||
.split(/[,\n]/)
|
||||
.map((p) => p.trim())
|
||||
.filter((p) => p && !/^portugal$/i.test(p));
|
||||
const venue = parts[0] ?? null;
|
||||
let city: string | null = null;
|
||||
for (const p of parts.slice(1)) {
|
||||
const postal = /^\d{4}-\d{3}\s+(.+)$/.exec(p);
|
||||
if (postal) city = postal[1]!.trim();
|
||||
}
|
||||
if (!city && parts.length > 1) {
|
||||
const last = parts[parts.length - 1]!;
|
||||
if (!/\d/.test(last)) city = last;
|
||||
}
|
||||
const where = [venue, city && city !== venue ? city : null].filter(Boolean).join(", ");
|
||||
const caption = `${e.summary}${where ? `, ${where}` : ""}.`;
|
||||
return { name: e.summary, venue, city, caption };
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
import type { FastifyInstance, FastifyReply } from "fastify";
|
||||
import { z } from "zod";
|
||||
import { currentUserId, requireAuth } from "../auth/guard.js";
|
||||
import type { SessionService } from "../auth/sessions.js";
|
||||
import { CalendarError, type CalendarService } from "./service.js";
|
||||
import { lisbonDay } from "./ics.js";
|
||||
|
||||
const ConnectBody = z.object({ url: z.string().max(2000).nullable() });
|
||||
const DayQuery = z.object({ date: z.string().regex(/^\d{4}-\d{2}-\d{2}$/).optional() });
|
||||
|
||||
function fail(reply: FastifyReply, err: unknown) {
|
||||
if (err instanceof CalendarError) return reply.code(err.status).send({ error: err.code });
|
||||
throw err;
|
||||
}
|
||||
|
||||
/** The signed-in person's own agenda (their calendar's secret iCal address). */
|
||||
export async function registerCalendarRoutes(app: FastifyInstance, deps: { sessions: SessionService; calendar: CalendarService }) {
|
||||
const authenticate = requireAuth(deps.sessions);
|
||||
const { calendar } = deps;
|
||||
|
||||
app.get("/v1/me/calendar", { preHandler: authenticate }, async (req) => ({ connected: await calendar.connected(currentUserId(req)) }));
|
||||
|
||||
app.put("/v1/me/calendar", { preHandler: authenticate, config: { rateLimit: { max: 10, timeWindow: "1 minute" } } }, async (req, reply) => {
|
||||
const { url } = ConnectBody.parse(req.body);
|
||||
try {
|
||||
return await calendar.connect(currentUserId(req), url);
|
||||
} catch (err) {
|
||||
return fail(reply, err);
|
||||
}
|
||||
});
|
||||
|
||||
app.get("/v1/me/calendar/events", { preHandler: authenticate, config: { rateLimit: { max: 60, timeWindow: "1 minute" } } }, async (req, reply) => {
|
||||
const { date } = DayQuery.parse(req.query);
|
||||
try {
|
||||
return { date: date ?? lisbonDay(new Date()), events: await calendar.day(currentUserId(req), date ?? lisbonDay(new Date())) };
|
||||
} catch (err) {
|
||||
return fail(reply, err);
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,180 @@
|
||||
import { lookup } from "node:dns/promises";
|
||||
import { isIP } from "node:net";
|
||||
import type { Db } from "../db.js";
|
||||
import type { SecretBox } from "../delivery/secrets.js";
|
||||
import { type CalendarEvent, eventsOn, parseIcs, suggestionFor, type EventSuggestion } from "./ics.js";
|
||||
|
||||
export class CalendarError extends Error {
|
||||
constructor(
|
||||
readonly code: "calendar_url" | "calendar_unreachable" | "calendar_invalid" | "calendar_not_connected" | "secrets_unavailable",
|
||||
readonly status: number,
|
||||
) {
|
||||
super(code);
|
||||
}
|
||||
}
|
||||
|
||||
export interface AgendaEntry {
|
||||
uid: string;
|
||||
title: string;
|
||||
start: string;
|
||||
end: string | null;
|
||||
allDay: boolean;
|
||||
location: string | null;
|
||||
description: string | null;
|
||||
suggestion: EventSuggestion;
|
||||
}
|
||||
|
||||
const MAX_BYTES = 5 * 1024 * 1024;
|
||||
const TIMEOUT_MS = 10_000;
|
||||
const CACHE_MS = 5 * 60_000;
|
||||
const MAX_REDIRECTS = 3;
|
||||
|
||||
/** Loopback, private, link-local, carrier-grade NAT and other non-public ranges: never fetched for a user. */
|
||||
export function isPublicAddress(ip: string): boolean {
|
||||
if (isIP(ip) === 4) {
|
||||
const [a, b] = ip.split(".").map(Number) as [number, number];
|
||||
if (a === 10 || a === 127 || a === 0 || a >= 224) return false;
|
||||
if (a === 169 && b === 254) return false;
|
||||
if (a === 172 && b >= 16 && b <= 31) return false;
|
||||
if (a === 192 && b === 168) return false;
|
||||
if (a === 100 && b >= 64 && b <= 127) return false;
|
||||
return true;
|
||||
}
|
||||
const v6 = ip.toLowerCase();
|
||||
if (v6 === "::1" || v6 === "::") return false;
|
||||
const mapped = /^::ffff:(\d+\.\d+\.\d+\.\d+)$/.exec(v6);
|
||||
if (mapped) return isPublicAddress(mapped[1]!);
|
||||
if (/^f[cd]/.test(v6) || /^fe[89ab]/.test(v6) || v6.startsWith("ff")) return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
/** `webcal://` (what Apple and Outlook hand out) is the same address over https. */
|
||||
export function normalizeCalendarUrl(input: string): URL {
|
||||
let url: URL;
|
||||
try {
|
||||
url = new URL(input.trim().replace(/^webcals?:\/\//i, "https://"));
|
||||
} catch {
|
||||
throw new CalendarError("calendar_url", 400);
|
||||
}
|
||||
if (url.protocol !== "https:" || url.username || url.password) throw new CalendarError("calendar_url", 400);
|
||||
return url;
|
||||
}
|
||||
|
||||
export type Resolve = (host: string) => Promise<string[]>;
|
||||
const resolveHost: Resolve = async (host) => (isIP(host) ? [host] : (await lookup(host, { all: true })).map((a) => a.address));
|
||||
|
||||
/**
|
||||
* A person's own agenda, read from the secret iCal address they paste once (stored encrypted). Used by the
|
||||
* new-event form to list the day's entries and fill a generic event from one.
|
||||
*/
|
||||
export class CalendarService {
|
||||
private cache = new Map<string, { at: number; events: CalendarEvent[] }>();
|
||||
|
||||
constructor(
|
||||
private readonly deps: { db: Db; secrets: SecretBox | undefined; fetchImpl?: typeof fetch; resolve?: Resolve },
|
||||
) {}
|
||||
|
||||
private box(): SecretBox {
|
||||
if (!this.deps.secrets) throw new CalendarError("secrets_unavailable", 503);
|
||||
return this.deps.secrets;
|
||||
}
|
||||
|
||||
async connected(userId: string): Promise<boolean> {
|
||||
const prefs = await this.deps.db.userPreferences.findUnique({ where: { userId }, select: { calendarUrl: true } });
|
||||
return !!prefs?.calendarUrl;
|
||||
}
|
||||
|
||||
/** Checks the address answers with a calendar, then keeps it (null forgets it). */
|
||||
async connect(userId: string, input: string | null): Promise<{ connected: boolean; events: number }> {
|
||||
if (input === null) {
|
||||
await this.deps.db.userPreferences.upsert({ where: { userId }, create: { userId, calendarUrl: null }, update: { calendarUrl: null } });
|
||||
this.cache.delete(userId);
|
||||
return { connected: false, events: 0 };
|
||||
}
|
||||
const url = normalizeCalendarUrl(input);
|
||||
const events = await this.download(url);
|
||||
const sealed = this.box().seal(url.toString());
|
||||
await this.deps.db.userPreferences.upsert({ where: { userId }, create: { userId, calendarUrl: sealed }, update: { calendarUrl: sealed } });
|
||||
this.cache.set(userId, { at: Date.now(), events });
|
||||
return { connected: true, events: events.length };
|
||||
}
|
||||
|
||||
/** The entries of one Lisbon day ("YYYY-MM-DD"), with what the form would fill from each. */
|
||||
async day(userId: string, day: string): Promise<AgendaEntry[]> {
|
||||
const events = await this.events(userId);
|
||||
return eventsOn(events, day).map((e) => ({
|
||||
uid: e.uid,
|
||||
title: e.summary,
|
||||
start: e.start.toISOString(),
|
||||
end: e.end?.toISOString() ?? null,
|
||||
allDay: e.allDay,
|
||||
location: e.location,
|
||||
description: e.description,
|
||||
suggestion: suggestionFor(e),
|
||||
}));
|
||||
}
|
||||
|
||||
private async events(userId: string): Promise<CalendarEvent[]> {
|
||||
const hit = this.cache.get(userId);
|
||||
if (hit && Date.now() - hit.at < CACHE_MS) return hit.events;
|
||||
const prefs = await this.deps.db.userPreferences.findUnique({ where: { userId }, select: { calendarUrl: true } });
|
||||
if (!prefs?.calendarUrl) throw new CalendarError("calendar_not_connected", 404);
|
||||
const events = await this.download(new URL(this.box().open(prefs.calendarUrl)));
|
||||
this.cache.set(userId, { at: Date.now(), events });
|
||||
return events;
|
||||
}
|
||||
|
||||
private async download(start: URL): Promise<CalendarEvent[]> {
|
||||
const fetchImpl = this.deps.fetchImpl ?? fetch;
|
||||
const resolve = this.deps.resolve ?? resolveHost;
|
||||
let url = start;
|
||||
for (let hop = 0; hop <= MAX_REDIRECTS; hop++) {
|
||||
// Only public hosts: a pasted address must not reach the servers' own network.
|
||||
let addresses: string[];
|
||||
try {
|
||||
addresses = await resolve(url.hostname.replace(/^\[|\]$/g, ""));
|
||||
} catch {
|
||||
throw new CalendarError("calendar_unreachable", 502);
|
||||
}
|
||||
if (!addresses.length || !addresses.every(isPublicAddress)) throw new CalendarError("calendar_url", 400);
|
||||
let res: Response;
|
||||
try {
|
||||
res = await fetchImpl(url, { redirect: "manual", signal: AbortSignal.timeout(TIMEOUT_MS), headers: { accept: "text/calendar, */*" } });
|
||||
} catch {
|
||||
throw new CalendarError("calendar_unreachable", 502);
|
||||
}
|
||||
if (res.status >= 300 && res.status < 400) {
|
||||
const next = res.headers.get("location");
|
||||
if (!next) throw new CalendarError("calendar_unreachable", 502);
|
||||
url = normalizeCalendarUrl(new URL(next, url).toString());
|
||||
continue;
|
||||
}
|
||||
if (!res.ok) throw new CalendarError("calendar_unreachable", 502);
|
||||
const text = await readCapped(res);
|
||||
try {
|
||||
return parseIcs(text);
|
||||
} catch {
|
||||
throw new CalendarError("calendar_invalid", 422);
|
||||
}
|
||||
}
|
||||
throw new CalendarError("calendar_unreachable", 502);
|
||||
}
|
||||
}
|
||||
|
||||
async function readCapped(res: Response): Promise<string> {
|
||||
if (!res.body) return res.text();
|
||||
const reader = res.body.getReader();
|
||||
const chunks: Uint8Array[] = [];
|
||||
let size = 0;
|
||||
for (;;) {
|
||||
const { done, value } = await reader.read();
|
||||
if (done) break;
|
||||
size += value.byteLength;
|
||||
if (size > MAX_BYTES) {
|
||||
await reader.cancel();
|
||||
throw new CalendarError("calendar_invalid", 422);
|
||||
}
|
||||
chunks.push(value);
|
||||
}
|
||||
return Buffer.concat(chunks).toString("utf8");
|
||||
}
|
||||
@@ -5,8 +5,9 @@
|
||||
*
|
||||
* - The subject is who is in focus, not who is biggest: blurred players in the foreground are scenery.
|
||||
* - With a ball near the subject, the ball and the sharp players contesting it come along.
|
||||
* - The crop is usually two thirds of the frame (the same shape), moved to put the subject in the middle with
|
||||
* room above the heads. Legs may be cut; heads and the ball may not.
|
||||
* - The crop is usually two thirds of the frame (the same shape), the subject in the middle across, the upper
|
||||
* body a little above the middle and little or no empty pitch under the feet (spare height goes above, to the
|
||||
* crowd and the stands). Legs may be cut; heads and the ball may not.
|
||||
* - Cutting another sharp person in half is avoided; cutting blurred ones doesn't matter.
|
||||
*
|
||||
* Boxes are fractions of the upright photo (0..1, y down).
|
||||
@@ -50,7 +51,23 @@ const MIN_BALL = 0.3;
|
||||
/** Smaller people (in photo heights) are too far away to be what the photo is about. */
|
||||
const MIN_HEIGHT = 0.08;
|
||||
/** Tuning, fitted to Peter's crops (exported so the evaluation script can sweep it). */
|
||||
export const TUNING = { inFocus: 0.55, usualScale: 0.72, wScale: 1.0, wFill: 0.6, wCentre: 1.2, wHead: 0.8, headAt: 0.1, wCut: 1.2, wJoint: 0.8 };
|
||||
export const TUNING = {
|
||||
inFocus: 0.55,
|
||||
usualScale: 0.72,
|
||||
wScale: 1.0,
|
||||
wFill: 1.0,
|
||||
fillAt: 0.6,
|
||||
wCentre: 1.2,
|
||||
wHead: 0.8,
|
||||
headMin: 0.04,
|
||||
headMax: 0.16,
|
||||
wChest: 1.4,
|
||||
chestAt: 0.42,
|
||||
wBelow: 2.5,
|
||||
belowMax: 0.08,
|
||||
wCut: 1.2,
|
||||
wJoint: 0.8,
|
||||
};
|
||||
|
||||
/**
|
||||
* Where the joints of a standing person roughly are, as fractions of their box from the top (neck, hips, knees,
|
||||
@@ -151,13 +168,17 @@ function frame(s: Box, ratio: number, mustBottom: number, headroom: number, tall
|
||||
ch = cw / ratio;
|
||||
}
|
||||
if (cw < w(s) + 0.01 || ch < mustBottom - s.y0 + headroom || cw < minWidth - 1e-9) continue;
|
||||
// Vertical positions: from the heads just under the top edge to the bottom of the subject just above the
|
||||
// bottom edge (all the spare height above them: the crowd, the stands, never a strip of empty pitch below).
|
||||
const top = s.y0 - headroom;
|
||||
const spare = Math.max(0, ch - (mustBottom - top));
|
||||
for (let i = 0; i <= 24; i++) {
|
||||
const x0 = Math.min(Math.max(0, s.x1 - cw + (i / 24) * (cw - w(s))), 1 - cw);
|
||||
for (let j = 0; j <= 16; j++) {
|
||||
const y0 = Math.min(Math.max(0, s.y0 - headroom - (j / 16) * 0.3 * ch), 1 - ch);
|
||||
for (let j = 0; j <= 20; j++) {
|
||||
const y0 = Math.min(Math.max(0, top - (j / 20) * spare), 1 - ch);
|
||||
const r = { x0, y0, x1: x0 + cw, y1: y0 + ch };
|
||||
if (r.x0 > s.x0 + 1e-6 || r.x1 < s.x1 - 1e-6 || r.y0 > Math.max(0, s.y0 - headroom) + 1e-6 || r.y1 < mustBottom - 1e-6) continue;
|
||||
const c = cost(r, s, others, ch, tallest, mainSharp, ratio) + jointCost(r, inSubject, others, mainSharp);
|
||||
const c = cost(r, s, others, ch, tallest, mainSharp, ratio, inSubject) + jointCost(r, inSubject, others, mainSharp);
|
||||
if (!best || c < best.cost) best = { rect: r, cost: c };
|
||||
}
|
||||
}
|
||||
@@ -166,7 +187,7 @@ function frame(s: Box, ratio: number, mustBottom: number, headroom: number, tall
|
||||
return { rect: best.rect, subject: s, reason, people: inSubject.length };
|
||||
}
|
||||
|
||||
function cost(r: Box, s: Box, others: Detection[], ch: number, tallest: number, mainSharp: number, ratio: number): number {
|
||||
function cost(r: Box, s: Box, others: Detection[], ch: number, tallest: number, mainSharp: number, ratio: number, inSubject: Detection[]): number {
|
||||
let c = 0;
|
||||
// Sharp people cut in half by the crop's edge look wrong; blurred ones (foreground, background) don't matter.
|
||||
for (const p of others) {
|
||||
@@ -181,11 +202,20 @@ function cost(r: Box, s: Box, others: Detection[], ch: number, tallest: number,
|
||||
const k = Math.max(ch, w(r) / ratio);
|
||||
c += TUNING.wScale * Math.abs(k - TUNING.usualScale);
|
||||
// The subject fills a good part of the height (people tall in the frame).
|
||||
c += TUNING.wFill * Math.max(0, 0.55 - tallest / ch);
|
||||
c += TUNING.wFill * Math.max(0, TUNING.fillAt - tallest / ch);
|
||||
// Centred across.
|
||||
c += TUNING.wCentre * (Math.abs(cx(s) - cx(r)) / w(r));
|
||||
// Heads a little below the top.
|
||||
c += TUNING.wHead * Math.abs((s.y0 - r.y0) / ch - TUNING.headAt);
|
||||
// Heads a little below the top: not touching it, not floating in empty space.
|
||||
const head = (s.y0 - r.y0) / ch;
|
||||
c += TUNING.wHead * (Math.max(0, TUNING.headMin - head) + Math.max(0, head - TUNING.headMax));
|
||||
// The upper body (chest, faces) near the middle, a little above it, as a photographer frames: not the knees in
|
||||
// the middle with a strip of grass below.
|
||||
const main = inSubject.reduce((a, b) => (h(b) > h(a) ? b : a));
|
||||
const chest = (main.y0 + 0.3 * h(main) - r.y0) / ch;
|
||||
c += TUNING.wChest * Math.abs(chest - TUNING.chestAt);
|
||||
// Empty space under the subject (pitch, floor) is the first thing an editor crops away.
|
||||
const below = (r.y1 - Math.min(s.y1, r.y1)) / ch;
|
||||
c += TUNING.wBelow * Math.max(0, below - TUNING.belowMax);
|
||||
return c;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import type { DeliveryItemSummary } from "@photoreport/contracts";
|
||||
import { buildVars, createdStamp, PathTemplateError, renderFileName, renderFolder } from "@photoreport/metadata";
|
||||
import { buildVars, createdStamp, eventName, PathTemplateError, renderFileName, renderFolder } from "@photoreport/metadata";
|
||||
import type { Db } from "../db.js";
|
||||
import type { DeliveryItem } from "../generated/prisma/client.js";
|
||||
import type { IngestLogger } from "../ingest/service.js";
|
||||
@@ -236,7 +236,7 @@ export class DeliveryService {
|
||||
log.warn({ itemId, attempt: item.attempts, error: message, final: update.status === "FAILED" }, "delivery: attempt failed");
|
||||
}
|
||||
const saved = await db.deliveryItem.update({ where: { id: itemId }, data: update });
|
||||
if (saved.status === "FAILED") await this.deps.notifications?.notifyRole(saved.organizationId, "ADMIN", { type: "delivery_failed", key: `target:${item.targetId}`, payload: { target: item.target.name, event: item.event ? `${item.event.home} x ${item.event.away}` : null, error: saved.lastError } });
|
||||
if (saved.status === "FAILED") await this.deps.notifications?.notifyRole(saved.organizationId, "ADMIN", { type: "delivery_failed", key: `target:${item.targetId}`, payload: { target: item.target.name, event: item.event ? eventName(item.event) : null, error: saved.lastError } });
|
||||
this.deps.broadcaster.library(saved.organizationId, { type: "delivery.updated", item: toItemSummary(saved) });
|
||||
return saved;
|
||||
}
|
||||
|
||||
@@ -60,7 +60,7 @@ export function newer(candidate: string, current: string): boolean {
|
||||
}
|
||||
|
||||
export class DesktopReleases {
|
||||
private cache: { at: number; release: GiteaRelease | null } | null = null;
|
||||
private cache: { at: number; releases: GiteaRelease[] } | null = null;
|
||||
|
||||
constructor(
|
||||
private readonly config: DesktopReleaseConfig,
|
||||
@@ -71,15 +71,26 @@ export class DesktopReleases {
|
||||
return { authorization: `token ${this.config.token}`, accept: "application/json" };
|
||||
}
|
||||
|
||||
/** The newest published `desktop-v*` release. */
|
||||
async latest(): Promise<GiteaRelease | null> {
|
||||
if (this.cache && Date.now() - this.cache.at < CACHE_MS) return this.cache.release;
|
||||
/** Published `desktop-v*` releases, newest first. */
|
||||
async releases(): Promise<GiteaRelease[]> {
|
||||
if (this.cache && Date.now() - this.cache.at < CACHE_MS) return this.cache.releases;
|
||||
const res = await this.fetchImpl(`${this.config.api.replace(/\/$/, "")}/releases?limit=50`, { headers: this.headers() });
|
||||
if (!res.ok) throw new Error(`gitea releases: ${res.status}`);
|
||||
const all = ((await res.json()) as GiteaRelease[]).filter((r) => !r.draft && !r.prerelease && r.tag_name.startsWith("desktop-v"));
|
||||
all.sort((x, y) => (newer(x.tag_name.slice(9), y.tag_name.slice(9)) ? -1 : 1));
|
||||
this.cache = { at: Date.now(), release: all[0] ?? null };
|
||||
return this.cache.release;
|
||||
this.cache = { at: Date.now(), releases: all };
|
||||
return all;
|
||||
}
|
||||
|
||||
/** The newest release that has this platform's update (a newer one may still be building, or wait for its Mac). */
|
||||
private async forPlatform(target: string, arch: string): Promise<{ release: GiteaRelease; manifest: GiteaAsset } | null> {
|
||||
// Universal macOS builds serve both Apple chips.
|
||||
const names = [`update-${target}-${arch}.json`, ...(target === "darwin" ? ["update-darwin-universal.json"] : [])];
|
||||
for (const release of await this.releases()) {
|
||||
const manifest = names.map((n) => release.assets.find((a) => a.name === n)).find(Boolean);
|
||||
if (manifest) return { release, manifest };
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private async download(asset: GiteaAsset): Promise<Response> {
|
||||
@@ -90,13 +101,10 @@ export class DesktopReleases {
|
||||
|
||||
/** Tauri's dynamic update answer for one platform, or null when there is nothing newer. */
|
||||
async updateFor(target: string, arch: string, current: string): Promise<{ version: string; notes: string; pub_date?: string; url: string; signature: string } | null> {
|
||||
const release = await this.latest();
|
||||
if (!release) return null;
|
||||
// Universal macOS builds serve both Apple chips.
|
||||
const names = [`update-${target}-${arch}.json`, ...(target === "darwin" ? ["update-darwin-universal.json"] : [])];
|
||||
const asset = names.map((n) => release.assets.find((a) => a.name === n)).find(Boolean);
|
||||
if (!asset) return null;
|
||||
const manifest = Manifest.parse(await (await this.download(asset)).json());
|
||||
const found = await this.forPlatform(target, arch);
|
||||
if (!found) return null;
|
||||
const { release } = found;
|
||||
const manifest = Manifest.parse(await (await this.download(found.manifest)).json());
|
||||
if (!newer(manifest.version, current)) return null;
|
||||
if (!release.assets.some((a) => a.name === manifest.file)) return null;
|
||||
return {
|
||||
@@ -108,10 +116,10 @@ export class DesktopReleases {
|
||||
};
|
||||
}
|
||||
|
||||
/** The installer itself, streamed from the release. */
|
||||
/** The installer itself, streamed from a desktop release. */
|
||||
async file(releaseId: number, name: string): Promise<{ body: Readable; size: string | null } | null> {
|
||||
const release = await this.latest();
|
||||
if (!release || release.id !== releaseId) return null;
|
||||
const release = (await this.releases()).find((r) => r.id === releaseId);
|
||||
if (!release) return null;
|
||||
const asset = release.assets.find((a) => a.name === name);
|
||||
if (!asset || /\.json$/.test(name)) return null;
|
||||
const res = await this.download(asset);
|
||||
|
||||
@@ -0,0 +1,61 @@
|
||||
/**
|
||||
* Face boxes are found on the photo as it arrived; the previews the app shows are the edited ones (straightened
|
||||
* and cropped). This maps a box from the original frame into the rendered one, with the crop maths the editor
|
||||
* and the engine use (apps/api/src/composition/geometry.ts): the crop is a box, normalised to the photo's size,
|
||||
* in the frame rotated by the straighten angle about its centre.
|
||||
*/
|
||||
export interface Box {
|
||||
x0: number;
|
||||
y0: number;
|
||||
x1: number;
|
||||
y1: number;
|
||||
}
|
||||
|
||||
export interface Crop {
|
||||
rect: Box;
|
||||
angle: number;
|
||||
}
|
||||
|
||||
/** The crop in a develop settings document (LightCraft JSON); null when the photo isn't cropped or straightened. */
|
||||
export function cropOfSettings(settings: unknown): Crop | null {
|
||||
const g = (settings as { crop?: { geometry?: { rect?: Box; angle?: number } } } | null)?.crop?.geometry;
|
||||
if (!g) return null;
|
||||
const rect = g.rect ?? { x0: 0, y0: 0, x1: 1, y1: 1 };
|
||||
const angle = g.angle ?? 0;
|
||||
if (!angle && rect.x0 <= 0 && rect.y0 <= 0 && rect.x1 >= 1 && rect.y1 >= 1) return null;
|
||||
return { rect, angle };
|
||||
}
|
||||
|
||||
/**
|
||||
* `box` (normalised, original frame) in the cropped frame, or null when it falls outside the crop. A box cut by the
|
||||
* crop's edge is clipped to it. `w` × `h`: the photo's size in pixels (the rotation is in pixels).
|
||||
*/
|
||||
export function boxInCrop(box: Box, crop: Crop | null, w: number, h: number): Box | null {
|
||||
if (!crop) return box;
|
||||
const a = (crop.angle * Math.PI) / 180;
|
||||
const [c, s] = [Math.cos(a), Math.sin(a)];
|
||||
const corners = [
|
||||
[box.x0, box.y0],
|
||||
[box.x1, box.y0],
|
||||
[box.x0, box.y1],
|
||||
[box.x1, box.y1],
|
||||
].map(([nx, ny]) => {
|
||||
// Original -> straightened: rotate by +angle about the centre (the inverse of insideRotated's mapping).
|
||||
const px = nx! * w - w / 2;
|
||||
const py = ny! * h - h / 2;
|
||||
return [(px * c - py * s + w / 2) / w, (px * s + py * c + h / 2) / h] as const;
|
||||
});
|
||||
const xs = corners.map((p) => p[0]);
|
||||
const ys = corners.map((p) => p[1]);
|
||||
const { rect } = crop;
|
||||
const rw = rect.x1 - rect.x0;
|
||||
const rh = rect.y1 - rect.y0;
|
||||
const out = {
|
||||
x0: (Math.min(...xs) - rect.x0) / rw,
|
||||
y0: (Math.min(...ys) - rect.y0) / rh,
|
||||
x1: (Math.max(...xs) - rect.x0) / rw,
|
||||
y1: (Math.max(...ys) - rect.y0) / rh,
|
||||
};
|
||||
if (out.x1 <= 0 || out.y1 <= 0 || out.x0 >= 1 || out.y0 >= 1) return null;
|
||||
return { x0: Math.max(0, out.x0), y0: Math.max(0, out.y0), x1: Math.min(1, out.x1), y1: Math.min(1, out.y1) };
|
||||
}
|
||||
@@ -54,3 +54,18 @@ export const THRESHOLDS: Record<string, { match: number; group: number; margin:
|
||||
* in the loupe, but never grouped: out-of-focus faces (crowd, background) all look alike to the embedder.
|
||||
*/
|
||||
export const MIN_SHARPNESS = 45;
|
||||
|
||||
/**
|
||||
* A face this much softer than the sharpest one in the same photo is out of the focus plane (the crowd behind the
|
||||
* player, a bench in front), however textured: not worth identifying.
|
||||
*/
|
||||
export const RELATIVE_SHARPNESS = 0.25;
|
||||
|
||||
/**
|
||||
* The faces worth identifying in one photo: the ones in focus. Faces with no measure (older analyses) stay.
|
||||
* Editors only want names for who the photo is about; boxes on a blurred crowd are noise.
|
||||
*/
|
||||
export function inFocus<T extends { sharpness?: number | null }>(faces: T[]): T[] {
|
||||
const sharpest = Math.max(0, ...faces.map((f) => f.sharpness ?? 0));
|
||||
return faces.filter((f) => f.sharpness == null || (f.sharpness >= MIN_SHARPNESS && f.sharpness >= RELATIVE_SHARPNESS * sharpest));
|
||||
}
|
||||
@@ -1,3 +1,4 @@
|
||||
import { boxInCrop, cropOfSettings } from "./frame.js";
|
||||
import { ConfirmFaceGroup, type FaceGroupSummary } from "@photoreport/contracts";
|
||||
import type { FastifyInstance } from "fastify";
|
||||
import { z } from "zod";
|
||||
@@ -9,7 +10,7 @@ import { createReadStream } from "node:fs";
|
||||
import sharp from "sharp";
|
||||
import type { LocalStorage, UrlSigner } from "../storage/storage.js";
|
||||
import { FaceRejected, JERSEY_MIN_SCORE, majorityNumber, type FaceService } from "./service.js";
|
||||
import { MIN_SHARPNESS } from "./math.js";
|
||||
import { inFocus, MIN_SHARPNESS } from "./math.js";
|
||||
|
||||
const EventParams = z.object({ eventId: z.uuid() });
|
||||
const GroupParams = z.object({ groupId: z.uuid() });
|
||||
@@ -135,10 +136,15 @@ export async function registerFaceRoutes(app: FastifyInstance, deps: { db: Db; s
|
||||
/** Faces of one photo with their names, for boxes in the loupe. */
|
||||
app.get("/v1/photos/:photoId/faces", { preHandler: authenticate }, async (req) => {
|
||||
const { photoId } = PhotoParams.parse(req.params);
|
||||
const photo = await db.photo.findUnique({ where: { id: photoId }, select: { organizationId: true, facesStatus: true } });
|
||||
const photo = await db.photo.findUnique({ where: { id: photoId }, select: { organizationId: true, facesStatus: true, width: true, height: true, renderedSeq: true, developSnapshot: true } });
|
||||
if (!photo) throw notFound("photo_not_found");
|
||||
await requireMembership(db, req, photo.organizationId, "INGESTER");
|
||||
const list = await db.face.findMany({ where: { photoId }, include: { group: { include: { person: true, suggested: true } } }, orderBy: { x0: "asc" } });
|
||||
const all = await db.face.findMany({ where: { photoId }, include: { group: { include: { person: true, suggested: true } } }, orderBy: { x0: "asc" } });
|
||||
// Blurred faces (photos analysed before they were left out) are not boxed, unless someone already named them.
|
||||
const focused = new Set(inFocus(all).map((f) => f.id));
|
||||
const list = all.filter((f) => focused.has(f.id) || f.group?.person);
|
||||
// The previews are the edited photo: boxes are also given in its (cropped, straightened) frame.
|
||||
const crop = photo.renderedSeq > 0 ? cropOfSettings(photo.developSnapshot) : null;
|
||||
return {
|
||||
status: photo.facesStatus,
|
||||
faces: list.map((f) => ({
|
||||
@@ -148,6 +154,7 @@ export async function registerFaceRoutes(app: FastifyInstance, deps: { db: Db; s
|
||||
y0: f.y0,
|
||||
x1: f.x1,
|
||||
y1: f.y1,
|
||||
inPreview: boxInCrop(f, crop, photo.width ?? 1, photo.height ?? 1),
|
||||
score: f.score,
|
||||
person: personOut(f.group?.person ?? null),
|
||||
suggestion: f.group?.suggested ? personOut(f.group.suggested) : null,
|
||||
|
||||
@@ -32,7 +32,7 @@ export function majorityNumber(faces: { jerseyNumber: string | null; jerseyScore
|
||||
}
|
||||
|
||||
const norm = (s: string) => s.normalize("NFD").replace(/[\u0300-\u036f]/g, "").toLowerCase().replace(/\s+/g, " ").trim();
|
||||
import { addToMean, cosine, mergeMeans, MIN_SHARPNESS, THRESHOLDS } from "./math.js";
|
||||
import { addToMean, cosine, inFocus, mergeMeans, MIN_SHARPNESS, THRESHOLDS } from "./math.js";
|
||||
import type { FaceEngine } from "./process.js";
|
||||
|
||||
/** Faces this small (fraction of the photo's longer side) are crowd, not subjects. */
|
||||
@@ -87,6 +87,18 @@ export class FaceService {
|
||||
return r.count;
|
||||
}
|
||||
|
||||
/**
|
||||
* Photos left without analysis in an organization that has face analysis on (they arrived while it was off, or
|
||||
* while a toggle raced their ingest): queue them. Cheap; the worker runs it at start and every minute.
|
||||
*/
|
||||
async queueMissed(): Promise<number> {
|
||||
const r = await this.deps.db.photo.updateMany({
|
||||
where: { facesStatus: "NONE", status: "READY", organization: { biometricsEnabled: true } },
|
||||
data: { facesStatus: "PENDING" },
|
||||
});
|
||||
return r.count;
|
||||
}
|
||||
|
||||
/** Detects, stores and groups the faces of one claimed photo. Never throws. */
|
||||
async process(photoId: string): Promise<void> {
|
||||
const { db, storage, log, engine } = this.deps;
|
||||
@@ -94,7 +106,8 @@ export class FaceService {
|
||||
if (!engine) throw new Error("face engine not configured");
|
||||
const photo = await db.photo.findUniqueOrThrow({ where: { id: photoId } });
|
||||
const analysis = await engine.analyse(storage.resolve(photo.storageKey));
|
||||
const faces = analysis.faces.filter((f) => Math.max(f.x1 - f.x0, f.y1 - f.y0) >= MIN_FACE_SIDE);
|
||||
// Only faces in focus are kept: the blurred crowd and benches are not who the photo is about.
|
||||
const faces = inFocus(analysis.faces.filter((f) => Math.max(f.x1 - f.x0, f.y1 - f.y0) >= MIN_FACE_SIDE));
|
||||
// The shirt number under each clear face, when a number model is installed.
|
||||
const numbers = new Map<number, JerseyReading>();
|
||||
if (this.deps.jersey) {
|
||||
@@ -399,8 +412,14 @@ export class FaceWorker {
|
||||
|
||||
start(): void {
|
||||
void this.service.requeueStale();
|
||||
let missedAt = 0;
|
||||
const tick = async () => {
|
||||
try {
|
||||
if (Date.now() - missedAt > 60_000) {
|
||||
missedAt = Date.now();
|
||||
const n = await this.service.queueMissed();
|
||||
if (n) this.opts.log.info({ photos: n }, "faces: queued photos left without analysis");
|
||||
}
|
||||
for (const id of await this.service.claimReferences(5)) await this.service.processReference(id);
|
||||
const ids = await this.service.claim(this.opts.concurrency - this.inFlight);
|
||||
for (const id of ids) {
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
import type { Db } from "../db.js";
|
||||
import { applyRename } from "./rename.js";
|
||||
|
||||
/**
|
||||
* Photos that just joined an event (moved by hand, or claimed from "Sem evento" when the event was created or its
|
||||
* window changed) get what arriving in it would have given them: the event's arrival name, faces analysed again so
|
||||
* they group with the event's people, and the event's autopilot edit (FTP and desktop photos only, as on arrival).
|
||||
*/
|
||||
export async function joinedEvent(db: Db, eventId: string, ids: string[]): Promise<void> {
|
||||
if (!ids.length) return;
|
||||
const event = await db.event.findUnique({ where: { id: eventId }, select: { autopilot: true, organization: { select: { biometricsEnabled: true } } } });
|
||||
if (!event) return;
|
||||
if (event.organization.biometricsEnabled) {
|
||||
await db.photo.updateMany({ where: { id: { in: ids }, status: "READY", facesStatus: { in: ["DONE", "FAILED"] } }, data: { facesStatus: "PENDING" } });
|
||||
}
|
||||
if ((event.autopilot as { enabled?: boolean } | null)?.enabled === true) {
|
||||
await db.photo.updateMany({ where: { id: { in: ids }, status: "READY", source: { not: "UPLOAD" }, autopilotStatus: "NONE" }, data: { autopilotStatus: "PENDING" } });
|
||||
}
|
||||
for (const id of ids) await applyRename(db, id);
|
||||
}
|
||||
|
||||
/**
|
||||
* Photos waiting in "Sem evento" taken during this event's ingest window (by the photographers it is assigned to,
|
||||
* or anyone when it has none): photos sent before the event was created, or before its times were corrected.
|
||||
*/
|
||||
export async function claimInbox(db: Db, eventId: string): Promise<string[]> {
|
||||
const event = await db.event.findUnique({
|
||||
where: { id: eventId },
|
||||
select: { organizationId: true, archivedAt: true, ingestFrom: true, ingestUntil: true, assignments: { select: { userId: true } } },
|
||||
});
|
||||
if (!event || event.archivedAt) return [];
|
||||
const photos = await db.photo.findMany({
|
||||
where: {
|
||||
organizationId: event.organizationId,
|
||||
eventId: null,
|
||||
capturedAt: { gte: event.ingestFrom, lte: event.ingestUntil },
|
||||
...(event.assignments.length && { uploaderId: { in: event.assignments.map((a) => a.userId) } }),
|
||||
},
|
||||
select: { id: true },
|
||||
take: 20_000,
|
||||
});
|
||||
const ids = photos.map((p) => p.id);
|
||||
if (!ids.length) return [];
|
||||
// Only the ones still in the inbox (another event may have claimed some meanwhile).
|
||||
await db.photo.updateMany({ where: { id: { in: ids }, eventId: null }, data: { eventId } });
|
||||
const claimed = (await db.photo.findMany({ where: { id: { in: ids }, eventId }, select: { id: true } })).map((p) => p.id);
|
||||
await joinedEvent(db, eventId, claimed);
|
||||
return claimed;
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
import { AutopilotSettings } from "@photoreport/contracts";
|
||||
import { IptcTemplate, NEWSROOM_TEMPLATE } from "@photoreport/metadata";
|
||||
import { eventName, GENERAL_TEMPLATE, IptcTemplate, NEWSROOM_TEMPLATE } from "@photoreport/metadata";
|
||||
import type { FastifyInstance, FastifyRequest } from "fastify";
|
||||
import { z } from "zod";
|
||||
import { ROLE_RANK, currentUserId, requireAuth, requireMembership } from "../auth/guard.js";
|
||||
@@ -8,7 +8,9 @@ import type { Db } from "../db.js";
|
||||
import { type Event, Prisma } from "../generated/prisma/client.js";
|
||||
import { compact } from "../lib/compact.js";
|
||||
import { badRequest, notFound } from "../lib/errors.js";
|
||||
import type { Broadcaster } from "../realtime.js";
|
||||
import type { SportsService } from "../sports/service.js";
|
||||
import { claimInbox } from "./adopt.js";
|
||||
|
||||
const HOUR = 3600_000;
|
||||
const OrgParams = z.object({ orgId: z.uuid() });
|
||||
@@ -18,8 +20,10 @@ const name = z.string().trim().min(1).max(120);
|
||||
const optional = z.string().trim().max(200).optional().nullable();
|
||||
|
||||
const EventFields = z.object({
|
||||
/** The home team, or the event's name when it is not a match. */
|
||||
home: name,
|
||||
away: name,
|
||||
/** Empty (or left out): not a match (a press conference, a gala, a presentation). */
|
||||
away: z.string().trim().max(120).optional(),
|
||||
homeShort: optional,
|
||||
awayShort: optional,
|
||||
venue: optional,
|
||||
@@ -56,7 +60,7 @@ function serialize(event: EventWithPeople) {
|
||||
return {
|
||||
...rest,
|
||||
organizationId,
|
||||
title: `${event.home} x ${event.away}`,
|
||||
title: eventName(event),
|
||||
photographers: assignments.map((a) => a.user),
|
||||
photoCount: _count.photos,
|
||||
};
|
||||
@@ -75,8 +79,20 @@ export function ingestWindow(startsAt: Date, from?: Date, until?: Date): { inges
|
||||
return { ingestFrom, ingestUntil };
|
||||
}
|
||||
|
||||
export async function registerEventRoutes(app: FastifyInstance, deps: { db: Db; sessions: SessionService; sports?: SportsService }) {
|
||||
export async function registerEventRoutes(app: FastifyInstance, deps: { db: Db; sessions: SessionService; sports?: SportsService; broadcaster?: Broadcaster }) {
|
||||
const { db } = deps;
|
||||
|
||||
/** Photos in "Sem evento" taken during the event join it (and the open libraries move them). */
|
||||
async function claim(orgId: string, eventId: string): Promise<void> {
|
||||
const ids = await claimInbox(db, eventId).catch((err) => {
|
||||
app.log.warn({ err, eventId }, "event: claiming inbox photos failed");
|
||||
return [] as string[];
|
||||
});
|
||||
if (ids.length) {
|
||||
app.log.info({ eventId, photos: ids.length }, "event: claimed photos from the inbox");
|
||||
deps.broadcaster?.library(orgId, { type: "photo.updated", ids, patch: { eventId } });
|
||||
}
|
||||
}
|
||||
const authenticate = requireAuth(deps.sessions);
|
||||
|
||||
const loadEvent = async (req: FastifyRequest, eventId: string, minRole: "PHOTOGRAPHER" | "INGESTER" | "EDITOR") => {
|
||||
@@ -143,18 +159,19 @@ export async function registerEventRoutes(app: FastifyInstance, deps: { db: Db;
|
||||
...compact(match),
|
||||
...(autopilot && { autopilot }),
|
||||
home: fields.home,
|
||||
away: fields.away,
|
||||
away: fields.away ?? "",
|
||||
startsAt: fields.startsAt,
|
||||
organizationId: orgId,
|
||||
createdById: currentUserId(req),
|
||||
...ingestWindow(body.startsAt, ingestFrom, ingestUntil),
|
||||
iptcTemplate: iptcTemplate ?? NEWSROOM_TEMPLATE,
|
||||
iptcTemplate: iptcTemplate ?? (fields.away ? NEWSROOM_TEMPLATE : GENERAL_TEMPLATE),
|
||||
...(photographerIds?.length && { assignments: { create: [...new Set(photographerIds)].map((userId) => ({ userId })) } }),
|
||||
},
|
||||
include,
|
||||
});
|
||||
if (event.homeTeamId || event.awayTeamId) syncSquads(event.id);
|
||||
return reply.code(201).send(serialize(event));
|
||||
await claim(orgId, event.id);
|
||||
return reply.code(201).send(serialize(await db.event.findUniqueOrThrow({ where: { id: event.id }, include })));
|
||||
});
|
||||
|
||||
app.get("/v1/events/:eventId", { preHandler: authenticate }, async (req) => {
|
||||
@@ -194,6 +211,11 @@ export async function registerEventRoutes(app: FastifyInstance, deps: { db: Db;
|
||||
});
|
||||
const teamsChanged = (match.homeTeamId !== undefined && match.homeTeamId !== current.homeTeamId) || (match.awayTeamId !== undefined && match.awayTeamId !== current.awayTeamId);
|
||||
if (teamsChanged && (event.homeTeamId || event.awayTeamId)) syncSquads(event.id);
|
||||
// New times, new photographers or back from the archive: photos waiting in "Sem evento" may now belong here.
|
||||
if (startsAt || ingestFrom || ingestUntil || photographerIds || archived === false) {
|
||||
await claim(event.organizationId, eventId);
|
||||
return serialize(await db.event.findUniqueOrThrow({ where: { id: eventId }, include }));
|
||||
}
|
||||
return serialize(event);
|
||||
});
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
import { applyTemplate, type ApplyResult, buildVars, IptcTemplate, parseCodeList } from "@photoreport/metadata";
|
||||
import { applyTemplate, type ApplyResult, buildVars, type CodeList, IptcTemplate, parseCodeList } from "@photoreport/metadata";
|
||||
import type { Db } from "../db.js";
|
||||
import type { Event } from "../generated/prisma/client.js";
|
||||
import { eventInfoOf } from "./event-info.js";
|
||||
|
||||
export const DEFAULT_CODE_LIST = "default";
|
||||
@@ -13,10 +14,23 @@ export async function iptcForPhoto(db: Db, photoId: string): Promise<(ApplyResul
|
||||
const photo = await db.photo.findUnique({ where: { id: photoId }, include: { event: true, uploader: { select: { name: true } } } });
|
||||
if (!photo) return undefined;
|
||||
if (!photo.event) return { organizationId: photo.organizationId, values: {}, issues: [] };
|
||||
const template = { ...IptcTemplate.parse(photo.event.iptcTemplate), ...IptcTemplate.partial().parse(photo.iptcOverrides ?? {}) };
|
||||
const codes = await db.codeList.findUnique({
|
||||
where: { organizationId_name: { organizationId: photo.organizationId, name: DEFAULT_CODE_LIST } },
|
||||
});
|
||||
const vars = buildVars(eventInfoOf(photo.event), { capturedAt: photo.capturedAt ?? undefined, players: photo.players }, photo.uploader?.name);
|
||||
return { organizationId: photo.organizationId, ...applyTemplate(template, vars, codes ? parseCodeList(codes.content).list : undefined) };
|
||||
return { organizationId: photo.organizationId, ...iptcOf(photo, photo.event, photo.uploader?.name, await codeListOf(db, photo.organizationId)) };
|
||||
}
|
||||
|
||||
/** The organization's code list, parsed (undefined when it has none). */
|
||||
export async function codeListOf(db: Db, organizationId: string): Promise<CodeList | undefined> {
|
||||
const codes = await db.codeList.findUnique({ where: { organizationId_name: { organizationId, name: DEFAULT_CODE_LIST } } });
|
||||
return codes ? parseCodeList(codes.content).list : undefined;
|
||||
}
|
||||
|
||||
/** The same as `iptcForPhoto` for a photo already loaded with its event (many photos: one code list query). */
|
||||
export function iptcOf(
|
||||
photo: { capturedAt: Date | null; players: string[]; iptcOverrides: unknown },
|
||||
event: Event,
|
||||
photographer: string | null | undefined,
|
||||
codes: CodeList | undefined,
|
||||
): ApplyResult {
|
||||
const template = { ...IptcTemplate.parse(event.iptcTemplate), ...IptcTemplate.partial().parse(photo.iptcOverrides ?? {}) };
|
||||
const vars = buildVars(eventInfoOf(event), { capturedAt: photo.capturedAt ?? undefined, players: photo.players }, photographer ?? undefined);
|
||||
return applyTemplate(template, vars, codes);
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
import { applyRename } from "./rename.js";
|
||||
import { joinedEvent } from "./adopt.js";
|
||||
import { createReadStream } from "node:fs";
|
||||
import { PhotoBatchPatch } from "@photoreport/contracts";
|
||||
import { expandCodes, IptcTemplate, parseCodeList } from "@photoreport/metadata";
|
||||
@@ -95,8 +95,8 @@ export async function registerPhotoRoutes(
|
||||
if (patch.eventId !== undefined) data.eventId = patch.eventId;
|
||||
const result = await db.photo.updateMany({ where: { id: { in: ids }, organizationId: orgId }, data });
|
||||
if (result.count !== ids.length) throw notFound("photo_not_found");
|
||||
// Moved to another event: arrival names that use the event follow it.
|
||||
if (patch.eventId) for (const id of ids) await applyRename(db, id);
|
||||
// Moved to another event: arrival names, faces and the autopilot follow it.
|
||||
if (patch.eventId) await joinedEvent(db, patch.eventId, ids);
|
||||
broadcaster.library(orgId, { type: "photo.updated", ids, patch });
|
||||
return { updated: result.count };
|
||||
});
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
import type { PhotoSummary } from "@photoreport/contracts";
|
||||
import { deliveryState, type PhotoSummary } from "@photoreport/contracts";
|
||||
import type { Photo } from "../generated/prisma/client.js";
|
||||
import type { UrlSigner } from "../storage/storage.js";
|
||||
import { deliveredName } from "../delivery/service.js";
|
||||
|
||||
export type PhotoWithUploader = Photo & { uploader: { id: string; name: string } | null };
|
||||
export type PhotoWithUploader = Photo & { uploader: { id: string; name: string } | null; deliveries?: { status: string }[] };
|
||||
|
||||
export const photoInclude = { uploader: { select: { id: true, name: true } } } as const;
|
||||
export const photoInclude = { uploader: { select: { id: true, name: true } }, deliveries: { select: { status: true } } } as const;
|
||||
|
||||
export function toSummary(photo: PhotoWithUploader, signer: UrlSigner): PhotoSummary {
|
||||
return {
|
||||
@@ -16,6 +16,8 @@ export function toSummary(photo: PhotoWithUploader, signer: UrlSigner): PhotoSum
|
||||
sha256: photo.sha256,
|
||||
originalStored: photo.originalStored,
|
||||
status: photo.status,
|
||||
...(photo.status === "FAILED" && { error: photo.error }),
|
||||
...(photo.deliveries && { delivery: deliveryState(photo.deliveries.map((d) => d.status)) }),
|
||||
width: photo.width,
|
||||
height: photo.height,
|
||||
capturedAt: photo.capturedAt?.toISOString() ?? null,
|
||||
|
||||
@@ -78,6 +78,8 @@ export async function registerUploadRoutes(
|
||||
height: z.number().int().positive().max(100_000).optional(),
|
||||
})
|
||||
.optional(),
|
||||
/** A full original from the desktop app's ingest (its local FTP), not a hand upload. */
|
||||
desktop: z.boolean().optional(),
|
||||
});
|
||||
|
||||
app.post("/v1/orgs/:orgId/uploads/resumable", { preHandler: authenticate }, async (req, reply) => {
|
||||
@@ -106,7 +108,7 @@ export async function registerUploadRoutes(
|
||||
if (known && known.status !== "FAILED") return reply.code(200).send({ status: "duplicate", photo: toSummary(known, signer) });
|
||||
}
|
||||
const upload = await db.pendingUpload.create({
|
||||
data: { organizationId: orgId, userId, eventId: body.eventId ?? null, fileName: name, size: body.size, fingerprint: body.fingerprint, ...(body.original && { original: body.original }) },
|
||||
data: { organizationId: orgId, userId, eventId: body.eventId ?? null, fileName: name, size: body.size, fingerprint: body.fingerprint, ...(body.original && { original: body.original }), ...(body.desktop && { fromDesktop: true }) },
|
||||
});
|
||||
return reply.code(201).send({ id: upload.id, offset: 0, size: upload.size });
|
||||
});
|
||||
@@ -152,7 +154,7 @@ export async function registerUploadRoutes(
|
||||
const outcome = await ingest.ingest(partPath(id), {
|
||||
organizationId: upload.organizationId,
|
||||
userId: upload.userId,
|
||||
source: upload.original ? "DESKTOP" : "UPLOAD",
|
||||
source: upload.original || upload.fromDesktop ? "DESKTOP" : "UPLOAD",
|
||||
originalName: upload.fileName,
|
||||
eventId: upload.eventId ?? undefined,
|
||||
original: (upload.original as PreviewOf | null) ?? undefined,
|
||||
|
||||
@@ -71,6 +71,31 @@ export async function registerPrintRoutes(app: FastifyInstance, deps: { db: Db;
|
||||
}),
|
||||
);
|
||||
|
||||
/** Kiosk link for a tablet at the event: a new secret each time (shown once; the old link stops working). */
|
||||
app.post(
|
||||
"/v1/print-events/:id/kiosk",
|
||||
{ preHandler: authenticate },
|
||||
handle(async (req) => {
|
||||
const { id } = IdParams.parse(req.params);
|
||||
const e = await eventInOrg(req, id);
|
||||
await requireMembership(db, req, e.organizationId, "EDITOR");
|
||||
const token = await print.enableKiosk(e);
|
||||
return { path: `/e/${e.slug}/quiosque?k=${token}` };
|
||||
}),
|
||||
);
|
||||
|
||||
app.delete(
|
||||
"/v1/print-events/:id/kiosk",
|
||||
{ preHandler: authenticate },
|
||||
handle(async (req, reply) => {
|
||||
const { id } = IdParams.parse(req.params);
|
||||
const e = await eventInOrg(req, id);
|
||||
await requireMembership(db, req, e.organizationId, "EDITOR");
|
||||
await print.disableKiosk(e);
|
||||
return reply.code(204).send();
|
||||
}),
|
||||
);
|
||||
|
||||
app.get("/v1/print-events/:id/jobs", { preHandler: authenticate }, async (req) => {
|
||||
const { id } = IdParams.parse(req.params);
|
||||
await eventInOrg(req, id);
|
||||
@@ -214,6 +239,52 @@ export async function registerPrintRoutes(app: FastifyInstance, deps: { db: Db;
|
||||
}),
|
||||
);
|
||||
|
||||
// ---- kiosk (a tablet at the event, behind the kiosk link) ---------------------------------------
|
||||
|
||||
const KioskToken = z.string().min(16).max(64);
|
||||
const Copies = z.coerce.number().int().min(1).max(5).default(1);
|
||||
|
||||
app.get(
|
||||
"/v1/public/print/:slug/kiosk",
|
||||
handle(async (req) => {
|
||||
const { slug } = SlugParams.parse(req.params);
|
||||
const { k } = z.object({ k: KioskToken }).parse(req.query);
|
||||
return print.kioskView(slug, k);
|
||||
}),
|
||||
);
|
||||
|
||||
app.post(
|
||||
"/v1/public/print/:slug/kiosk/pick",
|
||||
{ config: { rateLimit: { max: 60, timeWindow: "1 minute" } } },
|
||||
handle(async (req, reply) => {
|
||||
const { slug } = SlugParams.parse(req.params);
|
||||
const body = z.object({ k: KioskToken, photoId: z.uuid(), name: z.string().trim().max(60).optional(), copies: Copies }).parse(req.body);
|
||||
const job = await print.kioskPrint(slug, body.k, { photoId: body.photoId }, { name: body.name || null, copies: body.copies });
|
||||
return reply.code(201).send({ id: job.id, status: job.status });
|
||||
}),
|
||||
);
|
||||
|
||||
/** The photobooth: a picture taken with the tablet's camera (multipart: `k`, optional `name` and `copies`, then `file`). */
|
||||
app.post(
|
||||
"/v1/public/print/:slug/kiosk/capture",
|
||||
{ config: { rateLimit: { max: 60, timeWindow: "1 minute" } } },
|
||||
handle(async (req, reply) => {
|
||||
const { slug } = SlugParams.parse(req.params);
|
||||
const fields: Record<string, string> = {};
|
||||
let data: Buffer | undefined;
|
||||
for await (const part of req.parts({ limits: { fileSize: MAX_UPLOAD, files: 1 } })) {
|
||||
if (part.type === "file") {
|
||||
data = await part.toBuffer();
|
||||
if (part.file.truncated) throw badRequest("file_too_large");
|
||||
} else fields[part.fieldname] = String(part.value);
|
||||
}
|
||||
if (!data) throw badRequest("file_missing");
|
||||
const k = KioskToken.parse(fields.k);
|
||||
const job = await print.kioskPrint(slug, k, { image: data }, { name: fields.name?.trim().slice(0, 60) || null, copies: Copies.parse(fields.copies ?? 1) });
|
||||
return reply.code(201).send({ id: job.id, status: job.status });
|
||||
}),
|
||||
);
|
||||
|
||||
// ---- the print agent ----------------------------------------------------------------------------
|
||||
|
||||
app.post(
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { createHash, randomBytes, randomInt } from "node:crypto";
|
||||
import { createHash, randomBytes, randomInt, timingSafeEqual } from "node:crypto";
|
||||
import {
|
||||
type AgentHeartbeat,
|
||||
type ClaimedJob,
|
||||
@@ -10,6 +10,7 @@ import {
|
||||
type PrinterSummary,
|
||||
type PublicPrintEvent,
|
||||
type StationSummary,
|
||||
type KioskView,
|
||||
} from "@photoreport/contracts";
|
||||
import type { Db } from "../db.js";
|
||||
import type { PrintEvent, PrintJob, PrintStation, Printer, Prisma } from "../generated/prisma/client.js";
|
||||
@@ -114,6 +115,7 @@ export class PrintService {
|
||||
template: PrintTemplate.parse(e.template ?? {}),
|
||||
galleryId: e.galleryId,
|
||||
printerId: e.printerId,
|
||||
kiosk: !!e.kioskTokenHash,
|
||||
counts: { waiting, printed },
|
||||
};
|
||||
}
|
||||
@@ -215,7 +217,7 @@ export class PrintService {
|
||||
}
|
||||
|
||||
/** Lays out the print file and queues it (or holds it for approval). */
|
||||
async createJob(event: PrintEvent, source: "GUEST" | "GALLERY" | "OPERATOR", image: string | Buffer, extra: { guestName?: string | null; guestKey?: string | null; photoId?: string | null; copies?: number }): Promise<PrintJob> {
|
||||
async createJob(event: PrintEvent, source: "GUEST" | "GALLERY" | "OPERATOR", image: string | Buffer, extra: { guestName?: string | null; guestKey?: string | null; photoId?: string | null; copies?: number; kiosk?: boolean }): Promise<PrintJob> {
|
||||
const { db, storage } = this.deps;
|
||||
let file: Buffer;
|
||||
try {
|
||||
@@ -236,7 +238,8 @@ export class PrintService {
|
||||
fileKey,
|
||||
size: event.size,
|
||||
copies: extra.copies ?? 1,
|
||||
status: source === "OPERATOR" ? "QUEUED" : event.priceCents > 0 ? "PAYMENT" : event.requireApproval ? "APPROVAL" : "QUEUED",
|
||||
// At the kiosk a paid print is paid at the counter: it waits for the operator's OK instead of Stripe.
|
||||
status: source === "OPERATOR" ? "QUEUED" : event.priceCents > 0 ? (extra.kiosk ? "APPROVAL" : "PAYMENT") : event.requireApproval ? "APPROVAL" : "QUEUED",
|
||||
guestName: extra.guestName ?? null,
|
||||
guestKey: extra.guestKey ?? null,
|
||||
},
|
||||
@@ -310,6 +313,67 @@ export class PrintService {
|
||||
return this.createJob(event, "GALLERY", await this.sourceFor(photo), { guestName: guest.name, guestKey: guest.key, photoId });
|
||||
}
|
||||
|
||||
// ---- kiosk ---------------------------------------------------------------------------------------
|
||||
|
||||
/** A new kiosk link secret (the old one stops working); only its hash is kept. */
|
||||
async enableKiosk(event: PrintEvent): Promise<string> {
|
||||
const token = randomBytes(18).toString("base64url");
|
||||
await this.deps.db.printEvent.update({ where: { id: event.id }, data: { kioskTokenHash: kioskHash(token) } });
|
||||
return token;
|
||||
}
|
||||
|
||||
async disableKiosk(event: PrintEvent): Promise<void> {
|
||||
await this.deps.db.printEvent.update({ where: { id: event.id }, data: { kioskTokenHash: null } });
|
||||
}
|
||||
|
||||
/** The event behind a kiosk link; a wrong or revoked secret is a 404, like an unknown event. */
|
||||
async kioskEvent(slug: string, token: string): Promise<{ event: PrintEvent; view: PublicPrintEvent }> {
|
||||
const found = await this.publicEvent(slug);
|
||||
const hash = found.event.kioskTokenHash;
|
||||
const given = kioskHash(token);
|
||||
if (!hash || hash.length !== given.length || !timingSafeEqual(Buffer.from(hash), Buffer.from(given))) throw new PrintError("event_not_found", 404);
|
||||
return found;
|
||||
}
|
||||
|
||||
private kioskKey(event: PrintEvent) {
|
||||
return `kiosk-${event.id}`;
|
||||
}
|
||||
|
||||
async kioskView(slug: string, token: string): Promise<KioskView> {
|
||||
const { event, view } = await this.kioskEvent(slug, token);
|
||||
const recent = await this.deps.db.printJob.findMany({
|
||||
where: { printEventId: event.id, guestKey: this.kioskKey(event), createdAt: { gt: new Date(Date.now() - 6 * 3600_000) } },
|
||||
orderBy: { createdAt: "desc" },
|
||||
take: 8,
|
||||
});
|
||||
const jobs = await Promise.all(
|
||||
recent.map(async (j) => ({
|
||||
id: j.id,
|
||||
status: j.status,
|
||||
guestName: j.guestName,
|
||||
ahead: j.status === "QUEUED" || j.status === "APPROVAL" ? await this.deps.db.printJob.count({ where: { printEventId: event.id, status: { in: ["QUEUED", "APPROVAL"] }, createdAt: { lt: j.createdAt } } }) : 0,
|
||||
preview: this.previewUrl(j),
|
||||
createdAt: j.createdAt.toISOString(),
|
||||
})),
|
||||
);
|
||||
return { ...view, payAtCounter: event.priceCents > 0, jobs };
|
||||
}
|
||||
|
||||
/**
|
||||
* A print from the kiosk: one of the photographer's photos, or a picture taken with the tablet's camera
|
||||
* (photobooth). The tablet is shared and staffed, so the per-guest limit doesn't apply.
|
||||
*/
|
||||
async kioskPrint(slug: string, token: string, what: { photoId: string } | { image: Buffer }, guest: { name: string | null; copies: number }): Promise<PrintJob> {
|
||||
const { db } = this.deps;
|
||||
const { event } = await this.kioskEvent(slug, token);
|
||||
if (!event.active) throw new PrintError("event_closed", 409);
|
||||
const common = { guestName: guest.name, guestKey: this.kioskKey(event), copies: guest.copies, kiosk: true };
|
||||
if ("image" in what) return this.createJob(event, "GUEST", what.image, common);
|
||||
if (!event.galleryId || !(await db.galleryPhoto.findUnique({ where: { galleryId_photoId: { galleryId: event.galleryId, photoId: what.photoId } } }))) throw new PrintError("photo_not_found", 404);
|
||||
const photo = await db.photo.findUniqueOrThrow({ where: { id: what.photoId } });
|
||||
return this.createJob(event, "GALLERY", await this.sourceFor(photo), { ...common, photoId: what.photoId });
|
||||
}
|
||||
|
||||
async guestJobs(slug: string, guestKey: string): Promise<GuestJob[]> {
|
||||
const { db } = this.deps;
|
||||
const event = await db.printEvent.findUnique({ where: { slug } });
|
||||
@@ -473,3 +537,5 @@ export class PrintService {
|
||||
return this.deps.storage.resolve(job.fileKey);
|
||||
}
|
||||
}
|
||||
|
||||
const kioskHash = (token: string) => createHash("sha256").update(token).digest("hex");
|
||||
@@ -62,7 +62,39 @@ export async function registerPublicShopRoutes(app: FastifyInstance, deps: { sho
|
||||
|
||||
app.get(
|
||||
"/v1/public/galleries",
|
||||
handle(async (req) => ({ galleries: await shop.publicGalleries(await siteOf(req)) })),
|
||||
handle(async (req) => {
|
||||
const filter = z.object({ q: z.string().trim().max(80).optional(), sport: z.string().trim().max(40).optional() }).parse(req.query);
|
||||
return shop.publicGalleries(await siteOf(req), { ...(filter.q && { q: filter.q }), ...(filter.sport && { sport: filter.sport }) });
|
||||
}),
|
||||
);
|
||||
|
||||
/** "Mais vistas": the galleries most visited lately. */
|
||||
app.get(
|
||||
"/v1/public/popular",
|
||||
handle(async (req) => {
|
||||
const { days, limit } = z.object({ days: z.coerce.number().int().min(1).max(90).default(7), limit: z.coerce.number().int().min(1).max(24).default(6) }).parse(req.query);
|
||||
return { galleries: await shop.popularGalleries(await siteOf(req), days, limit) };
|
||||
}),
|
||||
);
|
||||
|
||||
/** A visit to a gallery page, sent once per browser session (counts for "Mais vistas"). */
|
||||
app.post(
|
||||
"/v1/public/galleries/:slug/view",
|
||||
{ config: { rateLimit: { max: 30, timeWindow: "1 minute" } } },
|
||||
handle(async (req, reply) => {
|
||||
const { slug } = SlugParams.parse(req.params);
|
||||
await shop.countView(await siteOf(req), slug);
|
||||
return reply.code(204).send();
|
||||
}),
|
||||
);
|
||||
|
||||
/** "Últimas do jogo": the photos just put in the public galleries. */
|
||||
app.get(
|
||||
"/v1/public/latest",
|
||||
handle(async (req) => {
|
||||
const { limit } = z.object({ limit: z.coerce.number().int().min(1).max(60).default(24) }).parse(req.query);
|
||||
return { photos: await shop.latestPhotos(await siteOf(req), limit) };
|
||||
}),
|
||||
);
|
||||
|
||||
app.get(
|
||||
|
||||
+112
-18
@@ -1,6 +1,6 @@
|
||||
import { createHmac, randomBytes, timingSafeEqual } from "node:crypto";
|
||||
import { applyBundles, type BundleOffer, type CreateOrder, type GallerySummary, type OrderView, type ProductSummary, type PublicGallery, type PublicGallerySummary, type PublicPhoto, type SiteInfo, type Skin } from "@photoreport/contracts";
|
||||
import { createdStamp } from "@photoreport/metadata";
|
||||
import { applyBundles, type BundleOffer, type CreateOrder, type GallerySummary, type LatestPhoto, type OrderView, type PopularGallery, type ProductSummary, type PublicGallery, type PublicGallerySummary, type PublicPhoto, type SiteInfo, type Skin } from "@photoreport/contracts";
|
||||
import { createdStamp, type IptcValues } from "@photoreport/metadata";
|
||||
import { hashPassword, verifyPassword } from "../auth/passwords.js";
|
||||
import type { Db } from "../db.js";
|
||||
import { renderDelivery } from "../delivery/render.js";
|
||||
@@ -9,7 +9,7 @@ import type { SecretBox } from "../delivery/secrets.js";
|
||||
import type { DevelopService } from "../develop/service.js";
|
||||
import type { Event, Gallery, Order, OrderItem, Photo, Product, Site } from "../generated/prisma/client.js";
|
||||
import type { IngestLogger } from "../ingest/service.js";
|
||||
import { iptcForPhoto } from "../library/iptc.js";
|
||||
import { codeListOf, iptcForPhoto, iptcOf } from "../library/iptc.js";
|
||||
import type { LocalStorage, UrlSigner } from "../storage/storage.js";
|
||||
import { EU, formatOrderNumber, priceOrder, splitVat } from "./pricing.js";
|
||||
import { createCheckout, verifyWebhook } from "./stripe.js";
|
||||
@@ -17,6 +17,11 @@ import { LiveGalleries } from "./live.js";
|
||||
import { checkVies } from "./vies.js";
|
||||
import { watermarked } from "./watermark.js";
|
||||
|
||||
/** What the site shows under a photo: the delivered caption (or headline) and who to credit. */
|
||||
export function captionOf(values: IptcValues): { caption: string | null; credit: string | null } {
|
||||
return { caption: values.caption || values.headline || null, credit: values.creator || values.credit || values.copyright || null };
|
||||
}
|
||||
|
||||
/** Downloads left on a bought file (an order's limit of 0: none). */
|
||||
const under = (item: { downloads: number }, max: number) => max === 0 || item.downloads < max;
|
||||
|
||||
@@ -160,7 +165,7 @@ export class ShopService {
|
||||
}
|
||||
|
||||
private eventInfo(e: Event | null) {
|
||||
return e ? { home: e.home, away: e.away || null, competition: e.competition, venue: e.venue, startsAt: e.startsAt.toISOString() } : null;
|
||||
return e ? { home: e.home, away: e.away || null, sport: e.sport || null, competition: e.competition, venue: e.venue, startsAt: e.startsAt.toISOString() } : null;
|
||||
}
|
||||
|
||||
private async coverOf(site: Site, gallery: Gallery): Promise<string | null> {
|
||||
@@ -170,27 +175,110 @@ export class ShopService {
|
||||
return photo ? this.publicImageUrl(site.id, photo, "thumb") : null;
|
||||
}
|
||||
|
||||
async publicGalleries(site: Site): Promise<PublicGallerySummary[]> {
|
||||
const galleries = await this.deps.db.gallery.findMany({
|
||||
where: { organizationId: site.organizationId, visibility: "PUBLIC", publishedAt: { not: null } },
|
||||
/**
|
||||
* The site's public galleries, newest first. `q` looks in the title, the teams, the competition, the venue and the
|
||||
* players named in the photos; `sport` keeps one sport. `sports` lists the sports there are, for the shortcuts.
|
||||
*/
|
||||
async publicGalleries(site: Site, filter: { q?: string; sport?: string } = {}): Promise<{ galleries: PublicGallerySummary[]; sports: string[] }> {
|
||||
const { db } = this.deps;
|
||||
const base = { organizationId: site.organizationId, visibility: "PUBLIC" as const, publishedAt: { not: null } };
|
||||
const q = filter.q?.trim();
|
||||
let byPlayer: string[] = [];
|
||||
if (q) {
|
||||
const like = `%${q.replace(/[\\%_]/g, (c) => `\\${c}`)}%`;
|
||||
const rows = await db.$queryRaw<{ id: string }[]>`
|
||||
SELECT DISTINCT gp.gallery_id AS id FROM gallery_photos gp
|
||||
JOIN photos p ON p.id = gp.photo_id
|
||||
JOIN galleries g ON g.id = gp.gallery_id
|
||||
WHERE g.organization_id = ${site.organizationId}::uuid AND g.visibility = 'PUBLIC' AND g.published_at IS NOT NULL
|
||||
AND array_to_string(p.players, ' ') ILIKE ${like}
|
||||
LIMIT 200`;
|
||||
byPlayer = rows.map((r) => r.id);
|
||||
}
|
||||
const text = q ? { contains: q, mode: "insensitive" as const } : undefined;
|
||||
const galleries = await db.gallery.findMany({
|
||||
where: {
|
||||
...base,
|
||||
...(filter.sport && { event: { sport: { equals: filter.sport, mode: "insensitive" } } }),
|
||||
...(text && {
|
||||
OR: [{ title: text }, { event: { home: text } }, { event: { away: text } }, { event: { competition: text } }, { event: { venue: text } }, { id: { in: byPlayer } }],
|
||||
}),
|
||||
},
|
||||
include: { event: true, _count: { select: { photos: true } } },
|
||||
orderBy: { publishedAt: "desc" },
|
||||
take: 200,
|
||||
});
|
||||
const sports = await db.event.findMany({ where: { organizationId: site.organizationId, sport: { not: null }, galleries: { some: base } }, distinct: ["sport"], select: { sport: true } });
|
||||
return {
|
||||
galleries: await Promise.all(
|
||||
galleries.map((g) => this.publicSummary(site, g)),
|
||||
),
|
||||
sports: [...new Set(sports.map((e) => e.sport!.trim().toLowerCase()).filter(Boolean))].sort(),
|
||||
};
|
||||
}
|
||||
|
||||
private async publicSummary(site: Site, g: Gallery & { event: Event | null; _count: { photos: number } }): Promise<PublicGallerySummary> {
|
||||
return {
|
||||
slug: g.slug,
|
||||
title: g.title,
|
||||
description: g.description,
|
||||
visibility: g.visibility,
|
||||
photoCount: g._count.photos,
|
||||
cover: await this.coverOf(site, g),
|
||||
event: this.eventInfo(g.event),
|
||||
publishedAt: g.publishedAt!.toISOString(),
|
||||
live: g.live !== "OFF" && !!g.eventId,
|
||||
};
|
||||
}
|
||||
|
||||
/** One visit to a gallery's page (the site sends it once per browser session). */
|
||||
async countView(site: Site, slug: string, at = new Date()): Promise<void> {
|
||||
const g = await this.publishedGallery(site, slug);
|
||||
const day = at.toISOString().slice(0, 10);
|
||||
await this.deps.db.$executeRaw`
|
||||
INSERT INTO gallery_views (gallery_id, day, views) VALUES (${g.id}::uuid, ${day}::date, 1)
|
||||
ON CONFLICT (gallery_id, day) DO UPDATE SET views = gallery_views.views + 1`;
|
||||
}
|
||||
|
||||
/** The site's public galleries most visited over the last `days` days ("Mais vistas"). */
|
||||
async popularGalleries(site: Site, days = 7, limit = 6, now = new Date()): Promise<PopularGallery[]> {
|
||||
const { db } = this.deps;
|
||||
const since = new Date(now.getTime() - (days - 1) * 86_400_000);
|
||||
since.setUTCHours(0, 0, 0, 0);
|
||||
const counts = await db.galleryView.groupBy({
|
||||
by: ["galleryId"],
|
||||
where: { day: { gte: since }, gallery: { organizationId: site.organizationId, visibility: "PUBLIC", publishedAt: { not: null } } },
|
||||
_sum: { views: true },
|
||||
orderBy: { _sum: { views: "desc" } },
|
||||
take: limit,
|
||||
});
|
||||
if (!counts.length) return [];
|
||||
const galleries = await db.gallery.findMany({ where: { id: { in: counts.map((c) => c.galleryId) } }, include: { event: true, _count: { select: { photos: true } } } });
|
||||
const byId = new Map(galleries.map((g) => [g.id, g]));
|
||||
return Promise.all(
|
||||
galleries.map(async (g) => ({
|
||||
slug: g.slug,
|
||||
title: g.title,
|
||||
description: g.description,
|
||||
visibility: g.visibility,
|
||||
photoCount: g._count.photos,
|
||||
cover: await this.coverOf(site, g),
|
||||
event: this.eventInfo(g.event),
|
||||
publishedAt: g.publishedAt!.toISOString(),
|
||||
})),
|
||||
counts.flatMap((c) => {
|
||||
const g = byId.get(c.galleryId);
|
||||
return g ? [this.publicSummary(site, g).then((summary) => ({ ...summary, views: c._sum.views ?? 0 }))] : [];
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
/** The photos most recently put in the site's public galleries, newest first. */
|
||||
async latestPhotos(site: Site, limit = 24): Promise<LatestPhoto[]> {
|
||||
const rows = await this.deps.db.galleryPhoto.findMany({
|
||||
where: { gallery: { organizationId: site.organizationId, visibility: "PUBLIC", publishedAt: { not: null } }, photo: { status: "READY" } },
|
||||
orderBy: { addedAt: "desc" },
|
||||
take: limit,
|
||||
include: { photo: { select: { id: true, renderedSeq: true } }, gallery: { select: { slug: true, title: true, live: true, eventId: true } } },
|
||||
});
|
||||
return rows.map((r) => ({
|
||||
id: r.photo.id,
|
||||
thumb: this.publicImageUrl(site.id, r.photo, "thumb"),
|
||||
gallery: { slug: r.gallery.slug, title: r.gallery.title, live: r.gallery.live !== "OFF" && !!r.gallery.eventId },
|
||||
addedAt: r.addedAt.toISOString(),
|
||||
}));
|
||||
}
|
||||
|
||||
/** A published gallery the request may see (PRIVATE ones need the unlock token). */
|
||||
async openGallery(site: Site, slug: string, token?: string) {
|
||||
const g = await this.publishedGallery(site, slug);
|
||||
@@ -217,9 +305,15 @@ export class ShopService {
|
||||
}
|
||||
// Live galleries show the newest first: people come back to see what just arrived.
|
||||
const rows = open
|
||||
? await this.deps.db.galleryPhoto.findMany({ where: { galleryId: g.id, photo: { status: "READY" } }, orderBy: { position: live ? "desc" : "asc" }, include: { photo: true } })
|
||||
? await this.deps.db.galleryPhoto.findMany({
|
||||
where: { galleryId: g.id, photo: { status: "READY" } },
|
||||
orderBy: { position: live ? "desc" : "asc" },
|
||||
include: { photo: { include: { event: true, uploader: { select: { name: true } } } } },
|
||||
})
|
||||
: [];
|
||||
const codes = rows.length ? await codeListOf(this.deps.db, g.organizationId) : undefined;
|
||||
const photos: PublicPhoto[] = rows.map(({ photo }) => ({
|
||||
...captionOf(photo.event ? iptcOf(photo, photo.event, photo.uploader?.name, codes).values : {}),
|
||||
id: photo.id,
|
||||
width: photo.width,
|
||||
height: photo.height,
|
||||
|
||||
@@ -0,0 +1,125 @@
|
||||
import { afterAll, beforeAll, beforeEach, describe, expect, it } from "vitest";
|
||||
import { eventsOn, parseIcs, suggestionFor } from "../src/calendar/ics.js";
|
||||
import { isPublicAddress, normalizeCalendarUrl } from "../src/calendar/service.js";
|
||||
import { bearer, createTestApp, login, resetDb, seedUser, type TestContext } from "./helpers.js";
|
||||
|
||||
const KEY = Buffer.alloc(32, 7).toString("base64");
|
||||
|
||||
// Google writes UTC times, Outlook a TZID with Windows names, Apple a TZID with folded lines.
|
||||
const ICS = [
|
||||
"BEGIN:VCALENDAR",
|
||||
"VERSION:2.0",
|
||||
"BEGIN:VEVENT",
|
||||
"UID:press@google",
|
||||
"DTSTART:20261014T100000Z",
|
||||
"DTEND:20261014T110000Z",
|
||||
"SUMMARY:Conferência de imprensa do FC Porto",
|
||||
"LOCATION:Estádio do Dragão\\, Via Futebol Clube do Porto\\, 4350-415 Porto\\, Portugal",
|
||||
"DESCRIPTION:Antevisão do clássico.\\nLevar 70-200.",
|
||||
"BEGIN:VALARM",
|
||||
"TRIGGER:-PT30M",
|
||||
"DESCRIPTION:Lembrete",
|
||||
"END:VALARM",
|
||||
"END:VEVENT",
|
||||
"BEGIN:VEVENT",
|
||||
"UID:gala@outlook",
|
||||
'DTSTART;TZID="GMT Standard Time":20261014T213000',
|
||||
"SUMMARY:Gala do Desporto de Bra",
|
||||
" ga",
|
||||
"LOCATION:Theatro Circo, Braga",
|
||||
"END:VEVENT",
|
||||
"BEGIN:VEVENT",
|
||||
"UID:cancelled",
|
||||
"DTSTART:20261014T150000Z",
|
||||
"SUMMARY:Treino aberto",
|
||||
"STATUS:CANCELLED",
|
||||
"END:VEVENT",
|
||||
"BEGIN:VEVENT",
|
||||
"UID:allday",
|
||||
"DTSTART;VALUE=DATE:20261015",
|
||||
"DTEND;VALUE=DATE:20261016",
|
||||
"SUMMARY:Folga",
|
||||
"END:VEVENT",
|
||||
"END:VCALENDAR",
|
||||
].join("\r\n");
|
||||
|
||||
describe("agenda (iCal)", () => {
|
||||
it("reads Google, Outlook and Apple entries in Lisbon time and skips cancelled ones", () => {
|
||||
const events = parseIcs(ICS);
|
||||
expect(events.map((e) => e.summary)).toEqual(["Conferência de imprensa do FC Porto", "Gala do Desporto de Braga", "Folga"]);
|
||||
expect(events[1]!.start.toISOString()).toBe("2026-10-14T20:30:00.000Z");
|
||||
expect(events[0]!.description).toBe("Antevisão do clássico.\nLevar 70-200.");
|
||||
expect(eventsOn(events, "2026-10-14").map((e) => e.uid)).toEqual(["press@google", "gala@outlook"]);
|
||||
expect(eventsOn(events, "2026-10-15").map((e) => e.uid)).toEqual(["allday"]);
|
||||
expect(eventsOn(events, "2026-10-16")).toEqual([]);
|
||||
expect(() => parseIcs("<html>login</html>")).toThrow();
|
||||
});
|
||||
|
||||
it("suggests the name, venue, city and a caption to start from", () => {
|
||||
const [press, gala] = parseIcs(ICS);
|
||||
expect(suggestionFor(press!)).toEqual({ name: "Conferência de imprensa do FC Porto", venue: "Estádio do Dragão", city: "Porto", caption: "Conferência de imprensa do FC Porto, Estádio do Dragão, Porto." });
|
||||
expect(suggestionFor(gala!)).toMatchObject({ venue: "Theatro Circo", city: "Braga" });
|
||||
});
|
||||
|
||||
it("only fetches public https addresses", () => {
|
||||
expect(normalizeCalendarUrl("webcal://p01-caldav.icloud.com/published/2/abc").toString()).toBe("https://p01-caldav.icloud.com/published/2/abc");
|
||||
expect(() => normalizeCalendarUrl("http://calendar.google.com/x.ics")).toThrow();
|
||||
expect(() => normalizeCalendarUrl("file:///etc/passwd")).toThrow();
|
||||
for (const ip of ["127.0.0.1", "10.1.2.3", "192.168.1.10", "172.20.0.1", "169.254.169.254", "100.64.0.1", "::1", "fd00::1", "fe80::1", "::ffff:10.0.0.1"]) expect(isPublicAddress(ip)).toBe(false);
|
||||
for (const ip of ["142.250.184.14", "2a00:1450:4003::200e"]) expect(isPublicAddress(ip)).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe("agenda routes", () => {
|
||||
let ctx: TestContext;
|
||||
const fetched: string[] = [];
|
||||
const fakeFetch: typeof fetch = async (input) => {
|
||||
const url = String(input);
|
||||
fetched.push(url);
|
||||
if (url === "https://203.0.113.10/moved.ics") return new Response(null, { status: 302, headers: { location: "https://203.0.113.10/cal.ics" } });
|
||||
if (url === "https://203.0.113.10/inside.ics") return new Response(null, { status: 302, headers: { location: "https://127.0.0.1/admin" } });
|
||||
if (url === "https://203.0.113.10/cal.ics") return new Response(ICS, { headers: { "content-type": "text/calendar" } });
|
||||
if (url === "https://203.0.113.10/page") return new Response("<html></html>");
|
||||
return new Response("nope", { status: 404 });
|
||||
};
|
||||
|
||||
beforeAll(async () => {
|
||||
ctx = await createTestApp({ DELIVERY_SECRET_KEY: KEY }, undefined, fakeFetch);
|
||||
});
|
||||
afterAll(async () => {
|
||||
await ctx.app.close();
|
||||
await ctx.db.$disconnect();
|
||||
});
|
||||
beforeEach(async () => {
|
||||
await resetDb(ctx.db);
|
||||
fetched.length = 0;
|
||||
});
|
||||
|
||||
it("connects a calendar once, keeps it sealed, and lists a day's entries with suggestions", async () => {
|
||||
await seedUser(ctx.db, "[email protected]", { org: "photoreport", role: "OWNER" });
|
||||
const token = (await login(ctx.app, "[email protected]")).body.accessToken;
|
||||
const call = (method: "GET" | "PUT", url: string, payload?: object) => ctx.app.inject({ method, url, headers: bearer(token), ...(payload && { payload }) });
|
||||
|
||||
expect((await call("GET", "/v1/me/calendar")).json()).toEqual({ connected: false });
|
||||
expect((await call("GET", "/v1/me/calendar/events?date=2026-10-14")).json()).toEqual({ error: "calendar_not_connected" });
|
||||
expect((await call("PUT", "/v1/me/calendar", { url: "http://203.0.113.10/cal.ics" })).json()).toEqual({ error: "calendar_url" });
|
||||
expect((await call("PUT", "/v1/me/calendar", { url: "https://203.0.113.10/inside.ics" })).json()).toEqual({ error: "calendar_url" });
|
||||
expect((await call("PUT", "/v1/me/calendar", { url: "https://203.0.113.10/page" })).json()).toEqual({ error: "calendar_invalid" });
|
||||
expect(fetched).not.toContain("https://127.0.0.1/admin");
|
||||
|
||||
expect((await call("PUT", "/v1/me/calendar", { url: "webcal://203.0.113.10/moved.ics" })).json()).toEqual({ connected: true, events: 3 });
|
||||
const stored = await ctx.db.userPreferences.findFirstOrThrow({ select: { calendarUrl: true } });
|
||||
expect(stored.calendarUrl).toMatch(/^v1\./);
|
||||
expect(stored.calendarUrl).not.toContain("203.0.113.10");
|
||||
|
||||
const day = (await call("GET", "/v1/me/calendar/events?date=2026-10-14")).json() as { date: string; events: { title: string; start: string; suggestion: { venue: string | null } }[] };
|
||||
expect(day.date).toBe("2026-10-14");
|
||||
expect(day.events.map((e) => [e.title, e.start, e.suggestion.venue])).toEqual([
|
||||
["Conferência de imprensa do FC Porto", "2026-10-14T10:00:00.000Z", "Estádio do Dragão"],
|
||||
["Gala do Desporto de Braga", "2026-10-14T20:30:00.000Z", "Theatro Circo"],
|
||||
]);
|
||||
|
||||
expect((await call("PUT", "/v1/me/calendar", { url: null })).json()).toEqual({ connected: false, events: 0 });
|
||||
expect((await call("GET", "/v1/me/calendar")).json()).toEqual({ connected: false });
|
||||
});
|
||||
});
|
||||
@@ -61,6 +61,20 @@ describe("automatic crop", () => {
|
||||
expect(minCropWidth(2048, 1365)).toBe(1);
|
||||
});
|
||||
|
||||
it("frames the upper body near the middle, with the spare height above and not a strip of pitch below", () => {
|
||||
// A player kneeling in celebration, small in a wide frame (Braga x Sporting, October 2026).
|
||||
const kneeling = { ...person(0.41, 0.19, 0.58, 0.55), sharpness: 1 };
|
||||
const c = compose({ width: 6000, height: 4000, people: [kneeling], balls: [] }, null, { minWidth: 0.4 })!;
|
||||
const ch = c.rect.y1 - c.rect.y0;
|
||||
const below = (c.rect.y1 - kneeling.y1) / ch;
|
||||
const chest = (kneeling.y0 + 0.3 * (kneeling.y1 - kneeling.y0) - c.rect.y0) / ch;
|
||||
expect(below).toBeLessThanOrEqual(0.12);
|
||||
expect(chest).toBeGreaterThan(0.3);
|
||||
expect(chest).toBeLessThan(0.5);
|
||||
// Heads below the top edge, never touching it.
|
||||
expect((kneeling.y0 - c.rect.y0) / ch).toBeGreaterThanOrEqual(0.03);
|
||||
});
|
||||
|
||||
it("proposes nothing for an empty pitch or a distant crowd", () => {
|
||||
expect(compose({ ...frame, people: [person(0.1, 0.4, 0.13, 0.45), person(0.5, 0.4, 0.52, 0.46)], balls: [] })).toBeNull();
|
||||
});
|
||||
|
||||
@@ -202,6 +202,9 @@ describe("delivery", () => {
|
||||
|
||||
const list = await ctx.app.inject({ method: "GET", url: `/v1/orgs/${orgId}/deliveries?targetId=${target.id}`, headers: bearer(token) });
|
||||
expect((list.json() as { counts: Record<string, number> }).counts).toEqual({ DONE: 2 });
|
||||
// The library shows them as sent (the "Enviadas" / "Por enviar" filters).
|
||||
const photos = await ctx.app.inject({ method: "GET", url: `/v1/orgs/${orgId}/photos`, headers: bearer(token) });
|
||||
expect((photos.json() as { photos: { delivery: string }[] }).photos.map((p) => p.delivery)).toEqual(["DONE", "DONE"]);
|
||||
const again = await ctx.app.inject({ method: "POST", url: `/v1/orgs/${orgId}/deliveries`, headers: bearer(token), payload: { targetId: target.id, photoIds: [first] } });
|
||||
expect(again.json()).toMatchObject({ queued: [], skipped: [{ photoId: first, reason: "already_delivered" }] });
|
||||
const resend = await ctx.app.inject({ method: "POST", url: `/v1/orgs/${orgId}/deliveries`, headers: bearer(token), payload: { targetId: target.id, photoIds: [first], again: true } });
|
||||
|
||||
@@ -53,4 +53,21 @@ describe("desktop updates", () => {
|
||||
expect(await r.file(3, "PhotoReport_universal.app.tar.gz")).toBeNull();
|
||||
expect(await r.file(7, "update-darwin-universal.json")).toBeNull();
|
||||
});
|
||||
|
||||
it("keeps offering the last release built for a platform while a newer one is still building", async () => {
|
||||
const releases = [
|
||||
// 0.3.5: Linux done, the Mac still building (or switched off).
|
||||
{ id: 12, tag_name: "desktop-v0.3.5", draft: false, prerelease: false, body: "", published_at: null, assets: [asset(20, "update-linux-x86_64.json"), asset(21, "PhotoReport_0.3.5_amd64.AppImage")] },
|
||||
{ id: 11, tag_name: "desktop-v0.3.4", draft: false, prerelease: false, body: "Mac", published_at: null, assets: [asset(10, "update-darwin-universal.json"), asset(11, "PhotoReport.app.tar.gz")] },
|
||||
];
|
||||
const files = {
|
||||
"update-linux-x86_64.json": { version: "0.3.5", file: "PhotoReport_0.3.5_amd64.AppImage", signature: "dW50cnVzdGVkIGNvbW1lbnQ6IHNpZw==" },
|
||||
"update-darwin-universal.json": { version: "0.3.4", file: "PhotoReport.app.tar.gz", signature: "dW50cnVzdGVkIGNvbW1lbnQ6IHNpZw==" },
|
||||
"PhotoReport.app.tar.gz": "mac bytes",
|
||||
};
|
||||
const r = new DesktopReleases({ api: API, token: "t" }, fakeGitea(releases, files).impl);
|
||||
expect(await r.updateFor("linux", "x86_64", "0.3.2")).toMatchObject({ version: "0.3.5", url: "/v1/desktop/download/12/PhotoReport_0.3.5_amd64.AppImage" });
|
||||
expect(await r.updateFor("darwin", "aarch64", "0.3.2")).toMatchObject({ version: "0.3.4", url: "/v1/desktop/download/11/PhotoReport.app.tar.gz" });
|
||||
expect(await r.file(11, "PhotoReport.app.tar.gz")).not.toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,39 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { insideRotated } from "../src/composition/geometry.js";
|
||||
import { boxInCrop, cropOfSettings } from "../src/faces/frame.js";
|
||||
|
||||
describe("face boxes on edited previews", () => {
|
||||
it("leaves an uncropped photo alone", () => {
|
||||
const box = { x0: 0.2, y0: 0.2, x1: 0.3, y1: 0.35 };
|
||||
expect(boxInCrop(box, cropOfSettings({ crop: { geometry: { rect: { x0: 0, y0: 0, x1: 1, y1: 1 }, angle: 0 } } }), 6000, 4000)).toEqual(box);
|
||||
expect(cropOfSettings(null)).toBeNull();
|
||||
});
|
||||
|
||||
it("moves and scales the box into the crop, and drops faces left outside", () => {
|
||||
const crop = cropOfSettings({ crop: { geometry: { rect: { x0: 0.25, y0: 0.2, x1: 0.75, y1: 0.7 } } } })!;
|
||||
const inside = boxInCrop({ x0: 0.5, y0: 0.4, x1: 0.55, y1: 0.5 }, crop, 6000, 4000)!;
|
||||
expect(inside.x0).toBeCloseTo(0.5);
|
||||
expect(inside.y0).toBeCloseTo(0.4);
|
||||
expect(inside.x1).toBeCloseTo(0.6);
|
||||
expect(inside.y1).toBeCloseTo(0.6);
|
||||
expect(boxInCrop({ x0: 0.05, y0: 0.1, x1: 0.1, y1: 0.15 }, crop, 6000, 4000)).toBeNull();
|
||||
// Cut by the crop's edge: clipped.
|
||||
expect(boxInCrop({ x0: 0.2, y0: 0.3, x1: 0.3, y1: 0.4 }, crop, 6000, 4000)!.x0).toBe(0);
|
||||
});
|
||||
|
||||
it("follows the straighten angle the same way the crop is checked against the photo", () => {
|
||||
const crop = { rect: { x0: 0.1, y0: 0.1, x1: 0.9, y1: 0.9 }, angle: 5 };
|
||||
// A tiny box at a point of the original lands where insideRotated (straightened -> original) would send it back.
|
||||
const p = boxInCrop({ x0: 0.7, y0: 0.3, x1: 0.7, y1: 0.3 }, { rect: { x0: 0, y0: 0, x1: 1, y1: 1 }, angle: 5 }, 6000, 4000)!;
|
||||
expect(insideRotated({ x0: p.x0, y0: p.y0, x1: p.x0, y1: p.y0 }, 5, 6000, 4000)).toBe(true);
|
||||
const back = (() => {
|
||||
const a = (-5 * Math.PI) / 180;
|
||||
const px = p.x0 * 6000 - 3000;
|
||||
const py = p.y0 * 4000 - 2000;
|
||||
return [(px * Math.cos(a) - py * Math.sin(a) + 3000) / 6000, (px * Math.sin(a) + py * Math.cos(a) + 2000) / 4000];
|
||||
})();
|
||||
expect(back[0]).toBeCloseTo(0.7, 6);
|
||||
expect(back[1]).toBeCloseTo(0.3, 6);
|
||||
expect(boxInCrop({ x0: 0.45, y0: 0.45, x1: 0.55, y1: 0.55 }, crop, 6000, 4000)).not.toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -83,7 +83,7 @@ describe("faces", () => {
|
||||
|
||||
/** Ingests a photo with the given people's faces in it. */
|
||||
let n = 0;
|
||||
async function photo(taken: string, people: number[], sharpness: number | null = 200): Promise<string> {
|
||||
async function photo(taken: string, people: number[], sharpness: number | null | (number | null)[] = 200): Promise<string> {
|
||||
n++;
|
||||
const data = await sharp({ create: { width: 600, height: 400, channels: 3, background: { r: n % 256, g: (n * 7) % 256, b: (n * 13) % 256 } } })
|
||||
.jpeg()
|
||||
@@ -97,7 +97,7 @@ describe("faces", () => {
|
||||
engine.byColor.set(sha, {
|
||||
width: 600,
|
||||
height: 400,
|
||||
faces: people.map((p, i) => ({ x0: 0.1 + i * 0.2, y0: 0.2, x1: 0.18 + i * 0.2, y1: 0.32, score: 0.9, sharpness, landmarks: [], embedding: personVector(p, n) })),
|
||||
faces: people.map((p, i) => ({ x0: 0.1 + i * 0.2, y0: 0.2, x1: 0.18 + i * 0.2, y1: 0.32, score: 0.9, sharpness: Array.isArray(sharpness) ? sharpness[i]! : sharpness, landmarks: [], embedding: personVector(p, n) })),
|
||||
});
|
||||
const out = await ingest.ingestFile(file);
|
||||
if (out.status !== "ingested") throw new Error(JSON.stringify(out));
|
||||
@@ -125,6 +125,20 @@ describe("faces", () => {
|
||||
expect(await faces.claim(5)).toEqual([id]);
|
||||
});
|
||||
|
||||
it("queues photos left without analysis while biometrics are on, and leaves other organizations alone", async () => {
|
||||
await setup(true);
|
||||
const id = await photo("2026:09:23 21:00:00", [1]);
|
||||
expect(await faces.claim(5)).toEqual([id]);
|
||||
await drain();
|
||||
// A photo that slipped through as "no analysis" (it arrived while a toggle raced its ingest).
|
||||
await ctx.db.photo.update({ where: { id }, data: { facesStatus: "NONE" } });
|
||||
const other = await seedUser(ctx.db, "[email protected]", { org: "clube", role: "OWNER" });
|
||||
const theirs = await ctx.db.photo.create({ data: { organizationId: other.org!.id, source: "UPLOAD", originalName: "x.jpg", sha256: "f".repeat(64), byteSize: 1, storageKey: "x", status: "READY" } });
|
||||
expect(await faces.queueMissed()).toBe(1);
|
||||
expect((await ctx.db.photo.findUniqueOrThrow({ where: { id } })).facesStatus).toBe("PENDING");
|
||||
expect((await ctx.db.photo.findUniqueOrThrow({ where: { id: theirs.id } })).facesStatus).toBe("NONE");
|
||||
});
|
||||
|
||||
it("reads the faces again from the original when it replaces a desktop preview", async () => {
|
||||
const { orgId } = await setup();
|
||||
const user = await ctx.db.user.findFirstOrThrow();
|
||||
@@ -219,17 +233,19 @@ describe("faces", () => {
|
||||
expect((await list())[0]!.ignored).toBe(true);
|
||||
});
|
||||
|
||||
it("keeps blurred faces out of the groups, and says how many", async () => {
|
||||
it("only identifies faces in focus: not soft photos, not the blurred crowd behind a sharp player", async () => {
|
||||
const { token, day1 } = await setup();
|
||||
await photo("2026:09:23 21:00:00", [1]);
|
||||
await photo("2026:09:23 21:01:00", [1]);
|
||||
// The player sharp, two fans in the stand behind him out of focus (textured, but far softer).
|
||||
const withCrowd = await photo("2026:09:23 21:01:00", [1, 8, 9], [400, 60, 50]);
|
||||
await photo("2026:09:23 21:02:00", [8], 12);
|
||||
await photo("2026:09:23 21:03:00", [9], 12);
|
||||
await drain();
|
||||
const body = (await ctx.app.inject({ method: "GET", url: `/v1/events/${day1.id}/face-groups`, headers: bearer(token) })).json() as { groups: { size: number }[]; unclear: number };
|
||||
expect(body.groups.map((g) => g.size)).toEqual([2]);
|
||||
expect(body.unclear).toBe(2);
|
||||
expect(await ctx.db.face.count()).toBe(4);
|
||||
expect(await ctx.db.face.count()).toBe(2);
|
||||
const boxes = (await ctx.app.inject({ method: "GET", url: `/v1/photos/${withCrowd}/faces`, headers: bearer(token) })).json() as { faces: unknown[] };
|
||||
expect(boxes.faces).toHaveLength(1);
|
||||
});
|
||||
|
||||
it("learns a person from a reference photo and suggests them from the first match", async () => {
|
||||
|
||||
@@ -119,6 +119,25 @@ describe("library", () => {
|
||||
expect((await ctx.app.inject({ method: "GET", url: `/v1/events/${event.id}`, headers: bearer(other) })).statusCode).toBe(404);
|
||||
});
|
||||
|
||||
it("makes generic events: a name and no away team, the caption left to the editor", async () => {
|
||||
const { orgId, admin } = await setup();
|
||||
const created = await ctx.app.inject({
|
||||
method: "POST",
|
||||
url: `/v1/orgs/${orgId}/events`,
|
||||
headers: bearer(admin),
|
||||
payload: { home: "Conferência de imprensa do FC Porto", venue: "Estádio do Dragão", city: "Porto", startsAt: "2026-10-14T10:00:00Z" },
|
||||
});
|
||||
expect(created.statusCode).toBe(201);
|
||||
const event = created.json() as { id: string; away: string; title: string; iptcTemplate: Record<string, unknown> };
|
||||
expect(event).toMatchObject({ away: "", title: "Conferência de imprensa do FC Porto", iptcTemplate: { location: "{venue}" } });
|
||||
expect(event.iptcTemplate.caption).toBeUndefined();
|
||||
// Turning a match into another kind of event keeps its template; the caption still reads well.
|
||||
const match = (await ctx.app.inject({ method: "GET", url: `/v1/orgs/${orgId}/events`, headers: bearer(admin) })).json() as { events: { id: string; away: string }[] };
|
||||
const vsc = match.events.find((e) => e.away === "AAAS")!;
|
||||
const patched = await ctx.app.inject({ method: "PATCH", url: `/v1/events/${vsc.id}`, headers: bearer(admin), payload: { home: "Apresentação do plantel", away: "" } });
|
||||
expect(patched.json()).toMatchObject({ title: "Apresentação do plantel", away: "" });
|
||||
});
|
||||
|
||||
it("ingests an FTP upload into the right event, with previews and a live message", async () => {
|
||||
const { orgId, admin, event } = await setup();
|
||||
const file = await drop("foto.r1", "R1_04126.JPG", await jpeg());
|
||||
@@ -159,6 +178,41 @@ describe("library", () => {
|
||||
expect((inbox.json() as { total: number }).total).toBe(1);
|
||||
});
|
||||
|
||||
it("an event created (or moved) after its photos arrived claims them from the inbox, live", async () => {
|
||||
const { orgId, admin, photographer } = await setup();
|
||||
const early = await service.ingestFile(await drop("foto.r1", "early.jpg", await jpeg({ color: "#994400", taken: "2026:10:09 20:26:47" })));
|
||||
const later = await service.ingestFile(await drop("foto.r1", "later.jpg", await jpeg({ color: "#004499", taken: "2026:10:09 22:17:05" })));
|
||||
const elsewhere = await service.ingestFile(await drop("foto.r1", "other.jpg", await jpeg({ color: "#449900", taken: "2026:09:03 16:37:46" })));
|
||||
expect([early, later, elsewhere].map((o) => (o as { eventId: string | null }).eventId)).toEqual([null, null, null]);
|
||||
broadcaster.sent.length = 0;
|
||||
|
||||
const created = await ctx.app.inject({
|
||||
method: "POST",
|
||||
url: `/v1/orgs/${orgId}/events`,
|
||||
headers: bearer(admin),
|
||||
payload: { home: "SC Braga", away: "Sporting CP", startsAt: "2026-10-09T19:15:00Z", photographerIds: [photographer.id] },
|
||||
});
|
||||
expect(created.statusCode).toBe(201);
|
||||
const event = created.json() as { id: string; photoCount: number };
|
||||
expect(event.photoCount).toBe(2);
|
||||
const ids = [early, later].map((o) => (o as { photoId: string }).photoId);
|
||||
expect(broadcaster.sent.map((s) => s.message)).toContainEqual({ type: "photo.updated", ids: expect.arrayContaining(ids), patch: { eventId: event.id } });
|
||||
const inbox = await ctx.app.inject({ method: "GET", url: `/v1/orgs/${orgId}/photos?event=inbox`, headers: bearer(admin) });
|
||||
expect((inbox.json() as { photos: { id: string }[] }).photos.map((p) => p.id)).toEqual([(elsewhere as { photoId: string }).photoId]);
|
||||
|
||||
// Moving its time to cover the September photo claims that one too.
|
||||
const moved = await ctx.app.inject({ method: "PATCH", url: `/v1/events/${event.id}`, headers: bearer(admin), payload: { startsAt: "2026-09-03T15:00:00Z" } });
|
||||
expect((moved.json() as { photoCount: number }).photoCount).toBe(3);
|
||||
});
|
||||
|
||||
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")));
|
||||
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) });
|
||||
});
|
||||
|
||||
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")));
|
||||
|
||||
@@ -55,7 +55,7 @@ describe("printing", () => {
|
||||
async function setup(event: Record<string, unknown> = {}) {
|
||||
const { org } = await seedUser(ctx.db, "[email protected]", { org: "events", role: "OWNER" });
|
||||
const token = (await login(ctx.app, "[email protected]")).body.accessToken;
|
||||
const api = (method: "GET" | "POST" | "PATCH" | "PUT", url: string, payload?: unknown) => ctx.app.inject({ method, url, headers: bearer(token), ...(payload !== undefined && { payload: payload as object }) });
|
||||
const api = (method: "GET" | "POST" | "PATCH" | "PUT" | "DELETE", url: string, payload?: unknown) => ctx.app.inject({ method, url, headers: bearer(token), ...(payload !== undefined && { payload: payload as object }) });
|
||||
const created = await api("POST", `/v1/orgs/${org!.id}/print-events`, { name: "Casamento Ana & Rui", template: { bandText: "Ana & Rui · 11.10.2026" }, ...event });
|
||||
expect(created.statusCode).toBe(201);
|
||||
return { orgId: org!.id, api, event: created.json() as { id: string; slug: string } };
|
||||
@@ -85,6 +85,36 @@ describe("printing", () => {
|
||||
expect(broadcaster.sent.filter((s) => s.message.type === "print.updated")).toHaveLength(3);
|
||||
});
|
||||
|
||||
it("runs a kiosk on a tablet behind a secret link: gallery picks and photobooth shots, paid ones at the counter", async () => {
|
||||
const { event, api } = await setup({ guestLimit: 1, priceCents: 300 });
|
||||
expect((await ctx.app.inject({ method: "GET", url: `/v1/public/print/${event.slug}/kiosk?k=nothing-here-0123456789` })).statusCode).toBe(404);
|
||||
const { path: link } = (await api("POST", `/v1/print-events/${event.id}/kiosk`, {})).json() as { path: string };
|
||||
expect(link).toMatch(new RegExp(`^/e/${event.slug}/quiosque\\?k=[\\w-]{20,}$`));
|
||||
const k = link.split("k=")[1]!;
|
||||
expect((await api("GET", `/v1/orgs/${(await ctx.db.printEvent.findUniqueOrThrow({ where: { id: event.id } })).organizationId}/print-events`)).json().events[0]).toMatchObject({ kiosk: true });
|
||||
|
||||
const view = (await ctx.app.inject({ method: "GET", url: `/v1/public/print/${event.slug}/kiosk?k=${k}` })).json() as { payAtCounter: boolean; jobs: unknown[] };
|
||||
expect(view).toMatchObject({ payAtCounter: true, jobs: [] });
|
||||
|
||||
// Two shots from the camera: the guest limit doesn't apply to the shared tablet, and paid prints wait for the counter.
|
||||
const shot = async (name: string) => ctx.app.inject({ method: "POST", url: `/v1/public/print/${event.slug}/kiosk/capture`, ...multipart({ k, name, copies: "2" }, await photo("#aa3355")) });
|
||||
expect((await shot("Mesa 4")).json()).toMatchObject({ status: "APPROVAL" });
|
||||
expect((await shot("Mesa 7")).json()).toMatchObject({ status: "APPROVAL" });
|
||||
expect(stripeCalls).toHaveLength(0);
|
||||
const after = (await ctx.app.inject({ method: "GET", url: `/v1/public/print/${event.slug}/kiosk?k=${k}` })).json() as { jobs: { guestName: string; ahead: number }[] };
|
||||
expect(after.jobs.map((j) => j.guestName)).toEqual(["Mesa 7", "Mesa 4"]);
|
||||
expect(after.jobs.map((j) => j.ahead)).toEqual([1, 0]);
|
||||
expect((await api("GET", `/v1/print-events/${event.id}/jobs`)).json().jobs[0]).toMatchObject({ copies: 2 });
|
||||
|
||||
// A photo that isn't in the event's gallery is refused; a new link retires the old one, and switching off ends it.
|
||||
expect((await ctx.app.inject({ method: "POST", url: `/v1/public/print/${event.slug}/kiosk/pick`, payload: { k, photoId: "00000000-0000-4000-8000-000000000000" } })).json()).toMatchObject({ error: "photo_not_found" });
|
||||
const { path: second } = (await api("POST", `/v1/print-events/${event.id}/kiosk`, {})).json() as { path: string };
|
||||
expect((await ctx.app.inject({ method: "GET", url: `/v1/public/print/${event.slug}/kiosk?k=${k}` })).statusCode).toBe(404);
|
||||
expect((await ctx.app.inject({ method: "GET", url: `/v1/public/print/${event.slug}/kiosk?k=${second.split("k=")[1]}` })).statusCode).toBe(200);
|
||||
expect((await api("DELETE", `/v1/print-events/${event.id}/kiosk`)).statusCode).toBe(204);
|
||||
expect((await ctx.app.inject({ method: "GET", url: `/v1/public/print/${event.slug}/kiosk?k=${second.split("k=")[1]}` })).statusCode).toBe(404);
|
||||
});
|
||||
|
||||
it("holds jobs for approval when the event asks for it", async () => {
|
||||
const { event, api } = await setup({ requireApproval: true });
|
||||
const { id } = (await upload(event.slug)).json() as { id: string };
|
||||
|
||||
@@ -81,6 +81,21 @@ describe("resumable uploads", () => {
|
||||
expect((await ctx.app.inject({ method: "POST", url: `/v1/photos/${photo.id}/original/request`, headers: bearer(token) })).json()).toEqual({ stored: true });
|
||||
});
|
||||
|
||||
it("counts a full original from the desktop app's FTP as camera ingest (the autopilot edits it), not a hand upload", async () => {
|
||||
const { org } = await seedUser(ctx.db, "[email protected]", { org: "fpa", role: "PHOTOGRAPHER" });
|
||||
const token = (await login(ctx.app, "[email protected]")).body.accessToken;
|
||||
const t = new Date("2026-10-13T15:00:00Z");
|
||||
const event = await ctx.db.event.create({ data: { organizationId: org!.id, home: "ABC", away: "FCP", startsAt: t, ingestFrom: t, ingestUntil: t, iptcTemplate: {}, autopilot: { enabled: true } } });
|
||||
const send = async (name: string, extra: object) => {
|
||||
const jpeg = await sharp({ create: { width: 900, height: 600, channels: 3, noise: { type: "gaussian", mean: 128, sigma: 40 } } }).jpeg().toBuffer();
|
||||
const { id } = (await ctx.app.inject({ method: "POST", url: `/v1/orgs/${org!.id}/uploads/resumable`, headers: bearer(token), payload: { name, size: jpeg.length, fingerprint: `${name}:${jpeg.length}`, eventId: event.id, ...extra } })).json() as { id: string };
|
||||
const done = await ctx.app.inject({ method: "PUT", url: `/v1/uploads/${id}?offset=0`, headers: { ...bearer(token), "content-type": "application/offset+octet-stream" }, payload: jpeg });
|
||||
return ctx.db.photo.findUniqueOrThrow({ where: { id: (done.json() as { photo: { id: string } }).photo.id } });
|
||||
};
|
||||
expect(await send("FTP_0001.JPG", { desktop: true })).toMatchObject({ source: "DESKTOP", autopilotStatus: "PENDING" });
|
||||
expect(await send("HAND_0001.JPG", {})).toMatchObject({ source: "UPLOAD", autopilotStatus: "NONE" });
|
||||
});
|
||||
|
||||
it("a photo that failed (a damaged file) is replaced when it is sent again", async () => {
|
||||
const { org } = await seedUser(ctx.db, "[email protected]", { org: "fpa", role: "PHOTOGRAPHER" });
|
||||
const token = (await login(ctx.app, "[email protected]")).body.accessToken;
|
||||
|
||||
@@ -329,6 +329,63 @@ describe("shop", () => {
|
||||
expect((await ctx.app.inject({ method: "GET", url: view.zip!.replace(/t=.*/, "t=wrongwrongwrong") })).statusCode).toBe(404);
|
||||
});
|
||||
|
||||
it("finds galleries by team, competition or player, keeps one sport, and lists the latest photos", async () => {
|
||||
const s = await setup();
|
||||
const t = new Date("2026-10-11T17:00:00Z");
|
||||
const event = await ctx.db.event.create({ data: { organizationId: s.orgId, home: "ABC Braga", away: "CDE Gil Eanes", sport: "Andebol", competition: "Campeonato Betclic", startsAt: t, ingestFrom: t, ingestUntil: t, iptcTemplate: {} } });
|
||||
const handball = await gallery(s, { title: "Jornada 8" });
|
||||
await ctx.db.gallery.updateMany({ where: { slug: handball.slug }, data: { eventId: event.id } });
|
||||
const other = await gallery(s, { title: "Treino aberto" });
|
||||
await ctx.db.photo.update({ where: { id: s.photos[0]! }, data: { players: ["Diogo Branquinho"] } });
|
||||
|
||||
type List = { galleries: { slug: string; event: { sport: string | null } | null; live: boolean }[]; sports: string[] };
|
||||
const list = async (query = "") => (await pub("GET", `/v1/public/galleries${query}`)).json() as List;
|
||||
const all = await list();
|
||||
expect(all.sports).toEqual(["andebol"]);
|
||||
expect(all.galleries.find((g) => g.slug === handball.slug)).toMatchObject({ event: { sport: "Andebol" }, live: false });
|
||||
expect((await list("?q=gil%20eanes")).galleries.map((g) => g.slug)).toEqual([handball.slug]);
|
||||
expect((await list("?q=betclic")).galleries.map((g) => g.slug)).toEqual([handball.slug]);
|
||||
// Players are named in the photos, which are in both galleries here.
|
||||
expect((await list("?q=branquinho")).galleries.map((g) => g.slug).sort()).toEqual([handball.slug, other.slug].sort());
|
||||
expect((await list("?q=50%25")).galleries).toEqual([]);
|
||||
expect((await list("?sport=andebol")).galleries.map((g) => g.slug)).toEqual([handball.slug]);
|
||||
|
||||
const latest = (await pub("GET", "/v1/public/latest?limit=4")).json() as { photos: { thumb: string; gallery: { slug: string } }[] };
|
||||
expect(latest.photos).toHaveLength(4);
|
||||
expect(latest.photos[0]!.thumb).toContain("/v1/public/files/");
|
||||
});
|
||||
|
||||
it("counts gallery visits for \"Mais vistas\" and captions each photo as it is delivered", async () => {
|
||||
const s = await setup();
|
||||
const t = new Date("2026-10-11T17:00:00Z");
|
||||
const event = await ctx.db.event.create({
|
||||
data: { organizationId: s.orgId, home: "ABC Braga", away: "FC Porto", sport: "andebol", startsAt: t, ingestFrom: t, ingestUntil: t, iptcTemplate: { caption: "{home} x {away}", creator: "Agência / PhotoReport.pt" } },
|
||||
});
|
||||
await ctx.db.photo.updateMany({ where: { id: { in: s.photos } }, data: { eventId: event.id } });
|
||||
await ctx.db.photo.update({ where: { id: s.photos[1]! }, data: { iptcOverrides: { caption: "Golo de {players}" }, players: ["Rui Silva"] } });
|
||||
const quiet = await gallery(s, { title: "Treino" });
|
||||
const busy = await gallery(s, { title: "Final" });
|
||||
|
||||
expect((await pub("GET", "/v1/public/popular")).json()).toEqual({ galleries: [] });
|
||||
for (let i = 0; i < 3; i++) expect((await pub("POST", `/v1/public/galleries/${busy.slug}/view`)).statusCode).toBe(204);
|
||||
expect((await pub("POST", `/v1/public/galleries/${quiet.slug}/view`)).statusCode).toBe(204);
|
||||
expect((await pub("POST", "/v1/public/galleries/nao-existe/view")).statusCode).toBe(404);
|
||||
// Old visits fall out of the window.
|
||||
const g = await ctx.db.gallery.findFirstOrThrow({ where: { slug: quiet.slug } });
|
||||
await ctx.db.galleryView.create({ data: { galleryId: g.id, day: new Date("2020-01-01"), views: 100 } });
|
||||
|
||||
const popular = (await pub("GET", "/v1/public/popular")).json() as { galleries: { slug: string; views: number }[] };
|
||||
expect(popular.galleries.map((x) => [x.slug, x.views])).toEqual([
|
||||
[busy.slug, 3],
|
||||
[quiet.slug, 1],
|
||||
]);
|
||||
|
||||
const view = (await pub("GET", `/v1/public/galleries/${busy.slug}`)).json() as { photos: { id: string; caption: string | null; credit: string | null }[] };
|
||||
const byId = new Map(view.photos.map((p) => [p.id, p]));
|
||||
expect(byId.get(s.photos[0]!)).toMatchObject({ caption: "ABC Braga x FC Porto", credit: "Agência / PhotoReport.pt" });
|
||||
expect(byId.get(s.photos[1]!)).toMatchObject({ caption: "Golo de Rui Silva" });
|
||||
});
|
||||
|
||||
it("sells photo packages: N photos or the whole gallery at one price, applied to the cart by itself", async () => {
|
||||
const s = await setup();
|
||||
const g = await gallery(s, { title: "Final da Taça" });
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
"build": "tsc -p tsconfig.json --noEmit && vite build",
|
||||
"build": "tsc -p tsconfig.json --noEmit && vite build && node scripts/ui-manifest.mjs",
|
||||
"typecheck": "tsc -p tsconfig.json --noEmit",
|
||||
"test": "vitest run",
|
||||
"preview": "vite preview"
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
// Writes dist/ui-manifest.json after `vite build`: every file of the build with its size and SHA-256, the version and
|
||||
// when it was built. The desktop app keeps the interface on disk and reads this to download only what changed
|
||||
// (apps/desktop/src-tauri/src/ui.rs).
|
||||
import { createHash } from "node:crypto";
|
||||
import { readdir, readFile, stat, writeFile } from "node:fs/promises";
|
||||
import path from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
const NAME = "ui-manifest.json";
|
||||
const dist = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "../dist");
|
||||
|
||||
async function walk(dir) {
|
||||
const out = [];
|
||||
for (const entry of await readdir(dir, { withFileTypes: true })) {
|
||||
const full = path.join(dir, entry.name);
|
||||
if (entry.isDirectory()) out.push(...(await walk(full)));
|
||||
else if (entry.isFile()) out.push(full);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
const files = [];
|
||||
for (const full of (await walk(dist)).sort()) {
|
||||
const rel = path.relative(dist, full).split(path.sep).join("/");
|
||||
if (rel === NAME) continue;
|
||||
const bytes = await readFile(full);
|
||||
files.push({ path: rel, size: (await stat(full)).size, sha256: createHash("sha256").update(bytes).digest("hex") });
|
||||
}
|
||||
const content = createHash("sha256").update(files.map((f) => `${f.path}:${f.sha256}`).join("\n")).digest("hex").slice(0, 16);
|
||||
const manifest = { version: process.env.VITE_APP_VERSION?.slice(0, 40) || content, builtAt: new Date().toISOString(), files };
|
||||
await writeFile(path.join(dist, NAME), JSON.stringify(manifest));
|
||||
console.log(`${NAME}: ${files.length} files, version ${manifest.version}`);
|
||||
@@ -7,4 +7,8 @@ describe("apiUrlFor", () => {
|
||||
expect(apiUrlFor(undefined, { protocol: "https:", hostname: "app.next.photoreport.pt" })).toBe("https://api.next.photoreport.pt");
|
||||
expect(apiUrlFor(undefined, { protocol: "http:", hostname: "localhost" })).toBe("http://localhost:3000");
|
||||
});
|
||||
|
||||
it("inside the desktop app, uses the API the app names (its interface may be the web build)", () => {
|
||||
expect(apiUrlFor(undefined, { protocol: "tauri:", hostname: "localhost" }, { api: "https://api.next.photoreport.pt/", app: "https://app.next.photoreport.pt" })).toBe("https://api.next.photoreport.pt");
|
||||
});
|
||||
});
|
||||
+5
-3
@@ -1,11 +1,13 @@
|
||||
import { ApiClient } from "@photoreport/sdk";
|
||||
import { desktopRefreshStore, isDesktop } from "./platform.js";
|
||||
import { desktopConfig, desktopRefreshStore, isDesktop } from "./platform.js";
|
||||
|
||||
/**
|
||||
* Where the API is: VITE_API_URL when the build sets it (the desktop app always does); otherwise next to this page,
|
||||
* Where the API is: what the desktop app says; VITE_API_URL when the build sets it; otherwise next to this page,
|
||||
* app.<domain> -> api.<domain>, so a web build works on any environment without rebuilding for it.
|
||||
*/
|
||||
export function apiUrlFor(configured: string | undefined, location: { protocol: string; hostname: string } | undefined): string {
|
||||
export function apiUrlFor(configured: string | undefined, location: { protocol: string; hostname: string } | undefined, desktop = desktopConfig()): string {
|
||||
// The desktop app says where its API is (its interface may be a version downloaded from the web build).
|
||||
if (desktop?.api) return desktop.api.replace(/\/+$/, "");
|
||||
if (configured) return configured.replace(/\/+$/, "");
|
||||
if (location?.hostname.startsWith("app.")) return `${location.protocol}//api.${location.hostname.slice(4)}`;
|
||||
return "http://localhost:3000";
|
||||
|
||||
@@ -10,6 +10,44 @@ interface UpdateInfo {
|
||||
|
||||
const EVERY_MS = 6 * 3600_000;
|
||||
|
||||
type Listen = (event: string, handler: () => void) => Promise<() => void>;
|
||||
|
||||
const tauriListen: Listen = async (event, handler) => (await import("@tauri-apps/api/event")).listen(event, handler);
|
||||
|
||||
/**
|
||||
* Desktop only: a newer interface was downloaded in the background (apps/desktop/src-tauri/src/ui.rs). It is used
|
||||
* from the next start; reloading now switches straight away (nothing is lost: edits wait in the local queue).
|
||||
*/
|
||||
export function UiReadyNotice({ listen = tauriListen, enabled = isDesktop(), reload = () => window.location.reload() }: { listen?: Listen; enabled?: boolean; reload?: () => void }) {
|
||||
const [ready, setReady] = useState(false);
|
||||
const [dismissed, setDismissed] = useState(false);
|
||||
useEffect(() => {
|
||||
if (!enabled) return;
|
||||
let stop: (() => void) | undefined;
|
||||
let alive = true;
|
||||
listen("ui-ready", () => setReady(true)).then(
|
||||
(unlisten) => (alive ? (stop = unlisten) : unlisten()),
|
||||
() => {},
|
||||
);
|
||||
return () => {
|
||||
alive = false;
|
||||
stop?.();
|
||||
};
|
||||
}, [enabled, listen]);
|
||||
if (!ready || dismissed) return null;
|
||||
return (
|
||||
<div role="status" className="flex flex-wrap items-center gap-3 border-b border-black bg-[#1d2a3a] px-4 py-1.5 text-[12px] text-ink">
|
||||
<span>{t.update.uiReady}</span>
|
||||
<button className="ml-auto h-7 bg-accent px-3 text-[12px] font-semibold text-white hover:bg-accent-strong" onClick={reload}>
|
||||
{t.update.reload}
|
||||
</button>
|
||||
<button className="text-faint hover:text-ink" onClick={() => setDismissed(true)} aria-label={t.update.later}>
|
||||
{t.update.later}
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/** Desktop only: a new version of the app's shell, installed with one click (it restarts). */
|
||||
export function UpdateNotice({ invoke = desktopInvoke, enabled = isDesktop() }: { invoke?: Invoke; enabled?: boolean }) {
|
||||
const [update, setUpdate] = useState<UpdateInfo | null>(null);
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
import { fireEvent, render, screen, waitFor } from "@testing-library/react";
|
||||
import { act, fireEvent, render, screen, waitFor } from "@testing-library/react";
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import type { Invoke } from "../platform.js";
|
||||
import { type CatalogFolder, LocalCatalog, type ScanStatus } from "./LocalCatalog.js";
|
||||
import { UpdateNotice } from "./UpdateNotice.js";
|
||||
import { UiReadyNotice, UpdateNotice } from "./UpdateNotice.js";
|
||||
|
||||
describe("local catalogue", () => {
|
||||
it("adds a folder through the system picker, indexes it and shows the count", async () => {
|
||||
@@ -37,6 +37,22 @@ describe("local catalogue", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("interface update notice", () => {
|
||||
it("says when a newer interface is ready and reloads into it", async () => {
|
||||
let fire: () => void = () => {};
|
||||
const listen = vi.fn(async (_event: string, handler: () => void) => {
|
||||
fire = handler;
|
||||
return () => {};
|
||||
});
|
||||
const reload = vi.fn();
|
||||
render(<UiReadyNotice listen={listen} enabled reload={reload} />);
|
||||
await waitFor(() => expect(listen).toHaveBeenCalledWith("ui-ready", expect.any(Function)));
|
||||
act(() => fire());
|
||||
fireEvent.click(await screen.findByText("Recarregar agora"));
|
||||
expect(reload).toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe("update notice", () => {
|
||||
it("offers a newer shell and installs it", async () => {
|
||||
const invoke = vi.fn(async (cmd: string) => (cmd === "update_check" ? { version: "0.3.0", currentVersion: "0.2.0", notes: "Catálogo local" } : null)) as unknown as Invoke;
|
||||
|
||||
+62
-2
@@ -34,12 +34,28 @@ export const t = {
|
||||
soon: "Em breve",
|
||||
events: "Eventos",
|
||||
inbox: "Sem evento",
|
||||
moveToEvent: "Mover para evento",
|
||||
movedToEvent: (n: number, name: string) => `${n} ${n === 1 ? "foto movida" : "fotos movidas"} para ${name}`,
|
||||
newEvent: "Novo evento",
|
||||
noEvents: "Sem eventos. Cria o primeiro.",
|
||||
noPhotos: "Sem fotografias neste filtro.",
|
||||
noPhotosYet: "Ainda não chegaram fotografias. Assim que o FTP receber ficheiros, aparecem aqui.",
|
||||
filter: "Filtro",
|
||||
filters: { all: "Todas", PICK: "Escolhidas", UNREJECTED: "Sem rejeitadas", REJECT: "Rejeitadas", stars: "★ 3+", noPlayers: "Sem jogador" },
|
||||
flagFilter: { all: "Todas", PICK: "Escolhidas", UNFLAGGED: "Sem marca", UNREJECTED: "Sem rejeitadas", REJECT: "Rejeitadas" },
|
||||
starsAtLeast: "Estrelas (pelo menos)",
|
||||
starsOrMore: (n: number) => (n === 1 ? "1 estrela ou mais" : `${n} estrelas ou mais`),
|
||||
colorLabel: "Cor",
|
||||
colors: { RED: "Vermelho", YELLOW: "Amarelo", GREEN: "Verde", BLUE: "Azul", PURPLE: "Roxo" },
|
||||
deliveryFilter: "Envio:",
|
||||
deliveryStates: { any: "Todas", unsent: "Por enviar", queued: "A enviar", sent: "Enviadas", failed: "Com erro" },
|
||||
noPlayersFilter: "Sem jogador",
|
||||
clearFilter: "Limpar filtro",
|
||||
sendN: (n: number) => (n ? `Enviar ${n}` : "Enviar"),
|
||||
sendTo: "Enviar para",
|
||||
selectToSend: "Seleciona as fotografias a enviar (⌘A seleciona todas as do filtro).",
|
||||
setUpDelivery: "Configurar envio",
|
||||
noTargetsHelp: "Ainda não há destinos de envio (FTP da agência, pasta, etc.). Cria um em Entregar.",
|
||||
deliveryBadge: { QUEUED: "A enviar", DONE: "Enviada", FAILED: "Envio falhou" },
|
||||
shortcuts: "P escolher · X rejeitar · U limpar · 0–5 estrelas · 6–9 cor · I informação · E/Enter lupa · G/Esc grelha · D revelar",
|
||||
selected: (n: number) => (n === 1 ? "1 selecionada" : `${n} selecionadas`),
|
||||
ofTotal: (n: number, total: number) => `${n} de ${total}`,
|
||||
@@ -66,6 +82,18 @@ export const t = {
|
||||
logins: "Logins",
|
||||
addLogin: "+ Outro login",
|
||||
removeLogin: "Remover login",
|
||||
loginOn: "Ativo",
|
||||
loginOff: "desligado",
|
||||
check: "Testar ligação",
|
||||
checking: "A testar…",
|
||||
checkTitle: "Teste de ligação",
|
||||
checkOk: "responde",
|
||||
checkFail: "não responde",
|
||||
checkHelp: "O teste liga-se a este computador como uma câmara. Se responde aqui e a câmara não liga, confirma que a câmara está na mesma rede (o mesmo Wi-Fi ou hotspot) e que escreveste o endereço e a porta certos.",
|
||||
checkFailHelp: "O servidor não respondeu. Se tens outro servidor FTP aberto neste computador (ex.: o FTP Server), fecha-o ou usa outra porta: dois servidores na mesma porta roubam as ligações um ao outro.",
|
||||
checkOutdated: "Para testar a ligação, instala a versão nova da app de computador.",
|
||||
firewallBlockAll: "A firewall do macOS está a bloquear todas as ligações de entrada: a câmara não consegue ligar. Definições do Sistema → Rede → Firewall → Opções → desliga “Bloquear todas as ligações de entrada”.",
|
||||
firewallAppBlocked: "A firewall do macOS está a bloquear a PhotoReport: a câmara não consegue ligar. Definições do Sistema → Rede → Firewall → Opções → PhotoReport → “Permitir ligações de entrada”.",
|
||||
ingest: "Pasta ingest",
|
||||
workFolder: "Pasta de trabalho",
|
||||
workFolderHelp: "{year}, {date} (dia do evento, AAAAMMDD) e {event} são preenchidos; sem evento fica só o dia. ~ é a tua pasta pessoal.",
|
||||
@@ -93,6 +121,7 @@ export const t = {
|
||||
users: "Cada login precisa de utilizador e palavra-passe.",
|
||||
folders: "Indica a pasta ingest e a pasta de trabalho.",
|
||||
ingest_is_home: "A pasta ingest não pode ser a tua pasta pessoal inteira.",
|
||||
duplicate_user: "Há dois logins com o mesmo utilizador.",
|
||||
},
|
||||
outdated: "Esta versão da app de computador ainda não tem FTP local. Instala a versão nova (0.2 ou mais recente).",
|
||||
},
|
||||
@@ -210,6 +239,35 @@ export const t = {
|
||||
cancel: "Cancelar",
|
||||
create: "Criar",
|
||||
eventForm: {
|
||||
kind: "Tipo de evento",
|
||||
kindMatch: "Jogo",
|
||||
kindOther: "Evento genérico",
|
||||
caption: "Legenda (IPTC)",
|
||||
captionHelp: "Escreves tu a legenda. Se a deixares vazia, defines depois no modelo IPTC do evento.",
|
||||
agenda: {
|
||||
title: "Da tua agenda",
|
||||
empty: "Nada na agenda neste dia.",
|
||||
prev: "Dia anterior",
|
||||
next: "Dia seguinte",
|
||||
today: "Hoje",
|
||||
allDay: "dia todo",
|
||||
connect: "Ligar a minha agenda",
|
||||
connectHelp:
|
||||
"Cola o endereço secreto iCal do teu calendário. Google: Definições do calendário → Integrar calendário → Endereço secreto no formato iCal. iCloud: partilhar o calendário como público e copiar o link. Outlook: Definições → Calendários partilhados → Publicar → ICS.",
|
||||
address: "Endereço iCal",
|
||||
save: "Ligar",
|
||||
disconnect: "Desligar a agenda",
|
||||
connected: (n: number) => `Agenda ligada (${n} ${n === 1 ? "entrada" : "entradas"}).`,
|
||||
pickHelp: "Escolhe uma entrada para preencher o evento e sugerir a legenda (podes alterá-la).",
|
||||
errors: {
|
||||
calendar_url: "Esse endereço não serve: tem de ser o link https (ou webcal) do calendário.",
|
||||
calendar_unreachable: "Não foi possível abrir esse calendário. Confirma o link.",
|
||||
calendar_invalid: "Esse link não devolve um calendário iCal.",
|
||||
secrets_unavailable: "O servidor não tem a chave para guardar o link em segurança.",
|
||||
} as Record<string, string>,
|
||||
},
|
||||
name: "Nome do evento",
|
||||
namePlaceholder: "Ex.: Conferência de imprensa do FC Porto",
|
||||
home: "Equipa da casa",
|
||||
away: "Equipa visitante",
|
||||
venue: "Local",
|
||||
@@ -222,7 +280,7 @@ export const t = {
|
||||
startsAt: "Início",
|
||||
photographers: "Fotógrafos",
|
||||
pickMatch: "Escolher o jogo",
|
||||
pickMatchHelp: "Jogos da Liga Portugal, FPF e FPA dos próximos dias. Preenche o evento e junta os plantéis às pessoas.",
|
||||
pickMatchHelp: "Jogos da Liga Portugal, FPF e FPA dos próximos dias (ao pesquisar, também os das últimas duas semanas). Preenche o evento e junta os plantéis às pessoas.",
|
||||
searchMatch: "Equipa, competição ou pavilhão",
|
||||
noMatches: "Nenhum jogo encontrado.",
|
||||
linked: "Ligado ao jogo oficial",
|
||||
@@ -287,6 +345,8 @@ export const t = {
|
||||
installing: "A instalar…",
|
||||
failed: "Não foi possível instalar. Tenta mais tarde.",
|
||||
later: "Mais tarde",
|
||||
uiReady: "Nova versão da interface descarregada. Fica ativa ao recarregar (ou no próximo arranque).",
|
||||
reload: "Recarregar agora",
|
||||
},
|
||||
editorPanelsHelp: "Escolhe os painéis que queres ver ao editar. A escolha acompanha-te no web e no desktop.",
|
||||
saved: "Guardado",
|
||||
|
||||
@@ -0,0 +1,84 @@
|
||||
import { fireEvent, render, screen, waitFor } from "@testing-library/react";
|
||||
import type { ApiClient } from "@photoreport/sdk";
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import { EventForm, shiftDay } from "./EventForm.js";
|
||||
|
||||
describe("new event form", () => {
|
||||
it("makes a generic event: a name, no teams, no official match, the caption typed by hand", async () => {
|
||||
const createEvent = vi.fn(async () => ({ id: "e1" }));
|
||||
const sportsFixtures = vi.fn(async () => ({ fixtures: [] }));
|
||||
const api = { createEvent, sportsFixtures, listPeople: async () => ({ people: [] }), calendarStatus: async () => ({ connected: false }) } as unknown as ApiClient;
|
||||
const onCreated = vi.fn();
|
||||
render(<EventForm api={api} orgId="o1" onClose={() => undefined} onCreated={onCreated} />);
|
||||
expect(screen.getByLabelText("Equipa visitante")).toBeTruthy();
|
||||
|
||||
fireEvent.click(screen.getByRole("radio", { name: "Evento genérico" }));
|
||||
expect(screen.queryByLabelText("Equipa visitante")).toBeNull();
|
||||
expect(screen.queryByLabelText("Equipa, competição ou pavilhão")).toBeNull();
|
||||
expect(screen.queryByLabelText("Jornada")).toBeNull();
|
||||
fireEvent.change(screen.getByLabelText("Nome do evento"), { target: { value: "Conferência de imprensa do FC Porto" } });
|
||||
fireEvent.change(screen.getByLabelText("Local"), { target: { value: "Estádio do Dragão" } });
|
||||
fireEvent.change(screen.getByLabelText("Início"), { target: { value: "2026-10-14T11:00" } });
|
||||
fireEvent.change(screen.getByLabelText("Legenda (IPTC)"), { target: { value: "Sérgio Conceição na antevisão do clássico" } });
|
||||
fireEvent.submit(screen.getByLabelText("Nome do evento").closest("form")!);
|
||||
|
||||
await waitFor(() => expect(onCreated).toHaveBeenCalled());
|
||||
expect(createEvent).toHaveBeenCalledWith("o1", {
|
||||
home: "Conferência de imprensa do FC Porto",
|
||||
away: "",
|
||||
venue: "Estádio do Dragão",
|
||||
city: null,
|
||||
sport: "andebol",
|
||||
startsAt: "2026-10-14T10:00:00.000Z",
|
||||
photographerIds: [],
|
||||
iptcTemplate: expect.objectContaining({ caption: "Sérgio Conceição na antevisão do clássico", headline: "Sérgio Conceição na antevisão do clássico", location: "{venue}" }),
|
||||
});
|
||||
});
|
||||
|
||||
it("fills a generic event from the agenda and suggests the caption", async () => {
|
||||
const createEvent = vi.fn(async () => ({ id: "e1" }));
|
||||
const agenda = vi.fn(async (date?: string) => ({
|
||||
date: date ?? "2026-10-14",
|
||||
events: [
|
||||
{
|
||||
uid: "press",
|
||||
title: "Conferência de imprensa do FC Porto",
|
||||
start: "2026-10-14T10:00:00.000Z",
|
||||
end: null,
|
||||
allDay: false,
|
||||
location: "Estádio do Dragão, Porto",
|
||||
description: null,
|
||||
suggestion: { name: "Conferência de imprensa do FC Porto", venue: "Estádio do Dragão", city: "Porto", caption: "Conferência de imprensa do FC Porto, Estádio do Dragão, Porto." },
|
||||
},
|
||||
],
|
||||
}));
|
||||
const api = { createEvent, sportsFixtures: async () => ({ fixtures: [] }), listPeople: async () => ({ people: [] }), calendarStatus: async () => ({ connected: true }), agenda } as unknown as ApiClient;
|
||||
const onCreated = vi.fn();
|
||||
render(<EventForm api={api} orgId="o1" onClose={() => undefined} onCreated={onCreated} />);
|
||||
fireEvent.click(screen.getByRole("radio", { name: "Evento genérico" }));
|
||||
fireEvent.click(await screen.findByText("Conferência de imprensa do FC Porto"));
|
||||
expect((screen.getByLabelText("Nome do evento") as HTMLInputElement).value).toBe("Conferência de imprensa do FC Porto");
|
||||
expect((screen.getByLabelText("Cidade") as HTMLInputElement).value).toBe("Porto");
|
||||
expect((screen.getByLabelText("Início") as HTMLInputElement).value).toBe("2026-10-14T11:00");
|
||||
const caption = screen.getByLabelText("Legenda (IPTC)") as HTMLTextAreaElement;
|
||||
expect(caption.value).toBe("Conferência de imprensa do FC Porto, Estádio do Dragão, Porto.");
|
||||
fireEvent.change(caption, { target: { value: "Sérgio Conceição na antevisão do clássico" } });
|
||||
fireEvent.submit(caption.closest("form")!);
|
||||
await waitFor(() => expect(onCreated).toHaveBeenCalled());
|
||||
expect(createEvent).toHaveBeenCalledWith("o1", expect.objectContaining({ home: "Conferência de imprensa do FC Porto", venue: "Estádio do Dragão", iptcTemplate: expect.objectContaining({ caption: "Sérgio Conceição na antevisão do clássico" }) }));
|
||||
expect(shiftDay("2026-10-31", 1)).toBe("2026-11-01");
|
||||
});
|
||||
|
||||
it("searches the last two weeks too, for an event made after the match", async () => {
|
||||
const sportsFixtures = vi.fn(async (_q: { from: string; q?: string }) => ({ fixtures: [] }));
|
||||
const api = { createEvent: vi.fn(), sportsFixtures, listPeople: async () => ({ people: [] }), calendarStatus: async () => ({ connected: false }) } as unknown as ApiClient;
|
||||
render(<EventForm api={api} orgId="o1" onClose={() => undefined} onCreated={() => undefined} />);
|
||||
await waitFor(() => expect(sportsFixtures).toHaveBeenCalled());
|
||||
const hours = (q: { from: string }) => (Date.now() - Date.parse(q.from)) / 3600_000;
|
||||
expect(hours(sportsFixtures.mock.calls[0]![0])).toBeLessThan(13);
|
||||
fireEvent.change(screen.getByLabelText("Equipa, competição ou pavilhão"), { target: { value: "braga" } });
|
||||
await waitFor(() => expect(sportsFixtures.mock.calls.some(([q]) => q.q === "braga")).toBe(true));
|
||||
const search = sportsFixtures.mock.calls.find(([q]) => q.q === "braga")![0];
|
||||
expect(hours(search)).toBeGreaterThan(14 * 24 - 1);
|
||||
});
|
||||
});
|
||||
@@ -1,4 +1,5 @@
|
||||
import { ApiError, type ApiClient, type EventSummary, type SportsFixture } from "@photoreport/sdk";
|
||||
import { ApiError, type AgendaEntry, type ApiClient, type EventSummary, type SportsFixture } from "@photoreport/sdk";
|
||||
import { GENERAL_TEMPLATE } from "@photoreport/metadata";
|
||||
import { useEffect, useState } from "react";
|
||||
import { t } from "../i18n.js";
|
||||
|
||||
@@ -48,6 +49,15 @@ export function teamDisplayName(name: string): string {
|
||||
}
|
||||
|
||||
const FIELDS = ["home", "away", "venue", "city", "sport", "competition", "competitionCode", "round", "matchNumber"] as const;
|
||||
/** A generic event (press conference, gala, presentation): a name instead of two teams, the caption written by hand. */
|
||||
const OTHER_FIELDS = ["home", "venue", "city", "sport"] as const;
|
||||
type Kind = "match" | "other";
|
||||
|
||||
/** The generic event template with the caption (and headline) the editor typed. */
|
||||
export function genericTemplate(caption: string): Record<string, string | string[]> {
|
||||
const base = Object.fromEntries(Object.entries(GENERAL_TEMPLATE).filter(([, v]) => v !== undefined)) as Record<string, string | string[]>;
|
||||
return { ...base, caption, headline: caption };
|
||||
}
|
||||
|
||||
export function EventForm({ api, orgId, onClose, onCreated }: { api: ApiClient; orgId: string; onClose: () => void; onCreated: (e: EventSummary) => void }) {
|
||||
const [values, setValues] = useState<Record<string, string>>({ sport: "andebol" });
|
||||
@@ -57,6 +67,9 @@ export function EventForm({ api, orgId, onClose, onCreated }: { api: ApiClient;
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [match, setMatch] = useState<SportsFixture | null>(null);
|
||||
const [kind, setKind] = useState<Kind>("match");
|
||||
const [caption, setCaption] = useState("");
|
||||
const fields: readonly (typeof FIELDS)[number][] = kind === "match" ? FIELDS : OTHER_FIELDS;
|
||||
|
||||
useEffect(() => {
|
||||
api.listPeople(orgId).then((r) => setPeople(r.people), () => setPeople([]));
|
||||
@@ -83,14 +96,15 @@ export function EventForm({ api, orgId, onClose, onCreated }: { api: ApiClient;
|
||||
setBusy(true);
|
||||
setError(null);
|
||||
try {
|
||||
const input = Object.fromEntries(FIELDS.map((f) => [f, values[f]?.trim() || null]));
|
||||
const input = Object.fromEntries(fields.map((f) => [f, values[f]?.trim() || null]));
|
||||
const event = await api.createEvent(orgId, {
|
||||
...input,
|
||||
home: values.home?.trim() ?? "",
|
||||
away: values.away?.trim() ?? "",
|
||||
away: kind === "match" ? (values.away?.trim() ?? "") : "",
|
||||
startsAt: lisbonLocalToIso(startsAt),
|
||||
photographerIds: [...chosen],
|
||||
...(match && {
|
||||
...(kind === "other" && caption.trim() && { iptcTemplate: genericTemplate(caption.trim()) }),
|
||||
...(kind === "match" && match && {
|
||||
fixtureId: match.id,
|
||||
homeShort: match.home.abbreviation,
|
||||
awayShort: match.away.abbreviation,
|
||||
@@ -111,18 +125,64 @@ export function EventForm({ api, orgId, onClose, onCreated }: { api: ApiClient;
|
||||
<div className="panel-head">
|
||||
<span>{t.newEvent}</span>
|
||||
</div>
|
||||
<FixturePicker api={api} match={match} onPick={pick} onClear={() => setMatch(null)} />
|
||||
<div className="grid grid-cols-2 gap-3 p-4 max-sm:grid-cols-1">
|
||||
{FIELDS.map((f) => (
|
||||
<label key={f} className="block">
|
||||
<span className="mb-1 block text-[11px] text-faint">{t.eventForm[f]}</span>
|
||||
<input className={input} required={f === "home" || f === "away"} value={values[f] ?? ""} onChange={(e) => setValues({ ...values, [f]: e.target.value })} />
|
||||
</label>
|
||||
<div role="radiogroup" aria-label={t.eventForm.kind} className="flex gap-1.5 border-b border-line px-4 py-3">
|
||||
{(["match", "other"] as const).map((k) => (
|
||||
<button
|
||||
type="button"
|
||||
role="radio"
|
||||
key={k}
|
||||
aria-checked={kind === k}
|
||||
onClick={() => {
|
||||
setKind(k);
|
||||
if (k === "other") setMatch(null);
|
||||
}}
|
||||
className={`h-7 border px-3 text-[12px] ${kind === k ? "border-accent bg-accent text-white" : "border-black bg-cell text-muted hover:text-ink"}`}
|
||||
>
|
||||
{k === "match" ? t.eventForm.kindMatch : t.eventForm.kindOther}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
{kind === "match" && <FixturePicker api={api} match={match} onPick={pick} onClear={() => setMatch(null)} />}
|
||||
{kind === "other" && (
|
||||
<AgendaPicker
|
||||
api={api}
|
||||
day={startsAt ? startsAt.slice(0, 10) : null}
|
||||
onPick={(e) => {
|
||||
setValues({ ...values, home: e.suggestion.name, venue: e.suggestion.venue ?? "", city: e.suggestion.city ?? "" });
|
||||
setStartsAt(e.allDay ? `${isoToLisbonLocal(e.start).slice(0, 10)}T09:00` : isoToLisbonLocal(e.start));
|
||||
setCaption(e.suggestion.caption);
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
<div className="grid grid-cols-2 gap-3 p-4 max-sm:grid-cols-1">
|
||||
{fields.map((f) => {
|
||||
const isName = kind === "other" && f === "home";
|
||||
return (
|
||||
<label key={f} className={`block ${isName ? "col-span-2 max-sm:col-span-1" : ""}`}>
|
||||
<span className="mb-1 block text-[11px] text-faint">{isName ? t.eventForm.name : t.eventForm[f]}</span>
|
||||
<input
|
||||
className={input}
|
||||
required={f === "home" || f === "away"}
|
||||
placeholder={isName ? t.eventForm.namePlaceholder : undefined}
|
||||
value={values[f] ?? ""}
|
||||
onChange={(e) => setValues({ ...values, [f]: e.target.value })}
|
||||
/>
|
||||
</label>
|
||||
);
|
||||
})}
|
||||
<label className="block">
|
||||
<span className="mb-1 block text-[11px] text-faint">{t.eventForm.startsAt}</span>
|
||||
<input type="datetime-local" required className={input} value={startsAt} onChange={(e) => setStartsAt(e.target.value)} />
|
||||
</label>
|
||||
{kind === "other" && (
|
||||
<div className="col-span-2 max-sm:col-span-1">
|
||||
<label className="block">
|
||||
<span className="mb-1 block text-[11px] text-faint">{t.eventForm.caption}</span>
|
||||
<textarea rows={3} className={`${input} h-auto py-1.5`} value={caption} onChange={(e) => setCaption(e.target.value)} />
|
||||
</label>
|
||||
<p className="mt-1 text-[11px] text-faint">{t.eventForm.captionHelp}</p>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
{people.length > 0 && (
|
||||
<fieldset className="border-t border-line px-4 py-3">
|
||||
@@ -175,8 +235,10 @@ export function FixturePicker({ api, match, onPick, onClear }: { api: ApiClient;
|
||||
useEffect(() => {
|
||||
if (match) return;
|
||||
const timer = setTimeout(() => {
|
||||
const from = new Date(Date.now() - 12 * 3600_000).toISOString();
|
||||
api.sportsFixtures({ from, ...(q.trim() && { q: q.trim() }) }).then((r) => setList(r.fixtures), () => setList([]));
|
||||
// Upcoming games by default; a search also finds the last two weeks (an event made after the match).
|
||||
const from = new Date(Date.now() - (q.trim() ? 14 * 24 : 12) * 3600_000).toISOString();
|
||||
const to = new Date(Date.now() + 14 * 24 * 3600_000).toISOString();
|
||||
api.sportsFixtures({ from, ...(q.trim() && { q: q.trim(), to }) }).then((r) => setList(r.fixtures), () => setList([]));
|
||||
}, 250);
|
||||
return () => clearTimeout(timer);
|
||||
}, [api, q, match]);
|
||||
@@ -223,3 +285,136 @@ export function FixturePicker({ api, match, onPick, onClear }: { api: ApiClient;
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const dayFmt = new Intl.DateTimeFormat("pt-PT", { timeZone: "Europe/Lisbon", weekday: "long", day: "numeric", month: "long" });
|
||||
const hourFmt = new Intl.DateTimeFormat("pt-PT", { timeZone: "Europe/Lisbon", hour: "2-digit", minute: "2-digit" });
|
||||
|
||||
/** Today in Lisbon, "YYYY-MM-DD". */
|
||||
export function lisbonToday(now = new Date()): string {
|
||||
return isoToLisbonLocal(now.toISOString()).slice(0, 10);
|
||||
}
|
||||
|
||||
/** "YYYY-MM-DD" moved by whole days. */
|
||||
export function shiftDay(day: string, by: number): string {
|
||||
const d = new Date(`${day}T12:00:00Z`);
|
||||
d.setUTCDate(d.getUTCDate() + by);
|
||||
return d.toISOString().slice(0, 10);
|
||||
}
|
||||
|
||||
/** The person's agenda for a day: picking an entry fills the generic event and suggests its caption. */
|
||||
export function AgendaPicker({ api, day: wanted, onPick }: { api: ApiClient; day: string | null; onPick: (e: AgendaEntry) => void }) {
|
||||
const A = t.eventForm.agenda;
|
||||
const [connected, setConnected] = useState<boolean | null>(null);
|
||||
const [day, setDay] = useState(wanted ?? lisbonToday());
|
||||
const [entries, setEntries] = useState<AgendaEntry[] | null>(null);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [form, setForm] = useState<string | null>(null);
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [note, setNote] = useState<string | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
api.calendarStatus().then((r) => setConnected(r.connected), () => setConnected(false));
|
||||
}, [api]);
|
||||
useEffect(() => {
|
||||
if (wanted) setDay(wanted);
|
||||
}, [wanted]);
|
||||
useEffect(() => {
|
||||
if (!connected) return;
|
||||
let live = true;
|
||||
setEntries(null);
|
||||
api.agenda(day).then(
|
||||
(r) => live && setEntries(r.events),
|
||||
(err) => {
|
||||
if (!live) return;
|
||||
setEntries([]);
|
||||
setError(err instanceof ApiError ? (A.errors[err.code] ?? err.code) : t.unexpectedError);
|
||||
},
|
||||
);
|
||||
return () => {
|
||||
live = false;
|
||||
};
|
||||
}, [api, connected, day, A.errors]);
|
||||
|
||||
const connect = async (url: string | null) => {
|
||||
setBusy(true);
|
||||
setError(null);
|
||||
try {
|
||||
const r = await api.connectCalendar(url);
|
||||
setConnected(r.connected);
|
||||
setForm(null);
|
||||
setNote(r.connected ? A.connected(r.events) : null);
|
||||
} catch (err) {
|
||||
setError(err instanceof ApiError ? (A.errors[err.code] ?? err.code) : t.unexpectedError);
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
};
|
||||
|
||||
if (connected === null) return null;
|
||||
return (
|
||||
<div className="border-b border-line px-4 py-3 text-[12px]">
|
||||
{connected ? (
|
||||
<>
|
||||
<div className="mb-1 flex items-center gap-2">
|
||||
<span className="text-[11px] text-faint">{A.title}</span>
|
||||
<button type="button" aria-label={A.prev} onClick={() => setDay(shiftDay(day, -1))} className="px-1 text-muted hover:text-ink">
|
||||
‹
|
||||
</button>
|
||||
<span className="text-ink">{dayFmt.format(new Date(`${day}T12:00:00Z`))}</span>
|
||||
<button type="button" aria-label={A.next} onClick={() => setDay(shiftDay(day, 1))} className="px-1 text-muted hover:text-ink">
|
||||
›
|
||||
</button>
|
||||
{day !== lisbonToday() && (
|
||||
<button type="button" onClick={() => setDay(lisbonToday())} className="text-faint underline hover:text-ink">
|
||||
{A.today}
|
||||
</button>
|
||||
)}
|
||||
<button type="button" onClick={() => void connect(null)} className="ml-auto text-[11px] text-faint underline hover:text-ink">
|
||||
{A.disconnect}
|
||||
</button>
|
||||
</div>
|
||||
<ul className="max-h-40 overflow-y-auto">
|
||||
{entries?.length === 0 && <li className="py-1 text-faint">{A.empty}</li>}
|
||||
{entries?.map((e) => (
|
||||
<li key={e.uid}>
|
||||
<button type="button" onClick={() => onPick(e)} className="flex w-full items-baseline gap-2 px-1 py-1 text-left hover:bg-cell-on">
|
||||
<span className="w-16 shrink-0 font-mono text-[11px] text-faint">{e.allDay ? A.allDay : hourFmt.format(new Date(e.start))}</span>
|
||||
<span className="truncate text-ink">{e.title}</span>
|
||||
{e.location && <span className="ml-auto shrink-0 truncate text-[11px] text-faint">{e.suggestion.venue}</span>}
|
||||
</button>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
<p className="mt-1 text-[11px] text-faint">{note ?? A.pickHelp}</p>
|
||||
</>
|
||||
) : form === null ? (
|
||||
<button type="button" onClick={() => setForm("")} className="text-accent underline">
|
||||
{A.connect}
|
||||
</button>
|
||||
) : (
|
||||
<div>
|
||||
<label className="block">
|
||||
<span className="mb-1 block text-[11px] text-faint">{A.address}</span>
|
||||
<input
|
||||
type="url"
|
||||
value={form}
|
||||
onChange={(e) => setForm(e.target.value)}
|
||||
placeholder="https://calendar.google.com/calendar/ical/…/basic.ics"
|
||||
className="h-8 w-full border border-black bg-[#161617] px-2 text-[13px] text-ink focus:border-accent focus:outline-none"
|
||||
/>
|
||||
</label>
|
||||
<p className="mt-1 text-[11px] text-faint">{A.connectHelp}</p>
|
||||
<div className="mt-2 flex gap-2">
|
||||
<button type="button" disabled={busy || !form.trim()} onClick={() => void connect(form.trim())} className="h-7 bg-accent px-3 text-white disabled:opacity-50">
|
||||
{A.save}
|
||||
</button>
|
||||
<button type="button" onClick={() => setForm(null)} className="h-7 border border-black bg-cell px-3 text-muted hover:text-ink">
|
||||
{t.cancel}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
{error && <p className="mt-1 text-danger">{error}</p>}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
import type { ColorLabel } from "@photoreport/contracts";
|
||||
import { t } from "../i18n.js";
|
||||
import { LABEL_COLOR } from "./Grid.js";
|
||||
import { ALL_PHOTOS, isAll, type LibraryFilter } from "./store.js";
|
||||
|
||||
const FLAGS: LibraryFilter["flag"][] = ["all", "PICK", "UNFLAGGED", "UNREJECTED", "REJECT"];
|
||||
const DELIVERY: LibraryFilter["delivery"][] = ["any", "unsent", "queued", "sent", "failed"];
|
||||
const COLORS = ["RED", "YELLOW", "GREEN", "BLUE", "PURPLE"] as const satisfies readonly ColorLabel[];
|
||||
|
||||
const chip = (on: boolean) => (on ? "font-semibold text-ink" : "text-faint hover:text-muted");
|
||||
|
||||
/**
|
||||
* Photo Mechanic / Lightroom style filter bar: flag, stars (at least), colour, delivery state and photos without
|
||||
* players, all combinable. Clicking an active stars or colour choice again turns it off.
|
||||
*/
|
||||
export function FilterBar(props: { filter: LibraryFilter; onChange: (f: LibraryFilter) => void }) {
|
||||
const { filter: f, onChange } = props;
|
||||
const set = (patch: Partial<LibraryFilter>) => onChange({ ...f, ...patch });
|
||||
return (
|
||||
<div role="group" aria-label={t.filter} className="flex flex-wrap items-center gap-x-3 gap-y-1">
|
||||
<span className="text-faint">{t.filter}:</span>
|
||||
{FLAGS.map((flag) => (
|
||||
<button key={flag} onClick={() => set({ flag })} aria-pressed={f.flag === flag} className={chip(f.flag === flag)}>
|
||||
{t.flagFilter[flag]}
|
||||
</button>
|
||||
))}
|
||||
<span aria-hidden="true" className="text-line">|</span>
|
||||
<span className="flex items-center" role="group" aria-label={t.starsAtLeast}>
|
||||
{[1, 2, 3, 4, 5].map((n) => (
|
||||
<button
|
||||
key={n}
|
||||
onClick={() => set({ minRating: f.minRating === n ? 0 : n })}
|
||||
aria-pressed={f.minRating === n}
|
||||
aria-label={t.starsOrMore(n)}
|
||||
title={t.starsOrMore(n)}
|
||||
className={`px-[1px] text-[13px] ${n <= f.minRating ? "text-star" : "text-faint hover:text-muted"}`}
|
||||
>
|
||||
★
|
||||
</button>
|
||||
))}
|
||||
</span>
|
||||
<span className="flex items-center gap-1" role="group" aria-label={t.colorLabel}>
|
||||
{COLORS.map((c) => (
|
||||
<button
|
||||
key={c}
|
||||
onClick={() => set({ color: f.color === c ? null : c })}
|
||||
aria-pressed={f.color === c}
|
||||
aria-label={t.colors[c]}
|
||||
title={t.colors[c]}
|
||||
className={`h-3 w-3 rounded-[2px] ${f.color === c ? "outline outline-1 outline-offset-1 outline-white" : "opacity-60 hover:opacity-100"}`}
|
||||
style={{ background: LABEL_COLOR[c] ?? undefined }}
|
||||
/>
|
||||
))}
|
||||
</span>
|
||||
<span aria-hidden="true" className="text-line">|</span>
|
||||
<label className="flex items-center gap-1">
|
||||
<span className="text-faint">{t.deliveryFilter}</span>
|
||||
<select
|
||||
value={f.delivery}
|
||||
onChange={(e) => set({ delivery: e.target.value as LibraryFilter["delivery"] })}
|
||||
className={`h-6 border border-black bg-cell px-1 text-[12px] ${f.delivery === "any" ? "text-muted" : "text-ink"}`}
|
||||
>
|
||||
{DELIVERY.map((d) => (
|
||||
<option key={d} value={d}>
|
||||
{t.deliveryStates[d]}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
<button onClick={() => set({ noPlayers: !f.noPlayers })} aria-pressed={f.noPlayers} className={chip(f.noPlayers)}>
|
||||
{t.noPlayersFilter}
|
||||
</button>
|
||||
{!isAll(f) && (
|
||||
<button onClick={() => onChange(ALL_PHOTOS)} className="text-accent hover:underline">
|
||||
{t.clearFilter}
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
import type { ColorLabel, PhotoSummary } from "@photoreport/contracts";
|
||||
import { memo, useEffect, useRef } from "react";
|
||||
import { t } from "../i18n.js";
|
||||
|
||||
export const LABEL_COLOR: Record<ColorLabel, string | null> = {
|
||||
NONE: null,
|
||||
@@ -58,6 +59,15 @@ const Cell = memo(function Cell({ photo, index, src, selected, focused, onPick,
|
||||
</span>
|
||||
<span aria-hidden="true" className="h-2.5 w-2.5 rounded-[2px]" style={{ background: label ?? "transparent" }} />
|
||||
</span>
|
||||
{photo.delivery && photo.delivery !== "NONE" && (
|
||||
<span
|
||||
title={t.deliveryBadge[photo.delivery]}
|
||||
aria-label={t.deliveryBadge[photo.delivery]}
|
||||
className={`absolute left-1.5 top-1 text-[11px] font-bold ${photo.delivery === "DONE" ? "text-ok" : photo.delivery === "FAILED" ? "text-[#f0a35a]" : "text-[#7fb0ff]"}`}
|
||||
>
|
||||
{photo.delivery === "DONE" ? "✓" : photo.delivery === "FAILED" ? "!" : "↑"}
|
||||
</span>
|
||||
)}
|
||||
{photo.players.length > 0 && (
|
||||
<span className="absolute right-1.5 top-1 max-w-[70%] truncate text-[10px] text-muted">{photo.players[0]}</span>
|
||||
)}
|
||||
|
||||
@@ -50,9 +50,9 @@ describe("local FTP feed", () => {
|
||||
{ path: "/x/FTP/B.JPG", name: "B.JPG", size: 10, modifiedMs: 2 },
|
||||
]);
|
||||
const added: { name: string; eventId: string | undefined; size: number; sha?: string }[] = [];
|
||||
const add = (files: Iterable<File>, eventId?: string, onSettled?: (f: File, s: UploadStatus) => void, original?: { sha256: string }) => {
|
||||
const add = (files: Iterable<File>, eventId?: string, onSettled?: (f: File, s: UploadStatus) => void, original?: { sha256: string } | "original") => {
|
||||
for (const f of files) {
|
||||
added.push({ name: f.name, eventId, size: f.size, ...(original && { sha: original.sha256 }) });
|
||||
added.push({ name: f.name, eventId, size: f.size, ...(original && original !== "original" && { sha: original.sha256 }) });
|
||||
onSettled?.(f, f.name === "A.JPG" ? "done" : "failed");
|
||||
}
|
||||
};
|
||||
@@ -110,4 +110,29 @@ describe("local FTP feed", () => {
|
||||
await act(() => result.current.start());
|
||||
expect(result.current.error).toMatch(/2121/);
|
||||
});
|
||||
|
||||
it("checks the server answers after starting, and reports the macOS firewall", async () => {
|
||||
const invoke = vi.fn(async (cmd: string) => {
|
||||
if (cmd === "ftp_start") return status(true);
|
||||
if (cmd === "ftp_check") return { ...status(true), checks: [{ address: "192.168.25.250", ok: true, detail: "220 PhotoReport" }], firewall: "app_blocked" };
|
||||
if (cmd === "ftp_take") return [];
|
||||
return status(false);
|
||||
}) as unknown as Invoke;
|
||||
const { result } = renderHook(() => useLocalFtp(() => {}, true, invoke));
|
||||
await waitFor(() => expect(result.current.status).not.toBeNull());
|
||||
await act(() => result.current.start());
|
||||
await waitFor(() => expect(result.current.checkState).toBe("done"));
|
||||
expect(result.current.status?.checks).toEqual([{ address: "192.168.25.250", ok: true, detail: "220 PhotoReport" }]);
|
||||
expect(result.current.status?.firewall).toBe("app_blocked");
|
||||
});
|
||||
|
||||
it("says when the desktop app is too old to test the connection", async () => {
|
||||
const invoke = vi.fn(async (cmd: string) => {
|
||||
if (cmd === "ftp_check") throw "command ftp_check not found";
|
||||
return status(false);
|
||||
}) as unknown as Invoke;
|
||||
const { result } = renderHook(() => useLocalFtp(() => {}, true, invoke));
|
||||
await act(() => result.current.check());
|
||||
expect(result.current.checkState).toBe("unsupported");
|
||||
});
|
||||
});
|
||||
@@ -2,12 +2,13 @@ import type { EventSummary } from "@photoreport/sdk";
|
||||
import { useCallback, useEffect, useRef, useState } from "react";
|
||||
import { t } from "../i18n.js";
|
||||
import { asArrayBuffer, prefs } from "../platform.js";
|
||||
import type { PreviewOf, UploadStatus } from "./uploads.js";
|
||||
import type { DesktopOrigin, PreviewOf, UploadStatus } from "./uploads.js";
|
||||
|
||||
/** Settings kept by the desktop shell (apps/desktop/src-tauri/src/ftp.rs). */
|
||||
export interface FtpSettings {
|
||||
port: number;
|
||||
users: { name: string; password: string }[];
|
||||
/** `enabled` missing (older desktop app): on. */
|
||||
users: { name: string; password: string; enabled?: boolean }[];
|
||||
ingest: string;
|
||||
workFolder: string;
|
||||
autoStart: boolean;
|
||||
@@ -21,6 +22,10 @@ export interface FtpStatus {
|
||||
addresses: string[];
|
||||
waiting: number;
|
||||
error: string | null;
|
||||
/** The last self-test (desktop app 0.3.3+): does the server answer on each address. */
|
||||
checks?: { address: string; ok: boolean; detail: string }[];
|
||||
/** macOS firewall stopping cameras: "block_all" or "app_blocked". */
|
||||
firewall?: string | null;
|
||||
}
|
||||
|
||||
export interface IncomingFile {
|
||||
@@ -45,7 +50,7 @@ const tauriInvoke: Invoke = async (cmd, args) => (await import("@tauri-apps/api/
|
||||
const IN_FLIGHT = 6;
|
||||
const POLL_MS = 1000;
|
||||
|
||||
type Add = (files: Iterable<File>, eventId?: string, onSettled?: (file: File, status: UploadStatus) => void, original?: PreviewOf) => void;
|
||||
type Add = (files: Iterable<File>, eventId?: string, onSettled?: (file: File, status: UploadStatus) => void, original?: DesktopOrigin) => void;
|
||||
|
||||
export const eventLabel = (e: Pick<EventSummary, "title" | "home" | "away">) => e.title || [e.home, e.away].filter(Boolean).join(" x ");
|
||||
|
||||
@@ -76,6 +81,8 @@ export function useLocalFtp(add: Add, enabled: boolean, invoke: Invoke = tauriIn
|
||||
const [outdated, setOutdated] = useState(false);
|
||||
const [target, setTargetState] = useState<FtpTarget | null>(savedTarget);
|
||||
const [counts, setCounts] = useState({ received: 0, sent: 0, failed: 0 });
|
||||
/** null: never tested; "busy" while testing; "unsupported": the desktop app predates the test. */
|
||||
const [checkState, setCheckState] = useState<null | "busy" | "done" | "unsupported">(null);
|
||||
const backlog = useRef<IncomingFile[]>([]);
|
||||
const inFlight = useRef(0);
|
||||
const targetRef = useRef(target);
|
||||
@@ -103,6 +110,7 @@ export function useLocalFtp(add: Add, enabled: boolean, invoke: Invoke = tauriIn
|
||||
full ? Promise.resolve(undefined) : invoke<PreviewOf>("ftp_info", { path: f.path }),
|
||||
]);
|
||||
const file = new File([bytes], f.name, { type: "image/jpeg", lastModified: f.modifiedMs });
|
||||
// A full original from the camera still counts as FTP (the event's autopilot edits it), not a hand upload.
|
||||
add([file], to?.id, (_file, result) => {
|
||||
inFlight.current--;
|
||||
if (result === "done" || result === "duplicate") {
|
||||
@@ -112,7 +120,7 @@ export function useLocalFtp(add: Add, enabled: boolean, invoke: Invoke = tauriIn
|
||||
setCounts((c) => ({ ...c, failed: c.failed + 1 }));
|
||||
}
|
||||
pump();
|
||||
}, original);
|
||||
}, original ?? "original");
|
||||
} catch {
|
||||
inFlight.current--;
|
||||
setCounts((c) => ({ ...c, failed: c.failed + 1 }));
|
||||
@@ -172,14 +180,28 @@ export function useLocalFtp(add: Add, enabled: boolean, invoke: Invoke = tauriIn
|
||||
};
|
||||
}, [running, invoke, pump, refresh]);
|
||||
|
||||
/** Connects to the server from this computer's own addresses, like a camera, and reads the firewall. */
|
||||
const check = useCallback(async () => {
|
||||
setCheckState("busy");
|
||||
try {
|
||||
setStatus(await invoke<FtpStatus>("ftp_check"));
|
||||
setCheckState("done");
|
||||
} catch {
|
||||
setCheckState("unsupported");
|
||||
}
|
||||
}, [invoke]);
|
||||
|
||||
const start = useCallback(async () => {
|
||||
setError(null);
|
||||
try {
|
||||
setStatus(await invoke<FtpStatus>("ftp_start"));
|
||||
const s = await invoke<FtpStatus>("ftp_start");
|
||||
setStatus(s);
|
||||
// Give the listener a moment, then check it really answers.
|
||||
if (s.running) setTimeout(() => void check(), 400);
|
||||
} catch (err) {
|
||||
setError(settingsError(err));
|
||||
}
|
||||
}, [invoke]);
|
||||
}, [invoke, check]);
|
||||
|
||||
const stop = useCallback(async () => {
|
||||
try {
|
||||
@@ -216,7 +238,7 @@ export function useLocalFtp(add: Add, enabled: boolean, invoke: Invoke = tauriIn
|
||||
[invoke],
|
||||
);
|
||||
|
||||
return { status, error, outdated, target, setTarget, counts, start, stop, save, retry, openFolder };
|
||||
return { status, error, outdated, target, setTarget, counts, start, stop, save, retry, openFolder, check, checkState };
|
||||
}
|
||||
|
||||
type LocalFtpState = ReturnType<typeof useLocalFtp>;
|
||||
@@ -242,7 +264,8 @@ function SettingsForm({ ftp, initial, onDone }: { ftp: LocalFtpState; initial: F
|
||||
<div>
|
||||
<span className="text-[11px] uppercase tracking-wide text-faint">{L.logins}</span>
|
||||
{s.users.map((u, i) => (
|
||||
<div key={i} className="mt-1 flex gap-1">
|
||||
<div key={i} className="mt-1 flex items-center gap-1">
|
||||
<input type="checkbox" aria-label={`${L.loginOn}: ${u.name || L.user}`} title={L.loginOn} checked={u.enabled !== false} onChange={(e) => setUser(i, { enabled: e.target.checked })} />
|
||||
<input className={field} aria-label={L.user} placeholder={L.user} value={u.name} onChange={(e) => setUser(i, { name: e.target.value })} autoComplete="off" />
|
||||
<input className={field} aria-label={L.password} placeholder={L.password} value={u.password} onChange={(e) => setUser(i, { password: e.target.value })} autoComplete="off" />
|
||||
{s.users.length > 1 && (
|
||||
@@ -252,7 +275,7 @@ function SettingsForm({ ftp, initial, onDone }: { ftp: LocalFtpState; initial: F
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
<button type="button" onClick={() => setS({ ...s, users: [...s.users, { name: "", password: "" }] })} className="mt-1 text-accent underline">
|
||||
<button type="button" onClick={() => setS({ ...s, users: [...s.users, { name: "", password: "", enabled: true }] })} className="mt-1 text-accent underline">
|
||||
{L.addLogin}
|
||||
</button>
|
||||
</div>
|
||||
@@ -349,8 +372,9 @@ export function LocalFtpButton({ ftp, events, openEventId }: { ftp: LocalFtpStat
|
||||
{status.settings.users.map((u) => (
|
||||
<div key={u.name} className="contents">
|
||||
<dt className="text-faint">{L.user}</dt>
|
||||
<dd className="select-all text-ink">
|
||||
<dd className={`select-all ${u.enabled === false ? "text-faint line-through" : "text-ink"}`}>
|
||||
{u.name} <span className="text-faint">/</span> {u.password}
|
||||
{u.enabled === false && <span className="ml-1 font-sans no-underline">({L.loginOff})</span>}
|
||||
</dd>
|
||||
</div>
|
||||
))}
|
||||
@@ -411,12 +435,49 @@ export function LocalFtpButton({ ftp, events, openEventId }: { ftp: LocalFtpStat
|
||||
)}
|
||||
</div>
|
||||
{!running && <p className="mt-2 text-[11px] text-faint">{L.firewall}</p>}
|
||||
{running && <CheckResults ftp={ftp} port={status.settings.port} />}
|
||||
</>
|
||||
)
|
||||
)}
|
||||
{(ftp.error || status?.error) && <p className="mt-2 text-[#f0a35a]">{ftp.error ?? L.error}</p>}
|
||||
{(ftp.error || status?.error) && (
|
||||
<p className="mt-2 text-[#f0a35a]">
|
||||
{ftp.error ?? L.error}
|
||||
{!ftp.error && status?.error && <span className="block font-mono text-[11px]">{status.error}</span>}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/** The self-test: each address the camera can use, whether the server answered there, and firewall problems. */
|
||||
function CheckResults({ ftp, port }: { ftp: LocalFtpState; port: number }) {
|
||||
const L = t.localFtp;
|
||||
const { status, checkState } = ftp;
|
||||
const checks = status?.checks ?? [];
|
||||
const failed = checks.some((c) => !c.ok);
|
||||
return (
|
||||
<div className="mt-3 border-t border-line pt-2">
|
||||
<div className="mb-1 flex items-center justify-between">
|
||||
<span className="text-[11px] uppercase tracking-wide text-faint">{L.checkTitle}</span>
|
||||
<button onClick={() => void ftp.check()} disabled={checkState === "busy"} className="text-accent underline disabled:opacity-50">
|
||||
{checkState === "busy" ? L.checking : L.check}
|
||||
</button>
|
||||
</div>
|
||||
{checkState === "unsupported" && <p className="text-[11px] text-[#f0a35a]">{L.checkOutdated}</p>}
|
||||
{checks.length > 0 && (
|
||||
<ul className="font-mono text-[11px]">
|
||||
{checks.map((c) => (
|
||||
<li key={c.address} className={c.ok ? "text-[#4cc38a]" : "text-[#f0a35a]"} title={c.detail}>
|
||||
{c.ok ? "✓" : "✗"} {c.address}:{port} {c.ok ? L.checkOk : `${L.checkFail} (${c.detail})`}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
{status?.firewall === "block_all" && <p className="mt-1 text-[11px] text-[#f0a35a]">{L.firewallBlockAll}</p>}
|
||||
{status?.firewall === "app_blocked" && <p className="mt-1 text-[11px] text-[#f0a35a]">{L.firewallAppBlocked}</p>}
|
||||
{checkState === "done" && <p className="mt-1 text-[11px] text-faint">{failed ? L.checkFailHelp : L.checkHelp}</p>}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
import type { DeliveryItemSummary, PhotoSummary } from "@photoreport/contracts";
|
||||
import { ApiError, type ApiClient, type DeliveryTarget } from "@photoreport/sdk";
|
||||
import { useEffect, useState } from "react";
|
||||
import { useNavigate } from "react-router";
|
||||
import { t } from "../i18n.js";
|
||||
import { prefs } from "../platform.js";
|
||||
|
||||
const LAST_TARGET = "deliver.target";
|
||||
|
||||
/**
|
||||
* Photo Mechanic's Upload Photos, in the library's top bar: sends the selected photos (rejects never) to a
|
||||
* destination. With no destination yet it leads to where one is set up.
|
||||
*/
|
||||
export function SendButton(props: { api: ApiClient; orgId: string; selection: PhotoSummary[]; targets: DeliveryTarget[]; onQueued: (items: DeliveryItemSummary[]) => void }) {
|
||||
const { api, orgId, selection, targets } = props;
|
||||
const navigate = useNavigate();
|
||||
const [targetId, setTargetId] = useState(() => prefs.get(LAST_TARGET) ?? "");
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [note, setNote] = useState<string | null>(null);
|
||||
useEffect(() => {
|
||||
if (targets.length && !targets.some((x) => x.id === targetId)) setTargetId(targets[0]!.id);
|
||||
}, [targets, targetId]);
|
||||
useEffect(() => {
|
||||
if (!note) return;
|
||||
const timer = setTimeout(() => setNote(null), 5000);
|
||||
return () => clearTimeout(timer);
|
||||
}, [note]);
|
||||
|
||||
if (!targets.length) {
|
||||
return (
|
||||
<button onClick={() => navigate("/delivery")} title={t.noTargetsHelp} className="h-6 border border-black bg-cell px-2.5 text-[12px] text-ink hover:bg-cell-on">
|
||||
{t.setUpDelivery}
|
||||
</button>
|
||||
);
|
||||
}
|
||||
|
||||
const photos = selection.filter((p) => p.flag !== "REJECT" && p.status === "READY");
|
||||
const send = async () => {
|
||||
setBusy(true);
|
||||
try {
|
||||
const r = await api.deliver(orgId, targetId, photos.map((p) => p.id));
|
||||
prefs.set(LAST_TARGET, targetId);
|
||||
props.onQueued(r.queued);
|
||||
setNote(t.delivered(r.queued.length, r.skipped.length));
|
||||
} catch (err) {
|
||||
setNote(err instanceof ApiError ? err.code : t.unexpectedError);
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<span className="flex items-center gap-1">
|
||||
{targets.length > 1 && (
|
||||
<select aria-label={t.deliverTo} value={targetId} onChange={(e) => setTargetId(e.target.value)} className="h-6 max-w-[140px] border border-black bg-cell px-1 text-[12px] text-ink">
|
||||
{targets.map((x) => (
|
||||
<option key={x.id} value={x.id}>
|
||||
{x.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
)}
|
||||
<button
|
||||
onClick={() => void send()}
|
||||
disabled={busy || !photos.length || !targetId}
|
||||
title={photos.length ? `${t.sendTo} ${targets.find((x) => x.id === targetId)?.name ?? ""}` : t.selectToSend}
|
||||
className="h-6 bg-accent px-3 text-[12px] font-semibold text-white hover:bg-accent-strong disabled:opacity-40"
|
||||
>
|
||||
{t.sendN(photos.length)}
|
||||
</button>
|
||||
{note && <span className="text-[11px] text-ok">{note}</span>}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
import { beforeEach, describe, expect, it } from "vitest";
|
||||
import { activePhoto, savedFilter, saveFilter, setActivePhoto } from "./active.js";
|
||||
import { ALL_PHOTOS } from "./store.js";
|
||||
|
||||
describe("active photo across modules", () => {
|
||||
beforeEach(() => window.localStorage.clear());
|
||||
|
||||
it("remembers the photo you were on for its folder, and the library filter", () => {
|
||||
expect(activePhoto("o1", "e1")).toBeNull();
|
||||
setActivePhoto("o1", "e1", "p7");
|
||||
expect(activePhoto("o1", "e1")).toBe("p7");
|
||||
// Another folder (or organization) does not open on it.
|
||||
expect(activePhoto("o1", "e2")).toBeNull();
|
||||
expect(activePhoto("o2", "e1")).toBeNull();
|
||||
// Search results are not a folder to come back to.
|
||||
setActivePhoto("o1", "search:Rui", "p9");
|
||||
expect(activePhoto("o1", "e1")).toBe("p7");
|
||||
|
||||
expect(savedFilter("o1")).toEqual(ALL_PHOTOS);
|
||||
const picksToSend = { ...ALL_PHOTOS, flag: "PICK" as const, minRating: 2, delivery: "unsent" as const };
|
||||
saveFilter("o1", picksToSend);
|
||||
expect(savedFilter("o1")).toEqual(picksToSend);
|
||||
// A filter saved by the previous version (one choice) still opens.
|
||||
window.localStorage.setItem("pr.filter:o1", "stars");
|
||||
expect(savedFilter("o1")).toEqual({ ...ALL_PHOTOS, minRating: 3 });
|
||||
window.localStorage.setItem("pr.filter:o1", "nonsense");
|
||||
expect(savedFilter("o1")).toEqual(ALL_PHOTOS);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,67 @@
|
||||
import { prefs } from "../platform.js";
|
||||
import { ALL_PHOTOS, type LibraryFilter } from "./store.js";
|
||||
|
||||
/**
|
||||
* Lightroom's active photo: the one every module opens on. Library (grid and loupe) and Develop share it, so
|
||||
* going from one to the other (D, G, E or the module links) stays on the photo you were on. Kept per
|
||||
* organization with the folder (event, inbox) it belongs to, and survives a reload.
|
||||
*/
|
||||
interface ActivePhoto {
|
||||
scope: string;
|
||||
id: string;
|
||||
}
|
||||
|
||||
const activeKey = (orgId: string) => `active:${orgId}`;
|
||||
const filterKey = (orgId: string) => `filter:${orgId}`;
|
||||
|
||||
/** The active photo of that folder, if there is one. */
|
||||
export function activePhoto(orgId: string, scope: string | null | undefined): string | null {
|
||||
if (!orgId || !scope) return null;
|
||||
try {
|
||||
const v = JSON.parse(prefs.get(activeKey(orgId)) ?? "null") as ActivePhoto | null;
|
||||
return v && typeof v.id === "string" && v.scope === scope ? v.id : null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export function setActivePhoto(orgId: string, scope: string | null | undefined, id: string | null | undefined): void {
|
||||
if (!orgId || !scope || !id || scope.startsWith("search:")) return;
|
||||
prefs.set(activeKey(orgId), JSON.stringify({ scope, id } satisfies ActivePhoto));
|
||||
}
|
||||
|
||||
/** Filters saved by earlier versions (one choice at a time). */
|
||||
const LEGACY: Record<string, Partial<LibraryFilter>> = {
|
||||
all: {},
|
||||
PICK: { flag: "PICK" },
|
||||
UNREJECTED: { flag: "UNREJECTED" },
|
||||
REJECT: { flag: "REJECT" },
|
||||
stars: { minRating: 3 },
|
||||
noPlayers: { noPlayers: true },
|
||||
};
|
||||
const FLAGS = ["all", "PICK", "UNREJECTED", "REJECT", "UNFLAGGED"];
|
||||
const DELIVERY = ["any", "unsent", "queued", "sent", "failed"];
|
||||
const COLORS = ["RED", "YELLOW", "GREEN", "BLUE", "PURPLE"];
|
||||
|
||||
/** The library filter, which Develop's filmstrip follows too (as Lightroom's filmstrip does). */
|
||||
export function savedFilter(orgId: string): LibraryFilter {
|
||||
const raw = prefs.get(filterKey(orgId));
|
||||
if (!raw) return ALL_PHOTOS;
|
||||
if (raw in LEGACY) return { ...ALL_PHOTOS, ...LEGACY[raw] };
|
||||
try {
|
||||
const v = JSON.parse(raw) as Partial<LibraryFilter>;
|
||||
return {
|
||||
flag: FLAGS.includes(v.flag as string) ? v.flag! : "all",
|
||||
minRating: Number.isInteger(v.minRating) && v.minRating! >= 0 && v.minRating! <= 5 ? v.minRating! : 0,
|
||||
color: COLORS.includes(v.color as string) ? v.color! : null,
|
||||
delivery: DELIVERY.includes(v.delivery as string) ? v.delivery! : "any",
|
||||
noPlayers: v.noPlayers === true,
|
||||
};
|
||||
} catch {
|
||||
return ALL_PHOTOS;
|
||||
}
|
||||
}
|
||||
|
||||
export function saveFilter(orgId: string, filter: LibraryFilter): void {
|
||||
if (orgId) prefs.set(filterKey(orgId), JSON.stringify(filter));
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
import type { PhotoSummary } from "@photoreport/contracts";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { initialLibrary, libraryReducer, matchesFilter, patchForKey } from "./store.js";
|
||||
import { ALL_PHOTOS, initialLibrary, type LibraryFilter, libraryReducer, matchesFilter, patchForKey } from "./store.js";
|
||||
|
||||
const photo = (id: string, capturedAt: string, extra: Partial<PhotoSummary> = {}): PhotoSummary => ({
|
||||
id,
|
||||
@@ -60,7 +60,49 @@ describe("library store", () => {
|
||||
expect(patchForKey("4")).toEqual({ rating: 4 });
|
||||
expect(patchForKey("6")).toEqual({ colorLabel: "RED" });
|
||||
expect(patchForKey("q")).toBeUndefined();
|
||||
expect(matchesFilter(photo("a", "", { flag: "REJECT" }), "UNREJECTED")).toBe(false);
|
||||
expect(matchesFilter(photo("a", "", { players: ["x"] }), "noPlayers")).toBe(false);
|
||||
const f = (patch: Partial<LibraryFilter>) => ({ ...ALL_PHOTOS, ...patch });
|
||||
expect(matchesFilter(photo("a", "", { flag: "REJECT" }), f({ flag: "UNREJECTED" }))).toBe(false);
|
||||
expect(matchesFilter(photo("a", "", { players: ["x"] }), f({ noPlayers: true }))).toBe(false);
|
||||
});
|
||||
|
||||
it("combines filters as Photo Mechanic does: picks with 2+ stars not sent yet", () => {
|
||||
const toSend = { ...ALL_PHOTOS, flag: "PICK" as const, minRating: 2, delivery: "unsent" as const };
|
||||
expect(matchesFilter(photo("a", "", { flag: "PICK", rating: 3 }), toSend)).toBe(true);
|
||||
expect(matchesFilter(photo("a", "", { flag: "PICK", rating: 3, delivery: "DONE" }), toSend)).toBe(false);
|
||||
expect(matchesFilter(photo("a", "", { flag: "PICK", rating: 1 }), toSend)).toBe(false);
|
||||
expect(matchesFilter(photo("a", "", { flag: "NONE", rating: 5 }), toSend)).toBe(false);
|
||||
expect(matchesFilter(photo("a", "", { colorLabel: "RED" }), { ...ALL_PHOTOS, color: "GREEN" })).toBe(false);
|
||||
expect(matchesFilter(photo("a", "", { delivery: "FAILED" }), { ...ALL_PHOTOS, delivery: "failed" })).toBe(true);
|
||||
});
|
||||
|
||||
it("follows deliveries live: on its way, then sent (a later failure elsewhere doesn't undo sent)", () => {
|
||||
const item = (status: "QUEUED" | "DONE" | "FAILED") => ({ id: "i", targetId: "t", photoId: "a", eventId: "e1", sequence: 1, status, attempts: 0, lastError: null, remotePath: null, byteSize: null, updatedAt: "" });
|
||||
let s = libraryReducer(initialLibrary, { type: "load", scope: "e1" });
|
||||
s = libraryReducer(s, { type: "loaded", scope: "e1", photos: [photo("a", "1")], done: true });
|
||||
s = libraryReducer(s, { type: "message", message: { type: "delivery.updated", item: item("QUEUED") } });
|
||||
expect(s.photos[0]!.delivery).toBe("QUEUED");
|
||||
s = libraryReducer(s, { type: "message", message: { type: "delivery.updated", item: item("DONE") } });
|
||||
s = libraryReducer(s, { type: "message", message: { type: "delivery.updated", item: item("FAILED") } });
|
||||
expect(s.photos[0]!.delivery).toBe("DONE");
|
||||
});
|
||||
|
||||
it("comes back to the active photo from another module, once its page arrives, unless you pick one first", () => {
|
||||
let s = libraryReducer(initialLibrary, { type: "load", scope: "e1", focus: "c" });
|
||||
s = libraryReducer(s, { type: "loaded", scope: "e1", photos: [photo("a", "1"), photo("b", "2")], done: false });
|
||||
// Not on the first page yet: the first photo shows meanwhile.
|
||||
expect(s.focus).toBe("a");
|
||||
s = libraryReducer(s, { type: "loaded", scope: "e1", photos: [photo("c", "3"), photo("d", "4")], done: true });
|
||||
expect([s.focus, [...s.selected], s.wanted]).toEqual(["c", ["c"], null]);
|
||||
|
||||
let t = libraryReducer(initialLibrary, { type: "load", scope: "e1", focus: "d" });
|
||||
t = libraryReducer(t, { type: "loaded", scope: "e1", photos: [photo("a", "1"), photo("b", "2")], done: false });
|
||||
t = libraryReducer(t, { type: "select", id: "b", mode: "single", visible: ["a", "b"] });
|
||||
t = libraryReducer(t, { type: "loaded", scope: "e1", photos: [photo("c", "3"), photo("d", "4")], done: true });
|
||||
expect(t.focus).toBe("b");
|
||||
|
||||
// Gone (deleted, moved): the first photo, and nothing left to look for.
|
||||
let u = libraryReducer(initialLibrary, { type: "load", scope: "e1", focus: "zz" });
|
||||
u = libraryReducer(u, { type: "loaded", scope: "e1", photos: [photo("a", "1")], done: true });
|
||||
expect([u.focus, u.wanted]).toEqual(["a", null]);
|
||||
});
|
||||
});
|
||||
@@ -1,4 +1,4 @@
|
||||
import type { LibraryMessage, PhotoPatch, PhotoSummary } from "@photoreport/contracts";
|
||||
import type { ColorLabel, LibraryMessage, PhotoPatch, PhotoSummary } from "@photoreport/contracts";
|
||||
|
||||
/** Photos of the open event (or the inbox), in capture order, plus the selection. */
|
||||
export interface LibraryState {
|
||||
@@ -9,12 +9,14 @@ export interface LibraryState {
|
||||
/** The photo keyboard actions start from (and the one shown in the loupe). */
|
||||
focus: string | null;
|
||||
anchor: string | null;
|
||||
/** The active photo to come back to once its page has loaded (the folder may be long). */
|
||||
wanted: string | null;
|
||||
}
|
||||
|
||||
export const initialLibrary: LibraryState = { scope: null, photos: [], loading: false, selected: new Set(), focus: null, anchor: null };
|
||||
export const initialLibrary: LibraryState = { scope: null, photos: [], loading: false, selected: new Set(), focus: null, anchor: null, wanted: null };
|
||||
|
||||
export type LibraryAction =
|
||||
| { type: "load"; scope: string }
|
||||
| { type: "load"; scope: string; focus?: string | null }
|
||||
| { type: "loaded"; scope: string; photos: PhotoSummary[]; done: boolean }
|
||||
| { type: "message"; message: LibraryMessage }
|
||||
| { type: "patch"; ids: string[]; patch: PhotoPatch }
|
||||
@@ -43,13 +45,19 @@ function inScope(scope: string | null, photo: PhotoSummary): boolean {
|
||||
export function libraryReducer(state: LibraryState, action: LibraryAction): LibraryState {
|
||||
switch (action.type) {
|
||||
case "load":
|
||||
return { ...initialLibrary, scope: action.scope, loading: true };
|
||||
return { ...initialLibrary, scope: action.scope, loading: true, wanted: action.focus ?? null };
|
||||
case "loaded": {
|
||||
if (action.scope !== state.scope) return state;
|
||||
const seen = new Set(state.photos.map((p) => p.id));
|
||||
const photos = [...state.photos, ...action.photos.filter((p) => !seen.has(p.id))];
|
||||
// The active photo from another module (or the last visit): selected as soon as its page arrives.
|
||||
if (state.wanted && photos.some((p) => p.id === state.wanted)) {
|
||||
const id = state.wanted;
|
||||
return { ...state, photos, loading: !action.done, focus: id, selected: new Set([id]), anchor: id, wanted: null };
|
||||
}
|
||||
const focus = state.focus ?? photos[0]?.id ?? null;
|
||||
return { ...state, photos, loading: !action.done, focus, selected: state.selected.size || !focus ? state.selected : new Set([focus]), anchor: state.anchor ?? focus };
|
||||
const wanted = action.done ? null : state.wanted;
|
||||
return { ...state, photos, loading: !action.done, focus, selected: state.selected.size || !focus ? state.selected : new Set([focus]), anchor: state.anchor ?? focus, wanted };
|
||||
}
|
||||
case "message": {
|
||||
const m = action.message;
|
||||
@@ -59,6 +67,17 @@ export function libraryReducer(state: LibraryState, action: LibraryAction): Libr
|
||||
}
|
||||
if (m.type === "photo.updated") return libraryReducer(state, { type: "patch", ids: m.ids, patch: m.patch });
|
||||
if (m.type === "photo.edited") return { ...state, photos: state.photos.map((p) => (p.id === m.photoId ? { ...p, developSeq: m.developSeq } : p)) };
|
||||
if (m.type === "delivery.updated") {
|
||||
const { photoId, status } = m.item;
|
||||
return {
|
||||
...state,
|
||||
photos: state.photos.map((p) => {
|
||||
if (p.id !== photoId || p.delivery === "DONE") return p;
|
||||
const delivery = status === "DONE" ? "DONE" : status === "FAILED" ? (p.delivery === "QUEUED" ? "QUEUED" : "FAILED") : "QUEUED";
|
||||
return { ...p, delivery };
|
||||
}),
|
||||
};
|
||||
}
|
||||
if (m.type === "photo.rendered") return { ...state, photos: state.photos.map((p) => (p.id === m.photoId ? { ...p, urls: { ...p.urls, ...m.urls } } : p)) };
|
||||
return state;
|
||||
}
|
||||
@@ -71,7 +90,8 @@ export function libraryReducer(state: LibraryState, action: LibraryAction): Libr
|
||||
}
|
||||
case "select": {
|
||||
const { id, mode, visible } = action;
|
||||
if (mode === "single") return { ...state, selected: new Set([id]), focus: id, anchor: id };
|
||||
// Picking a photo by hand wins over the one still being looked for.
|
||||
if (mode === "single") return { ...state, selected: new Set([id]), focus: id, anchor: id, wanted: null };
|
||||
if (mode === "toggle") {
|
||||
const selected = new Set(state.selected);
|
||||
if (selected.has(id)) selected.delete(id);
|
||||
@@ -92,28 +112,43 @@ export function libraryReducer(state: LibraryState, action: LibraryAction): Libr
|
||||
const at = state.focus ? visible.indexOf(state.focus) : -1;
|
||||
const next = visible[Math.max(0, Math.min(visible.length - 1, at < 0 ? 0 : at + delta))]!;
|
||||
if (extend) return libraryReducer({ ...state }, { type: "select", id: next, mode: "range", visible });
|
||||
return { ...state, selected: new Set([next]), focus: next, anchor: next };
|
||||
return { ...state, selected: new Set([next]), focus: next, anchor: next, wanted: null };
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export type FilterId = "all" | "PICK" | "UNREJECTED" | "REJECT" | "stars" | "noPlayers";
|
||||
/**
|
||||
* The library filter, combinable as in Photo Mechanic and Lightroom's filter bar: flag, minimum stars, colour,
|
||||
* delivery state and photos still without players. Every part narrows; the defaults show everything.
|
||||
*/
|
||||
export interface LibraryFilter {
|
||||
flag: "all" | "PICK" | "UNREJECTED" | "REJECT" | "UNFLAGGED";
|
||||
minRating: number;
|
||||
color: ColorLabel | null;
|
||||
delivery: "any" | "unsent" | "queued" | "sent" | "failed";
|
||||
noPlayers: boolean;
|
||||
}
|
||||
|
||||
export function matchesFilter(photo: PhotoSummary, filter: FilterId): boolean {
|
||||
switch (filter) {
|
||||
case "all":
|
||||
return true;
|
||||
case "PICK":
|
||||
return photo.flag === "PICK";
|
||||
case "REJECT":
|
||||
return photo.flag === "REJECT";
|
||||
case "UNREJECTED":
|
||||
return photo.flag !== "REJECT";
|
||||
case "stars":
|
||||
return photo.rating >= 3;
|
||||
case "noPlayers":
|
||||
return photo.players.length === 0;
|
||||
}
|
||||
export const ALL_PHOTOS: LibraryFilter = { flag: "all", minRating: 0, color: null, delivery: "any", noPlayers: false };
|
||||
|
||||
export function isAll(f: LibraryFilter): boolean {
|
||||
return f.flag === "all" && !f.minRating && !f.color && f.delivery === "any" && !f.noPlayers;
|
||||
}
|
||||
|
||||
export function matchesFilter(photo: PhotoSummary, f: LibraryFilter): boolean {
|
||||
if (f.flag === "PICK" && photo.flag !== "PICK") return false;
|
||||
if (f.flag === "REJECT" && photo.flag !== "REJECT") return false;
|
||||
if (f.flag === "UNREJECTED" && photo.flag === "REJECT") return false;
|
||||
if (f.flag === "UNFLAGGED" && photo.flag !== "NONE") return false;
|
||||
if (f.minRating && photo.rating < f.minRating) return false;
|
||||
if (f.color && photo.colorLabel !== f.color) return false;
|
||||
const d = photo.delivery ?? "NONE";
|
||||
if (f.delivery === "unsent" && d !== "NONE") return false;
|
||||
if (f.delivery === "queued" && d !== "QUEUED") return false;
|
||||
if (f.delivery === "sent" && d !== "DONE") return false;
|
||||
if (f.delivery === "failed" && d !== "FAILED") return false;
|
||||
if (f.noPlayers && photo.players.length) return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
/** Lightroom keys: P pick, X reject, U unflag, 0–5 stars, 6–9 colour labels (red, yellow, green, blue). */
|
||||
|
||||
@@ -63,20 +63,23 @@ export interface PreviewOf {
|
||||
height: number;
|
||||
}
|
||||
|
||||
/** What a desktop ingest sends: a preview standing for its original, or the full original ("original"). */
|
||||
export type DesktopOrigin = PreviewOf | "original";
|
||||
|
||||
export async function sendResumable(
|
||||
api: ApiClient,
|
||||
orgId: string,
|
||||
file: File,
|
||||
eventId: string | undefined,
|
||||
onProgress: (p: number) => void,
|
||||
original?: PreviewOf,
|
||||
origin?: DesktopOrigin,
|
||||
): Promise<{ status: number; body: unknown }> {
|
||||
const fingerprint = `${file.name}:${file.size}:${file.lastModified}`;
|
||||
const begin = await xhr(
|
||||
"POST",
|
||||
api.absolute(`/v1/orgs/${orgId}/uploads/resumable`),
|
||||
await api.realtimeToken(),
|
||||
JSON.stringify({ name: file.name, size: file.size, fingerprint, ...(eventId && { eventId }), ...(original && { original }) }),
|
||||
JSON.stringify({ name: file.name, size: file.size, fingerprint, ...(eventId && { eventId }), ...(origin === "original" ? { desktop: true } : origin ? { original: origin } : {}) }),
|
||||
"application/json",
|
||||
);
|
||||
if (begin.status !== 200 && begin.status !== 201) return begin;
|
||||
@@ -131,7 +134,7 @@ export async function sendResumable(
|
||||
*/
|
||||
export function useUploadQueue(api: ApiClient, orgId: string) {
|
||||
const [items, setItems] = useState<UploadItem[]>([]);
|
||||
const queue = useRef<{ item: UploadItem; file: File; eventId: string | undefined; original?: PreviewOf; onSettled?: (status: UploadStatus) => void }[]>([]);
|
||||
const queue = useRef<{ item: UploadItem; file: File; eventId: string | undefined; original?: DesktopOrigin; onSettled?: (status: UploadStatus) => void }[]>([]);
|
||||
const running = useRef(0);
|
||||
|
||||
const update = useCallback((id: string, patch: Partial<UploadItem>) => {
|
||||
@@ -163,8 +166,8 @@ export function useUploadQueue(api: ApiClient, orgId: string) {
|
||||
original,
|
||||
);
|
||||
// The server took the file but could not read it as a photo: not sent (FTP keeps the original in ingest).
|
||||
const unreadable = (res.body as { photo?: { status?: string } } | null)?.photo?.status === "FAILED";
|
||||
if (unreadable) res.body = { error: "processing_failed" };
|
||||
const photo = (res.body as { photo?: { status?: string; error?: string | null } } | null)?.photo;
|
||||
if (photo?.status === "FAILED") res.body = { error: photo.error ? `processing_failed: ${photo.error}` : "processing_failed" };
|
||||
else if (res.status === 201) final = "done";
|
||||
else if (res.status === 200) final = "duplicate";
|
||||
if (final === "failed") update(item.id, { status: "failed", error: (res.body as { error?: string } | null)?.error ?? `http_${res.status}` });
|
||||
@@ -182,7 +185,7 @@ export function useUploadQueue(api: ApiClient, orgId: string) {
|
||||
|
||||
const add = useCallback(
|
||||
/** `onSettled` is called once per accepted file, after it is sent (or definitely failed). */
|
||||
(files: Iterable<File>, eventId?: string, onSettled?: (file: File, status: UploadStatus) => void, original?: PreviewOf) => {
|
||||
(files: Iterable<File>, eventId?: string, onSettled?: (file: File, status: UploadStatus) => void, original?: DesktopOrigin) => {
|
||||
const added: UploadItem[] = [];
|
||||
for (const file of files) {
|
||||
const item: UploadItem = { id: crypto.randomUUID(), name: file.name, size: file.size, status: "queued", progress: 0 };
|
||||
|
||||
@@ -8,7 +8,8 @@ import { DevelopPanels, Section, Slider } from "../develop/Panels.js";
|
||||
import { type Crop, cropOf, DevelopSession, localOutbox } from "../develop/session.js";
|
||||
import { constrainRotated, engineAuto, fitAspect, Viewer } from "../develop/Viewer.js";
|
||||
import { IptcInfo } from "../library/IptcInfo.js";
|
||||
import { applyPatch, patchForKey } from "../library/store.js";
|
||||
import { activePhoto, savedFilter, setActivePhoto } from "../library/active.js";
|
||||
import { applyPatch, type LibraryFilter, matchesFilter, patchForKey } from "../library/store.js";
|
||||
import { t } from "../i18n.js";
|
||||
import { useLibraryLive } from "../library/realtime.js";
|
||||
import { isDesktop, localOriginal, prefs } from "../platform.js";
|
||||
@@ -28,6 +29,8 @@ const ASPECTS: { label: string; value: [number, number] | "original" | null }[]
|
||||
];
|
||||
|
||||
const CLIPBOARD = "develop.clipboard";
|
||||
/** The filmstrip loads the whole folder in pages of this size (a match can have thousands of photos). */
|
||||
const PAGE = 500;
|
||||
/** The aspect a new crop starts with (the last one chosen): "free", "original" or "W:H". Lightroom's default is the original. */
|
||||
const CROP_ASPECT = "develop.cropAspect";
|
||||
type AspectChoice = (typeof ASPECTS)[number]["value"];
|
||||
@@ -90,20 +93,51 @@ export function DevelopPage() {
|
||||
api.listDeliveryTargets(orgId).then((r) => setTargets(r.targets.filter((x) => !x.disabledAt)), () => {});
|
||||
}, [api, orgId, role]);
|
||||
|
||||
// The event (or inbox) the library has open.
|
||||
// The event (or inbox) the library has open, all of it (page by page), as the library shows it.
|
||||
const scope = orgId ? (prefs.get(`scope:${orgId}`) ?? null) : null;
|
||||
const [all, setAll] = useState<PhotoSummary[] | null>(null);
|
||||
useEffect(() => {
|
||||
if (!orgId) return;
|
||||
const scope = prefs.get(`scope:${orgId}`) ?? undefined;
|
||||
api.listPhotos(orgId, { ...(scope && { event: scope }), limit: 500 }).then(
|
||||
(r) => setPhotos(r.photos.filter((p) => p.status === "READY")),
|
||||
() => setPhotos([]),
|
||||
);
|
||||
}, [api, orgId]);
|
||||
let alive = true;
|
||||
void (async () => {
|
||||
const got: PhotoSummary[] = [];
|
||||
try {
|
||||
for (let offset = 0; ; offset += PAGE) {
|
||||
const page = await api.listPhotos(orgId, { ...(scope && { event: scope }), offset, limit: PAGE });
|
||||
got.push(...page.photos);
|
||||
if (!alive) return;
|
||||
setAll([...got]);
|
||||
if (offset + page.photos.length >= page.total || page.photos.length === 0) break;
|
||||
}
|
||||
} catch {
|
||||
if (alive) setAll((a) => a ?? []);
|
||||
}
|
||||
})();
|
||||
return () => {
|
||||
alive = false;
|
||||
};
|
||||
}, [api, orgId, scope]);
|
||||
// The filmstrip follows the library's filter, like Lightroom's (the open photo stays even if it doesn't match).
|
||||
const filterJson = JSON.stringify(savedFilter(orgId));
|
||||
const filter = useMemo(() => JSON.parse(filterJson) as LibraryFilter, [filterJson]);
|
||||
useEffect(() => {
|
||||
if (!all) return;
|
||||
const ready = all.filter((p) => p.status === "READY");
|
||||
const shown = ready.filter((p) => matchesFilter(p, filter) || p.id === photoId);
|
||||
setPhotos(shown.length ? shown : ready);
|
||||
}, [all, filter]); // eslint-disable-line react-hooks/exhaustive-deps
|
||||
|
||||
const current = photos.find((p) => p.id === photoId) ?? null;
|
||||
// Opened from the module link (no photo in the address): the active photo, the one you were on.
|
||||
useEffect(() => {
|
||||
if (!photoId && photos[0]) navigate(`/develop/${photos[0].id}`, { replace: true });
|
||||
}, [photoId, photos, navigate]);
|
||||
if (photoId || !photos.length) return;
|
||||
const active = activePhoto(orgId, scope);
|
||||
const start = (active && photos.find((p) => p.id === active)) || photos[0]!;
|
||||
navigate(`/develop/${start.id}`, { replace: true });
|
||||
}, [photoId, photos, navigate, orgId, scope]);
|
||||
useEffect(() => {
|
||||
if (current) setActivePhoto(orgId, scope, current.id);
|
||||
}, [orgId, scope, current?.id]); // eslint-disable-line react-hooks/exhaustive-deps
|
||||
|
||||
const canEdit = !!current && !!role && (hasRole(role, "INGESTER") || current.uploader?.id === me?.user.id);
|
||||
|
||||
@@ -192,6 +226,8 @@ export function DevelopPage() {
|
||||
else if (e.key === "ArrowLeft") go(-1);
|
||||
else if (e.key === "\\") setBefore((b) => !b);
|
||||
else if (!mod && !e.altKey && e.key.toLowerCase() === "g") navigate("/", { state: { focus: current?.id } });
|
||||
// Lightroom: E is the library loupe on the same photo.
|
||||
else if (!mod && !e.altKey && !e.shiftKey && e.key.toLowerCase() === "e") navigate("/", { state: { focus: current?.id, loupe: true } });
|
||||
else if (!mod && e.shiftKey && e.key.toLowerCase() === "a" && canEdit) void autoAllRef.current();
|
||||
else if (!mod && !e.shiftKey && e.key.toLowerCase() === "i" && canCull && current) setInfo(true);
|
||||
else if (!mod && !e.altKey && patchForKey(e.key)) {
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
import { fireEvent, render, screen, waitFor } from "@testing-library/react";
|
||||
import type { PrintEventSummary } from "@photoreport/contracts";
|
||||
import type { ApiClient } from "@photoreport/sdk";
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import { AuthProvider } from "../auth.js";
|
||||
import { KioskPanel } from "./PrintPage.js";
|
||||
|
||||
const event = { id: "e1", slug: "casamento", name: "Casamento", priceCents: 300, kiosk: false } as PrintEventSummary;
|
||||
|
||||
describe("kiosk panel", () => {
|
||||
it("makes a kiosk link on the events site and says paid prints are paid at the counter", async () => {
|
||||
const enablePrintKiosk = vi.fn(async () => ({ path: "/e/casamento/quiosque?k=secret-0123456789abcdef" }));
|
||||
const onChange = vi.fn();
|
||||
render(
|
||||
<AuthProvider api={{ resume: vi.fn(async () => false), enablePrintKiosk } as unknown as ApiClient}>
|
||||
<KioskPanel event={event} onChange={onChange} />
|
||||
</AuthProvider>,
|
||||
);
|
||||
expect(screen.getByText(/paga ao balcão/)).toBeTruthy();
|
||||
fireEvent.click(screen.getByText("Ligar quiosque"));
|
||||
await waitFor(() => expect(screen.getByText("https://events.photoreport.pt/e/casamento/quiosque?k=secret-0123456789abcdef")).toBeTruthy());
|
||||
expect(onChange).toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -16,11 +16,13 @@ import { useIngest } from "../library/ingest.js";
|
||||
import { LocalFtpButton } from "../library/LocalFtp.js";
|
||||
import { AutopilotButton } from "../library/Autopilot.js";
|
||||
import { SquadsButton } from "../library/Squads.js";
|
||||
import { type FilterId, initialLibrary, libraryReducer, matchesFilter, patchForKey } from "../library/store.js";
|
||||
import { initialLibrary, type LibraryFilter, libraryReducer, matchesFilter, patchForKey } from "../library/store.js";
|
||||
import { FilterBar } from "../library/FilterBar.js";
|
||||
import { SendButton } from "../library/SendButton.js";
|
||||
import { prefs } from "../platform.js";
|
||||
import { activePhoto, savedFilter, saveFilter, setActivePhoto } from "../library/active.js";
|
||||
|
||||
const PAGE = 500;
|
||||
const FILTERS: FilterId[] = ["all", "PICK", "UNREJECTED", "REJECT", "stars", "noPlayers"];
|
||||
|
||||
const isTyping = (target: EventTarget | null) =>
|
||||
target instanceof HTMLElement && (target.isContentEditable || ["INPUT", "TEXTAREA", "SELECT"].includes(target.tagName));
|
||||
@@ -37,7 +39,15 @@ export function LibraryPage() {
|
||||
const [targets, setTargets] = useState<DeliveryTarget[]>([]);
|
||||
const [iptcOpen, setIptcOpen] = useState(false);
|
||||
const [state, dispatch] = useReducer(libraryReducer, initialLibrary);
|
||||
const [filter, setFilter] = useState<FilterId>("all");
|
||||
const [filter, setFilterState] = useState<LibraryFilter>(() => savedFilter(orgId));
|
||||
useEffect(() => setFilterState(savedFilter(orgId)), [orgId]);
|
||||
const setFilter = useCallback(
|
||||
(f: LibraryFilter) => {
|
||||
setFilterState(f);
|
||||
saveFilter(orgId, f);
|
||||
},
|
||||
[orgId],
|
||||
);
|
||||
const [loupe, setLoupe] = useState(false);
|
||||
const [creating, setCreating] = useState(false);
|
||||
const [view, setView] = useState<"grid" | "faces">("grid");
|
||||
@@ -58,7 +68,8 @@ export function LibraryPage() {
|
||||
|
||||
const open = useCallback(
|
||||
async (scope: string) => {
|
||||
dispatch({ type: "load", scope });
|
||||
// Back on the photo that was active here, in any module (Lightroom keeps one active photo).
|
||||
dispatch({ type: "load", scope, focus: activePhoto(orgId, scope) });
|
||||
setLoupe(false);
|
||||
setSuggested([]);
|
||||
if (scope.startsWith("search:")) {
|
||||
@@ -95,16 +106,33 @@ export function LibraryPage() {
|
||||
};
|
||||
}, [api, orgId, canCull, loadEvents, open]);
|
||||
|
||||
// Photos moved between events (by hand, or claimed from "Sem evento" when an event is created or its times
|
||||
// change): the counts follow, and the open event shows the ones that arrived in it.
|
||||
const scopeRef = useRef(state.scope);
|
||||
scopeRef.current = state.scope;
|
||||
const moved = useRef<ReturnType<typeof setTimeout> | null>(null);
|
||||
const onMoved = useCallback(
|
||||
(eventId: string | null) => {
|
||||
if (moved.current) clearTimeout(moved.current);
|
||||
moved.current = setTimeout(() => {
|
||||
void loadEvents().catch(() => {});
|
||||
if (eventId !== null && scopeRef.current === eventId) void open(eventId).catch(() => {});
|
||||
}, 400);
|
||||
},
|
||||
[loadEvents, open],
|
||||
);
|
||||
|
||||
const onMessage = useCallback(
|
||||
(message: LibraryMessage) => {
|
||||
dispatch({ type: "message", message });
|
||||
if (message.type === "photo.updated" && message.patch.eventId !== undefined) onMoved(message.patch.eventId);
|
||||
if (message.type === "faces.updated") setFacesTick((n) => n + 1);
|
||||
if (message.type === "photo.added") {
|
||||
if (message.photo.eventId === null) setInboxCount((n) => n + 1);
|
||||
else setEvents((list) => list.map((e) => (e.id === message.photo.eventId ? { ...e, photoCount: e.photoCount + 1 } : e)));
|
||||
}
|
||||
},
|
||||
[dispatch],
|
||||
[dispatch, onMoved],
|
||||
);
|
||||
const live = useLibraryLive(api, onMessage);
|
||||
const { uploads, localFtp, desktop } = useIngest();
|
||||
@@ -175,15 +203,22 @@ export function LibraryPage() {
|
||||
return () => window.removeEventListener("keydown", onKey);
|
||||
}, [visibleIds, selection, focus, loupe, patch, navigate, canCull]);
|
||||
|
||||
// The photo you are on is the active one for every module (Develop opens on it).
|
||||
useEffect(() => {
|
||||
if (!state.wanted) setActivePhoto(orgId, state.scope, state.focus);
|
||||
}, [orgId, state.scope, state.focus, state.wanted]);
|
||||
|
||||
// Back from Develop (G): the photo that was open there is the one selected here.
|
||||
const location = useLocation();
|
||||
const backFocus = (location.state as { focus?: string } | null)?.focus;
|
||||
const back = location.state as { focus?: string; loupe?: boolean } | null;
|
||||
const backFocus = back?.focus;
|
||||
useEffect(() => {
|
||||
if (!backFocus || !state.photos.some((p) => p.id === backFocus)) return;
|
||||
dispatch({ type: "select", id: backFocus, mode: "single", visible: [] });
|
||||
if (back?.loupe) setLoupe(true);
|
||||
requestAnimationFrame(() => document.querySelector(`[data-photo-id="${backFocus}"]`)?.scrollIntoView({ block: "nearest" }));
|
||||
navigate(".", { replace: true, state: null });
|
||||
}, [backFocus, state.photos, navigate]);
|
||||
}, [backFocus, back?.loupe, state.photos, navigate]);
|
||||
|
||||
const onPick = useCallback(
|
||||
(id: string, e: React.MouseEvent) => dispatch({ type: "select", id, mode: e.shiftKey ? "range" : e.metaKey || e.ctrlKey ? "toggle" : "single", visible: visibleIds }),
|
||||
@@ -199,7 +234,10 @@ export function LibraryPage() {
|
||||
if (!loupe || !focus || !canCull) return;
|
||||
let alive = true;
|
||||
api.photoFaces(focus.id).then(
|
||||
(r) => alive && setLoupeFaces(r.faces.map((f) => ({ id: f.id, x0: f.x0, y0: f.y0, x1: f.x1, y1: f.y1, label: f.person?.name ?? f.suggestion?.name ?? null, suggested: !f.person }))),
|
||||
(r) => alive && setLoupeFaces(
|
||||
// The loupe shows the edited preview: boxes in its frame, faces cropped out left out.
|
||||
r.faces.flatMap((f) => (f.inPreview ? [{ id: f.id, ...f.inPreview, label: f.person?.name ?? f.suggestion?.name ?? null, suggested: !f.person }] : [])),
|
||||
),
|
||||
() => {},
|
||||
);
|
||||
return () => {
|
||||
@@ -226,12 +264,7 @@ 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]">
|
||||
<span className="text-faint">{t.filter}:</span>
|
||||
{FILTERS.map((f) => (
|
||||
<button key={f} onClick={() => setFilter(f)} aria-pressed={filter === f} className={filter === f ? "font-semibold text-ink" : "text-faint hover:text-muted"}>
|
||||
{t.filters[f]}
|
||||
</button>
|
||||
))}
|
||||
<FilterBar filter={filter} onChange={setFilter} />
|
||||
{canCull && state.scope && state.scope !== "inbox" && !state.scope.startsWith("search:") && (
|
||||
<button
|
||||
onClick={() => setView(view === "faces" ? "grid" : "faces")}
|
||||
@@ -279,6 +312,44 @@ export function LibraryPage() {
|
||||
))}
|
||||
</select>
|
||||
)}
|
||||
{canCull && (
|
||||
<SendButton
|
||||
api={api}
|
||||
orgId={orgId}
|
||||
selection={selection}
|
||||
targets={targets}
|
||||
onQueued={(items) => items.forEach((item) => dispatch({ type: "message", message: { type: "delivery.updated", item } }))}
|
||||
/>
|
||||
)}
|
||||
{canCull && selection.length > 0 && !state.scope?.startsWith("search:") && (
|
||||
<select
|
||||
aria-label={t.moveToEvent}
|
||||
className="h-6 border border-black bg-cell px-1.5 text-[12px] text-ink"
|
||||
value=""
|
||||
onChange={(e) => {
|
||||
const target = events.find((x) => x.id === e.target.value);
|
||||
if (!target) return;
|
||||
const ids = selection.map((p) => p.id);
|
||||
void api.updatePhotos(orgId, ids, { eventId: target.id }).then(
|
||||
() => {
|
||||
dispatch({ type: "patch", ids, patch: { eventId: target.id } });
|
||||
setInfo(t.movedToEvent(ids.length, target.title));
|
||||
setTimeout(() => setInfo(null), 4000);
|
||||
},
|
||||
() => setError(t.unexpectedError),
|
||||
);
|
||||
}}
|
||||
>
|
||||
<option value="">{t.moveToEvent}…</option>
|
||||
{events
|
||||
.filter((x) => x.id !== state.scope && !x.archivedAt)
|
||||
.map((x) => (
|
||||
<option key={x.id} value={x.id}>
|
||||
{x.title}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
)}
|
||||
{info && <span className="text-[11px] text-ok">{info}</span>}
|
||||
{canCull && prefs.get("develop.clipboard") && selection.length > 0 && (
|
||||
<button
|
||||
|
||||
@@ -191,6 +191,7 @@ export function PrintPage() {
|
||||
|
||||
<aside className="w-80 shrink-0 space-y-0 border-l border-line bg-panel max-lg:w-full">
|
||||
{event && <EventPanel event={event} galleries={galleries} printers={printers} canEdit={canEdit} onChange={loadEvents} />}
|
||||
{event && canEdit && <KioskPanel event={event} onChange={loadEvents} />}
|
||||
<Printers orgId={orgId} printers={printers} stations={stations} isAdmin={isAdmin} canEdit={canEdit} onChange={loadPrinters} />
|
||||
</aside>
|
||||
</div>
|
||||
@@ -198,6 +199,67 @@ export function PrintPage() {
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Kiosk mode: a tablet at the event shows the photographer's photos big, takes pictures with its camera
|
||||
* (photobooth) and sends prints to the queue. Its link carries a secret (shown when made; a new one retires it).
|
||||
*/
|
||||
export function KioskPanel({ event, onChange }: { event: PrintEventSummary; onChange: () => void }) {
|
||||
const { api } = useAuth();
|
||||
const [link, setLink] = useState<string | null>(null);
|
||||
const [qr, setQr] = useState("");
|
||||
useEffect(() => {
|
||||
setLink(null);
|
||||
}, [event.id]);
|
||||
useEffect(() => {
|
||||
if (!link) return setQr("");
|
||||
QRCode.toString(link, { type: "svg", margin: 1, errorCorrectionLevel: "M" }).then(setQr, () => setQr(""));
|
||||
}, [link]);
|
||||
const make = () =>
|
||||
void api.enablePrintKiosk(event.id).then((r) => {
|
||||
setLink(guestUrl(event.slug).replace(/\/e\/[^/]+$/, "") + r.path);
|
||||
onChange();
|
||||
});
|
||||
return (
|
||||
<div className="border-b border-line">
|
||||
<div className="panel-head">
|
||||
<span>Quiosque</span>
|
||||
<span className="normal-case tracking-normal text-faint">{event.kiosk ? "ligado" : "desligado"}</span>
|
||||
</div>
|
||||
<div className="space-y-2 p-3 text-[12px] text-muted">
|
||||
<p className="text-[11px] text-faint">
|
||||
Um tablet no evento mostra as fotos em grande, tira fotos com a câmara (photobooth) e manda imprimir.
|
||||
{event.priceCents > 0 && " Como as impressões são pagas, as do quiosque ficam à espera da tua aprovação: o convidado paga ao balcão."}
|
||||
</p>
|
||||
{link && (
|
||||
<div className="space-y-2">
|
||||
<div className="mx-auto w-40 bg-white p-2" dangerouslySetInnerHTML={{ __html: qr }} aria-label={link} />
|
||||
<p className="break-all font-mono text-[10.5px] text-ink">{link}</p>
|
||||
<p className="text-[11px] text-faint">Abre este link no tablet (ou lê o código). Não volta a ser mostrado: um novo link desliga este.</p>
|
||||
</div>
|
||||
)}
|
||||
<div className="flex gap-2">
|
||||
<button className="h-7 border border-black bg-cell px-2 text-[11px] text-ink hover:bg-cell-on" onClick={make}>
|
||||
{event.kiosk ? "Novo link" : "Ligar quiosque"}
|
||||
</button>
|
||||
{event.kiosk && (
|
||||
<button
|
||||
className="h-7 border border-black bg-cell px-2 text-[11px] text-ink hover:bg-cell-on"
|
||||
onClick={() =>
|
||||
void api.disablePrintKiosk(event.id).then(() => {
|
||||
setLink(null);
|
||||
onChange();
|
||||
})
|
||||
}
|
||||
>
|
||||
Desligar
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function EventPanel({ event, galleries, printers, canEdit, onChange }: { event: PrintEventSummary; galleries: GallerySummary[]; printers: PrinterSummary[]; canEdit: boolean; onChange: () => void }) {
|
||||
const { api } = useAuth();
|
||||
const [qr, setQr] = useState<string>("");
|
||||
|
||||
@@ -4,7 +4,7 @@ import { useAuth } from "../auth.js";
|
||||
import { Bell } from "../components/Bell.js";
|
||||
import { Logo } from "../components/ui.js";
|
||||
import { t } from "../i18n.js";
|
||||
import { UpdateNotice } from "../desktop/UpdateNotice.js";
|
||||
import { UiReadyNotice, UpdateNotice } from "../desktop/UpdateNotice.js";
|
||||
import { IngestProvider } from "../library/ingest.js";
|
||||
|
||||
const moduleClass = ({ isActive }: { isActive: boolean }) =>
|
||||
@@ -116,6 +116,7 @@ export function Shell() {
|
||||
</details>
|
||||
</header>
|
||||
<UpdateNotice />
|
||||
<UiReadyNotice />
|
||||
<main className="min-h-0 flex-1 overflow-auto">
|
||||
<IngestProvider>
|
||||
<Outlet />
|
||||
|
||||
@@ -1,5 +1,10 @@
|
||||
import type { RefreshTokenStore } from "@photoreport/sdk";
|
||||
|
||||
/** Set by the desktop app before the page runs (apps/desktop/src-tauri/src/lib.rs, `init_script`). */
|
||||
export function desktopConfig(): { api: string; app: string } | undefined {
|
||||
return typeof window === "undefined" ? undefined : (window as { __PHOTOREPORT__?: { api: string; app: string } }).__PHOTOREPORT__;
|
||||
}
|
||||
|
||||
/** True inside the Tauri desktop shell. */
|
||||
export const isDesktop = (): boolean => typeof window !== "undefined" && "__TAURI_INTERNALS__" in window;
|
||||
|
||||
|
||||
@@ -9,5 +9,6 @@ export default defineConfig({
|
||||
server: { port: 5173, strictPort: true },
|
||||
// No source maps in production: the browser gets minified code only, never the readable sources.
|
||||
build: { target: "es2022", sourcemap: false },
|
||||
test: { environment: "jsdom", setupFiles: ["./src/test-setup.ts"] },
|
||||
// Whole-app renders type character by character; on a busy CI runner they pass 5 s.
|
||||
test: { environment: "jsdom", setupFiles: ["./src/test-setup.ts"], testTimeout: 20_000 },
|
||||
});
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@photoreport/desktop",
|
||||
"version": "0.3.1",
|
||||
"version": "0.3.6",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "photoreport-desktop"
|
||||
version = "0.3.1"
|
||||
version = "0.3.6"
|
||||
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."
|
||||
@@ -23,13 +23,16 @@ dirs = "6"
|
||||
libunftp = { version = "0.23.1", default-features = false, features = ["ring"] }
|
||||
unftp-sbe-fs = "0.4.0"
|
||||
async-trait = "0.1"
|
||||
tokio = { version = "1", features = ["sync", "time", "fs"] }
|
||||
tokio = { version = "1", features = ["sync", "time", "fs", "net", "io-util"] }
|
||||
unftp-core = "0.1.0"
|
||||
serde_json = "1"
|
||||
sha2 = "0.10"
|
||||
image = { version = "0.25", default-features = false, features = ["jpeg"] }
|
||||
tauri-plugin-dialog = "2"
|
||||
tauri-plugin-updater = "2"
|
||||
# New versions of the interface (see src/ui.rs). Already built for the updater: same versions, no new crates.
|
||||
reqwest = { version = "0.13", default-features = false, features = ["rustls-no-provider"] }
|
||||
rustls = { version = "0.23", default-features = false, features = ["ring"] }
|
||||
|
||||
# Release builds: no symbols or debug info, whole-program optimisation, no unwinding tables. The binary only tells
|
||||
# a disassembler what machine code does, not what the functions were called.
|
||||
|
||||
@@ -9,6 +9,7 @@ fn main() {
|
||||
"ftp_start",
|
||||
"ftp_stop",
|
||||
"ftp_status",
|
||||
"ftp_check",
|
||||
"ftp_take",
|
||||
"ftp_retry",
|
||||
"ftp_read",
|
||||
@@ -26,6 +27,8 @@ fn main() {
|
||||
"catalog_cancel",
|
||||
"update_check",
|
||||
"update_install",
|
||||
"ui_status",
|
||||
"ui_check",
|
||||
]),
|
||||
))
|
||||
.expect("failed to run tauri-build");
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"$schema": "../gen/schemas/desktop-schema.json",
|
||||
"identifier": "default",
|
||||
"description": "Main window: core APIs, the keychain and local FTP commands and opening PhotoReport pages in the system browser. The window shows the web app from the server (always the latest version), so the server's pages get the same access.",
|
||||
"description": "Main window: core APIs, the keychain and local FTP commands and opening PhotoReport pages in the system browser. The window shows the interface kept on this computer (updated in the background from the server); the server's pages keep the same access.",
|
||||
"windows": [
|
||||
"main"
|
||||
],
|
||||
@@ -24,6 +24,7 @@
|
||||
"allow-ftp-start",
|
||||
"allow-ftp-stop",
|
||||
"allow-ftp-status",
|
||||
"allow-ftp-check",
|
||||
"allow-ftp-take",
|
||||
"allow-ftp-retry",
|
||||
"allow-ftp-read",
|
||||
@@ -40,7 +41,9 @@
|
||||
"allow-catalog-status",
|
||||
"allow-catalog-cancel",
|
||||
"allow-update-check",
|
||||
"allow-update-install"
|
||||
"allow-update-install",
|
||||
"allow-ui-status",
|
||||
"allow-ui-check"
|
||||
],
|
||||
"remote": {
|
||||
"urls": [
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
# Automatically generated - DO NOT EDIT!
|
||||
|
||||
[[permission]]
|
||||
identifier = "allow-ftp-check"
|
||||
description = "Enables the ftp_check command without any pre-configured scope."
|
||||
commands.allow = ["ftp_check"]
|
||||
|
||||
[[permission]]
|
||||
identifier = "deny-ftp-check"
|
||||
description = "Denies the ftp_check command without any pre-configured scope."
|
||||
commands.deny = ["ftp_check"]
|
||||
@@ -0,0 +1,11 @@
|
||||
# Automatically generated - DO NOT EDIT!
|
||||
|
||||
[[permission]]
|
||||
identifier = "allow-ui-check"
|
||||
description = "Enables the ui_check command without any pre-configured scope."
|
||||
commands.allow = ["ui_check"]
|
||||
|
||||
[[permission]]
|
||||
identifier = "deny-ui-check"
|
||||
description = "Denies the ui_check command without any pre-configured scope."
|
||||
commands.deny = ["ui_check"]
|
||||
@@ -0,0 +1,11 @@
|
||||
# Automatically generated - DO NOT EDIT!
|
||||
|
||||
[[permission]]
|
||||
identifier = "allow-ui-status"
|
||||
description = "Enables the ui_status command without any pre-configured scope."
|
||||
commands.allow = ["ui_status"]
|
||||
|
||||
[[permission]]
|
||||
identifier = "deny-ui-status"
|
||||
description = "Denies the ui_status command without any pre-configured scope."
|
||||
commands.deny = ["ui_status"]
|
||||
@@ -35,6 +35,13 @@ const STABLE_MS: u64 = 2_000;
|
||||
pub struct FtpUser {
|
||||
pub name: String,
|
||||
pub password: String,
|
||||
/// Switched off: the login stays saved but the server refuses it (one per camera body, like other FTP servers).
|
||||
#[serde(default = "enabled_by_default")]
|
||||
pub enabled: bool,
|
||||
}
|
||||
|
||||
fn enabled_by_default() -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
|
||||
@@ -60,6 +67,7 @@ impl Default for FtpSettings {
|
||||
users: vec![FtpUser {
|
||||
name: "photoreport".into(),
|
||||
password: new_password(),
|
||||
enabled: true,
|
||||
}],
|
||||
ingest: "~/Desktop/ingest".into(),
|
||||
work_folder: "~/Desktop/{year}/{date} - {event}".into(),
|
||||
@@ -82,6 +90,11 @@ impl FtpSettings {
|
||||
{
|
||||
return Err("users".into());
|
||||
}
|
||||
let mut names: Vec<&str> = self.users.iter().map(|u| u.name.trim()).collect();
|
||||
names.sort_unstable();
|
||||
if names.windows(2).any(|w| w[0] == w[1]) {
|
||||
return Err("duplicate_user".into());
|
||||
}
|
||||
if self.ingest.trim().is_empty() || self.work_folder.trim().is_empty() {
|
||||
return Err("folders".into());
|
||||
}
|
||||
@@ -112,6 +125,19 @@ pub struct FtpStatus {
|
||||
/// Photos in the ingest folder not handed to the web app yet.
|
||||
waiting: usize,
|
||||
error: Option<String>,
|
||||
/// The last self-test: does the server answer on each address the camera can use.
|
||||
checks: Vec<AddressCheck>,
|
||||
/// macOS firewall: "block_all" or "app_blocked" when it stops cameras from connecting; null when fine.
|
||||
firewall: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct AddressCheck {
|
||||
address: String,
|
||||
ok: bool,
|
||||
/// What answered (the FTP greeting) or why not.
|
||||
detail: String,
|
||||
}
|
||||
|
||||
struct Running {
|
||||
@@ -132,6 +158,8 @@ pub struct FtpState {
|
||||
/// Paths already handed to the web app (so the next scan does not send them twice).
|
||||
taken: Mutex<HashSet<String>>,
|
||||
last_error: Arc<Mutex<Option<String>>>,
|
||||
checks: Mutex<Vec<AddressCheck>>,
|
||||
firewall: Mutex<Option<String>>,
|
||||
}
|
||||
|
||||
fn home() -> PathBuf {
|
||||
@@ -230,6 +258,76 @@ fn lan_addresses() -> Vec<String> {
|
||||
v.into_iter().map(|(_, ip)| ip).collect()
|
||||
}
|
||||
|
||||
/// Opens the FTP control connection like a camera and reads the greeting ("220 PhotoReport").
|
||||
async fn probe(address: &str, port: u16) -> (bool, String) {
|
||||
use tokio::io::AsyncReadExt;
|
||||
let connect = tokio::net::TcpStream::connect((address, port));
|
||||
let mut stream = match tokio::time::timeout(std::time::Duration::from_secs(2), connect).await {
|
||||
Ok(Ok(s)) => s,
|
||||
Ok(Err(e)) => return (false, e.to_string()),
|
||||
Err(_) => return (false, "timeout".into()),
|
||||
};
|
||||
let mut buf = [0u8; 256];
|
||||
match tokio::time::timeout(std::time::Duration::from_secs(2), stream.read(&mut buf)).await {
|
||||
Ok(Ok(n)) if n > 0 => {
|
||||
let greeting = String::from_utf8_lossy(&buf[..n]).trim().to_string();
|
||||
(
|
||||
greeting.starts_with("220") && greeting.contains("PhotoReport"),
|
||||
greeting,
|
||||
)
|
||||
}
|
||||
Ok(Ok(_)) => (false, "closed".into()),
|
||||
Ok(Err(e)) => (false, e.to_string()),
|
||||
Err(_) => (false, "no greeting".into()),
|
||||
}
|
||||
}
|
||||
|
||||
/// The macOS application firewall settings that stop a camera from reaching the server. Reading them needs no
|
||||
/// admin rights; other systems: None.
|
||||
fn firewall_problem() -> Option<String> {
|
||||
#[cfg(target_os = "macos")]
|
||||
{
|
||||
let fw = |arg: &[&str]| {
|
||||
std::process::Command::new("/usr/libexec/ApplicationFirewall/socketfilterfw")
|
||||
.args(arg)
|
||||
.output()
|
||||
.ok()
|
||||
.map(|o| String::from_utf8_lossy(&o.stdout).to_lowercase())
|
||||
.unwrap_or_default()
|
||||
};
|
||||
firewall_verdict(
|
||||
&fw(&["--getglobalstate"]),
|
||||
&fw(&["--getblockall"]),
|
||||
&std::env::current_exe()
|
||||
.ok()
|
||||
.map(|exe| fw(&["--getappblocked", &exe.to_string_lossy()]))
|
||||
.unwrap_or_default(),
|
||||
)
|
||||
}
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
{
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
/// From socketfilterfw's answers (lower-cased): what to tell the photographer.
|
||||
#[cfg_attr(not(target_os = "macos"), allow(dead_code))]
|
||||
fn firewall_verdict(global: &str, block_all: &str, app: &str) -> Option<String> {
|
||||
let on = global.contains("enabled")
|
||||
|| global.contains("(state = 1")
|
||||
|| global.contains("(state = 2");
|
||||
if !on {
|
||||
return None;
|
||||
}
|
||||
if block_all.contains("enabled") || block_all.contains("is on") {
|
||||
return Some("block_all".into());
|
||||
}
|
||||
if app.contains("blocked") && !app.contains("permitted") {
|
||||
return Some("app_blocked".into());
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// Keeps a folder name valid on macOS and Windows.
|
||||
fn clean_segment(s: &str) -> String {
|
||||
let cleaned: String = s
|
||||
@@ -293,7 +391,7 @@ impl Authenticator for Logins {
|
||||
let user = self
|
||||
.users
|
||||
.iter()
|
||||
.find(|u| u.name == username)
|
||||
.find(|u| u.enabled && u.name == username)
|
||||
.ok_or(AuthenticationError::BadUser)?;
|
||||
match creds.password.as_deref() {
|
||||
Some(p) if p == user.password => Ok(Principal {
|
||||
@@ -390,9 +488,31 @@ impl FtpState {
|
||||
addresses: lan_addresses(),
|
||||
waiting,
|
||||
error: self.last_error.lock().unwrap().clone(),
|
||||
checks: self.checks.lock().unwrap().clone(),
|
||||
firewall: self.firewall.lock().unwrap().clone(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Connects to the server on every LAN address, as a camera would, and reads the macOS firewall settings.
|
||||
pub async fn check(&self) -> FtpStatus {
|
||||
let port = self.settings().port;
|
||||
let running = self.running.lock().unwrap().is_some();
|
||||
let mut checks = Vec::new();
|
||||
if running {
|
||||
for address in lan_addresses() {
|
||||
let (ok, detail) = probe(&address, port).await;
|
||||
checks.push(AddressCheck {
|
||||
address,
|
||||
ok,
|
||||
detail,
|
||||
});
|
||||
}
|
||||
}
|
||||
*self.checks.lock().unwrap() = checks;
|
||||
*self.firewall.lock().unwrap() = firewall_problem();
|
||||
self.status()
|
||||
}
|
||||
|
||||
pub fn start(&self) -> Result<FtpStatus, String> {
|
||||
if self.running.lock().unwrap().is_some() {
|
||||
return Ok(self.status());
|
||||
@@ -442,6 +562,7 @@ impl FtpState {
|
||||
if let Some(r) = self.running.lock().unwrap().take() {
|
||||
let _ = r.stop.send(());
|
||||
}
|
||||
self.checks.lock().unwrap().clear();
|
||||
}
|
||||
|
||||
/// Complete photos in the ingest folder not handed out yet, oldest first.
|
||||
@@ -552,6 +673,12 @@ pub fn ftp_status(state: tauri::State<'_, FtpState>) -> FtpStatus {
|
||||
state.status()
|
||||
}
|
||||
|
||||
/// Tests the server from this computer's own network addresses and reads the firewall settings.
|
||||
#[tauri::command]
|
||||
pub async fn ftp_check(state: tauri::State<'_, FtpState>) -> Result<FtpStatus, String> {
|
||||
Ok(state.check().await)
|
||||
}
|
||||
|
||||
/// Saves the settings; a running server restarts with them.
|
||||
#[tauri::command]
|
||||
pub async fn ftp_save_settings(
|
||||
@@ -717,15 +844,57 @@ mod tests {
|
||||
assert_eq!(day, PathBuf::from("/w/2026/20261012"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reads_the_macos_firewall() {
|
||||
assert_eq!(
|
||||
firewall_verdict("firewall is disabled. (state = 0)", "", ""),
|
||||
None
|
||||
);
|
||||
assert_eq!(
|
||||
firewall_verdict(
|
||||
"firewall is enabled. (state = 1)",
|
||||
"block all disabled!",
|
||||
"the application is permitted"
|
||||
),
|
||||
None
|
||||
);
|
||||
assert_eq!(
|
||||
firewall_verdict("firewall is enabled. (state = 1)", "block all enabled!", ""),
|
||||
Some("block_all".into())
|
||||
);
|
||||
assert_eq!(
|
||||
firewall_verdict(
|
||||
"firewall is enabled. (state = 1)",
|
||||
"block all disabled!",
|
||||
"the application /applications/photoreport.app is blocked"
|
||||
),
|
||||
Some("app_blocked".into())
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn settings_are_checked() {
|
||||
let mut s = FtpSettings::default();
|
||||
assert!(s.check().is_ok());
|
||||
s.users = vec![FtpUser {
|
||||
name: "1dx".into(),
|
||||
password: "1dx".into(),
|
||||
}];
|
||||
s.users = vec![
|
||||
FtpUser {
|
||||
name: "1dx".into(),
|
||||
password: "1dx".into(),
|
||||
enabled: true,
|
||||
},
|
||||
FtpUser {
|
||||
name: "R3".into(),
|
||||
password: "r3".into(),
|
||||
enabled: false,
|
||||
},
|
||||
];
|
||||
assert!(s.check().is_ok());
|
||||
s.users[1].name = "1dx".into();
|
||||
assert_eq!(s.check().unwrap_err(), "duplicate_user");
|
||||
s.users[1].name = "R3".into();
|
||||
// Settings saved by an older app have no "enabled": the login is on.
|
||||
let old: FtpUser = serde_json::from_str(r#"{"name":"r1","password":"r1"}"#).unwrap();
|
||||
assert!(old.enabled);
|
||||
s.port = 21;
|
||||
assert_eq!(s.check().unwrap_err(), "port_low");
|
||||
s.port = 2121;
|
||||
@@ -754,10 +923,18 @@ mod tests {
|
||||
state
|
||||
.save(FtpSettings {
|
||||
port,
|
||||
users: vec![FtpUser {
|
||||
name: "1dx".into(),
|
||||
password: "1dx".into(),
|
||||
}],
|
||||
users: vec![
|
||||
FtpUser {
|
||||
name: "1dx".into(),
|
||||
password: "1dx".into(),
|
||||
enabled: true,
|
||||
},
|
||||
FtpUser {
|
||||
name: "R3".into(),
|
||||
password: "r3".into(),
|
||||
enabled: false,
|
||||
},
|
||||
],
|
||||
ingest: dir.join("ingest").to_string_lossy().into_owned(),
|
||||
work_folder: dir
|
||||
.join("{year}/{date} - {event}")
|
||||
@@ -806,6 +983,16 @@ mod tests {
|
||||
.status
|
||||
.success()
|
||||
);
|
||||
// A login switched off is refused.
|
||||
assert!(
|
||||
!curl("R3:r3", format!("ftp://[email protected]:{port}/"))
|
||||
.status
|
||||
.success()
|
||||
);
|
||||
// The self-test reaches the server like a camera would and reads its greeting.
|
||||
let (ok, greeting) = rt.block_on(probe("127.0.0.1", port));
|
||||
assert!(ok, "{greeting}");
|
||||
assert!(!rt.block_on(probe("127.0.0.1", port + 1)).0);
|
||||
|
||||
std::thread::sleep(std::time::Duration::from_millis(300));
|
||||
let got = state.take();
|
||||
|
||||
@@ -8,35 +8,31 @@ mod catalog;
|
||||
mod ftp;
|
||||
mod local;
|
||||
mod preview;
|
||||
mod ui;
|
||||
mod updater;
|
||||
|
||||
use keyring::Entry;
|
||||
use tauri::{WebviewUrl, WebviewWindowBuilder};
|
||||
|
||||
/// The web app the window shows. Loading it from the server means the desktop app is always on the latest version:
|
||||
/// every web deploy updates it, with no installer to rebuild. Set at build time (`PHOTOREPORT_APP_URL`).
|
||||
const APP_URL: &str = match option_env!("PHOTOREPORT_APP_URL") {
|
||||
/// Where new versions of the interface are published (`ui-manifest.json`, see `ui`). Set at build time
|
||||
/// (`PHOTOREPORT_APP_URL`).
|
||||
pub(crate) const APP_URL: &str = match option_env!("PHOTOREPORT_APP_URL") {
|
||||
Some(url) => url,
|
||||
None => "https://app.next.photoreport.pt",
|
||||
};
|
||||
|
||||
/// Whether the server answers: without a network the window opens the copy of the web app bundled in the installer
|
||||
/// (same interface, the photo engine included), so local work (catalogue, local FTP, editing originals on disk with
|
||||
/// the offline queue) still goes on. A TCP connection within 2.5 s is enough: a slow network still gets the live app.
|
||||
fn server_reachable(url: &str) -> bool {
|
||||
use std::net::{TcpStream, ToSocketAddrs};
|
||||
use std::time::Duration;
|
||||
let Ok(parsed) = url.parse::<tauri::Url>() else {
|
||||
return false;
|
||||
};
|
||||
let Some(host) = parsed.host_str() else {
|
||||
return false;
|
||||
};
|
||||
let port = parsed.port_or_known_default().unwrap_or(443);
|
||||
let Ok(mut addrs) = (host, port).to_socket_addrs() else {
|
||||
return false;
|
||||
};
|
||||
addrs.any(|a| TcpStream::connect_timeout(&a, Duration::from_millis(2500)).is_ok())
|
||||
const API_URL: &str = match option_env!("PHOTOREPORT_API_URL") {
|
||||
Some(url) => url,
|
||||
None => "https://api.next.photoreport.pt",
|
||||
};
|
||||
|
||||
/// Tells the interface (whichever version is on disk) where the API is and where its updates come from.
|
||||
fn init_script() -> String {
|
||||
format!(
|
||||
"window.__PHOTOREPORT__ = Object.freeze({{ api: {}, app: {} }});",
|
||||
serde_json::to_string(API_URL).unwrap(),
|
||||
serde_json::to_string(APP_URL).unwrap()
|
||||
)
|
||||
}
|
||||
|
||||
const KEYCHAIN_SERVICE: &str = "pt.photoreport.desktop";
|
||||
@@ -70,6 +66,14 @@ fn refresh_token_clear() -> Result<(), String> {
|
||||
|
||||
#[cfg_attr(mobile, tauri::mobile_entry_point)]
|
||||
pub fn run() {
|
||||
// The interface is served from disk: the downloaded version in use, else the installer's copy (see `ui`).
|
||||
let shared = ui::Ui::default();
|
||||
let mut context = tauri::generate_context!();
|
||||
let embedded = context.set_assets(Box::new(ui::NoAssets));
|
||||
context.set_assets(Box::new(ui::UiAssets {
|
||||
embedded,
|
||||
shared: shared.clone(),
|
||||
}));
|
||||
let result = tauri::Builder::default()
|
||||
.plugin(tauri_plugin_opener::init())
|
||||
.plugin(tauri_plugin_dialog::init())
|
||||
@@ -77,17 +81,19 @@ pub fn run() {
|
||||
.manage(ftp::FtpState::default())
|
||||
.manage(local::LocalIndex::default())
|
||||
.manage(catalog::Catalog::default())
|
||||
.manage(shared)
|
||||
.setup(|app| {
|
||||
use tauri::Manager;
|
||||
ftp::auto_start(&app.state::<ftp::FtpState>());
|
||||
// `tauri dev` keeps using the local dev server; installed builds load the live web app, or the bundled
|
||||
// copy when the server can't be reached.
|
||||
let url = if cfg!(debug_assertions) || !server_reachable(APP_URL) {
|
||||
WebviewUrl::App("index.html".into())
|
||||
} else {
|
||||
WebviewUrl::External(APP_URL.parse().expect("PHOTOREPORT_APP_URL must be a URL"))
|
||||
};
|
||||
// `tauri dev` serves the dev server: nothing to update.
|
||||
if !cfg!(debug_assertions) {
|
||||
ui::watch(app.handle().clone());
|
||||
}
|
||||
// Always the interface on this computer (`tauri dev`: the dev server). No download to start, and it
|
||||
// works without a network; new versions arrive in the background (see `ui`).
|
||||
let url = WebviewUrl::App("index.html".into());
|
||||
WebviewWindowBuilder::new(app, "main", url)
|
||||
.initialization_script(init_script())
|
||||
.title("PhotoReport")
|
||||
.inner_size(1440.0, 900.0)
|
||||
.min_inner_size(1024.0, 680.0)
|
||||
@@ -102,6 +108,7 @@ pub fn run() {
|
||||
ftp::ftp_start,
|
||||
ftp::ftp_stop,
|
||||
ftp::ftp_status,
|
||||
ftp::ftp_check,
|
||||
ftp::ftp_take,
|
||||
ftp::ftp_retry,
|
||||
ftp::ftp_read,
|
||||
@@ -118,9 +125,11 @@ pub fn run() {
|
||||
catalog::catalog_status,
|
||||
catalog::catalog_cancel,
|
||||
updater::update_check,
|
||||
updater::update_install
|
||||
updater::update_install,
|
||||
ui::ui_status,
|
||||
ui::ui_check
|
||||
])
|
||||
.run(tauri::generate_context!());
|
||||
.run(context);
|
||||
if let Err(err) = result {
|
||||
eprintln!("PhotoReport desktop failed to start: {err}");
|
||||
std::process::exit(1);
|
||||
|
||||
@@ -0,0 +1,473 @@
|
||||
//! The interface lives on this computer. The window always opens the web app from disk (no download to start, works
|
||||
//! without a network); new versions of the interface are fetched in the background, only the files that changed, and
|
||||
//! used from the next start (or when the photographer chooses to reload).
|
||||
//!
|
||||
//! Every web deploy publishes `ui-manifest.json` next to the app (path, size and SHA-256 of each file, when it was
|
||||
//! built). In the background (`watch`, or now with `ui_check`) the app compares it with the version in use, copies
|
||||
//! the files it already has (same hash, in the installer or the version in use), downloads only the others, checks
|
||||
//! every hash, then switches and tells the window (`ui-ready`). The installer's own copy is the fallback, and wins
|
||||
//! when it is newer (after a shell update).
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
use sha2::{Digest, Sha256};
|
||||
use std::borrow::Cow;
|
||||
use std::path::{Component, Path, PathBuf};
|
||||
use std::sync::{Arc, RwLock};
|
||||
use tauri::utils::assets::{AssetKey, AssetsIter, CspHash};
|
||||
use tauri::{App, Assets, Manager, Runtime};
|
||||
|
||||
const MANIFEST: &str = "ui-manifest.json";
|
||||
const CURRENT: &str = "current";
|
||||
|
||||
#[derive(Clone, Debug, Default, Deserialize, Serialize, PartialEq)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct ManifestFile {
|
||||
pub path: String,
|
||||
pub size: u64,
|
||||
pub sha256: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default, Deserialize, Serialize, PartialEq)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct Manifest {
|
||||
pub version: String,
|
||||
/// ISO 8601; compares as text.
|
||||
pub built_at: String,
|
||||
pub files: Vec<ManifestFile>,
|
||||
}
|
||||
|
||||
/// Shared by the asset provider (which serves the files) and the commands (which install new versions).
|
||||
#[derive(Default)]
|
||||
pub struct UiShared {
|
||||
/// `<app data>/ui`: one folder per version, and `current` naming the one in use.
|
||||
root: RwLock<Option<PathBuf>>,
|
||||
/// The downloaded version in use, when it is newer than the installer's.
|
||||
active: RwLock<Option<(Manifest, PathBuf)>>,
|
||||
/// The installer's own copy.
|
||||
embedded: RwLock<Option<Manifest>>,
|
||||
}
|
||||
|
||||
pub type Ui = Arc<UiShared>;
|
||||
|
||||
/// A path from the manifest or the webview, made safe to join under a folder: no `..`, no absolute paths.
|
||||
fn safe(rel: &str) -> Option<PathBuf> {
|
||||
let rel = rel.trim_start_matches('/');
|
||||
let p = Path::new(rel);
|
||||
if rel.is_empty() || p.components().any(|c| !matches!(c, Component::Normal(_))) {
|
||||
return None;
|
||||
}
|
||||
Some(p.to_path_buf())
|
||||
}
|
||||
|
||||
fn sha256_hex(bytes: &[u8]) -> String {
|
||||
Sha256::digest(bytes)
|
||||
.iter()
|
||||
.map(|b| format!("{b:02x}"))
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn read_manifest(dir: &Path) -> Option<Manifest> {
|
||||
serde_json::from_slice(&std::fs::read(dir.join(MANIFEST)).ok()?).ok()
|
||||
}
|
||||
|
||||
impl UiShared {
|
||||
/// Picks the version to serve: the downloaded one named in `current` if it is complete and newer than the
|
||||
/// installer's copy.
|
||||
fn choose(&self, root: &Path) {
|
||||
let embedded_at = self
|
||||
.embedded
|
||||
.read()
|
||||
.unwrap()
|
||||
.as_ref()
|
||||
.map(|m| m.built_at.clone())
|
||||
.unwrap_or_default();
|
||||
let chosen = std::fs::read_to_string(root.join(CURRENT))
|
||||
.ok()
|
||||
.and_then(|name| safe(name.trim()))
|
||||
.map(|name| root.join(name))
|
||||
.and_then(|dir| read_manifest(&dir).map(|m| (m, dir)))
|
||||
.filter(|(m, dir)| m.built_at > embedded_at && dir.join("index.html").is_file());
|
||||
*self.active.write().unwrap() = chosen;
|
||||
}
|
||||
|
||||
fn status(&self) -> UiStatus {
|
||||
if let Some((m, _)) = self.active.read().unwrap().as_ref() {
|
||||
return UiStatus {
|
||||
version: m.version.clone(),
|
||||
built_at: m.built_at.clone(),
|
||||
downloaded: true,
|
||||
};
|
||||
}
|
||||
let e = self.embedded.read().unwrap();
|
||||
UiStatus {
|
||||
version: e.as_ref().map(|m| m.version.clone()).unwrap_or_default(),
|
||||
built_at: e.as_ref().map(|m| m.built_at.clone()).unwrap_or_default(),
|
||||
downloaded: false,
|
||||
}
|
||||
}
|
||||
|
||||
fn root(&self) -> Result<PathBuf, String> {
|
||||
self.root
|
||||
.read()
|
||||
.unwrap()
|
||||
.clone()
|
||||
.ok_or_else(|| "ui_not_ready".into())
|
||||
}
|
||||
}
|
||||
|
||||
/// Serves the interface: the downloaded version in use when there is one, else (and for anything it lacks) the
|
||||
/// copy built into the installer. The window's origin stays the app's own, so nothing else changes.
|
||||
pub struct UiAssets<R: Runtime> {
|
||||
pub embedded: Box<dyn Assets<R>>,
|
||||
pub shared: Ui,
|
||||
}
|
||||
|
||||
impl<R: Runtime> Assets<R> for UiAssets<R> {
|
||||
fn setup(&self, app: &App<R>) {
|
||||
self.embedded.setup(app);
|
||||
let embedded: Option<Manifest> = self
|
||||
.embedded
|
||||
.get(&AssetKey::from(MANIFEST))
|
||||
.and_then(|b| serde_json::from_slice(&b).ok());
|
||||
*self.shared.embedded.write().unwrap() = embedded;
|
||||
if let Ok(dir) = app.path().app_data_dir() {
|
||||
let root = dir.join("ui");
|
||||
let _ = std::fs::create_dir_all(&root);
|
||||
self.shared.choose(&root);
|
||||
*self.shared.root.write().unwrap() = Some(root);
|
||||
}
|
||||
}
|
||||
|
||||
fn get(&self, key: &AssetKey) -> Option<Cow<'_, [u8]>> {
|
||||
if let Some((_, dir)) = self.shared.active.read().unwrap().as_ref()
|
||||
&& let Some(rel) = safe(key.as_ref())
|
||||
&& let Ok(bytes) = std::fs::read(dir.join(rel))
|
||||
{
|
||||
return Some(Cow::Owned(bytes));
|
||||
}
|
||||
self.embedded.get(key)
|
||||
}
|
||||
|
||||
fn iter(&self) -> Box<AssetsIter<'_>> {
|
||||
self.embedded.iter()
|
||||
}
|
||||
|
||||
fn csp_hashes(&self, html_path: &AssetKey) -> Box<dyn Iterator<Item = CspHash<'_>> + '_> {
|
||||
self.embedded.csp_hashes(html_path)
|
||||
}
|
||||
}
|
||||
|
||||
/// An empty provider, only to take the generated one out of the context.
|
||||
pub struct NoAssets;
|
||||
|
||||
impl<R: Runtime> Assets<R> for NoAssets {
|
||||
fn get(&self, _: &AssetKey) -> Option<Cow<'_, [u8]>> {
|
||||
None
|
||||
}
|
||||
fn iter(&self) -> Box<AssetsIter<'_>> {
|
||||
Box::new(std::iter::empty())
|
||||
}
|
||||
fn csp_hashes(&self, _: &AssetKey) -> Box<dyn Iterator<Item = CspHash<'_>> + '_> {
|
||||
Box::new(std::iter::empty())
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, PartialEq)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct UiStatus {
|
||||
pub version: String,
|
||||
pub built_at: String,
|
||||
/// False: the installer's copy.
|
||||
pub downloaded: bool,
|
||||
}
|
||||
|
||||
/// The interface version in use.
|
||||
#[tauri::command]
|
||||
pub fn ui_status(ui: tauri::State<'_, Ui>) -> UiStatus {
|
||||
ui.status()
|
||||
}
|
||||
|
||||
/// Looks for a newer interface now (it is also done in the background): true when one was installed, to use on reload.
|
||||
#[tauri::command]
|
||||
pub async fn ui_check(app: tauri::AppHandle) -> Result<bool, String> {
|
||||
check(&app).await
|
||||
}
|
||||
|
||||
/// How often the background check runs, and how long after start the first one waits (the window comes first).
|
||||
const EVERY: std::time::Duration = std::time::Duration::from_secs(30 * 60);
|
||||
const FIRST: std::time::Duration = std::time::Duration::from_secs(20);
|
||||
|
||||
/// Checks for new interface versions while the app runs; tells the window when one is ready (`ui-ready`).
|
||||
pub fn watch(app: tauri::AppHandle) {
|
||||
tauri::async_runtime::spawn(async move {
|
||||
tokio::time::sleep(FIRST).await;
|
||||
loop {
|
||||
match check(&app).await {
|
||||
Ok(true) => {
|
||||
use tauri::Emitter;
|
||||
let _ = app.emit("ui-ready", app.state::<Ui>().status());
|
||||
}
|
||||
Ok(false) => {}
|
||||
// No network, server down: nothing to do, the interface on disk keeps working.
|
||||
Err(err) => eprintln!("interface update: {err}"),
|
||||
}
|
||||
tokio::time::sleep(EVERY).await;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
fn client() -> Result<reqwest::Client, String> {
|
||||
if rustls::crypto::CryptoProvider::get_default().is_none() {
|
||||
let _ = rustls::crypto::ring::default_provider().install_default();
|
||||
}
|
||||
reqwest::Client::builder()
|
||||
.user_agent(concat!("PhotoReport-desktop/", env!("CARGO_PKG_VERSION")))
|
||||
.timeout(std::time::Duration::from_secs(120))
|
||||
.build()
|
||||
.map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
/// One check: the published manifest (a few KB), and only if it is newer than what is in use, the files that changed.
|
||||
async fn check(app: &tauri::AppHandle) -> Result<bool, String> {
|
||||
let ui = app.state::<Ui>().inner().clone();
|
||||
let base = crate::APP_URL.trim_end_matches('/');
|
||||
let http = client()?;
|
||||
let res = http
|
||||
.get(format!("{base}/{MANIFEST}"))
|
||||
.send()
|
||||
.await
|
||||
.map_err(|e| e.to_string())?;
|
||||
if !res.status().is_success() {
|
||||
return Err(format!("manifest: {}", res.status()));
|
||||
}
|
||||
let manifest: Manifest = res.json().await.map_err(|e| e.to_string())?;
|
||||
let current = ui.status();
|
||||
if manifest.version == current.version || manifest.built_at <= current.built_at {
|
||||
return Ok(false);
|
||||
}
|
||||
let root = ui.root()?;
|
||||
let missing = prepare(&ui, &root, &manifest, |path| {
|
||||
app.asset_resolver().get(path.to_string()).map(|a| a.bytes)
|
||||
})?;
|
||||
for path in missing {
|
||||
let file = manifest
|
||||
.files
|
||||
.iter()
|
||||
.find(|f| f.path == path)
|
||||
.ok_or("bad_manifest")?;
|
||||
let res = http
|
||||
.get(format!("{base}/{path}"))
|
||||
.send()
|
||||
.await
|
||||
.map_err(|e| e.to_string())?;
|
||||
if !res.status().is_success() {
|
||||
return Err(format!("{path}: {}", res.status()));
|
||||
}
|
||||
let bytes = res.bytes().await.map_err(|e| e.to_string())?;
|
||||
if sha256_hex(&bytes) != file.sha256 {
|
||||
return Err(format!("{path}: hash_mismatch"));
|
||||
}
|
||||
write(
|
||||
&staging(&root, &manifest.version)?.join(safe(&path).ok_or("bad_path")?),
|
||||
&bytes,
|
||||
)?;
|
||||
}
|
||||
activate(&ui, &root, &manifest)?;
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
fn staging(root: &Path, version: &str) -> Result<PathBuf, String> {
|
||||
let name = safe(version)
|
||||
.filter(|p| p.components().count() == 1)
|
||||
.ok_or("bad_version")?;
|
||||
Ok(root.join(format!("{}.part", name.display())))
|
||||
}
|
||||
|
||||
/// Starts installing `manifest`: copies into a staging folder every file this computer already has (same hash, in the
|
||||
/// version in use or the installer's copy) and returns the paths still to download.
|
||||
fn prepare(
|
||||
ui: &UiShared,
|
||||
root: &Path,
|
||||
manifest: &Manifest,
|
||||
embedded: impl Fn(&str) -> Option<Vec<u8>>,
|
||||
) -> Result<Vec<String>, String> {
|
||||
let stage = staging(root, &manifest.version)?;
|
||||
std::fs::create_dir_all(&stage).map_err(|e| e.to_string())?;
|
||||
let active = ui.active.read().unwrap().as_ref().map(|(_, d)| d.clone());
|
||||
let mut missing = Vec::new();
|
||||
for f in &manifest.files {
|
||||
let rel = safe(&f.path).ok_or("bad_path")?;
|
||||
let target = stage.join(&rel);
|
||||
let ok = |b: &[u8]| sha256_hex(b) == f.sha256;
|
||||
if std::fs::read(&target).is_ok_and(|b| ok(&b)) {
|
||||
continue;
|
||||
}
|
||||
let local = active
|
||||
.as_ref()
|
||||
.and_then(|d| std::fs::read(d.join(&rel)).ok())
|
||||
.filter(|b| ok(b))
|
||||
.or_else(|| embedded(&f.path).filter(|b| ok(b)));
|
||||
match local {
|
||||
Some(bytes) => write(&target, &bytes)?,
|
||||
None => missing.push(f.path.clone()),
|
||||
}
|
||||
}
|
||||
Ok(missing)
|
||||
}
|
||||
|
||||
fn write(target: &Path, bytes: &[u8]) -> Result<(), String> {
|
||||
if let Some(parent) = target.parent() {
|
||||
std::fs::create_dir_all(parent).map_err(|e| e.to_string())?;
|
||||
}
|
||||
std::fs::write(target, bytes).map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
/// Switches to `manifest` once every file is in place and checks out; the version it replaces is kept as a fallback,
|
||||
/// older ones removed. Served from the next start, or now if the window reloads.
|
||||
fn activate(ui: &UiShared, root: &Path, manifest: &Manifest) -> Result<(), String> {
|
||||
let stage = staging(root, &manifest.version)?;
|
||||
for f in &manifest.files {
|
||||
let bytes = std::fs::read(stage.join(safe(&f.path).ok_or("bad_path")?))
|
||||
.map_err(|_| format!("missing:{}", f.path))?;
|
||||
if sha256_hex(&bytes) != f.sha256 {
|
||||
return Err(format!("hash_mismatch:{}", f.path));
|
||||
}
|
||||
}
|
||||
if !manifest.files.iter().any(|f| f.path == "index.html") {
|
||||
return Err("no_index".into());
|
||||
}
|
||||
write(
|
||||
&stage.join(MANIFEST),
|
||||
&serde_json::to_vec(manifest).map_err(|e| e.to_string())?,
|
||||
)?;
|
||||
let dir = root.join(&manifest.version);
|
||||
let previous = ui.active.read().unwrap().as_ref().map(|(_, d)| d.clone());
|
||||
if Some(&dir) != previous.as_ref() {
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
std::fs::rename(&stage, &dir).map_err(|e| e.to_string())?;
|
||||
write(&root.join(CURRENT), manifest.version.as_bytes())?;
|
||||
ui.choose(root);
|
||||
if let Ok(entries) = std::fs::read_dir(root) {
|
||||
for e in entries.flatten() {
|
||||
let p = e.path();
|
||||
if p.is_dir() && p != dir && Some(&p) != previous.as_ref() {
|
||||
let _ = std::fs::remove_dir_all(p);
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn paths_stay_inside_the_folder() {
|
||||
assert_eq!(
|
||||
safe("/assets/index-abc.js"),
|
||||
Some(PathBuf::from("assets/index-abc.js"))
|
||||
);
|
||||
assert_eq!(safe("index.html"), Some(PathBuf::from("index.html")));
|
||||
assert_eq!(safe("../etc/passwd"), None);
|
||||
assert_eq!(safe("assets/../../x"), None);
|
||||
assert_eq!(safe(""), None);
|
||||
assert!(staging(Path::new("/r"), "a/b").is_err());
|
||||
assert!(staging(Path::new("/r"), "..").is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn installs_only_what_changed_and_checks_every_file() {
|
||||
let root = std::env::temp_dir().join(format!("pr-ui-install-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&root);
|
||||
std::fs::create_dir_all(&root).unwrap();
|
||||
let file = |path: &str, body: &str| ManifestFile {
|
||||
path: path.into(),
|
||||
size: body.len() as u64,
|
||||
sha256: sha256_hex(body.as_bytes()),
|
||||
};
|
||||
let ui = UiShared::default();
|
||||
*ui.embedded.write().unwrap() = Some(Manifest {
|
||||
version: "v1".into(),
|
||||
built_at: "2026-10-12T10:00:00Z".into(),
|
||||
files: vec![],
|
||||
});
|
||||
let embedded = |p: &str| match p {
|
||||
"index.html" => Some(b"<html>v1</html>".to_vec()),
|
||||
"engine.wasm" => Some(b"wasm".to_vec()),
|
||||
_ => None,
|
||||
};
|
||||
let v2 = Manifest {
|
||||
version: "v2".into(),
|
||||
built_at: "2026-10-13T16:00:00Z".into(),
|
||||
files: vec![
|
||||
file("index.html", "<html>v2</html>"),
|
||||
file("engine.wasm", "wasm"),
|
||||
file("assets/app-2.js", "js2"),
|
||||
],
|
||||
};
|
||||
// The engine didn't change: copied from the installer, not downloaded.
|
||||
assert_eq!(
|
||||
prepare(&ui, &root, &v2, embedded).unwrap(),
|
||||
vec!["index.html", "assets/app-2.js"]
|
||||
);
|
||||
// Not everything there yet: refused.
|
||||
assert!(activate(&ui, &root, &v2).is_err());
|
||||
let stage = staging(&root, "v2").unwrap();
|
||||
write(&stage.join("index.html"), b"<html>v2</html>").unwrap();
|
||||
write(&stage.join("assets/app-2.js"), b"tampered").unwrap();
|
||||
assert!(
|
||||
activate(&ui, &root, &v2)
|
||||
.unwrap_err()
|
||||
.starts_with("hash_mismatch")
|
||||
);
|
||||
write(&stage.join("assets/app-2.js"), b"js2").unwrap();
|
||||
activate(&ui, &root, &v2).unwrap();
|
||||
assert_eq!(ui.status().version, "v2");
|
||||
assert!(ui.status().downloaded);
|
||||
let _ = std::fs::remove_dir_all(&root);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn serves_the_downloaded_version_only_when_newer_than_the_installer() {
|
||||
let root = std::env::temp_dir().join(format!("pr-ui-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&root);
|
||||
let dir = root.join("v2");
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
std::fs::write(dir.join("index.html"), "<html>v2</html>").unwrap();
|
||||
let m = Manifest {
|
||||
version: "v2".into(),
|
||||
built_at: "2026-10-13T16:00:00Z".into(),
|
||||
files: vec![],
|
||||
};
|
||||
std::fs::write(dir.join(MANIFEST), serde_json::to_vec(&m).unwrap()).unwrap();
|
||||
std::fs::write(root.join(CURRENT), "v2").unwrap();
|
||||
|
||||
let ui = UiShared::default();
|
||||
*ui.embedded.write().unwrap() = Some(Manifest {
|
||||
version: "v1".into(),
|
||||
built_at: "2026-10-12T10:00:00Z".into(),
|
||||
files: vec![],
|
||||
});
|
||||
ui.choose(&root);
|
||||
assert_eq!(
|
||||
ui.status(),
|
||||
UiStatus {
|
||||
version: "v2".into(),
|
||||
built_at: "2026-10-13T16:00:00Z".into(),
|
||||
downloaded: true
|
||||
}
|
||||
);
|
||||
|
||||
// A newer installer (the shell was updated): its own copy wins.
|
||||
*ui.embedded.write().unwrap() = Some(Manifest {
|
||||
version: "v3".into(),
|
||||
built_at: "2026-10-20T10:00:00Z".into(),
|
||||
files: vec![],
|
||||
});
|
||||
ui.choose(&root);
|
||||
assert!(!ui.status().downloaded);
|
||||
let _ = std::fs::remove_dir_all(&root);
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
//! Updates of the native shell. The web app inside the window already updates with every web deploy; only the
|
||||
//! shell itself (local FTP, catalogue, keychain) needs an installer, and this keeps it current too.
|
||||
//! Updates of the native shell. The interface inside the window updates itself from every web deploy (see `ui`:
|
||||
//! downloaded in the background, only what changed); only the shell itself (local FTP, catalogue, keychain) needs an
|
||||
//! installer, and this keeps it current too.
|
||||
//!
|
||||
//! The app asks the API (`/v1/desktop/update/{target}/{arch}/{version}`), which reads the latest `desktop-v*`
|
||||
//! release. Installers are signed at build time with the release key; the matching public key is compiled in
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"$schema": "https://schema.tauri.app/config/2",
|
||||
"productName": "PhotoReport",
|
||||
"version": "0.3.1",
|
||||
"version": "0.3.6",
|
||||
"identifier": "pt.photoreport.desktop",
|
||||
"build": {
|
||||
"devUrl": "http://localhost:5173",
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
//! The web app is loaded from the server (a remote origin), so every command it calls must be listed in build.rs
|
||||
//! (to get an ACL permission) and allowed in capabilities/default.json. A command registered in lib.rs but missing
|
||||
//! from either is refused at runtime and looks like "this desktop app is too old" in the web app.
|
||||
|
||||
use std::path::Path;
|
||||
|
||||
fn read(rel: &str) -> String {
|
||||
std::fs::read_to_string(Path::new(env!("CARGO_MANIFEST_DIR")).join(rel)).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_registered_command_is_allowed_for_the_web_app() {
|
||||
let lib = read("src/lib.rs");
|
||||
let start =
|
||||
lib.find("generate_handler![").expect("generate_handler") + "generate_handler![".len();
|
||||
let end = start + lib[start..].find(']').unwrap();
|
||||
let commands: Vec<String> = lib[start..end]
|
||||
.split(',')
|
||||
.map(|c| c.trim().rsplit("::").next().unwrap_or("").to_string())
|
||||
.filter(|c| !c.is_empty())
|
||||
.collect();
|
||||
assert!(commands.len() > 10, "{commands:?}");
|
||||
|
||||
let build = read("build.rs");
|
||||
let capabilities = read("capabilities/default.json");
|
||||
for c in &commands {
|
||||
assert!(
|
||||
build.contains(&format!("\"{c}\"")),
|
||||
"{c} is not listed in build.rs"
|
||||
);
|
||||
let permission = format!("\"allow-{}\"", c.replace('_', "-"));
|
||||
assert!(
|
||||
capabilities.contains(&permission),
|
||||
"{permission} is missing from capabilities/default.json"
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
# apps/print-agent
|
||||
|
||||
Runs on the computer next to the printers (macOS or Linux with CUPS). It pairs with PhotoReport once, tells the
|
||||
Runs on the computer next to the printers (macOS or Linux with CUPS, or Windows with the printer's driver). It pairs with PhotoReport once, tells the
|
||||
server which printers it sees, takes print jobs for printers loaded with the job's paper, prints them and
|
||||
reports back. Jobs from a station that dies mid-print go back to the queue after five minutes.
|
||||
|
||||
@@ -15,4 +15,9 @@ node apps/print-agent/dist/cli.js run
|
||||
printers (Gutenprint, Mitsubishi CP-D90DW): 10x15 `w288h432`, 15x20 `w432h576`, 20x30 `w576h864`; override
|
||||
with `"media": {"15x20": "..."}` in the config file (`~/.config/photoreport-print-agent/config.json`).
|
||||
- `--folder <dir>` at pairing prints into folders instead (training, tests without paper).
|
||||
- Windows: not yet (needs a provider for the Windows spooler).
|
||||
- Windows: the spooler, through Windows PowerShell 5.1 and .NET (nothing else to install besides Node 22). It picks
|
||||
the driver's paper that matches the job's size (4x6, 5x7, 6x8 or 8x12 in), prints without margins and turns
|
||||
the photo to the paper. If a driver names a size differently, set `"paper": {"15x20": [600, 800]}` (hundredths
|
||||
of an inch) in the config, `%APPDATA%\PhotoReport\photoreport-print-agent\config.json`. To start it with
|
||||
Windows: `schtasks /Create /SC ONLOGON /TN "PhotoReport impressao" /TR "node C:\photoreport\apps\print-agent\dist\cli.js run"`.
|
||||
Still to confirm on a real Windows computer with a dye-sub printer (DNP, Mitsubishi).
|
||||
@@ -1,3 +1,4 @@
|
||||
import { parseWindowsPrinters, WINDOWS_PAPER, windowsProvider } from "./providers.js";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { PrintAgent, pair } from "./agent.js";
|
||||
import { parseLpstat, type PrintProvider } from "./providers.js";
|
||||
@@ -55,4 +56,24 @@ describe("print agent", () => {
|
||||
await agent.once();
|
||||
expect(results).toEqual([{ ok: false, error: "lp: printer offline" }]);
|
||||
});
|
||||
|
||||
it("lists and prints through the Windows spooler, values passed outside the script", async () => {
|
||||
expect(parseWindowsPrinters('{"Name":"DNP DS620","Status":"Normal"}')).toEqual([{ systemName: "DNP DS620", state: "idle" }]);
|
||||
expect(parseWindowsPrinters('[{"Name":"A","Status":"Printing"},{"Name":"B","Status":"Offline"}]').map((p) => p.state)).toEqual(["printing", "offline"]);
|
||||
expect(parseWindowsPrinters("")).toEqual([]);
|
||||
|
||||
const calls: { file: string; args: string[]; env?: NodeJS.ProcessEnv }[] = [];
|
||||
const runner = async (file: string, args: string[], opts: { env?: NodeJS.ProcessEnv }) => {
|
||||
calls.push({ file, args, ...(opts.env && { env: opts.env }) });
|
||||
return { stdout: '{"Name":"Mitsubishi CP-D90DW","Status":"Normal"}' };
|
||||
};
|
||||
const win = windowsProvider(WINDOWS_PAPER, runner);
|
||||
expect(await win.list()).toEqual([{ systemName: "Mitsubishi CP-D90DW", state: "idle" }]);
|
||||
await win.print("Sala \"VIP\" D90", "C:\\Temp\\job 1.jpg", { size: "15x20", copies: 2 });
|
||||
const job = calls[1]!;
|
||||
expect(job.file).toBe("powershell.exe");
|
||||
expect(job.args.slice(0, 4)).toEqual(["-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass"]);
|
||||
expect(job.args.at(-1)).not.toContain("VIP");
|
||||
expect(job.env).toMatchObject({ PR_PRINTER: 'Sala "VIP" D90', PR_FILE: "C:\\Temp\\job 1.jpg", PR_COPIES: "2", PR_PAPER_W: "600", PR_PAPER_H: "800" });
|
||||
});
|
||||
});
|
||||
@@ -3,18 +3,22 @@ import { chmod, mkdir, readFile, writeFile } from "node:fs/promises";
|
||||
import { homedir, hostname } from "node:os";
|
||||
import path from "node:path";
|
||||
import { PrintAgent, pair } from "./agent.js";
|
||||
import { CUPS_MEDIA, cupsProvider, folderProvider } from "./providers.js";
|
||||
import { CUPS_MEDIA, cupsProvider, folderProvider, WINDOWS_PAPER, windowsProvider } from "./providers.js";
|
||||
|
||||
const VERSION = "0.1.0";
|
||||
const CONFIG = process.env.PR_AGENT_CONFIG ?? path.join(homedir(), ".config", "photoreport-print-agent", "config.json");
|
||||
// Windows keeps per-user settings in %APPDATA%; macOS and Linux in ~/.config.
|
||||
const CONFIG_DIR = process.platform === "win32" && process.env.APPDATA ? path.join(process.env.APPDATA, "PhotoReport") : path.join(homedir(), ".config");
|
||||
const CONFIG = process.env.PR_AGENT_CONFIG ?? path.join(CONFIG_DIR, "photoreport-print-agent", "config.json");
|
||||
|
||||
interface Config {
|
||||
api: string;
|
||||
token: string;
|
||||
provider?: "cups" | "folder";
|
||||
provider?: "cups" | "windows" | "folder";
|
||||
folder?: string;
|
||||
folderPrinters?: string[];
|
||||
media?: Record<string, string>;
|
||||
/** Windows: paper per size in hundredths of an inch ([width, height]), when a driver names it differently. */
|
||||
paper?: Record<string, [number, number]>;
|
||||
}
|
||||
|
||||
const usage = `PhotoReport print agent ${VERSION}
|
||||
@@ -33,8 +37,9 @@ async function load(): Promise<Config> {
|
||||
}
|
||||
}
|
||||
|
||||
function provider(c: Pick<Config, "provider" | "folder" | "folderPrinters" | "media">) {
|
||||
function provider(c: Pick<Config, "provider" | "folder" | "folderPrinters" | "media" | "paper">) {
|
||||
if (c.provider === "folder") return folderProvider(c.folder ?? path.join(homedir(), "photoreport-prints"), c.folderPrinters);
|
||||
if (c.provider === "windows" || (!c.provider && process.platform === "win32")) return windowsProvider({ ...WINDOWS_PAPER, ...c.paper });
|
||||
return cupsProvider({ ...CUPS_MEDIA, ...c.media });
|
||||
}
|
||||
|
||||
|
||||
@@ -73,3 +73,86 @@ export function folderProvider(root: string, names: string[] = ["Teste"]): Print
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Paper sizes in hundredths of an inch (the unit of .NET's PaperSize) for the Windows spooler:
|
||||
* 10x15 = 4x6 in, 13x18 = 5x7 in, 15x20 = 6x8 in, 20x30 = 8x12 in.
|
||||
*/
|
||||
export const WINDOWS_PAPER: Record<string, [number, number]> = {
|
||||
"10x15": [400, 600],
|
||||
"13x18": [500, 700],
|
||||
"15x20": [600, 800],
|
||||
"20x30": [800, 1200],
|
||||
};
|
||||
|
||||
/** `Get-Printer` as JSON (one object, or an array): name and status. */
|
||||
export function parseWindowsPrinters(json: string): LocalPrinter[] {
|
||||
if (!json.trim()) return [];
|
||||
const raw = JSON.parse(json) as { Name: string; Status?: string | null } | { Name: string; Status?: string | null }[];
|
||||
return (Array.isArray(raw) ? raw : [raw]).map((p) => {
|
||||
const s = String(p.Status ?? "").toLowerCase();
|
||||
return { systemName: p.Name, state: s === "normal" || s === "" ? "idle" : s === "printing" ? "printing" : s.slice(0, 120) };
|
||||
});
|
||||
}
|
||||
|
||||
const LIST_PS = `Get-Printer | Select-Object Name,@{n='Status';e={"$($_.PrinterStatus)"}} | ConvertTo-Json -Compress`;
|
||||
|
||||
/**
|
||||
* Prints one photo through the Windows spooler with .NET (System.Drawing, in Windows PowerShell 5.1, no install):
|
||||
* the paper of the job's size when the driver has it, no margins, the photo turned to the paper's orientation and
|
||||
* fitted (the server already laid it out at the paper's proportions). Values come in environment variables, never
|
||||
* inside the script, so names with quotes or spaces can't break it.
|
||||
*/
|
||||
const PRINT_PS = `
|
||||
$ErrorActionPreference = 'Stop'
|
||||
Add-Type -AssemblyName System.Drawing
|
||||
$img = [System.Drawing.Image]::FromFile($env:PR_FILE)
|
||||
$doc = New-Object System.Drawing.Printing.PrintDocument
|
||||
$doc.PrinterSettings.PrinterName = $env:PR_PRINTER
|
||||
if (-not $doc.PrinterSettings.IsValid) { throw "printer not found: $($env:PR_PRINTER)" }
|
||||
$doc.PrinterSettings.Copies = [int]$env:PR_COPIES
|
||||
$w = [int]$env:PR_PAPER_W; $h = [int]$env:PR_PAPER_H
|
||||
if ($w -gt 0) {
|
||||
$paper = $doc.PrinterSettings.PaperSizes | Where-Object { ([math]::Abs($_.Width - $w) -le 25 -and [math]::Abs($_.Height - $h) -le 25) -or ([math]::Abs($_.Width - $h) -le 25 -and [math]::Abs($_.Height - $w) -le 25) } | Select-Object -First 1
|
||||
if ($paper) { $doc.DefaultPageSettings.PaperSize = $paper }
|
||||
}
|
||||
$doc.DefaultPageSettings.Landscape = ($img.Width -gt $img.Height)
|
||||
$doc.DefaultPageSettings.Margins = New-Object System.Drawing.Printing.Margins(0, 0, 0, 0)
|
||||
$doc.OriginAtMargins = $false
|
||||
$doc.DocumentName = 'PhotoReport ' + [System.IO.Path]::GetFileName($env:PR_FILE)
|
||||
$doc.add_PrintPage({
|
||||
param($sender, $e)
|
||||
$b = $e.PageBounds
|
||||
$scale = [math]::Min($b.Width / $img.Width, $b.Height / $img.Height)
|
||||
$dw = $img.Width * $scale; $dh = $img.Height * $scale
|
||||
$e.Graphics.InterpolationMode = [System.Drawing.Drawing2D.InterpolationMode]::HighQualityBicubic
|
||||
$e.Graphics.DrawImage($img, [single](($b.Width - $dw) / 2), [single](($b.Height - $dh) / 2), [single]$dw, [single]$dh)
|
||||
$e.HasMorePages = $false
|
||||
})
|
||||
try { $doc.Print() } finally { $img.Dispose() }
|
||||
`;
|
||||
|
||||
type Runner = (file: string, args: string[], opts: { timeout: number; env?: NodeJS.ProcessEnv }) => Promise<{ stdout: string }>;
|
||||
|
||||
const powershell = (script: string) => ["-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass", "-Command", script];
|
||||
|
||||
/** The Windows spooler (any installed printer driver, e.g. DNP or Mitsubishi), through Windows PowerShell. */
|
||||
export function windowsProvider(paper: Record<string, [number, number]> = WINDOWS_PAPER, runner: Runner = run as unknown as Runner): PrintProvider {
|
||||
return {
|
||||
async list() {
|
||||
try {
|
||||
const { stdout } = await runner("powershell.exe", powershell(LIST_PS), { timeout: 20_000 });
|
||||
return parseWindowsPrinters(stdout);
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
},
|
||||
async print(printer, file, opts) {
|
||||
const [w, h] = paper[opts.size] ?? [0, 0];
|
||||
await runner("powershell.exe", powershell(PRINT_PS), {
|
||||
timeout: 120_000,
|
||||
env: { ...process.env, PR_PRINTER: printer, PR_FILE: file, PR_COPIES: String(opts.copies), PR_PAPER_W: String(w), PR_PAPER_H: String(h) },
|
||||
});
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,318 @@
|
||||
"use client";
|
||||
|
||||
import type { KioskView } from "@photoreport/contracts";
|
||||
import { useCallback, useEffect, useRef, useState } from "react";
|
||||
|
||||
const IDLE_MS = 60_000;
|
||||
const THANKS_MS = 7_000;
|
||||
|
||||
const STATUS: Record<KioskView["jobs"][number]["status"], string> = {
|
||||
PAYMENT: "a pagar",
|
||||
APPROVAL: "à espera do balcão",
|
||||
QUEUED: "na fila",
|
||||
PRINTING: "a imprimir",
|
||||
DONE: "pronta",
|
||||
FAILED: "falhou",
|
||||
CANCELLED: "cancelada",
|
||||
};
|
||||
|
||||
type Screen = { kind: "grid" } | { kind: "photo"; id: string; preview: string } | { kind: "camera" } | { kind: "shot"; blob: Blob; url: string } | { kind: "sent"; status: string };
|
||||
|
||||
const dark = "#0e0e0f";
|
||||
const accent = "#e2001a";
|
||||
const big: React.CSSProperties = { height: 72, padding: "0 32px", fontSize: 26, fontWeight: 700, border: 0, borderRadius: 14, color: "#fff", background: accent, cursor: "pointer" };
|
||||
const ghost: React.CSSProperties = { ...big, background: "#2a2a2c" };
|
||||
|
||||
/**
|
||||
* The kiosk: full screen, touch only, no account. Guests tap one of the photographer's photos (or take one with the
|
||||
* tablet's camera), say their name and how many copies, and it goes to the event's print queue. After a minute
|
||||
* without a touch it goes back to the start, so the next guest never sees the previous one's choice.
|
||||
*/
|
||||
export function Kiosk({ slug, token }: { slug: string; token: string }) {
|
||||
const [view, setView] = useState<KioskView | null>(null);
|
||||
const [failed, setFailed] = useState<string | null>(null);
|
||||
const [screen, setScreen] = useState<Screen>({ kind: "grid" });
|
||||
const [name, setName] = useState("");
|
||||
const [copies, setCopies] = useState(1);
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const idle = useRef<ReturnType<typeof setTimeout>>(undefined);
|
||||
|
||||
const load = useCallback(async () => {
|
||||
const res = await fetch(`/v1/public/print/${encodeURIComponent(slug)}/kiosk?k=${encodeURIComponent(token)}`, { cache: "no-store" }).catch(() => null);
|
||||
if (!res) return; // offline for a moment: keep what is on screen
|
||||
if (res.status === 404) return setFailed("Este link de quiosque já não é válido. Pede um novo na app (Impressão → Quiosque).");
|
||||
if (res.ok) {
|
||||
setFailed(null);
|
||||
setView((await res.json()) as KioskView);
|
||||
}
|
||||
}, [slug, token]);
|
||||
|
||||
const reset = useCallback(() => {
|
||||
setScreen((s) => {
|
||||
if (s.kind === "shot") URL.revokeObjectURL(s.url);
|
||||
return { kind: "grid" };
|
||||
});
|
||||
setName("");
|
||||
setCopies(1);
|
||||
setError(null);
|
||||
}, []);
|
||||
|
||||
// New photos arrive during the event; the strip of recent prints follows the queue.
|
||||
useEffect(() => {
|
||||
void load();
|
||||
const t = setInterval(load, 15_000);
|
||||
return () => clearInterval(t);
|
||||
}, [load]);
|
||||
|
||||
// Back to the start after a minute without a touch.
|
||||
useEffect(() => {
|
||||
const poke = () => {
|
||||
clearTimeout(idle.current);
|
||||
idle.current = setTimeout(reset, IDLE_MS);
|
||||
};
|
||||
poke();
|
||||
for (const e of ["pointerdown", "keydown"]) window.addEventListener(e, poke);
|
||||
return () => {
|
||||
clearTimeout(idle.current);
|
||||
for (const e of ["pointerdown", "keydown"]) window.removeEventListener(e, poke);
|
||||
};
|
||||
}, [reset]);
|
||||
|
||||
// Keep the screen on while the kiosk is open (where the browser allows it).
|
||||
useEffect(() => {
|
||||
let lock: { release: () => Promise<void> } | null = null;
|
||||
const take = async () => {
|
||||
try {
|
||||
lock = (await (navigator as unknown as { wakeLock?: { request: (t: string) => Promise<{ release: () => Promise<void> }> } }).wakeLock?.request("screen")) ?? null;
|
||||
} catch {
|
||||
lock = null;
|
||||
}
|
||||
};
|
||||
void take();
|
||||
const again = () => document.visibilityState === "visible" && void take();
|
||||
document.addEventListener("visibilitychange", again);
|
||||
return () => {
|
||||
document.removeEventListener("visibilitychange", again);
|
||||
void lock?.release().catch(() => {});
|
||||
};
|
||||
}, []);
|
||||
|
||||
const finish = async (res: Response | null) => {
|
||||
setBusy(false);
|
||||
if (!res?.ok) {
|
||||
const code = res ? ((await res.json().catch(() => ({}))) as { error?: string }).error : undefined;
|
||||
setError(code === "event_closed" ? "As impressões deste evento estão fechadas." : "Não foi possível enviar. Tenta outra vez.");
|
||||
return;
|
||||
}
|
||||
const { status } = (await res.json()) as { status: string };
|
||||
setScreen({ kind: "sent", status });
|
||||
void load();
|
||||
setTimeout(reset, THANKS_MS);
|
||||
};
|
||||
|
||||
const printPhoto = async (photoId: string) => {
|
||||
setBusy(true);
|
||||
await finish(
|
||||
await fetch(`/v1/public/print/${encodeURIComponent(slug)}/kiosk/pick`, {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json" },
|
||||
body: JSON.stringify({ k: token, photoId, copies, ...(name.trim() && { name: name.trim() }) }),
|
||||
}).catch(() => null),
|
||||
);
|
||||
};
|
||||
|
||||
const printShot = async (blob: Blob) => {
|
||||
setBusy(true);
|
||||
const form = new FormData();
|
||||
form.append("k", token);
|
||||
form.append("copies", String(copies));
|
||||
if (name.trim()) form.append("name", name.trim());
|
||||
form.append("file", blob, "photobooth.jpg");
|
||||
await finish(await fetch(`/v1/public/print/${encodeURIComponent(slug)}/kiosk/capture`, { method: "POST", body: form }).catch(() => null));
|
||||
};
|
||||
|
||||
const fullscreen = () => void document.documentElement.requestFullscreen?.().catch(() => {});
|
||||
|
||||
const shell: React.CSSProperties = { position: "fixed", inset: 0, zIndex: 1000, background: dark, color: "#f2f2f2", display: "flex", flexDirection: "column", fontFamily: "inherit", userSelect: "none", touchAction: "manipulation" };
|
||||
|
||||
if (failed || !token) return <div style={{ ...shell, alignItems: "center", justifyContent: "center", padding: 40, fontSize: 24, textAlign: "center" }}>{failed ?? "Falta o código do quiosque no link."}</div>;
|
||||
if (!view) return <div style={{ ...shell, alignItems: "center", justifyContent: "center", fontSize: 24 }}>A carregar…</div>;
|
||||
|
||||
const price = view.priceCents ? `${(view.priceCents / 100).toFixed(2).replace(".", ",")} € por foto, paga no balcão` : null;
|
||||
|
||||
return (
|
||||
<div style={shell}>
|
||||
<header style={{ display: "flex", alignItems: "center", gap: 16, padding: "18px 28px", borderBottom: "1px solid #222" }}>
|
||||
<div style={{ flex: 1 }}>
|
||||
<div style={{ fontSize: 30, fontWeight: 800 }}>{view.name}</div>
|
||||
<div style={{ fontSize: 16, color: "#9a9a9e" }}>
|
||||
Impressão {view.size.replace("x", " × ")} cm{price ? ` · ${price}` : " · grátis"}
|
||||
</div>
|
||||
</div>
|
||||
{screen.kind === "grid" && (
|
||||
<button style={big} onClick={() => setScreen({ kind: "camera" })} disabled={!view.active}>
|
||||
📷 Tirar foto
|
||||
</button>
|
||||
)}
|
||||
<button style={{ ...ghost, height: 48, fontSize: 16, padding: "0 16px" }} onClick={fullscreen} aria-label="Ecrã inteiro">
|
||||
⛶
|
||||
</button>
|
||||
</header>
|
||||
|
||||
<main style={{ flex: 1, overflow: "auto", position: "relative" }}>
|
||||
{!view.active && <p style={{ padding: 40, fontSize: 26, textAlign: "center" }}>As impressões deste evento estão fechadas.</p>}
|
||||
|
||||
{view.active && screen.kind === "grid" && (
|
||||
<>
|
||||
{view.photos.length === 0 ? (
|
||||
<p style={{ padding: 40, fontSize: 24, textAlign: "center", color: "#9a9a9e" }}>As fotos do fotógrafo aparecem aqui assim que chegarem. Entretanto, tira uma foto com o tablet.</p>
|
||||
) : (
|
||||
<div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fill, minmax(220px, 1fr))", gap: 10, padding: 16 }}>
|
||||
{view.photos.map((p) => (
|
||||
<button key={p.id} onClick={() => setScreen({ kind: "photo", id: p.id, preview: p.preview })} style={{ padding: 0, border: 0, background: "#1a1a1c", borderRadius: 10, overflow: "hidden", aspectRatio: "1", cursor: "pointer" }} aria-label="Escolher esta foto">
|
||||
<img src={p.thumb} alt="" loading="lazy" style={{ width: "100%", height: "100%", objectFit: "cover", display: "block" }} />
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
|
||||
{screen.kind === "camera" && <Camera onShot={(blob) => setScreen({ kind: "shot", blob, url: URL.createObjectURL(blob) })} onCancel={reset} />}
|
||||
|
||||
{(screen.kind === "photo" || screen.kind === "shot") && (
|
||||
<div style={{ display: "grid", gridTemplateColumns: "minmax(0, 3fr) minmax(320px, 2fr)", gap: 28, padding: 28, height: "100%", boxSizing: "border-box" }}>
|
||||
<div style={{ display: "flex", alignItems: "center", justifyContent: "center", minHeight: 0 }}>
|
||||
<figure style={{ margin: 0, background: view.template.borderMm ? "#fff" : "transparent", padding: view.template.borderMm ? 12 : 0, maxHeight: "100%" }}>
|
||||
<img src={screen.kind === "photo" ? screen.preview : screen.url} alt="" style={{ display: "block", maxWidth: "100%", maxHeight: "62vh", objectFit: "contain" }} />
|
||||
{view.template.bandText && (
|
||||
<figcaption style={{ background: view.template.bandColor, color: view.template.textColor, textAlign: "center", padding: "10px 8px", fontSize: 20, fontWeight: 600 }}>{view.template.bandText}</figcaption>
|
||||
)}
|
||||
</figure>
|
||||
</div>
|
||||
<div style={{ display: "flex", flexDirection: "column", gap: 20, justifyContent: "center" }}>
|
||||
<label style={{ display: "grid", gap: 8, fontSize: 20 }}>
|
||||
O teu nome (para te chamarmos)
|
||||
<input value={name} onChange={(e) => setName(e.target.value)} maxLength={60} style={{ height: 64, fontSize: 26, padding: "0 16px", borderRadius: 12, border: "1px solid #333", background: "#18181a", color: "#fff" }} />
|
||||
</label>
|
||||
<div style={{ display: "flex", alignItems: "center", gap: 16, fontSize: 22 }}>
|
||||
Cópias
|
||||
<button style={{ ...ghost, width: 72, padding: 0 }} onClick={() => setCopies((c) => Math.max(1, c - 1))} aria-label="Menos uma cópia">
|
||||
−
|
||||
</button>
|
||||
<span style={{ fontSize: 34, fontWeight: 800, minWidth: 40, textAlign: "center" }}>{copies}</span>
|
||||
<button style={{ ...ghost, width: 72, padding: 0 }} onClick={() => setCopies((c) => Math.min(5, c + 1))} aria-label="Mais uma cópia">
|
||||
+
|
||||
</button>
|
||||
</div>
|
||||
{error && (
|
||||
<p role="alert" style={{ color: "#ff8a8a", fontSize: 20, margin: 0 }}>
|
||||
{error}
|
||||
</p>
|
||||
)}
|
||||
<button style={big} disabled={busy} onClick={() => void (screen.kind === "photo" ? printPhoto(screen.id) : printShot(screen.blob))}>
|
||||
{busy ? "A enviar…" : copies > 1 ? `Imprimir ${copies}` : "Imprimir"}
|
||||
</button>
|
||||
<button style={ghost} disabled={busy} onClick={() => (screen.kind === "shot" ? setScreen({ kind: "camera" }) : reset())}>
|
||||
{screen.kind === "shot" ? "Repetir a foto" : "Voltar"}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{screen.kind === "sent" && (
|
||||
<div style={{ display: "flex", flexDirection: "column", alignItems: "center", justifyContent: "center", height: "100%", gap: 18, textAlign: "center", padding: 40 }}>
|
||||
<div style={{ fontSize: 64 }}>✓</div>
|
||||
<div style={{ fontSize: 40, fontWeight: 800 }}>{name.trim() ? `Obrigado, ${name.trim()}!` : "Obrigado!"}</div>
|
||||
<div style={{ fontSize: 24, color: "#bdbdc2" }}>{screen.status === "APPROVAL" ? (view.payAtCounter ? "Paga no balcão e a foto sai logo a seguir." : "A foto sai assim que a equipa a aprovar.") : "A tua foto está na fila. Levanta-a junto da impressora."}</div>
|
||||
<button style={ghost} onClick={reset}>
|
||||
Começar de novo
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
</main>
|
||||
|
||||
{view.jobs.length > 0 && screen.kind === "grid" && (
|
||||
<footer style={{ display: "flex", gap: 12, padding: "12px 20px", borderTop: "1px solid #222", overflowX: "auto" }} aria-label="Últimas impressões">
|
||||
{view.jobs.map((j) => (
|
||||
<div key={j.id} style={{ display: "flex", alignItems: "center", gap: 10, background: "#18181a", borderRadius: 10, padding: 8, minWidth: 220 }}>
|
||||
<img src={j.preview} alt="" style={{ width: 56, height: 56, objectFit: "cover", borderRadius: 6 }} />
|
||||
<div>
|
||||
<div style={{ fontSize: 16, fontWeight: 700 }}>{j.guestName ?? "Sem nome"}</div>
|
||||
<div style={{ fontSize: 14, color: j.status === "DONE" ? "#7ad38a" : "#9a9a9e" }}>
|
||||
{STATUS[j.status]}
|
||||
{j.ahead > 0 && (j.status === "QUEUED" || j.status === "APPROVAL") ? ` · ${j.ahead} à frente` : ""}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</footer>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/** The photobooth: the tablet's front camera, a 3-2-1 countdown, then the picture (mirrored on screen, not on paper). */
|
||||
function Camera({ onShot, onCancel }: { onShot: (blob: Blob) => void; onCancel: () => void }) {
|
||||
const video = useRef<HTMLVideoElement>(null);
|
||||
const [count, setCount] = useState<number | null>(null);
|
||||
const [problem, setProblem] = useState<string | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
let stream: MediaStream | null = null;
|
||||
navigator.mediaDevices
|
||||
?.getUserMedia({ video: { facingMode: "user", width: { ideal: 1920 }, height: { ideal: 1440 } }, audio: false })
|
||||
.then((s) => {
|
||||
stream = s;
|
||||
if (video.current) {
|
||||
video.current.srcObject = s;
|
||||
void video.current.play();
|
||||
}
|
||||
})
|
||||
.catch(() => setProblem("Não foi possível abrir a câmara. Autoriza a câmara neste browser."));
|
||||
if (!navigator.mediaDevices) setProblem("Este browser não dá acesso à câmara.");
|
||||
return () => stream?.getTracks().forEach((t) => t.stop());
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
if (count === null) return;
|
||||
if (count === 0) {
|
||||
const v = video.current;
|
||||
if (!v || !v.videoWidth) return setCount(null);
|
||||
const canvas = document.createElement("canvas");
|
||||
canvas.width = v.videoWidth;
|
||||
canvas.height = v.videoHeight;
|
||||
canvas.getContext("2d")!.drawImage(v, 0, 0);
|
||||
canvas.toBlob((b) => b && onShot(b), "image/jpeg", 0.92);
|
||||
return;
|
||||
}
|
||||
const t = setTimeout(() => setCount(count - 1), 1000);
|
||||
return () => clearTimeout(t);
|
||||
}, [count, onShot]);
|
||||
|
||||
if (problem) {
|
||||
return (
|
||||
<div style={{ padding: 40, textAlign: "center", fontSize: 22 }}>
|
||||
<p>{problem}</p>
|
||||
<button style={ghost} onClick={onCancel}>
|
||||
Voltar
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<div style={{ position: "relative", height: "100%", display: "flex", flexDirection: "column", alignItems: "center", justifyContent: "center", gap: 20, padding: 20, boxSizing: "border-box" }}>
|
||||
<video ref={video} playsInline muted style={{ maxWidth: "100%", maxHeight: "70vh", borderRadius: 14, transform: "scaleX(-1)", background: "#000" }} />
|
||||
{count !== null && count > 0 && <div style={{ position: "absolute", fontSize: 220, fontWeight: 900, color: "#fff", textShadow: "0 4px 30px rgba(0,0,0,.6)" }}>{count}</div>}
|
||||
<div style={{ display: "flex", gap: 16 }}>
|
||||
<button style={big} disabled={count !== null} onClick={() => setCount(3)}>
|
||||
Tirar foto
|
||||
</button>
|
||||
<button style={ghost} onClick={onCancel}>
|
||||
Voltar
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
import type { Metadata } from "next";
|
||||
import { Kiosk } from "./Kiosk";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
export const metadata: Metadata = { title: "Quiosque", robots: { index: false } };
|
||||
|
||||
/** Kiosk mode: a tablet at the event (link with its secret made in the app, Impressão → Quiosque). */
|
||||
export default async function KioskPage({ params, searchParams }: { params: Promise<{ slug: string }>; searchParams: Promise<{ k?: string }> }) {
|
||||
const { slug } = await params;
|
||||
const { k } = await searchParams;
|
||||
return <Kiosk slug={slug} token={k ?? ""} />;
|
||||
}
|
||||
@@ -5,7 +5,7 @@ import Link from "next/link";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useCallback, useEffect, useState } from "react";
|
||||
import { addToCart, useCart } from "../../../lib/cart";
|
||||
import { eur } from "../../../lib/format";
|
||||
import { eur, shotAt, sizeLabel } from "../../../lib/format";
|
||||
import { useProofing } from "../../../lib/proofing";
|
||||
import { Refresh } from "../../../lib/Refresh";
|
||||
import { affiliateRef } from "../../../lib/ref";
|
||||
@@ -13,8 +13,13 @@ import { affiliateRef } from "../../../lib/ref";
|
||||
const MAX_ORDER_ITEMS = 200;
|
||||
|
||||
/** The photos, a lightbox to look closer, the products to buy each one as, and (when on) the client's selection. */
|
||||
export function GalleryView({ gallery, products, token }: { gallery: PublicGallery; products: ProductSummary[]; token: string | null }) {
|
||||
const [open, setOpen] = useState<number | null>(null);
|
||||
export function GalleryView({ gallery, products, token, initialPhotoId = null }: { gallery: PublicGallery; products: ProductSummary[]; token: string | null; initialPhotoId?: string | null }) {
|
||||
// A shared link (`?foto=<id>`) opens the gallery on that photo.
|
||||
const [open, setOpen] = useState<number | null>(() => {
|
||||
const i = initialPhotoId ? gallery.photos.findIndex((p) => p.id === initialPhotoId) : -1;
|
||||
return i >= 0 ? i : null;
|
||||
});
|
||||
const [copied, setCopied] = useState(false);
|
||||
const [query, setQuery] = useState("");
|
||||
const [onlyFavorites, setOnlyFavorites] = useState(false);
|
||||
const [added, setAdded] = useState<string | null>(null);
|
||||
@@ -45,6 +50,26 @@ export function GalleryView({ gallery, products, token }: { gallery: PublicGalle
|
||||
};
|
||||
}, [open, move]);
|
||||
|
||||
// The address follows the open photo, so it can be copied or shared from the browser too.
|
||||
const openId = photo?.id ?? null;
|
||||
useEffect(() => {
|
||||
const url = openId ? `${window.location.pathname}?foto=${openId}` : window.location.pathname;
|
||||
if (url !== window.location.pathname + window.location.search) window.history.replaceState(window.history.state, "", url);
|
||||
setCopied(false);
|
||||
}, [openId]);
|
||||
|
||||
// One visit per browser session counts for the home page's "Mais vistas".
|
||||
useEffect(() => {
|
||||
const key = `gv_${gallery.slug}`;
|
||||
try {
|
||||
if (sessionStorage.getItem(key)) return;
|
||||
sessionStorage.setItem(key, "1");
|
||||
} catch {
|
||||
// No storage (private mode): count it anyway.
|
||||
}
|
||||
void fetch(`/v1/public/galleries/${encodeURIComponent(gallery.slug)}/view`, { method: "POST" }).catch(() => undefined);
|
||||
}, [gallery.slug]);
|
||||
|
||||
const hasNames = gallery.photos.some((p) => p.players.length);
|
||||
const cartGallery = { slug: gallery.slug, title: gallery.title, token, bundles: gallery.bundles, photoCount: gallery.photos.length };
|
||||
const favoriteNames = gallery.photos.filter((p) => proofing.favorites.has(p.id)).map((p) => p.name);
|
||||
@@ -113,6 +138,39 @@ export function GalleryView({ gallery, products, token }: { gallery: PublicGalle
|
||||
Foto {open! + 1} de {photos.length} · <span className="mono">{photo.name}</span>
|
||||
</span>
|
||||
{photo.players.length > 0 && <h2 className="title" style={{ fontSize: 30, marginTop: 6 }}>{photo.players.join(", ")}</h2>}
|
||||
{photo.caption && <p style={{ margin: "8px 0 0" }}>{photo.caption}</p>}
|
||||
<dl className="photo-meta">
|
||||
{photo.credit && (
|
||||
<>
|
||||
<dt>Fotografia</dt>
|
||||
<dd>{photo.credit}</dd>
|
||||
</>
|
||||
)}
|
||||
{photo.capturedAt && (
|
||||
<>
|
||||
<dt>Data</dt>
|
||||
<dd>{shotAt(photo.capturedAt)}</dd>
|
||||
</>
|
||||
)}
|
||||
{sizeLabel(photo.width, photo.height) && (
|
||||
<>
|
||||
<dt>Original</dt>
|
||||
<dd>{sizeLabel(photo.width, photo.height)}</dd>
|
||||
</>
|
||||
)}
|
||||
</dl>
|
||||
<button
|
||||
className="button ghost"
|
||||
style={{ marginTop: 4 }}
|
||||
onClick={() =>
|
||||
navigator.clipboard?.writeText(window.location.href).then(
|
||||
() => setCopied(true),
|
||||
() => undefined,
|
||||
)
|
||||
}
|
||||
>
|
||||
{copied ? "Ligação copiada" : "Copiar ligação da foto"}
|
||||
</button>
|
||||
{proofing.ready && (
|
||||
<button className={`button ${proofing.favorites.has(photo.id) ? "" : "ghost"}`} style={{ marginTop: 12 }} onClick={() => proofing.toggle(photo.id)} aria-pressed={proofing.favorites.has(photo.id)}>
|
||||
{proofing.favorites.has(photo.id) ? "♥ Na minha seleção" : "♡ Adicionar à seleção"}
|
||||
|
||||
@@ -8,7 +8,7 @@ import { Unlock } from "./Unlock";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
type Params = { params: Promise<{ slug: string }> };
|
||||
type Params = { params: Promise<{ slug: string }>; searchParams: Promise<{ foto?: string }> };
|
||||
|
||||
async function load(slug: string) {
|
||||
try {
|
||||
@@ -19,13 +19,23 @@ async function load(slug: string) {
|
||||
}
|
||||
}
|
||||
|
||||
export async function generateMetadata({ params }: Params): Promise<Metadata> {
|
||||
export async function generateMetadata({ params, searchParams }: Params): Promise<Metadata> {
|
||||
const g = await load((await params).slug);
|
||||
return { title: g.title, ...(g.visibility !== "PUBLIC" && { robots: { index: false } }), ...(g.cover && { openGraph: { images: [g.cover] } }) };
|
||||
const robots = g.visibility !== "PUBLIC" ? { robots: { index: false } } : {};
|
||||
// A shared photo link previews that photo, with its caption.
|
||||
const { foto } = await searchParams;
|
||||
const photo = foto ? g.photos.find((p) => p.id === foto) : undefined;
|
||||
if (photo) {
|
||||
const title = photo.players.length ? `${photo.players.join(", ")} · ${g.title}` : g.title;
|
||||
const description = [photo.caption, photo.credit && `Fotografia: ${photo.credit}`].filter(Boolean).join(" · ") || undefined;
|
||||
return { title, ...(description && { description }), ...robots, openGraph: { title, ...(description && { description }), images: [photo.preview] } };
|
||||
}
|
||||
return { title: g.title, ...robots, ...(g.cover && { openGraph: { images: [g.cover] } }) };
|
||||
}
|
||||
|
||||
export default async function GalleryPage({ params }: Params) {
|
||||
export default async function GalleryPage({ params, searchParams }: Params) {
|
||||
const { slug } = await params;
|
||||
const { foto } = await searchParams;
|
||||
const [gallery, products] = await Promise.all([load(slug), getProducts()]);
|
||||
const token = (await cookies()).get(galleryCookie(slug))?.value ?? null;
|
||||
const e = gallery.event;
|
||||
@@ -46,7 +56,7 @@ export default async function GalleryPage({ params }: Params) {
|
||||
{gallery.locked ? (
|
||||
<Unlock slug={slug} />
|
||||
) : (
|
||||
<GalleryView gallery={gallery} products={products.filter((p) => gallery.forSale || (gallery.freeDownloads && p.kind === "DIGITAL"))} token={token} />
|
||||
<GalleryView gallery={gallery} products={products.filter((p) => gallery.forSale || (gallery.freeDownloads && p.kind === "DIGITAL"))} token={token} initialPhotoId={foto ?? null} />
|
||||
)}
|
||||
</main>
|
||||
);
|
||||
|
||||
@@ -177,6 +177,134 @@ select {
|
||||
.hero p {
|
||||
margin: 16px 0 0;
|
||||
}
|
||||
.search {
|
||||
display: flex;
|
||||
gap: 8px;
|
||||
margin-top: 24px;
|
||||
max-width: 640px;
|
||||
}
|
||||
.search input {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
height: 44px;
|
||||
padding: 0 14px;
|
||||
border: 1px solid var(--line);
|
||||
background: var(--surface);
|
||||
color: var(--ink);
|
||||
font: inherit;
|
||||
font-size: 17px;
|
||||
border-radius: var(--radius);
|
||||
}
|
||||
.chips {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 8px;
|
||||
margin-top: 16px;
|
||||
}
|
||||
.chip {
|
||||
padding: 6px 14px;
|
||||
border: 1px solid var(--line);
|
||||
font-family: var(--display);
|
||||
font-weight: 600;
|
||||
font-size: 15px;
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.04em;
|
||||
color: var(--muted);
|
||||
border-radius: 999px;
|
||||
}
|
||||
.chip:hover,
|
||||
.chip.on {
|
||||
border-color: var(--ink);
|
||||
color: var(--ink);
|
||||
}
|
||||
.strip {
|
||||
display: grid;
|
||||
grid-auto-flow: column;
|
||||
grid-auto-columns: 180px;
|
||||
gap: 8px;
|
||||
overflow-x: auto;
|
||||
padding-bottom: 8px;
|
||||
scroll-snap-type: x mandatory;
|
||||
}
|
||||
.strip-item {
|
||||
position: relative;
|
||||
aspect-ratio: 3 / 2;
|
||||
background: var(--line);
|
||||
overflow: hidden;
|
||||
scroll-snap-align: start;
|
||||
}
|
||||
.strip-item img {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
object-fit: cover;
|
||||
}
|
||||
.card .frame {
|
||||
position: relative;
|
||||
}
|
||||
.live {
|
||||
position: absolute;
|
||||
top: 8px;
|
||||
left: 8px;
|
||||
padding: 2px 8px;
|
||||
background: #e2001a;
|
||||
color: #fff;
|
||||
font-family: var(--display);
|
||||
font-weight: 700;
|
||||
font-size: 13px;
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.05em;
|
||||
}
|
||||
.ranked {
|
||||
list-style: none;
|
||||
margin: 0 0 8px;
|
||||
padding: 0;
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
|
||||
gap: 8px 24px;
|
||||
}
|
||||
.ranked a {
|
||||
display: grid;
|
||||
grid-template-columns: 32px 96px 1fr;
|
||||
gap: 12px;
|
||||
align-items: center;
|
||||
padding: 8px 0;
|
||||
border-bottom: 1px solid var(--line);
|
||||
}
|
||||
.ranked .rank {
|
||||
font-family: var(--display);
|
||||
font-weight: 700;
|
||||
font-size: 28px;
|
||||
color: var(--muted);
|
||||
}
|
||||
.ranked .thumb {
|
||||
aspect-ratio: 3 / 2;
|
||||
background: var(--line);
|
||||
overflow: hidden;
|
||||
}
|
||||
.ranked .thumb img {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
object-fit: cover;
|
||||
}
|
||||
.ranked strong {
|
||||
display: block;
|
||||
line-height: 1.25;
|
||||
}
|
||||
.photo-meta {
|
||||
margin: 12px 0 0;
|
||||
display: grid;
|
||||
gap: 4px;
|
||||
}
|
||||
.photo-meta dt {
|
||||
font-family: var(--display);
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.05em;
|
||||
font-size: 12px;
|
||||
color: var(--muted);
|
||||
}
|
||||
.photo-meta dd {
|
||||
margin: 0 0 6px;
|
||||
}
|
||||
.section-head {
|
||||
display: flex;
|
||||
align-items: baseline;
|
||||
|
||||
@@ -6,6 +6,7 @@ import "@fontsource/barlow-condensed/800.css";
|
||||
import "@fontsource/space-mono/400.css";
|
||||
import "./globals.css";
|
||||
import type { Metadata } from "next";
|
||||
import { headers } from "next/headers";
|
||||
import Link from "next/link";
|
||||
import type { ReactNode } from "react";
|
||||
import { CartLink } from "../components/CartLink";
|
||||
@@ -27,6 +28,14 @@ export default async function RootLayout({ children }: { children: ReactNode })
|
||||
site = await getSite();
|
||||
} catch (err) {
|
||||
if (!(err instanceof NotFound)) throw err;
|
||||
// The events domain (events.photoreport.pt) has no storefront: its event pages (QR page, kiosk) stand alone.
|
||||
if ((await headers()).get("x-pr-path")?.startsWith("/e/")) {
|
||||
return (
|
||||
<html lang="pt">
|
||||
<body>{children}</body>
|
||||
</html>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<html lang="pt">
|
||||
<body>
|
||||
|
||||
+86
-10
@@ -1,20 +1,28 @@
|
||||
import Link from "next/link";
|
||||
import { getGalleries, getSite, NotFound } from "../lib/api";
|
||||
import { getGalleries, getLatest, getPopular, getSite, NotFound } from "../lib/api";
|
||||
import { eventTitle, longDate } from "../lib/format";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
async function load() {
|
||||
const SPORT_NAMES: Record<string, string> = { andebol: "Andebol", futebol: "Futebol", futsal: "Futsal", basquetebol: "Basquetebol", voleibol: "Voleibol", hoquei: "Hóquei", "hóquei em patins": "Hóquei em patins", rugby: "Râguebi", atletismo: "Atletismo" };
|
||||
const sportName = (s: string) => SPORT_NAMES[s] ?? s.charAt(0).toUpperCase() + s.slice(1);
|
||||
|
||||
async function load(q: string, sport: string) {
|
||||
try {
|
||||
return await Promise.all([getSite(), getGalleries()]);
|
||||
const filtered = !!(q || sport);
|
||||
return await Promise.all([getSite(), getGalleries({ q, sport }), filtered ? Promise.resolve([]) : getLatest(), filtered ? Promise.resolve([]) : getPopular()]);
|
||||
} catch (err) {
|
||||
if (err instanceof NotFound) return null;
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
export default async function Home() {
|
||||
const loaded = await load();
|
||||
/** Home: search, sport shortcuts, the photos that just arrived, then the galleries. */
|
||||
export default async function Home({ searchParams }: { searchParams: Promise<{ q?: string; desporto?: string }> }) {
|
||||
const params = await searchParams;
|
||||
const q = (params.q ?? "").trim().slice(0, 80);
|
||||
const sport = (params.desporto ?? "").trim().slice(0, 40);
|
||||
const loaded = await load(q, sport);
|
||||
// A domain that points here before anyone set up its shop (Loja → Sites in the app).
|
||||
if (!loaded) {
|
||||
return (
|
||||
@@ -25,7 +33,8 @@ export default async function Home() {
|
||||
</main>
|
||||
);
|
||||
}
|
||||
const [site, galleries] = loaded;
|
||||
const [site, { galleries, sports }, latest, popular] = loaded;
|
||||
const filtered = !!(q || sport);
|
||||
return (
|
||||
<main>
|
||||
<section className="hero">
|
||||
@@ -33,20 +42,87 @@ export default async function Home() {
|
||||
<span className="kicker">{site.skin === "shootyourmove" ? "Cada jogada, a tua fotografia" : "Agência de fotografia de desporto"}</span>
|
||||
<h1 className="title h1">{site.settings.tagline ?? "As fotos do jogo"}</h1>
|
||||
<p className="lead">Encontra o teu jogo, escolhe as fotos e descarrega-as em alta resolução, ou recebe-as impressas.</p>
|
||||
<form className="search" action="/" method="get" role="search">
|
||||
<input name="q" defaultValue={q} placeholder="Equipa, jogador, competição ou pavilhão" aria-label="Procurar" />
|
||||
{sport && <input type="hidden" name="desporto" value={sport} />}
|
||||
<button className="button">Procurar</button>
|
||||
</form>
|
||||
{sports.length > 1 && (
|
||||
<nav className="chips" aria-label="Modalidades">
|
||||
<Link href={q ? `/?q=${encodeURIComponent(q)}` : "/"} className={`chip${sport ? "" : " on"}`}>
|
||||
Todas
|
||||
</Link>
|
||||
{sports.map((s) => (
|
||||
<Link key={s} href={`/?desporto=${encodeURIComponent(s)}${q ? `&q=${encodeURIComponent(q)}` : ""}`} className={`chip${sport.toLowerCase() === s ? " on" : ""}`}>
|
||||
{sportName(s)}
|
||||
</Link>
|
||||
))}
|
||||
</nav>
|
||||
)}
|
||||
</div>
|
||||
</section>
|
||||
<div className="wrap">
|
||||
{latest.length > 0 && (
|
||||
<section aria-label="Últimas do jogo">
|
||||
<div className="section-head">
|
||||
<h2 className="title h2">Últimas do jogo</h2>
|
||||
<span className="meta">acabadas de chegar</span>
|
||||
</div>
|
||||
<div className="strip">
|
||||
{latest.map((p) => (
|
||||
<Link key={`${p.gallery.slug}-${p.id}`} href={`/galeria/${p.gallery.slug}`} className="strip-item" title={p.gallery.title}>
|
||||
<img src={p.thumb} alt="" loading="lazy" />
|
||||
{p.gallery.live && <span className="live">Ao vivo</span>}
|
||||
</Link>
|
||||
))}
|
||||
</div>
|
||||
</section>
|
||||
)}
|
||||
{/* With one or two galleries a ranking says nothing. */}
|
||||
{popular.length >= 3 && (
|
||||
<section aria-label="Mais vistas">
|
||||
<div className="section-head">
|
||||
<h2 className="title h2">Mais vistas</h2>
|
||||
<span className="meta">nos últimos 7 dias</span>
|
||||
</div>
|
||||
<ol className="ranked">
|
||||
{popular.map((g, i) => (
|
||||
<li key={g.slug}>
|
||||
<Link href={`/galeria/${g.slug}`}>
|
||||
<span className="rank">{i + 1}</span>
|
||||
<span className="thumb">{g.cover ? <img src={g.cover} alt="" loading="lazy" /> : null}</span>
|
||||
<span>
|
||||
<strong>{g.title || (g.event ? eventTitle(g.event) : "")}</strong>
|
||||
<span className="meta">{[g.event?.competition, longDate(g.event?.startsAt ?? g.publishedAt)].filter(Boolean).join(" · ")}</span>
|
||||
</span>
|
||||
</Link>
|
||||
</li>
|
||||
))}
|
||||
</ol>
|
||||
</section>
|
||||
)}
|
||||
<div className="section-head">
|
||||
<h2 className="title h2">Galerias</h2>
|
||||
<span className="meta">{galleries.length} publicadas</span>
|
||||
<h2 className="title h2">{filtered ? (q ? `Resultados para “${q}”` : sportName(sport)) : "Galerias"}</h2>
|
||||
<span className="meta">
|
||||
{galleries.length} {galleries.length === 1 ? "galeria" : "galerias"}
|
||||
{filtered && (
|
||||
<>
|
||||
{" · "}
|
||||
<Link href="/">limpar</Link>
|
||||
</>
|
||||
)}
|
||||
</span>
|
||||
</div>
|
||||
{galleries.length === 0 ? (
|
||||
<p className="empty">Ainda não há galerias publicadas.</p>
|
||||
<p className="empty">{filtered ? "Nenhuma galeria encontrada. Tenta outro nome ou outra modalidade." : "Ainda não há galerias publicadas."}</p>
|
||||
) : (
|
||||
<div className="cards">
|
||||
{galleries.map((g) => (
|
||||
<Link key={g.slug} href={`/galeria/${g.slug}`} className="card">
|
||||
<div className="frame">{g.cover ? <img src={g.cover} alt="" loading="lazy" /> : null}</div>
|
||||
<div className="frame">
|
||||
{g.cover ? <img src={g.cover} alt="" loading="lazy" /> : null}
|
||||
{g.live && <span className="live">Ao vivo</span>}
|
||||
</div>
|
||||
<span className="kicker">
|
||||
{[g.event?.competition, g.event ? longDate(g.event.startsAt) : longDate(g.publishedAt)].filter(Boolean).join(" · ")}
|
||||
</span>
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import type { OrderView, ProductSummary, PublicGallery, PublicGallerySummary, SiteInfo } from "@photoreport/contracts";
|
||||
import type { LatestPhoto, OrderView, PopularGallery, ProductSummary, PublicGallery, PublicGallerySummary, SiteInfo } from "@photoreport/contracts";
|
||||
import { cookies, headers } from "next/headers";
|
||||
|
||||
const API = process.env.API_URL ?? "http://localhost:3000";
|
||||
@@ -19,7 +19,13 @@ async function get<T>(path: string, extra: Record<string, string> = {}): Promise
|
||||
}
|
||||
|
||||
export const getSite = () => get<SiteInfo>("/v1/public/site");
|
||||
export const getGalleries = () => get<{ galleries: PublicGallerySummary[] }>("/v1/public/galleries").then((r) => r.galleries);
|
||||
/** Public galleries (optionally searched, or one sport) and the sports there are. */
|
||||
export const getGalleries = (filter: { q?: string; sport?: string } = {}) => {
|
||||
const params = new URLSearchParams(Object.entries(filter).filter(([, v]) => v) as [string, string][]);
|
||||
return get<{ galleries: PublicGallerySummary[]; sports: string[] }>(`/v1/public/galleries${params.size ? `?${params}` : ""}`);
|
||||
};
|
||||
export const getLatest = (limit = 18) => get<{ photos: LatestPhoto[] }>(`/v1/public/latest?limit=${limit}`).then((r) => r.photos);
|
||||
export const getPopular = (limit = 6) => get<{ galleries: PopularGallery[] }>(`/v1/public/popular?limit=${limit}`).then((r) => r.galleries);
|
||||
export const getProducts = () => get<{ products: ProductSummary[] }>("/v1/public/products").then((r) => r.products);
|
||||
|
||||
/** The gallery's unlock token lives in a cookie the unlock form sets. */
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { eur, eventTitle } from "./format";
|
||||
import { eur, eventTitle, shotAt, sizeLabel } from "./format";
|
||||
|
||||
describe("format", () => {
|
||||
it("shows euros the Portuguese way and names matches", () => {
|
||||
@@ -7,4 +7,11 @@ describe("format", () => {
|
||||
expect(eventTitle({ home: "SC Braga", away: "Sporting CP" })).toBe("SC Braga x Sporting CP");
|
||||
expect(eventTitle({ home: "Gala do Desporto", away: null })).toBe("Gala do Desporto");
|
||||
});
|
||||
|
||||
it("dates a shot to the second in Lisbon time and gives the photo size", () => {
|
||||
expect(shotAt("2026-10-11T17:03:09Z")).toBe("11 de outubro de 2026, 18:03:09");
|
||||
expect(sizeLabel(6000, 4000)).toBe("6000 × 4000 px · 24 MP");
|
||||
expect(sizeLabel(1200, 800)).toBe("1200 × 800 px · 1,0 MP");
|
||||
expect(sizeLabel(null, 800)).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -4,6 +4,17 @@ export const eur = (cents: number) => money.format(cents / 100);
|
||||
const day = new Intl.DateTimeFormat("pt-PT", { day: "numeric", month: "long", year: "numeric", timeZone: "Europe/Lisbon" });
|
||||
export const longDate = (iso: string) => day.format(new Date(iso));
|
||||
|
||||
const clock = new Intl.DateTimeFormat("pt-PT", { hour: "2-digit", minute: "2-digit", second: "2-digit", timeZone: "Europe/Lisbon" });
|
||||
/** When a photo was taken, to the second (sport photos are told apart by the moment). */
|
||||
export const shotAt = (iso: string) => `${day.format(new Date(iso))}, ${clock.format(new Date(iso))}`;
|
||||
|
||||
/** "6000 × 4000 px · 24 MP". */
|
||||
export function sizeLabel(width: number | null, height: number | null): string | null {
|
||||
if (!width || !height) return null;
|
||||
const mp = (width * height) / 1e6;
|
||||
return `${width} × ${height} px · ${mp >= 10 ? Math.round(mp) : mp.toFixed(1).replace(".", ",")} MP`;
|
||||
}
|
||||
|
||||
export function eventTitle(e: { home: string; away: string | null }): string {
|
||||
return e.away ? `${e.home} x ${e.away}` : e.home;
|
||||
}
|
||||
@@ -1,10 +1,15 @@
|
||||
import { type NextRequest, NextResponse } from "next/server";
|
||||
|
||||
/** An affiliate link (`?ref=CODE`) is remembered for 30 days; the order sends it and the API credits the affiliate. */
|
||||
/**
|
||||
* An affiliate link (`?ref=CODE`) is remembered for 30 days; the order sends it and the API credits the affiliate.
|
||||
* The path is passed on to the layout (`x-pr-path`): the event pages (`/e/…`) work on a domain without a site.
|
||||
*/
|
||||
export function middleware(req: NextRequest) {
|
||||
const headers = new Headers(req.headers);
|
||||
headers.set("x-pr-path", req.nextUrl.pathname);
|
||||
const ref = req.nextUrl.searchParams.get("ref")?.trim();
|
||||
if (!ref || !/^[A-Za-z0-9_-]{3,40}$/.test(ref)) return NextResponse.next();
|
||||
const res = NextResponse.next();
|
||||
if (!ref || !/^[A-Za-z0-9_-]{3,40}$/.test(ref)) return NextResponse.next({ request: { headers } });
|
||||
const res = NextResponse.next({ request: { headers } });
|
||||
res.cookies.set("pr_ref", ref.toUpperCase(), { maxAge: 30 * 24 * 3600, path: "/", sameSite: "lax", secure: req.nextUrl.protocol === "https:" });
|
||||
return res;
|
||||
}
|
||||
|
||||
+37
-2
@@ -65,6 +65,18 @@ in MB and files (0: none). Giving a login a plan sets its end date (now + days);
|
||||
from the end date, or from now once ended; the end date can also be set by hand. The auth hook refuses an ended
|
||||
login and hands SFTPGo `expiration_date`, `quota_size` and `quota_files`, which SFTPGo enforces as it counts uploads.
|
||||
|
||||
Local FTP (desktop app, `apps/desktop/src-tauri/src/ftp.rs`, libunftp): the camera sends to the photographer's own
|
||||
computer on the same network (port 2121, passive 50000-50100, all IPv4 interfaces), with as many logins as there are
|
||||
bodies, each switchable off. "Testar ligação" (`ftp_check`, run after every start) connects to each LAN address
|
||||
like a camera and reads the greeting, and on macOS reads the application firewall (`socketfilterfw`: block all, or
|
||||
PhotoReport blocked) to tell the photographer what to change. Another FTP server on the same port takes the
|
||||
connections, so the panel says to close it.
|
||||
Photos from the local FTP count as camera ingest (`source` DESKTOP), previews and full originals alike (the
|
||||
resumable start says `desktop: true` for an original), so the event's autopilot edits them; only hand uploads are
|
||||
left as sent. Faces and the autopilot work per event: photos with no event (the inbox) are analysed for faces but
|
||||
not grouped or edited. The face worker also queues, every minute, photos left at "no analysis" in organizations
|
||||
with biometrics on.
|
||||
|
||||
Uploads from the browser or desktop (`POST /v1/orgs/:orgId/uploads`, one photo per request) go through the
|
||||
same pipeline; an upload can target an open event directly. Still to come: resumable uploads (tus, preview
|
||||
first from the desktop), OCR and faces at ingest, and the final export
|
||||
@@ -81,6 +93,10 @@ it when files must be served from more than one host.
|
||||
event with its picks. Public (listed), unlisted (link only) or private (link + password; the unlock returns a
|
||||
token valid for a week, kept in a cookie). Photos on the sites are watermarked with the site's name (600 and
|
||||
1600 px), made on first view from the edited preview and cached until the edit changes; URLs are signed.
|
||||
- Site home: search (title, teams, competition, venue and the players named in the photos), sport shortcuts,
|
||||
"Últimas do jogo" (the photos last added to public galleries) and "Mais vistas" (visits over 7 days, one per
|
||||
browser session, in `gallery_views` per gallery and day). A photo opened in a gallery shows its delivered IPTC
|
||||
caption and credit, when it was taken and its size, and has its own link (`?foto=<id>`, previewed with that photo).
|
||||
- Live galleries (`live` PICKS or ALL, linked to an event): the gallery fills itself while the match is on, from
|
||||
the event's picks or every ready photo that is not rejected. Photos it added leave again when they stop matching;
|
||||
photos taken out by hand are kept as exclusions and never come back; photos added by hand stay. The sync runs when
|
||||
@@ -132,6 +148,15 @@ it when files must be served from more than one host.
|
||||
they agree. A package's price is spread over its photos, so order lines, VAT, shares and refunds work as before
|
||||
(the line reads "<product> · <package>"); a press discount applies on top. The gallery page lists the packages
|
||||
and has "Comprar todas" for the whole-gallery one. Orders take up to 1000 lines for that.
|
||||
- Kiosk (Impressão → Quiosque; `/e/<slug>/quiosque?k=<secret>` on the events site): a tablet at the event shows
|
||||
the photographer's photos big and the front camera as a photobooth (3-2-1, then the picture), takes the guest's
|
||||
name and copies (1-5) and sends the print to the queue. Only the hash of the link's secret is kept; a new link
|
||||
retires the old one. The tablet is shared and staffed, so the per-guest limit doesn't apply; on a paid event the
|
||||
kiosk's prints wait for approval (paid at the counter) instead of going through Stripe. Full screen, screen kept
|
||||
on, back to the start after a minute without a touch.
|
||||
- Faces on edited photos: boxes are stored in the original frame; `GET /v1/photos/:id/faces` also gives each box in
|
||||
the rendered preview's frame (`inPreview`, the crop and straighten of the snapshot it was rendered from; null when
|
||||
cropped out), which is what the loupe draws (`apps/api/src/faces/frame.ts`).
|
||||
- PATCH bodies are parsed with `patchOf(schema)` (contracts): zod's `.partial()` keeps defaults, which made a
|
||||
title change turn a private gallery public; galleries, sites and print events use it.
|
||||
- Products per organization: JPEG downloads (long edge, 0 = original) and prints (size, lead days); prices are
|
||||
@@ -202,6 +227,15 @@ What organisations do with it:
|
||||
editor's own lines keep priority. The block is regenerated when squads change. Code = team prefix + number,
|
||||
with the same prefixes and templates as the old app.
|
||||
- **Events from fixtures:** an event created from a fixture keeps `fixtureId` and both teams.
|
||||
- **Generic events** (press conferences, galas, presentations; "Evento genérico" in the form): `home` holds the
|
||||
name and `away` is empty. Nothing is guessed for the caption: the default IPTC template (`GENERAL_TEMPLATE`)
|
||||
has no caption, headline or event, and the form's "Legenda" fills caption and headline when typed. `{event}` is
|
||||
the name alone, and a match template left on such an event drops the dangling "x".
|
||||
- **Agenda:** each person can connect their own calendar by its secret iCal address (Google, iCloud, Outlook;
|
||||
`webcal://` is read as https). It is sealed with the secret box in `user_preferences.calendar_url`, fetched only
|
||||
from public https hosts (private, loopback and link-local addresses refused, redirects checked again, 5 MB, 10 s)
|
||||
and cached 5 minutes. For a generic event the form lists the day's entries; picking one fills name, venue, city
|
||||
and time and suggests a caption ("Title, Venue, City.") to edit. Repeating entries show their first date only.
|
||||
- **People from squads:** squads become people (club, number, `sportsPlayerId`). With biometrics on, the Liga
|
||||
headshot becomes the reference photo, and number suggestions for faces use the event's squads.
|
||||
|
||||
@@ -306,8 +340,9 @@ run on the `next` containers (the phase gate).
|
||||
invoices through InvoiceXpress, press accounts on credit with a monthly invoice, photo packages, download
|
||||
limits, FTP packages with quotas).
|
||||
4. Events and printing (done: QR guest page, print layout with band and border, approval and limits, queue
|
||||
in the app, print agent with CUPS and pairing, paper per printer, paid prints through Stripe. Open: kiosk mode
|
||||
on a tablet, photobooth capture, Windows agent, a real event printed).
|
||||
in the app, print agent with CUPS and pairing, paper per printer, paid prints through Stripe, kiosk mode on a
|
||||
tablet with photobooth capture, Windows agent (spooler through PowerShell). Open: the Windows agent on real
|
||||
hardware, a real event printed).
|
||||
5. Player identification: faces (done: detect, group, confirm, propagate, suggest across events), jersey
|
||||
numbers with squads, global search (parity with old projects validated).
|
||||
6. Cutover: final import, redirects, old projects read-only, then switched off.
|
||||
|
||||
@@ -98,6 +98,16 @@ Gitea -> webhook -> the container pulls and redeploys itself. No manual `scp`/`r
|
||||
Not deployed by webhook. A tag `desktop-v*` / `agent-v*` triggers Gitea Actions to build installers per OS and
|
||||
publish a Gitea release; the Tauri updater and the agent's updater read from it.
|
||||
|
||||
The desktop app keeps the interface on disk and never needs the server to open. Each web deploy writes
|
||||
`ui-manifest.json` (every file of the build with its SHA-256); the app checks it 20 s after start and every 30 minutes,
|
||||
downloads only the files that changed, checks each hash and uses the new version from the next start (or when the
|
||||
photographer reloads). The installer's own copy is the fallback, and wins when it is newer.
|
||||
|
||||
macOS builds on a Mac registered once as a runner (`bash infra/desktop/macos-runner.sh`, with a registration token
|
||||
from Gitea → Actions → Runners; label `macos`, a launchd service of that user). Its builds carry the updater key, so
|
||||
apps installed from a release update themselves; an app compiled by hand without the key never does. A release made
|
||||
while the Mac is off waits for it.
|
||||
|
||||
## Importing the old app.photoreport.pt
|
||||
|
||||
`apps/api/scripts/import-legacy.ts` reads the old MySQL database, read-only. It brings over accounts, squads, events,
|
||||
|
||||
@@ -30,6 +30,9 @@ Following the AP and NPPA codes:
|
||||
- **Edges:** no slivers of other in-focus people at the crop edge: either in, or out. Blurred foreground and
|
||||
background people don't count.
|
||||
- **Headroom:** heads a little below the top edge, not touching it, not floating in empty space.
|
||||
- **Vertical placement:** the upper body (chest, faces) a little above the middle of the crop, never the knees.
|
||||
Little or no empty pitch or floor under the feet: when the crop is taller than the subject, the spare height
|
||||
goes above them (crowd, stands), not below.
|
||||
- **Distractions:** prefer the crop that leaves out half-bodies, empty floor and bright clutter at the edges,
|
||||
as long as nothing that matters goes with them.
|
||||
- **Resolution:** never crop below what the delivery needs. Default: the crop keeps at least 2400 px on its long
|
||||
@@ -57,7 +60,9 @@ Per event (and an organisation default), off unless switched on. When on, every
|
||||
the local FTP of the desktop app or auto-ingest is, in order:
|
||||
|
||||
1. analysed (people, ball, focus);
|
||||
2. edited: white balance, tone, level (only with a clear horizon or verticals, at most a few degrees), crop;
|
||||
2. edited: white balance, tone, level (only with a clear horizon or verticals, at most a few degrees), crop.
|
||||
The level reads the advertising boards, stands, posts and railings, never the pitch markings (lines on grass),
|
||||
which perspective tilts; when those lines disagree the photo is left as it is;
|
||||
3. scored within its burst; when the burst ends, its best frames are flagged as picks;
|
||||
4. optionally delivered (rendered with the edits, IPTC from the event) to the event's delivery target.
|
||||
|
||||
|
||||
@@ -0,0 +1,188 @@
|
||||
//! Levelling for sports photos. Lightroom's Level (LightCraft's `level_degrees`) reads every long line, and in a
|
||||
//! stadium the longest lines are the pitch markings, which perspective tilts by 10 to 30 degrees: they outvote
|
||||
//! the advertising boards and the stands, so the photo is left crooked (or levelled to a touchline). Here the
|
||||
//! markings are left out (lines with grass on both sides), only lines within a few degrees of level or plumb
|
||||
//! count (a crooked camera is a few degrees off; more is perspective or a creative tilt), and the boards,
|
||||
//! stands, posts and railings that remain have to agree.
|
||||
|
||||
use lightcraft_pipeline::upright::{Segment, detect_segments};
|
||||
use lightcraft_raster::resample::{Filter, fit};
|
||||
use lightcraft_raster::{Plane, Rgb32f};
|
||||
|
||||
/// Analysis size (long edge), as LightCraft's Upright.
|
||||
const LONG: usize = 1024;
|
||||
/// Lines further than this from level (or plumb) are perspective, not a crooked camera.
|
||||
const MAX_DEV: f64 = 8.0;
|
||||
/// Lines within this much of each other agree.
|
||||
const AGREE: f64 = 0.75;
|
||||
/// Shortest line that counts, as a fraction of the long edge.
|
||||
const MIN_LEN: f64 = 0.06;
|
||||
|
||||
/// The crop angle (degrees, LightCraft's sign) that levels a sports photo, or None when its lines don't agree.
|
||||
pub fn sports_level(image: &Rgb32f) -> Option<f64> {
|
||||
let img = if image.width.max(image.height) > LONG {
|
||||
fit(image, LONG, LONG, Filter::Mitchell)
|
||||
} else {
|
||||
image.clone()
|
||||
};
|
||||
let (w, h) = (img.width, img.height);
|
||||
if w < 32 || h < 32 {
|
||||
return None;
|
||||
}
|
||||
let segs = detect_segments(&lightness(&img));
|
||||
let half = w.max(h) as f64 / 2.0;
|
||||
let to_px = |x: f64, y: f64| (x * half + w as f64 / 2.0, y * half + h as f64 / 2.0);
|
||||
|
||||
let mut devs: Vec<(f64, f64)> = Vec::new();
|
||||
for s in &segs {
|
||||
let len = s.len() / 2.0; // fraction of the long edge
|
||||
if len < MIN_LEN {
|
||||
continue;
|
||||
}
|
||||
let Some(d) = deviation(s) else { continue };
|
||||
let (ax, ay) = to_px(s.a.x, s.a.y);
|
||||
let (bx, by) = to_px(s.b.x, s.b.y);
|
||||
if on_grass(&img, ax, ay, bx, by) {
|
||||
continue;
|
||||
}
|
||||
devs.push((d, len));
|
||||
}
|
||||
let total: f64 = devs.iter().map(|d| d.1).sum();
|
||||
// Too little structure to trust (close-ups, crowds): left alone.
|
||||
if total < 0.35 {
|
||||
return None;
|
||||
}
|
||||
// The angle most of the line length agrees on (the mode, not the median: people, flags and the odd
|
||||
// perspective line scatter around, while the boards and the stands agree with each other).
|
||||
let support = |c: f64| {
|
||||
devs.iter()
|
||||
.filter(|(d, _)| (d - c).abs() <= AGREE)
|
||||
.map(|x| x.1)
|
||||
.sum::<f64>()
|
||||
};
|
||||
let (best, weight) = devs
|
||||
.iter()
|
||||
.map(|(d, _)| (*d, support(*d)))
|
||||
.max_by(|a, b| a.1.total_cmp(&b.1))?;
|
||||
// Another, different angle almost as supported: the scene is ambiguous, better left alone.
|
||||
let rival = devs
|
||||
.iter()
|
||||
.filter(|(d, _)| (d - best).abs() > 2.0 * AGREE)
|
||||
.map(|(d, _)| support(*d))
|
||||
.fold(0.0, f64::max);
|
||||
if weight < 0.3 || weight < 0.35 * total || rival > 0.7 * weight {
|
||||
return None;
|
||||
}
|
||||
let inliers: Vec<&(f64, f64)> = devs
|
||||
.iter()
|
||||
.filter(|(d, _)| (d - best).abs() <= AGREE)
|
||||
.collect();
|
||||
let mean = inliers.iter().map(|(d, l)| d * l).sum::<f64>()
|
||||
/ inliers.iter().map(|(_, l)| l).sum::<f64>();
|
||||
Some(((-mean) * 100.0).round() / 100.0)
|
||||
}
|
||||
|
||||
/// Signed deviation (degrees) of a near-level or near-plumb line, in the sign of LightCraft's `level_angle`.
|
||||
fn deviation(s: &Segment) -> Option<f64> {
|
||||
let (dx, dy) = (s.b.x - s.a.x, s.b.y - s.a.y);
|
||||
let fold = |a: f64| {
|
||||
if a > 90.0 {
|
||||
a - 180.0
|
||||
} else if a < -90.0 {
|
||||
a + 180.0
|
||||
} else {
|
||||
a
|
||||
}
|
||||
};
|
||||
let horizontal = fold(dy.atan2(dx).to_degrees());
|
||||
if horizontal.abs() <= MAX_DEV {
|
||||
return Some(horizontal);
|
||||
}
|
||||
let vertical = -fold(dx.atan2(dy).to_degrees());
|
||||
(vertical.abs() <= MAX_DEV).then_some(vertical)
|
||||
}
|
||||
|
||||
/// Perceptual lightness normalised to the bright end, as LightCraft's analysis does.
|
||||
fn lightness(img: &Rgb32f) -> Plane {
|
||||
let lum = img.luminance();
|
||||
let mut v: Vec<f32> = lum.data.iter().copied().filter(|x| x.is_finite()).collect();
|
||||
v.sort_by(f32::total_cmp);
|
||||
let white = v.get(v.len() * 99 / 100).copied().unwrap_or(1.0).max(1e-4);
|
||||
lum.map(|x| (x.max(0.0) / white).min(1.5).powf(1.0 / 2.4))
|
||||
}
|
||||
|
||||
fn green(p: [f32; 3]) -> bool {
|
||||
let [r, g, b] = p;
|
||||
g > 0.004 && g > r * 1.15 && g > b * 1.15
|
||||
}
|
||||
|
||||
/// A pitch marking (or the pitch's edge): grass on both sides along most of the line.
|
||||
fn on_grass(img: &Rgb32f, ax: f64, ay: f64, bx: f64, by: f64) -> bool {
|
||||
let (dx, dy) = (bx - ax, by - ay);
|
||||
let len = dx.hypot(dy).max(1e-9);
|
||||
let (nx, ny) = (-dy / len * 5.0, dx / len * 5.0);
|
||||
let at = |x: f64, y: f64| {
|
||||
let (xi, yi) = (x.round(), y.round());
|
||||
if xi < 0.0 || yi < 0.0 || xi >= img.width as f64 || yi >= img.height as f64 {
|
||||
return None;
|
||||
}
|
||||
Some(img.data[yi as usize * img.width + xi as usize])
|
||||
};
|
||||
let (mut grass, mut n) = (0, 0);
|
||||
for i in 1..10 {
|
||||
let t = i as f64 / 10.0;
|
||||
let (x, y) = (ax + dx * t, ay + dy * t);
|
||||
// A line on grass has grass on both sides; the board above the pitch has it on one side at most.
|
||||
let (Some(p), Some(q)) = (at(x + nx, y + ny), at(x - nx, y - ny)) else {
|
||||
continue;
|
||||
};
|
||||
n += 1;
|
||||
if green(p) && green(q) {
|
||||
grass += 1;
|
||||
}
|
||||
}
|
||||
n > 0 && grass * 10 >= n * 5
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// A stadium-like scene: a board along the top (its lower edge tilted by `tilt` degrees), grass below with a
|
||||
/// touchline drawn in perspective at `line` degrees.
|
||||
fn stadium(tilt: f64, line: f64) -> Rgb32f {
|
||||
let (w, h) = (900usize, 600usize);
|
||||
let (t, l) = (tilt.to_radians().tan(), line.to_radians().tan());
|
||||
Rgb32f::from_fn(w, h, |x, y| {
|
||||
let xc = x as f64 - w as f64 / 2.0;
|
||||
let board = 200.0 + xc * t;
|
||||
let touch = 420.0 + xc * l;
|
||||
let y = y as f64;
|
||||
if y < board - 120.0 {
|
||||
[0.05, 0.05, 0.06] // stands
|
||||
} else if y < board {
|
||||
[0.6, 0.08, 0.06] // red board
|
||||
} else if (y - touch).abs() < 3.0 {
|
||||
[0.8, 0.8, 0.8] // the white line
|
||||
} else {
|
||||
[0.05, 0.25, 0.04] // grass
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn levels_by_the_boards_not_the_pitch_markings() {
|
||||
// Board 2.5 degrees off, touchline at 18 degrees in perspective: the board decides.
|
||||
let d = sports_level(&stadium(2.5, 18.0)).expect("level found");
|
||||
assert!((d + 2.5).abs() < 0.6, "{d}");
|
||||
// A level board stays level, whatever the touchline does.
|
||||
let d = sports_level(&stadium(0.0, -14.0)).expect("level found");
|
||||
assert!(d.abs() < 0.4, "{d}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn leaves_alone_what_has_no_lines() {
|
||||
let flat = Rgb32f::from_fn(400, 300, |_, _| [0.1, 0.3, 0.05]);
|
||||
assert_eq!(sports_level(&flat), None);
|
||||
}
|
||||
}
|
||||
@@ -4,6 +4,7 @@
|
||||
//! small JSON edit commands addressed by LightCraft control ids (`light.exposure`, `effects.clarity`, ...).
|
||||
//! Updating LightCraft should only ever require changes in this crate.
|
||||
|
||||
pub mod level;
|
||||
pub mod render;
|
||||
|
||||
pub use lightcraft_develop::DevelopSettings;
|
||||
|
||||
@@ -82,6 +82,12 @@ impl Source {
|
||||
.map(|d| (d.clamp(-45.0, 45.0) * 100.0).round() / 100.0)
|
||||
}
|
||||
|
||||
/// Auto straighten for sports and press photos: levels by the boards, stands, posts and railings, never by the
|
||||
/// pitch markings (which perspective tilts). `None` when those lines don't agree.
|
||||
pub fn auto_level_scene(&self) -> Option<f64> {
|
||||
crate::level::sports_level(&self.image)
|
||||
}
|
||||
|
||||
/// Automatic white balance (grey world on mid-tone, low-chroma pixels): `wb.temp` and `wb.tint`.
|
||||
pub fn auto_wb(&self) -> Vec<(&'static str, f64)> {
|
||||
let (temp, tint) = lightcraft_pipeline::auto::auto_wb(&self.image, &self.info);
|
||||
|
||||
Executable
+86
@@ -0,0 +1,86 @@
|
||||
#!/usr/bin/env bash
|
||||
# Turns a Mac into the macOS builder for desktop releases (run once, on the Mac that will build).
|
||||
# bash ~/Projects/photoreport-build/infra/desktop/macos-runner.sh
|
||||
#
|
||||
# It installs Gitea's act_runner as a background service of this user (starts at login, restarts if it stops) with
|
||||
# the label "macos". From then on every `desktop-v*` release also builds the signed .dmg and the macOS update, and the
|
||||
# installed apps update themselves: nobody compiles by hand again. The Mac only has to be on (and logged in) when a
|
||||
# release is made; a release made while it is off waits and builds when it comes back.
|
||||
#
|
||||
# The registration token comes from Gitea (BitReport.pt/photoreport → Definições → Actions → Runners → Criar
|
||||
# runner). The script asks for it; it is used once and not saved.
|
||||
set -Eeuo pipefail
|
||||
|
||||
VERSION="${ACT_RUNNER_VERSION:-0.2.11}"
|
||||
INSTANCE="${GITEA_URL:-https://git.bitreport.pt}"
|
||||
HOME_DIR="$HOME/.photoreport-runner"
|
||||
PLIST="$HOME/Library/LaunchAgents/pt.photoreport.act-runner.plist"
|
||||
|
||||
step() { printf '\n\033[1;34m== %s\033[0m\n' "$*"; }
|
||||
|
||||
[[ "$(uname)" == Darwin ]] || { echo "Run this on a Mac." >&2; exit 1; }
|
||||
xcode-select -p >/dev/null 2>&1 || { xcode-select --install; echo "Install the Xcode command line tools, then run this again." >&2; exit 1; }
|
||||
command -v node >/dev/null || { echo "Node.js 22 is needed: brew install node@22" >&2; exit 1; }
|
||||
|
||||
step "Rust"
|
||||
if ! command -v cargo >/dev/null; then curl -fsSL https://sh.rustup.rs | sh -s -- -y; fi
|
||||
# shellcheck disable=SC1091
|
||||
source "$HOME/.cargo/env"
|
||||
rustup target add aarch64-apple-darwin x86_64-apple-darwin wasm32-unknown-unknown >/dev/null
|
||||
|
||||
step "pnpm"
|
||||
command -v pnpm >/dev/null || corepack enable pnpm 2>/dev/null || npm install -g pnpm
|
||||
|
||||
step "act_runner $VERSION"
|
||||
mkdir -p "$HOME_DIR"
|
||||
cd "$HOME_DIR"
|
||||
arch="$(uname -m)"; [[ "$arch" == "arm64" ]] || arch="amd64"
|
||||
if [[ ! -x ./act_runner ]] || ! ./act_runner --version 2>/dev/null | grep -q "$VERSION"; then
|
||||
curl -fsSL -o act_runner "https://dl.gitea.com/act_runner/${VERSION}/act_runner-${VERSION}-darwin-${arch}"
|
||||
chmod +x act_runner
|
||||
fi
|
||||
|
||||
if [[ ! -f .runner ]]; then
|
||||
step "Register with $INSTANCE"
|
||||
token="${GITEA_RUNNER_TOKEN:-}"
|
||||
if [[ -z "$token" ]]; then read -rsp "Registration token (Gitea → Actions → Runners → Criar runner): " token; echo; fi
|
||||
[[ -n "$token" ]] || { echo "No token." >&2; exit 1; }
|
||||
./act_runner generate-config > config.yaml
|
||||
# One build at a time; jobs run on this Mac directly (no containers on macOS).
|
||||
sed -i '' 's/^ capacity: .*/ capacity: 1/' config.yaml
|
||||
./act_runner register --no-interactive --config config.yaml --instance "$INSTANCE" --token "$token" \
|
||||
--name "$(scutil --get ComputerName | tr ' ' '-')-macos" --labels "macos:host"
|
||||
fi
|
||||
|
||||
step "Background service"
|
||||
mkdir -p "$(dirname "$PLIST")"
|
||||
cat > "$PLIST" <<PLIST
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
||||
<plist version="1.0">
|
||||
<dict>
|
||||
<key>Label</key><string>pt.photoreport.act-runner</string>
|
||||
<key>ProgramArguments</key><array><string>$HOME_DIR/act_runner</string><string>daemon</string><string>--config</string><string>$HOME_DIR/config.yaml</string></array>
|
||||
<key>WorkingDirectory</key><string>$HOME_DIR</string>
|
||||
<key>EnvironmentVariables</key><dict>
|
||||
<key>PATH</key><string>$HOME/.cargo/bin:/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin</string>
|
||||
<key>HOME</key><string>$HOME</string>
|
||||
</dict>
|
||||
<key>RunAtLoad</key><true/>
|
||||
<key>KeepAlive</key><true/>
|
||||
<key>StandardOutPath</key><string>$HOME_DIR/runner.log</string>
|
||||
<key>StandardErrorPath</key><string>$HOME_DIR/runner.log</string>
|
||||
</dict>
|
||||
</plist>
|
||||
PLIST
|
||||
launchctl bootout "gui/$(id -u)" "$PLIST" 2>/dev/null || true
|
||||
launchctl bootstrap "gui/$(id -u)" "$PLIST"
|
||||
|
||||
sleep 3
|
||||
if launchctl print "gui/$(id -u)/pt.photoreport.act-runner" >/dev/null 2>&1; then
|
||||
printf '\n\033[1;32mDone.\033[0m This Mac now builds the macOS version of every desktop release.\n'
|
||||
printf 'Log: %s/runner.log Stop: launchctl bootout gui/%s %s\n' "$HOME_DIR" "$(id -u)" "$PLIST"
|
||||
else
|
||||
echo "The service did not start; see $HOME_DIR/runner.log" >&2
|
||||
exit 1
|
||||
fi
|
||||
@@ -52,6 +52,15 @@ export const PhotoBatchPatch = z.object({
|
||||
});
|
||||
export type PhotoBatchPatch = z.infer<typeof PhotoBatchPatch>;
|
||||
|
||||
export type PhotoDelivery = "NONE" | "QUEUED" | "DONE" | "FAILED";
|
||||
|
||||
/** A photo's overall delivery state from the status of each of its deliveries. */
|
||||
export function deliveryState(statuses: readonly string[]): PhotoDelivery {
|
||||
if (statuses.includes("DONE")) return "DONE";
|
||||
if (statuses.some((x) => x === "QUEUED" || x === "RUNNING")) return "QUEUED";
|
||||
return statuses.length ? "FAILED" : "NONE";
|
||||
}
|
||||
|
||||
export interface PhotoSummary {
|
||||
id: string;
|
||||
eventId: string | null;
|
||||
@@ -63,6 +72,10 @@ export interface PhotoSummary {
|
||||
/** False when only a preview is on the server and the original stays on the photographer's computer. */
|
||||
originalStored: boolean;
|
||||
status: "PROCESSING" | "READY" | "FAILED";
|
||||
/** Why a FAILED photo could not be read (damaged or cut-off file, unsupported format). */
|
||||
error?: string | null;
|
||||
/** Where its deliveries stand: DONE once any destination has it, QUEUED while one is on its way, FAILED otherwise. */
|
||||
delivery?: PhotoDelivery;
|
||||
width: number | null;
|
||||
height: number | null;
|
||||
capturedAt: string | null;
|
||||
|
||||
@@ -59,6 +59,8 @@ export interface PrintEventSummary {
|
||||
template: PrintTemplate;
|
||||
galleryId: string | null;
|
||||
printerId: string | null;
|
||||
/** A kiosk link is on (the link itself is only shown when made). */
|
||||
kiosk: boolean;
|
||||
counts: { waiting: number; printed: number };
|
||||
}
|
||||
|
||||
@@ -116,6 +118,13 @@ export interface PublicPrintEvent {
|
||||
photos: { id: string; thumb: string; preview: string }[];
|
||||
}
|
||||
|
||||
/** What the kiosk (a tablet at the event, `/e/<slug>/quiosque?k=…`) shows: the event and its latest prints. */
|
||||
export interface KioskView extends PublicPrintEvent {
|
||||
/** Paid events: the kiosk sends prints for approval and the guest pays at the counter. */
|
||||
payAtCounter: boolean;
|
||||
jobs: { id: string; status: PrintJobStatus; guestName: string | null; ahead: number; preview: string; createdAt: string }[];
|
||||
}
|
||||
|
||||
export interface GuestJob {
|
||||
id: string;
|
||||
status: PrintJobStatus;
|
||||
|
||||
Loaded 100 of 107 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user