desktop-release / build (--target universal-apple-darwin, dmg,app, darwin-universal, macos) (push) Successful in 7m45s
ci / rust (push) Successful in 14m15s
ci / typescript (push) Successful in 17m16s
desktop-release / build (deb,appimage, linux-x86_64, ubuntu-latest) (push) Successful in 37m8s
A delivery waiting for an original never got it when Photo Mechanic had written captions into the file on the computer (its fingerprint changed, so the desktop could not find it). The desktop now sends the file it recorded for that photo to POST /v1/photos/:id/original, which takes it when it has the photo's pixel size. The "best" delivery gets an option to send again the ones the destination already has. Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_01HT6iXLYUUp9pJz5Kza9xCW
207 lines
11 KiB
TypeScript
207 lines
11 KiB
TypeScript
import multipart from "@fastify/multipart";
|
|
import { randomUUID } from "node:crypto";
|
|
import { createWriteStream } from "node:fs";
|
|
import { appendFile, mkdir, rm, stat } from "node:fs/promises";
|
|
import path from "node:path";
|
|
import { pipeline } from "node:stream/promises";
|
|
import type { FastifyInstance } from "fastify";
|
|
import sharp from "sharp";
|
|
import { z } from "zod";
|
|
import { currentUserId, requireAuth, requireMembership } from "../auth/guard.js";
|
|
import type { SessionService } from "../auth/sessions.js";
|
|
import type { Db } from "../db.js";
|
|
import { ACCEPTED_EXTENSIONS, type IngestService, type PreviewOf } from "../ingest/service.js";
|
|
import { AppError, badRequest } from "../lib/errors.js";
|
|
import type { LocalStorage, UrlSigner } from "../storage/storage.js";
|
|
import { photoInclude, toSummary } from "./serialize.js";
|
|
|
|
const OrgParams = z.object({ orgId: z.uuid() });
|
|
const UploadQuery = z.object({ eventId: z.uuid().optional() });
|
|
const PhotoParams = z.object({ photoId: z.uuid() });
|
|
export const MAX_UPLOAD_BYTES = 200 * 1024 * 1024;
|
|
|
|
/**
|
|
* Upload from the browser or the desktop app: one photo per request (the client runs several in parallel),
|
|
* through the same pipeline as FTP. The file is streamed to the storage volume first, so moving it into place
|
|
* is a rename.
|
|
*/
|
|
export async function registerUploadRoutes(
|
|
app: FastifyInstance,
|
|
deps: { db: Db; sessions: SessionService; ingest: IngestService; storage: LocalStorage; signer: UrlSigner },
|
|
) {
|
|
const { db, ingest, storage, signer } = deps;
|
|
const authenticate = requireAuth(deps.sessions);
|
|
await app.register(multipart, { limits: { fileSize: MAX_UPLOAD_BYTES, files: 1, fields: 5 } });
|
|
|
|
app.post("/v1/orgs/:orgId/uploads", { preHandler: authenticate }, async (req, reply) => {
|
|
const { orgId } = OrgParams.parse(req.params);
|
|
const { eventId } = UploadQuery.parse(req.query);
|
|
await requireMembership(db, req, orgId, "PHOTOGRAPHER");
|
|
if (eventId && !(await db.event.findFirst({ where: { id: eventId, organizationId: orgId }, select: { id: true } }))) {
|
|
throw badRequest("event_not_in_organization");
|
|
}
|
|
const part = await req.file();
|
|
if (!part) throw badRequest("file_missing");
|
|
const name = path.basename(part.filename || "upload.jpg");
|
|
if (!ACCEPTED_EXTENSIONS.has(path.extname(name).toLowerCase())) {
|
|
part.file.resume();
|
|
throw new AppError(415, "unsupported_type", "JPEG only for now");
|
|
}
|
|
const tmpDir = storage.resolve(".uploads");
|
|
await mkdir(tmpDir, { recursive: true });
|
|
const tmp = path.join(tmpDir, `${randomUUID()}.part`);
|
|
try {
|
|
await pipeline(part.file, createWriteStream(tmp));
|
|
if (part.file.truncated) throw new AppError(413, "file_too_large");
|
|
const outcome = await ingest.ingest(tmp, { organizationId: orgId, userId: currentUserId(req), source: "UPLOAD", originalName: name, eventId });
|
|
const photo = await db.photo.findUniqueOrThrow({ where: { id: outcome.photoId }, include: photoInclude });
|
|
return reply.code(outcome.status === "duplicate" ? 200 : 201).send({ status: outcome.status, photo: toSummary(photo, signer) });
|
|
} finally {
|
|
await rm(tmp, { force: true });
|
|
}
|
|
});
|
|
|
|
/**
|
|
* The desktop app sends the original of a photo that only has its preview here, when the file on that computer
|
|
* no longer has the fingerprint it had on arrival (Photo Mechanic wrote captions into it afterwards). Same photo:
|
|
* the same pixel size as declared then; the library keeps the photo's own fingerprint and metadata.
|
|
*/
|
|
app.post("/v1/photos/:photoId/original", { preHandler: authenticate }, async (req, reply) => {
|
|
const { photoId } = PhotoParams.parse(req.params);
|
|
const photo = await db.photo.findUnique({ where: { id: photoId }, select: { id: true, organizationId: true, sha256: true, storageKey: true, originalStored: true, width: true, height: true } });
|
|
if (!photo) throw new AppError(404, "photo_not_found");
|
|
await requireMembership(db, req, photo.organizationId, "PHOTOGRAPHER");
|
|
const part = await req.file();
|
|
if (!part) throw badRequest("file_missing");
|
|
if (photo.originalStored) {
|
|
part.file.resume();
|
|
return { stored: true };
|
|
}
|
|
const tmpDir = storage.resolve(".uploads");
|
|
await mkdir(tmpDir, { recursive: true });
|
|
const tmp = path.join(tmpDir, `${randomUUID()}.part`);
|
|
try {
|
|
await pipeline(part.file, createWriteStream(tmp));
|
|
if (part.file.truncated) throw new AppError(413, "file_too_large");
|
|
const meta = await sharp(tmp).metadata().catch(() => null);
|
|
const turned = (meta?.orientation ?? 1) >= 5;
|
|
const [w, h] = turned ? [meta?.height, meta?.width] : [meta?.width, meta?.height];
|
|
if (meta?.format !== "jpeg" || !photo.width || w !== photo.width || h !== photo.height) return reply.code(409).send({ error: "not_the_same_photo" });
|
|
await ingest.storeOriginal(photo, tmp, ".jpg");
|
|
return { stored: true };
|
|
} finally {
|
|
await rm(tmp, { force: true });
|
|
}
|
|
});
|
|
|
|
// ---- resumable (chunked) uploads ----------------------------------------------------------------
|
|
// Weak venue Wi-Fi and mobile data drop big uploads: the client sends 4 MB chunks, and after a failure (or a
|
|
// reload, same file) asks where the server is and carries on from there.
|
|
|
|
const partPath = (id: string) => path.join(storage.resolve(".uploads"), `${id}.resumable`);
|
|
const StartBody = z.object({
|
|
name: z.string().min(1).max(255),
|
|
size: z.number().int().positive().max(MAX_UPLOAD_BYTES),
|
|
fingerprint: z.string().min(1).max(300),
|
|
eventId: z.uuid().optional(),
|
|
/** This file is a preview made by the desktop app; the original stays there. */
|
|
original: z
|
|
.object({
|
|
sha256: z.string().regex(/^[0-9a-f]{64}$/),
|
|
size: z.number().int().positive(),
|
|
width: z.number().int().positive().max(100_000).optional(),
|
|
height: z.number().int().positive().max(100_000).optional(),
|
|
})
|
|
.optional(),
|
|
/** A full original from the desktop app's ingest (its local FTP), not a hand upload. */
|
|
desktop: z.boolean().optional(),
|
|
});
|
|
|
|
app.post("/v1/orgs/:orgId/uploads/resumable", { preHandler: authenticate }, async (req, reply) => {
|
|
const { orgId } = OrgParams.parse(req.params);
|
|
const body = StartBody.parse(req.body);
|
|
await requireMembership(db, req, orgId, "PHOTOGRAPHER");
|
|
const name = path.basename(body.name);
|
|
if (!ACCEPTED_EXTENSIONS.has(path.extname(name).toLowerCase())) throw new AppError(415, "unsupported_type", "JPEG only for now");
|
|
if (body.eventId && !(await db.event.findFirst({ where: { id: body.eventId, organizationId: orgId }, select: { id: true } }))) throw badRequest("event_not_in_organization");
|
|
const userId = currentUserId(req);
|
|
// Abandoned uploads of this user (older than two days) are cleared on the way.
|
|
for (const old of await db.pendingUpload.findMany({ where: { userId, updatedAt: { lt: new Date(Date.now() - 2 * 86_400_000) } } })) {
|
|
await rm(partPath(old.id), { force: true });
|
|
await db.pendingUpload.delete({ where: { id: old.id } }).catch(() => {});
|
|
}
|
|
const existing = await db.pendingUpload.findFirst({ where: { userId, organizationId: orgId, fingerprint: body.fingerprint, size: body.size } });
|
|
if (existing) {
|
|
const onDisk = await stat(partPath(existing.id)).then((s) => s.size, () => 0);
|
|
if (onDisk !== existing.offset) await db.pendingUpload.update({ where: { id: existing.id }, data: { offset: onDisk } });
|
|
return { id: existing.id, offset: onDisk, size: existing.size };
|
|
}
|
|
await mkdir(storage.resolve(".uploads"), { recursive: true });
|
|
// The same photo already here (sent in full or as a preview before): nothing to send.
|
|
if (body.original) {
|
|
const known = await db.photo.findUnique({ where: { organizationId_sha256: { organizationId: orgId, sha256: body.original.sha256 } }, include: photoInclude });
|
|
if (known && known.status !== "FAILED") return reply.code(200).send({ status: "duplicate", photo: toSummary(known, signer) });
|
|
}
|
|
const upload = await db.pendingUpload.create({
|
|
data: { organizationId: orgId, userId, eventId: body.eventId ?? null, fileName: name, size: body.size, fingerprint: body.fingerprint, ...(body.original && { original: body.original }), ...(body.desktop && { fromDesktop: true }) },
|
|
});
|
|
return reply.code(201).send({ id: upload.id, offset: 0, size: upload.size });
|
|
});
|
|
|
|
async function pendingOf(req: Parameters<typeof currentUserId>[0], id: string) {
|
|
const upload = await db.pendingUpload.findUnique({ where: { id } });
|
|
if (!upload || upload.userId !== currentUserId(req)) throw new AppError(404, "upload_not_found");
|
|
return upload;
|
|
}
|
|
|
|
app.get("/v1/uploads/:id", { preHandler: authenticate }, async (req) => {
|
|
const { id } = z.object({ id: z.uuid() }).parse(req.params);
|
|
const upload = await pendingOf(req, id);
|
|
return { id, offset: upload.offset, size: upload.size };
|
|
});
|
|
|
|
await app.register(async (scoped) => {
|
|
scoped.addContentTypeParser("application/offset+octet-stream", { parseAs: "buffer", bodyLimit: 9 * 1024 * 1024 }, (_req, body, done) => done(null, body));
|
|
scoped.put("/v1/uploads/:id", { preHandler: authenticate, bodyLimit: 9 * 1024 * 1024 }, async (req, reply) => {
|
|
const { id } = z.object({ id: z.uuid() }).parse(req.params);
|
|
const { offset } = z.object({ offset: z.coerce.number().int().min(0) }).parse(req.query);
|
|
const chunk = req.body as Buffer;
|
|
if (!Buffer.isBuffer(chunk) || !chunk.length) throw badRequest("empty_chunk");
|
|
await pendingOf(req, id);
|
|
// One writer at a time per upload; only the next bytes are accepted, so a chunk sent twice (its answer
|
|
// was lost) is answered with the real offset instead of being appended again.
|
|
const step = await db.$transaction(async (tx) => {
|
|
await tx.$executeRaw`SELECT pg_advisory_xact_lock(hashtext(${`upload:${id}`}))`;
|
|
const upload = await tx.pendingUpload.findUniqueOrThrow({ where: { id } });
|
|
if (offset !== upload.offset) return { mismatch: upload.offset, upload };
|
|
if (offset + chunk.length > upload.size) throw badRequest("beyond_size");
|
|
await appendFile(partPath(id), chunk);
|
|
await tx.pendingUpload.update({ where: { id }, data: { offset: offset + chunk.length } });
|
|
return { next: offset + chunk.length, upload };
|
|
}, { timeout: 30_000 });
|
|
if (step.mismatch !== undefined) return reply.code(409).send({ error: "offset_mismatch", offset: step.mismatch });
|
|
const { upload } = step;
|
|
const next = step.next!;
|
|
if (next < upload.size) return { offset: next };
|
|
// Clean up before answering: the client may start the next file as soon as it hears back.
|
|
let done: { code: number; body: unknown };
|
|
try {
|
|
const outcome = await ingest.ingest(partPath(id), {
|
|
organizationId: upload.organizationId,
|
|
userId: upload.userId,
|
|
source: upload.original || upload.fromDesktop ? "DESKTOP" : "UPLOAD",
|
|
originalName: upload.fileName,
|
|
eventId: upload.eventId ?? undefined,
|
|
original: (upload.original as PreviewOf | null) ?? undefined,
|
|
});
|
|
const photo = await db.photo.findUniqueOrThrow({ where: { id: outcome.photoId }, include: photoInclude });
|
|
done = { code: outcome.status === "duplicate" ? 200 : 201, body: { offset: next, status: outcome.status, photo: toSummary(photo, signer) } };
|
|
} finally {
|
|
await rm(partPath(id), { force: true });
|
|
await db.pendingUpload.delete({ where: { id } }).catch(() => {});
|
|
}
|
|
return reply.code(done.code).send(done.body);
|
|
});
|
|
});
|
|
}
|