145 lines
4.4 KiB
TypeScript
145 lines
4.4 KiB
TypeScript
import "server-only";
|
|
|
|
import { and, eq, sql } from "drizzle-orm";
|
|
|
|
import { getDb } from "@/db";
|
|
import { media } from "@/db/schema";
|
|
import { getMediaStorage, publicMediaUrl } from "@/lib/media/storage";
|
|
import {
|
|
hasValidImageSignature,
|
|
MAX_MEDIA_BYTES,
|
|
mediaUploadSchema,
|
|
safeObjectFileName,
|
|
type MediaUploadInput,
|
|
} from "@/lib/media/validation";
|
|
|
|
export async function createPendingMedia(
|
|
input: MediaUploadInput,
|
|
authorId: string,
|
|
): Promise<{ id: string; objectKey: string; uploadUrl: string; expiresIn: number }> {
|
|
const id = crypto.randomUUID();
|
|
const objectKey = `media/${id}/${safeObjectFileName(input.fileName)}`;
|
|
const expiresIn = 5 * 60;
|
|
await getDb().insert(media).values({
|
|
id,
|
|
objectKey,
|
|
fileName: input.fileName,
|
|
mimeType: input.mimeType,
|
|
byteSize: input.byteSize,
|
|
status: "pending",
|
|
createdById: authorId,
|
|
});
|
|
const uploadUrl = (await getMediaStorage()).presign(objectKey, {
|
|
method: "PUT",
|
|
expiresIn,
|
|
type: input.mimeType,
|
|
acl: "private",
|
|
});
|
|
return { id, objectKey, uploadUrl, expiresIn };
|
|
}
|
|
|
|
export async function uploadPublicMedia(
|
|
file: File,
|
|
authorId: string,
|
|
): Promise<{ id: string; url: string; fileName: string }> {
|
|
const parsed = mediaUploadSchema.parse({
|
|
fileName: file.name,
|
|
mimeType: file.type,
|
|
byteSize: file.size,
|
|
});
|
|
const bytes = new Uint8Array(await file.arrayBuffer());
|
|
if (!hasValidImageSignature(bytes.subarray(0, 16), parsed.mimeType)) {
|
|
throw new Error("ไฟล์ไม่ตรงกับชนิดรูปภาพที่ระบุ");
|
|
}
|
|
|
|
const id = crypto.randomUUID();
|
|
const objectKey = `uploads/${id}/${safeObjectFileName(parsed.fileName)}`;
|
|
const storage = await getMediaStorage();
|
|
await storage.write(objectKey, bytes, { type: parsed.mimeType, acl: "public-read" });
|
|
try {
|
|
await getDb().insert(media).values({
|
|
id,
|
|
objectKey,
|
|
fileName: parsed.fileName,
|
|
mimeType: parsed.mimeType,
|
|
byteSize: parsed.byteSize,
|
|
status: "ready",
|
|
currentReferenceCount: 0,
|
|
createdById: authorId,
|
|
});
|
|
} catch (cause) {
|
|
await storage.delete(objectKey).catch(() => undefined);
|
|
throw cause;
|
|
}
|
|
return { id, url: publicMediaUrl(objectKey), fileName: parsed.fileName };
|
|
}
|
|
|
|
export async function addCurrentMediaReference(mediaId: string): Promise<void> {
|
|
await getDb()
|
|
.update(media)
|
|
.set({ currentReferenceCount: sql`${media.currentReferenceCount} + 1` })
|
|
.where(eq(media.id, mediaId));
|
|
}
|
|
|
|
export async function completePendingMedia(mediaId: string) {
|
|
const [record] = await getDb()
|
|
.select()
|
|
.from(media)
|
|
.where(and(eq(media.id, mediaId), eq(media.status, "pending")))
|
|
.limit(1);
|
|
if (!record) return { status: "not-found" as const };
|
|
|
|
const file = (await getMediaStorage()).file(record.objectKey);
|
|
try {
|
|
const stat = await file.stat();
|
|
const prefix = await file.slice(0, 16).bytes();
|
|
const valid =
|
|
stat.size > 0 &&
|
|
stat.size <= MAX_MEDIA_BYTES &&
|
|
stat.size === record.byteSize &&
|
|
hasValidImageSignature(prefix, record.mimeType as Parameters<typeof hasValidImageSignature>[1]);
|
|
if (!valid) {
|
|
await file.delete().catch(() => undefined);
|
|
await getDb().update(media).set({ status: "failed" }).where(eq(media.id, record.id));
|
|
return { status: "invalid" as const };
|
|
}
|
|
const [updated] = await getDb()
|
|
.update(media)
|
|
.set({
|
|
status: "ready",
|
|
byteSize: stat.size,
|
|
checksum: stat.etag,
|
|
})
|
|
.where(and(eq(media.id, record.id), eq(media.status, "pending")))
|
|
.returning();
|
|
return updated
|
|
? { status: "ready" as const, media: updated }
|
|
: { status: "not-found" as const };
|
|
} catch {
|
|
return { status: "missing" as const };
|
|
}
|
|
}
|
|
|
|
export async function discardUnreferencedMedia(mediaId: string): Promise<boolean> {
|
|
const [record] = await getDb().select().from(media).where(eq(media.id, mediaId)).limit(1);
|
|
if (
|
|
!record ||
|
|
record.currentReferenceCount > 0 ||
|
|
record.revisionReferenceCount > 0
|
|
) {
|
|
return false;
|
|
}
|
|
await (await getMediaStorage()).delete(record.objectKey).catch(() => undefined);
|
|
await getDb().delete(media).where(eq(media.id, mediaId));
|
|
return true;
|
|
}
|
|
|
|
export async function getReadyMedia(mediaId: string) {
|
|
const [record] = await getDb()
|
|
.select()
|
|
.from(media)
|
|
.where(and(eq(media.id, mediaId), eq(media.status, "ready")))
|
|
.limit(1);
|
|
return record ?? null;
|
|
}
|