299 lines
16 KiB
TypeScript
299 lines
16 KiB
TypeScript
import cookie from "@fastify/cookie";
|
|
import cors from "@fastify/cors";
|
|
import { originAllowed, requestHost } from "./lib/origins.js";
|
|
import rateLimit from "@fastify/rate-limit";
|
|
import { EditEnvelope } from "@photoreport/contracts";
|
|
import Fastify, { type FastifyInstance } from "fastify";
|
|
import { registerArchiveRoutes } from "./archive/routes.js";
|
|
import { ArchiveService } from "./archive/service.js";
|
|
import { registerArchiveViewerRoutes, ViewerTokens } from "./archive/viewer.js";
|
|
import { requireAuth } from "./auth/guard.js";
|
|
import { registerAuthRoutes } from "./auth/routes.js";
|
|
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";
|
|
import { DeliveryService } from "./delivery/service.js";
|
|
import { registerEventRoutes } from "./library/events.js";
|
|
import { registerFtpRoutes } from "./library/ftp.js";
|
|
import { registerPhotoRoutes } from "./library/photos.js";
|
|
import { registerCompositionRoutes } from "./composition/routes.js";
|
|
import { registerUploadRoutes } from "./library/uploads.js";
|
|
import { IngestService } from "./ingest/service.js";
|
|
import { CorrectionRecorder } from "./autopilot/learning.js";
|
|
import { registerAutopilotRoutes } from "./autopilot/routes.js";
|
|
import { registerRealEstateRoutes } from "./realestate/routes.js";
|
|
import { registerDevelopRoutes } from "./develop/routes.js";
|
|
import { DevelopService } from "./develop/service.js";
|
|
import { registerFaceRoutes } from "./faces/routes.js";
|
|
import { FaceLookup, IdleEngine } from "./faces/lookup.js";
|
|
import { registerLookupRoutes } from "./faces/lookupRoutes.js";
|
|
import { type FaceEngine, FaceProcess, GrowingFacePool } from "./faces/process.js";
|
|
import { faceWorkerLive } from "./faces/heartbeat.js";
|
|
import { faceEnginePaths, jerseyModelDir, scanSlots } from "./lib/engines.js";
|
|
import { modelsDir } from "./lib/models.js";
|
|
import { JerseyModel, JerseyPool } from "./jersey/model.js";
|
|
import type { JerseyReader } from "./faces/lookup.js";
|
|
import { registerJerseyRoutes } from "./jersey/routes.js";
|
|
import { smtpMailer } from "./lib/mailer.js";
|
|
import { clientGalleryOrigin, registerSiteGalleryRoutes } from "./site-galleries/routes.js";
|
|
import { JerseyService } from "./jersey/service.js";
|
|
import { registerSearchRoutes } from "./library/search.js";
|
|
import { registerPrintRoutes } from "./print/routes.js";
|
|
import { PrintService } from "./print/service.js";
|
|
import { DesktopReleases, registerDesktopRoutes } from "./desktop/updates.js";
|
|
import { registerShopAdminRoutes } from "./shop/admin-routes.js";
|
|
import { EarningsService } from "./shop/earnings.js";
|
|
import { Notifications } from "./notifications/service.js";
|
|
import { InvoicingService } from "./invoicing/service.js";
|
|
import { registerInvoicingRoutes } from "./invoicing/routes.js";
|
|
import { registerNotificationRoutes } from "./notifications/routes.js";
|
|
import { registerEarningsRoutes } from "./shop/earnings-routes.js";
|
|
import { PressService } from "./shop/press.js";
|
|
import { registerPressRoutes } from "./shop/press-routes.js";
|
|
import { ProofingService } from "./shop/proofing.js";
|
|
import { registerPublicShopRoutes } from "./shop/public-routes.js";
|
|
import { ShopService } from "./shop/service.js";
|
|
import { FaceService } from "./faces/service.js";
|
|
import { moduleFromRecord, moduleFromUrl, requireAppModule } from "./modules/access.js";
|
|
import { registerOrgRoutes } from "./orgs/routes.js";
|
|
import { registerSportsRoutes } from "./sports/routes.js";
|
|
import { jogaClientFromConfig, jogaFetch } from "./sports/joga.js";
|
|
import { SportsService } from "./sports/service.js";
|
|
import { attachRealtime, type Broadcaster, silentBroadcaster } from "./realtime.js";
|
|
import { LocalStorage, UrlSigner } from "./storage/storage.js";
|
|
import { registerClientErrors } from "./lib/clientErrors.js";
|
|
import { type ErrorReporter, reporterFor } from "./lib/reporter.js";
|
|
|
|
export { reporterFor };
|
|
|
|
export interface AppDeps {
|
|
config: Config;
|
|
db: Db;
|
|
/** `socket`: realtime over socket.io on the API server. Tests pass a recording broadcaster. */
|
|
realtime?: "socket" | Broadcaster;
|
|
/** Outgoing HTTP for deliveries (tests point it at a fake Nextcloud). */
|
|
fetchImpl?: typeof fetch;
|
|
/** Errors to errors.bitreport.pt (made from the config when not given). */
|
|
reporter?: ErrorReporter;
|
|
/** The face engine for search by photo (tests pass a fake; otherwise the built engine, started on demand). */
|
|
faceEngine?: FaceEngine;
|
|
/** Shirt numbers on a card scan. Tests pass a fake; otherwise the model is loaded on the first scan. */
|
|
jersey?: JerseyReader | null;
|
|
/** Whether the worker is running face analysis. Tests set this; otherwise a heartbeat file next to storage. */
|
|
engineOnline?: () => boolean;
|
|
}
|
|
|
|
/**
|
|
* Builds the API. Modules (ingest, library, oplog, galleries, sales, events, print, delivery) register here as
|
|
* they are built.
|
|
*/
|
|
export async function buildApp({ config, db, realtime, fetchImpl, reporter: given, faceEngine, engineOnline, jersey }: AppDeps): Promise<FastifyInstance> {
|
|
const reporter = given ?? reporterFor(config);
|
|
const app = Fastify({
|
|
// Error lines (and warnings carrying an error) also go to errors.bitreport.pt.
|
|
logger: config.NODE_ENV === "test" ? false : { level: config.LOG_LEVEL, hooks: reporter.logHooks("api") },
|
|
trustProxy: true,
|
|
});
|
|
const sessions = new SessionService(db, config);
|
|
const storage = new LocalStorage(config.STORAGE_ROOT);
|
|
const signer = new UrlSigner(config.JWT_SECRET, config.FILE_URL_TTL_SEC);
|
|
const broadcaster =
|
|
realtime === "socket"
|
|
? attachRealtime(app.server, {
|
|
db,
|
|
sessions,
|
|
databaseUrl: config.DATABASE_URL,
|
|
corsOrigins: config.corsOrigins,
|
|
onError: (err) => app.log.error({ err }, "realtime error"),
|
|
})
|
|
: (realtime ?? silentBroadcaster);
|
|
app.addHook("onClose", async () => broadcaster.close());
|
|
const secrets = config.DELIVERY_SECRET_KEY ? new SecretBox(config.DELIVERY_SECRET_KEY) : undefined;
|
|
const sports = new SportsService({
|
|
db,
|
|
storage,
|
|
signer,
|
|
log: app.log,
|
|
fetch: fetchImpl ?? fetch,
|
|
joga: jogaClientFromConfig(config, fetchImpl ?? jogaFetch),
|
|
});
|
|
// Archive clouds: the API connects them, matches galleries and streams originals; the worker walks and indexes.
|
|
const archive = new ArchiveService({ db, secrets, log: app.log, syncSquads: (id) => sports.syncEventSquads(id), ligaSeason: (season) => sports.importLigaSeason(season), storageRoot: config.STORAGE_ROOT, minFreeBytes: config.ARCHIVE_MIN_FREE_GB * 1e9, storage, ...(fetchImpl && { fetchImpl }) });
|
|
const delivery = new DeliveryService({ db, storage, secrets, broadcaster, log: app.log, originals: archive, ...(fetchImpl && { fetchImpl }) });
|
|
|
|
registerErrorHandler(app);
|
|
app.addHook("onClose", async () => reporter.flush());
|
|
await app.register(cookie);
|
|
await app.register(cors, {
|
|
delegator: (req, cb) =>
|
|
cb(null, {
|
|
origin: originAllowed(req.headers.origin, config.corsOrigins, requestHost(req.headers, req.hostname)) ? req.headers.origin! : false,
|
|
credentials: true,
|
|
methods: ["GET", "HEAD", "POST", "PUT", "PATCH", "DELETE"],
|
|
}),
|
|
});
|
|
await app.register(rateLimit, { global: false });
|
|
|
|
registerClientErrors(app, reporter);
|
|
|
|
app.get("/health", async () => {
|
|
await db.$queryRaw`SELECT 1`;
|
|
return { status: "ok", version: config.APP_VERSION };
|
|
});
|
|
|
|
const authenticate = requireAuth(sessions);
|
|
// A module route answers only when this person has that module. Shared library and develop routes stay open.
|
|
app.addHook("preHandler", async (req, reply) => {
|
|
const gated = moduleFromUrl(req.url) ?? (await moduleFromRecord(db, req.url));
|
|
if (!gated) return;
|
|
await authenticate(req, reply);
|
|
await requireAppModule(db, req, gated.orgId, gated.module, config.appModules);
|
|
});
|
|
|
|
await registerAuthRoutes(app, { db, config, sessions });
|
|
await registerMeRoutes(app, { db, sessions, broadcaster, serverModules: config.appModules });
|
|
await registerCalendarRoutes(app, { sessions, calendar: new CalendarService({ db, secrets, ...(fetchImpl && { fetchImpl }) }) });
|
|
await registerOrgRoutes(app, { db, sessions, serverModules: config.appModules });
|
|
await registerEventRoutes(app, { db, sessions, sports, broadcaster });
|
|
await registerSportsRoutes(app, { db, sessions, sports });
|
|
// Photos whose IPTC changes go again to where they went.
|
|
await registerPhotoRoutes(app, {
|
|
db,
|
|
sessions,
|
|
storage,
|
|
signer,
|
|
broadcaster,
|
|
archive,
|
|
resend: (orgId, ids) => delivery.resendPhotos(orgId, ids),
|
|
queueColor: async (orgId, ids, colorLabel) => {
|
|
const target = await db.deliveryTarget.findFirst({
|
|
where: { organizationId: orgId, colorLabel: colorLabel as "RED" | "YELLOW" | "GREEN" | "BLUE" | "PURPLE", disabledAt: null, mirrorOfId: null },
|
|
select: { id: true },
|
|
});
|
|
if (!target) return;
|
|
await delivery.enqueue({ organizationId: orgId, targetId: target.id, photoIds: ids, again: false, requestedById: null });
|
|
},
|
|
});
|
|
await registerArchiveRoutes(app, { db, sessions, archive, storageRoot: config.STORAGE_ROOT, minFreeBytes: config.ARCHIVE_MIN_FREE_GB * 1e9 });
|
|
// The API never runs the face engine: it confirms and merges groups; the worker detects and groups.
|
|
const faces = new FaceService({ db, storage, broadcaster, log: app.log, resend: (orgId, ids) => delivery.resendPhotos(orgId, ids) });
|
|
// Search by photo (library, archive editors, "Encontra-te"): the API's own face engine, started on demand.
|
|
const facePaths = faceEnginePaths(config);
|
|
const slots = scanSlots();
|
|
const lookupEngine = new IdleEngine(
|
|
faceEngine
|
|
? () => faceEngine
|
|
: facePaths && config.NODE_ENV !== "test"
|
|
? () => new GrowingFacePool(() => new FaceProcess({ bin: facePaths.bin, modelsDir: facePaths.modelsDir, embedder: config.FACES_EMBEDDER }), slots)
|
|
: null,
|
|
);
|
|
app.addHook("onClose", async () => (faceEngine ? undefined : lookupEngine.close()));
|
|
const lookup = new FaceLookup({ db, engine: () => lookupEngine.get() });
|
|
await registerArchiveViewerRoutes(app, {
|
|
db,
|
|
secrets,
|
|
signer,
|
|
archive,
|
|
tokens: new ViewerTokens(config.JWT_SECRET),
|
|
faces,
|
|
storage,
|
|
secret: config.JWT_SECRET,
|
|
fetchImpl,
|
|
sports,
|
|
lookup,
|
|
});
|
|
await registerCompositionRoutes(app, { db, sessions, storage, storageRoot: config.STORAGE_ROOT });
|
|
await registerSearchRoutes(app, { db, sessions, signer });
|
|
await registerFtpRoutes(app, { db, sessions, ingestRoot: config.INGEST_ROOT, hookSecret: config.SFTPGO_HOOK_KEY });
|
|
const ingest = new IngestService({ db, storage, signer, broadcaster, ingestRoot: config.INGEST_ROOT, log: app.log });
|
|
ingest.arrivals = (photo) => delivery.queueArrival(photo);
|
|
await registerUploadRoutes(app, { db, sessions, ingest, storage, signer });
|
|
// The worker writes the heartbeat. Tests have no worker, so they say the engine is on unless a case says otherwise.
|
|
const facesOnline = engineOnline ?? (() => (config.NODE_ENV === "test" ? true : faceEnginePaths(config) !== null && faceWorkerLive(config.STORAGE_ROOT)));
|
|
await registerFaceRoutes(app, { db, sessions, faces, signer, storage, engineOnline: facesOnline });
|
|
let jerseyOnce: Promise<JerseyReader | null> | null = null;
|
|
const jerseyOf = (): Promise<JerseyReader | null> => {
|
|
if (jersey !== undefined) return Promise.resolve(jersey);
|
|
if (config.NODE_ENV === "test") return Promise.resolve(null);
|
|
jerseyOnce ??= (async () => {
|
|
const dir = jerseyModelDir(config);
|
|
if (!dir) return null;
|
|
const first = await JerseyModel.load(dir).catch((err: unknown) => {
|
|
app.log.warn({ err }, "jersey model not loaded for card scan");
|
|
return null;
|
|
});
|
|
if (!first) return null;
|
|
const copies = Math.min(slots, 8);
|
|
if (copies === 1) return first;
|
|
const rest = await Promise.all(Array.from({ length: copies - 1 }, () => JerseyModel.load(dir).catch(() => null)));
|
|
const models = [first, ...rest.filter((model): model is JerseyModel => !!model)];
|
|
return models.length === 1 ? models[0]! : new JerseyPool(models);
|
|
})();
|
|
return jerseyOnce;
|
|
};
|
|
await registerLookupRoutes(app, { db, sessions, lookup, signer, jersey: jerseyOf, models: modelsDir(config.STORAGE_ROOT) });
|
|
await registerDeliveryRoutes(app, { db, sessions, secrets, delivery, storage });
|
|
// Edits are stored and fanned out here; the worker replays and renders them.
|
|
// Corrections to the autopilot's edits teach it (autopilot/learning.ts).
|
|
const corrections = new CorrectionRecorder(db, 5_000, (err) => app.log.warn({ err }, "autopilot: correction not recorded"));
|
|
app.addHook("onClose", async () => corrections.flush());
|
|
const develop = new DevelopService({
|
|
db,
|
|
storage,
|
|
signer,
|
|
broadcaster,
|
|
log: app.log,
|
|
onHumanEdit: (id) => {
|
|
corrections.schedule(id);
|
|
// A crop or tone changed after the file already went out: send the new one. Un-pick is a library flag and retracts.
|
|
void db.photo
|
|
.findUnique({ where: { id }, select: { organizationId: true } })
|
|
.then((photo) => (photo ? delivery.resendPhotos(photo.organizationId, [id]) : 0))
|
|
.catch((err) => app.log.warn({ err }, "delivery: resend after edit failed"));
|
|
},
|
|
});
|
|
await registerDevelopRoutes(app, { db, sessions, develop });
|
|
await registerAutopilotRoutes(app, { db, sessions });
|
|
await registerRealEstateRoutes(app, { db, sessions });
|
|
// Shop: the public sites read galleries and place orders; the worker renders the bought files.
|
|
const print = new PrintService({ db, storage, signer, broadcaster, log: app.log, secret: config.JWT_SECRET, secrets, stripeApiUrl: config.STRIPE_API_URL, ...(fetchImpl && { fetchImpl }) });
|
|
const notifications = new Notifications(db, (err) => app.log.warn({ err }, "notifications: not written"));
|
|
await registerNotificationRoutes(app, { sessions, notifications });
|
|
const invoicing = new InvoicingService({ db, secrets, log: app.log, fetchImpl, notifications });
|
|
await registerInvoicingRoutes(app, { db, sessions, invoicing });
|
|
const press = new PressService({ db, secret: config.JWT_SECRET });
|
|
const earnings = new EarningsService({ db, secrets, log: app.log, stripeApiUrl: config.STRIPE_API_URL, fetchImpl, notifications });
|
|
const shop = new ShopService({ db, storage, signer, secrets, log: app.log, secret: config.JWT_SECRET, stripeApiUrl: config.STRIPE_API_URL, earnings, notifications, invoicing, press, prints: { paid: (id, ref) => print.paid(id, ref), expired: (id) => print.expired(id) }, ...(fetchImpl && { fetchImpl }) });
|
|
const proofing = new ProofingService({ db, shop, signer, notifications });
|
|
await registerShopAdminRoutes(app, { db, sessions, shop, proofing, broadcaster, secrets });
|
|
await registerPublicShopRoutes(app, { shop, proofing, lookup });
|
|
await registerEarningsRoutes(app, { db, sessions, earnings, appUrl: config.APP_PUBLIC_URL });
|
|
await registerPressRoutes(app, { db, sessions, shop, press });
|
|
await registerPrintRoutes(app, { db, sessions, print });
|
|
const releases = config.DESKTOP_RELEASES_API && config.DESKTOP_RELEASES_TOKEN ? new DesktopReleases({ api: config.DESKTOP_RELEASES_API, token: config.DESKTOP_RELEASES_TOKEN }, fetchImpl ?? fetch) : undefined;
|
|
await registerDesktopRoutes(app, { releases, publicApiUrl: config.API_PUBLIC_URL });
|
|
await registerJerseyRoutes(app, { db, sessions, jersey: new JerseyService({ db, storage, secret: config.JWT_SECRET }) });
|
|
const mailer = config.SMTP_URL ? smtpMailer(config.SMTP_URL, config.MAIL_FROM) : undefined;
|
|
await registerSiteGalleryRoutes(app, {
|
|
db,
|
|
storage,
|
|
secret: config.JWT_SECRET,
|
|
publicOrigin: clientGalleryOrigin(config.API_PUBLIC_URL, config.SITE_PUBLIC_URL),
|
|
...(mailer ? { mailer } : {}),
|
|
});
|
|
|
|
// Validation-only endpoint for the edit contract; the realtime path reuses the same schema.
|
|
app.post("/v1/edits/validate", async (req) => {
|
|
EditEnvelope.parse(req.body);
|
|
return { ok: true };
|
|
});
|
|
|
|
return app;
|
|
}
|