A drop was refused with event_not_in_organization, so most of the files never appeared. The photo is filed by its capture time instead. The desktop reads every file in the drop, not only the few the page list kept.
308 lines
16 KiB
TypeScript
308 lines
16 KiB
TypeScript
import multipart from "@fastify/multipart";
|
|
import { randomUUID } from "node:crypto";
|
|
import { createWriteStream } from "node:fs";
|
|
import { appendFile, mkdir, open, 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 { ROLE_RANK, 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(),
|
|
silent: z.string().optional(),
|
|
inbox: z.string().optional(),
|
|
/** Attribute the photo to this org member (INGESTER+; local FTP second photographer). */
|
|
uploaderUserId: z.uuid().optional(),
|
|
});
|
|
const LinearQuery = z.object({
|
|
capturedAt: z.string().optional(),
|
|
width: z.coerce.number().int().positive().max(100_000),
|
|
height: z.coerce.number().int().positive().max(100_000),
|
|
});
|
|
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 query = UploadQuery.parse(req.query);
|
|
// A computer can still name an event that was removed or belongs to somewhere else. Refusing the file
|
|
// drops the photo. Ingest keeps the event only when it is this organization's, and otherwise uses the clock.
|
|
const eventId = query.eventId;
|
|
const membership = await requireMembership(db, req, orgId, "PHOTOGRAPHER");
|
|
let uploaderId = currentUserId(req);
|
|
if (query.uploaderUserId && query.uploaderUserId !== uploaderId) {
|
|
if (ROLE_RANK[membership.role] < ROLE_RANK.INGESTER) throw badRequest("uploader_forbidden");
|
|
const other = await db.membership.findUnique({
|
|
where: { userId_organizationId: { userId: query.uploaderUserId, organizationId: orgId } },
|
|
select: { userId: true },
|
|
});
|
|
if (!other) throw badRequest("uploader_not_in_organization");
|
|
uploaderId = other.userId;
|
|
}
|
|
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: uploaderId,
|
|
source: "UPLOAD",
|
|
originalName: name,
|
|
eventId,
|
|
...(query.inbox === "1" && { inbox: true }),
|
|
...(query.silent === "1" && { held: true }),
|
|
});
|
|
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 linear DNG of a merge, replacing the JPEG preview uploaded just before (held, not announced).
|
|
* One announcement goes out, for the DNG, so the collection shows it once.
|
|
*/
|
|
app.post("/v1/photos/:photoId/linear-dng", { preHandler: authenticate }, async (req) => {
|
|
const { photoId } = PhotoParams.parse(req.params);
|
|
const query = LinearQuery.parse(req.query);
|
|
const capturedAt = query.capturedAt ? new Date(query.capturedAt) : null;
|
|
if (query.capturedAt && (capturedAt === null || Number.isNaN(capturedAt.getTime()))) throw badRequest("bad_date");
|
|
const photo = await db.photo.findUnique({
|
|
where: { id: photoId },
|
|
select: { id: true, organizationId: true, sha256: true, storageKey: true, originalName: 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");
|
|
const tmpDir = storage.resolve(".uploads");
|
|
await mkdir(tmpDir, { recursive: true });
|
|
const tmp = path.join(tmpDir, `${randomUUID()}.part`);
|
|
let stored = false;
|
|
try {
|
|
await pipeline(part.file, createWriteStream(tmp));
|
|
if (part.file.truncated) throw new AppError(413, "file_too_large");
|
|
if (!(await isTiff(tmp))) throw badRequest("not_a_dng");
|
|
const outcome = await ingest.attachLinearDng(photo, tmp, { width: query.width, height: query.height, capturedAt });
|
|
stored = true;
|
|
const full = await db.photo.findUniqueOrThrow({ where: { id: outcome.photoId }, include: photoInclude });
|
|
return { status: outcome.status, photo: toSummary(full, signer) };
|
|
} catch (err) {
|
|
if (!stored) await ingest.discardHeld(photo.id).catch(() => {});
|
|
await rm(tmp, { force: true });
|
|
throw err;
|
|
}
|
|
});
|
|
|
|
/**
|
|
* 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(),
|
|
/** Attribute the photo to this org member (INGESTER+; local FTP second photographer). */
|
|
uploaderUserId: z.uuid().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);
|
|
const membership = 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");
|
|
const userId = currentUserId(req);
|
|
let uploaderUserId: string | null = null;
|
|
if (body.uploaderUserId && body.uploaderUserId !== userId) {
|
|
if (ROLE_RANK[membership.role] < ROLE_RANK.INGESTER) throw badRequest("uploader_forbidden");
|
|
const other = await db.membership.findUnique({
|
|
where: { userId_organizationId: { userId: body.uploaderUserId, organizationId: orgId } },
|
|
select: { userId: true },
|
|
});
|
|
if (!other) throw badRequest("uploader_not_in_organization");
|
|
uploaderUserId = other.userId;
|
|
}
|
|
// 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 }),
|
|
...(uploaderUserId && { uploaderUserId }),
|
|
},
|
|
});
|
|
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.uploaderUserId ?? 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);
|
|
});
|
|
});
|
|
}
|
|
|
|
/** LightCraft's linear DNG is a TIFF. A mosaic raw is not accepted through this door. */
|
|
async function isTiff(file: string): Promise<boolean> {
|
|
const handle = await open(file, "r");
|
|
try {
|
|
const buf = Buffer.alloc(4);
|
|
const { bytesRead } = await handle.read(buf, 0, 4, 0);
|
|
if (bytesRead < 4) return false;
|
|
const little = buf[0] === 0x49 && buf[1] === 0x49 && buf[2] === 0x2a && buf[3] === 0x00;
|
|
const big = buf[0] === 0x4d && buf[1] === 0x4d && buf[2] === 0x00 && buf[3] === 0x2a;
|
|
return little || big;
|
|
} finally {
|
|
await handle.close();
|
|
}
|
|
}
|