Compare commits

...
Author SHA1 Message Date
spark 24ec8095f6 Desktop 0.3.4: allow ftp_check for the web app, and a test that every command is allowed
ci / typescript (push) Failing after 21m10s
ci / rust (push) Successful in 22m51s
desktop-release / build (deb,appimage, linux-x86_64, ubuntu-latest) (push) Successful in 1h19m4s
Claude-Session: https://claude.ai/code/session_01HT6iXLYUUp9pJz5Kza9xCW
2026-10-13 14:13:22 +01:00
spark 82ab4a3888 Local FTP: logins can be switched off, a connection test, macOS firewall warnings; desktop 0.3.3
ci / rust (push) Successful in 15m32s
ci / typescript (push) Successful in 16m47s
desktop-release / build (deb,appimage, linux-x86_64, ubuntu-latest) (push) Successful in 1h16m6s
Claude-Session: https://claude.ai/code/session_01HT6iXLYUUp9pJz5Kza9xCW
2026-10-13 13:56:24 +01:00
spark 91a88c1aaa Agenda: connect your calendar (iCal) to fill generic events and suggest captions
ci / rust (push) Successful in 10m1s
ci / typescript (push) Successful in 12m33s
Claude-Session: https://claude.ai/code/session_01HT6iXLYUUp9pJz5Kza9xCW
2026-10-13 13:44:56 +01:00
spark edf8c21488 Generic events: no guessed caption, written in the form or the event's IPTC template
ci / rust (push) Successful in 7m38s
ci / typescript (push) Successful in 11m0s
Claude-Session: https://claude.ai/code/session_01HT6iXLYUUp9pJz5Kza9xCW
2026-10-13 13:33:21 +01:00
spark 112cea980f Events that are not a match: a name instead of two teams, captioned by the name
ci / rust (push) Successful in 7m42s
ci / typescript (push) Successful in 9m58s
Claude-Session: https://claude.ai/code/session_01HT6iXLYUUp9pJz5Kza9xCW
2026-10-13 13:15:54 +01:00
spark 4e1d293d06 App tests: 20 s limit, whole-app renders went past 5 s on a busy runner
ci / rust (push) Successful in 8m59s
ci / typescript (push) Successful in 11m41s
Claude-Session: https://claude.ai/code/session_01HT6iXLYUUp9pJz5Kza9xCW
2026-10-13 12:49:47 +01:00
spark c94772e78e Site: most viewed galleries, photo caption and credit, a link per photo
ci / rust (push) Successful in 8m43s
ci / typescript (push) Successful in 11m58s
Claude-Session: https://claude.ai/code/session_01HT6iXLYUUp9pJz5Kza9xCW
2026-10-13 12:43:19 +01:00
spark e9fcf973c3 Site home: search by team, player or competition, sport shortcuts, latest photos and live badges
ci / typescript (push) Successful in 18m48s
ci / rust (push) Successful in 15m24s
Claude-Session: https://claude.ai/code/session_01HT6iXLYUUp9pJz5Kza9xCW
2026-10-13 11:42:14 +01:00
44 changed files with 1941 additions and 92 deletions

No files matched your search

@@ -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;
+16
View File
@@ -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
+3
View File
@@ -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,6 +105,7 @@ 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 });
+215
View File
@@ -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 };
}
+40
View File
@@ -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);
}
});
}
+180
View File
@@ -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");
}
+2 -2
View File
@@ -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;
}
+7 -5
View File
@@ -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";
@@ -18,8 +18,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 +58,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,
};
@@ -143,12 +145,12 @@ 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,
+21 -7
View File
@@ -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);
}
+33 -1
View File
@@ -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
View File
@@ -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,
+125
View File
@@ -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 });
});
});
+19
View File
@@ -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());
+57
View File
@@ -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" });
+42
View File
@@ -66,6 +66,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 +105,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 +223,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",
+71
View File
@@ -0,0 +1,71 @@
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");
});
});
+204 -11
View File
@@ -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">
@@ -223,3 +283,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>
);
}
+25
View File
@@ -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");
});
});
+68 -8
View File
@@ -7,7 +7,8 @@ import type { 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 {
@@ -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);
@@ -172,14 +179,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 +237,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 +263,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 +274,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 +371,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 +434,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>
);
}
+2 -1
View File
@@ -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 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@photoreport/desktop",
"version": "0.3.2",
"version": "0.3.4",
"private": true,
"type": "module",
"scripts": {
+2 -2
View File
@@ -1,6 +1,6 @@
[package]
name = "photoreport-desktop"
version = "0.3.2"
version = "0.3.4"
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,7 +23,7 @@ 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"
+1
View File
@@ -9,6 +9,7 @@ fn main() {
"ftp_start",
"ftp_stop",
"ftp_status",
"ftp_check",
"ftp_take",
"ftp_retry",
"ftp_read",
@@ -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",
@@ -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"]
+196 -9
View File
@@ -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();
+1
View File
@@ -102,6 +102,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,
+1 -1
View File
@@ -1,7 +1,7 @@
{
"$schema": "https://schema.tauri.app/config/2",
"productName": "PhotoReport",
"version": "0.3.2",
"version": "0.3.4",
"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"
);
}
}
@@ -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"}
+15 -5
View File
@@ -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>
);
+128
View File
@@ -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;
+86 -10
View File
@@ -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>
+8 -2
View File
@@ -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. */
+8 -1
View File
@@ -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();
});
});
+11
View File
@@ -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;
}
+20
View File
@@ -65,6 +65,13 @@ 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.
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 +88,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
@@ -211,6 +222,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.
+21
View File
@@ -41,6 +41,8 @@ export type GalleryVisibility = "PUBLIC" | "UNLISTED" | "PRIVATE";
export interface GalleryEventInfo {
home: string;
away: string | null;
/** The event's sport as the agenda names it (andebol, futebol…); null when not set. */
sport: string | null;
competition: string | null;
venue: string | null;
startsAt: string;
@@ -106,6 +108,21 @@ export interface PublicGallerySummary {
cover: string | null;
event: GalleryEventInfo | null;
publishedAt: string;
/** New photos keep arriving (a live gallery). */
live: boolean;
}
/** A gallery on the home page's "Mais vistas": its visits over the last days. */
export interface PopularGallery extends PublicGallerySummary {
views: number;
}
/** One of the latest photos published across a site's public galleries ("Últimas do jogo"). */
export interface LatestPhoto {
id: string;
thumb: string;
gallery: { slug: string; title: string; live: boolean };
addedAt: string;
}
export interface PublicPhoto {
@@ -116,6 +133,10 @@ export interface PublicPhoto {
players: string[];
/** File name (the arrival rename, or the camera's): what clients quote back in a selection. */
name: string;
/** The IPTC caption the photo is delivered with (event template, the photo's overrides, players). */
caption: string | null;
/** Who to credit (IPTC creator, else credit or copyright): "Name / Agency". */
credit: string | null;
/** Watermarked, 600 px and 1600 px. */
thumb: string;
preview: string;
+19 -1
View File
@@ -84,6 +84,20 @@ export const NEWSROOM_TEMPLATE: IptcTemplate = {
personsShown: ["{players}"],
};
/**
* The default for generic events (press conferences, galas, presentations): nothing is guessed for the caption,
* headline or event; the editor writes them (the new event form, or the event's IPTC template later).
*/
export const GENERAL_TEMPLATE: IptcTemplate = {
title: "{players}",
location: "{venue}",
city: "{city}",
copyright: "{photographer} / PhotoReport.pt",
source: "{photographer} / PhotoReport.pt",
creator: "{photographer} / PhotoReport.pt",
personsShown: ["{players}"],
};
export interface IptcIssue {
field: IptcFieldKey;
kind: "missing_variable" | "unknown_code";
@@ -106,7 +120,11 @@ function fill(template: string, vars: TemplateVars, codes: CodeList | undefined,
/** Collapse the spaces an empty variable leaves behind. Missing variables are always reported as issues. */
function tidy(value: string): string {
return value.replace(/\s{2,}/g, " ").trim();
// A match template on an event without an away team: "Gala x , em Braga" → "Gala, em Braga".
return value
.replace(/\s{2,}/g, " ")
.replace(/\s+x\s*(?=,|$)/g, "")
.trim();
}
/**
+15
View File
@@ -5,7 +5,9 @@ import {
codeList,
createdStamp,
DESTINATION_EXAMPLES,
eventName,
expandCodes,
GENERAL_TEMPLATE,
NEWSROOM_TEMPLATE,
parseCodeList,
PathTemplateError,
@@ -80,6 +82,19 @@ describe("IPTC template", () => {
expect(issues.filter((i) => i.kind === "missing_variable").map((i) => i.field)).toEqual(["title"]);
});
it("leaves the caption of a generic event to the editor, and a match template drops the dangling x", () => {
const press = { home: "Conferência de imprensa do FC Porto", away: "", venue: "Estádio do Dragão", city: "Porto", startsAt: new Date("2026-10-14T10:00:00Z") };
expect(eventName(press)).toBe("Conferência de imprensa do FC Porto");
expect(eventName(braga)).toBe("ABC Braga x CDE Gil Eanes");
const general = applyTemplate(GENERAL_TEMPLATE, buildVars(press, {}, "Peter Spark"));
expect(general.values).toEqual({ location: "Estádio do Dragão", city: "Porto", copyright: "Peter Spark / PhotoReport.pt", source: "Peter Spark / PhotoReport.pt", creator: "Peter Spark / PhotoReport.pt" });
expect(general.issues.filter((i) => i.field !== "title")).toEqual([]);
// An event moved to "not a match" keeps its old template: no dangling "x".
const old = applyTemplate(NEWSROOM_TEMPLATE, buildVars(press, {}, "Peter Spark")).values;
expect(old.caption).toBe("Conferência de imprensa do FC Porto, em Porto, no Estádio do Dragão");
expect(old.event).toBe("Conferência de imprensa do FC Porto");
});
it("expands codes typed by an editor and keeps long venues whole", () => {
const { values, issues } = applyTemplate({ title: "\\v7\\", location: "{venue}" }, buildVars(braga), codeList({ v7: "Miguel Silva (VSC)" }));
expect(values.title).toBe("Miguel Silva (VSC)");
+9 -2
View File
@@ -2,7 +2,9 @@ import type { TemplateVars } from "./template.js";
/** What an event knows about itself; filled by an admin or editor when the event is created. */
export interface EventInfo {
/** The home team; for an event that is not a match (a press conference, a gala), its name. */
home: string;
/** Empty when the event is not a match. */
away: string;
homeShort?: string | undefined;
awayShort?: string | undefined;
@@ -53,6 +55,11 @@ export function seasonOf(date: Date): { start: number; end: number } {
return { start, end: start + 1 };
}
/** "Home x Away", or the event's name when it is not a match (no away team). */
export function eventName(event: { home: string; away: string | null }): string {
return event.away ? `${event.home} x ${event.away}` : event.home;
}
/** The variables available to every template (IPTC, folders, file names). */
export function buildVars(event: EventInfo, photo: PhotoInfo = {}, photographer?: string): TemplateVars {
const day = parts(event.startsAt);
@@ -61,8 +68,8 @@ export function buildVars(event: EventInfo, photo: PhotoInfo = {}, photographer?
return {
home: event.home,
away: event.away,
/** "Home x Away", like the Event field in Photo Mechanic's templates. */
event: `${event.home} x ${event.away}`,
/** "Home x Away", like the Event field in Photo Mechanic's templates; the name alone when it is not a match. */
event: eventName(event),
homeShort: event.homeShort ?? event.home,
awayShort: event.awayShort ?? event.away,
venue: event.venue,
+16 -1
View File
@@ -1,5 +1,5 @@
import type { BundleInput, BundleSummary, PressAccountInput, PressAccountSummary, PressStatement, NotificationView, AffiliateInput, AffiliateSummary, EarningsOverview, EarningsSettings, MemberPayoutInput, MyEarnings, PayeeAccount, PayoutInput, PayoutView, CodeGeneratorSettings, CodeLine, ConfirmFaceGroup, DeliveryItemSummary, DevelopState, EditLogEntry, FaceGroupSummary, GalleryInput, GalleryPhotosChange, GallerySummary, Module, OrderView, PhotoPatch, PhotoSummary, PostEdits, PrinterSummary, PrintEventInput, PrintEventSummary, PrintJobSummary, ProductInput, ProofingReport, ProductSummary, SiteInfo, SiteInput, StationSummary } from "@photoreport/contracts";
import type { InvoiceSummary, AutopilotStyle, DeliveryTarget, DeliveryTargetInput, JerseySample, JerseyStats, PersonSummary, PhotoFace, ShopSettings, SquadPerson, DeviceGrant, FtpAccount, FtpPlan, EventInput, EventSquads, EventSummary, IptcIssue, SportsCompetition, SportsFixture, SportsPlayer, SportsTeam, Me, Member, PhotoQuery, Role } from "./types.js";
import type { AgendaEntry, InvoiceSummary, AutopilotStyle, DeliveryTarget, DeliveryTargetInput, JerseySample, JerseyStats, PersonSummary, PhotoFace, ShopSettings, SquadPerson, DeviceGrant, FtpAccount, FtpPlan, EventInput, EventSquads, EventSummary, IptcIssue, SportsCompetition, SportsFixture, SportsPlayer, SportsTeam, Me, Member, PhotoQuery, Role } from "./types.js";
/**
* Where the refresh token lives. The web app leaves it in an httpOnly cookie (no store); the desktop app keeps it
@@ -178,6 +178,21 @@ export class ApiClient {
return this.request<{ editorModules: Module[] }>("PUT", "/v1/me/preferences", { editorModules });
}
/** Whether the person connected their calendar (its secret iCal address). */
calendarStatus() {
return this.request<{ connected: boolean }>("GET", "/v1/me/calendar");
}
/** Connect a calendar by its secret iCal address (checked first), or forget it with null. */
connectCalendar(url: string | null) {
return this.request<{ connected: boolean; events: number }>("PUT", "/v1/me/calendar", { url });
}
/** The agenda entries of one day ("YYYY-MM-DD", Lisbon; default today). */
agenda(date?: string) {
return this.request<{ date: string; events: AgendaEntry[] }>("GET", `/v1/me/calendar/events${date ? `?date=${date}` : ""}`);
}
// ---- organizations ----------------------------------------------------------------------------------
listMembers(orgId: string): Promise<Member[]> {
+15 -1
View File
@@ -74,9 +74,23 @@ export interface EventSummary {
awayTeamId?: string | null;
}
/** An entry of the person's own agenda (their calendar), with what the new-event form fills from it. */
export interface AgendaEntry {
uid: string;
title: string;
start: string;
end: string | null;
allDay: boolean;
location: string | null;
description: string | null;
suggestion: { name: string; venue: string | null; city: string | null; caption: string };
}
export interface EventInput {
/** The home team, or the event's name when it is not a match. */
home: string;
away: string;
/** Empty: not a match (press conference, gala…). */
away?: string;
venue?: string | null;
city?: string | null;
sport?: string | null;