1import type { Database } from "bun:sqlite";234export const FILES_PER_POST = 4;5export const FILE_BYTES_PER_HOUR = 64 * 1024 * 1024;678export const ATTACHMENT_BYTES_PER_DAY = 200 * 1024 * 1024;9const IMAGE_BYTES = 8 * 1024 * 1024;10const LOG_BYTES = 2 * 1024 * 1024;1112const PREVIEW_BYTES = 16 * 1024;131415let day = -1;16let bytesToday = 0;1718function rollDay(at: number): void {19 const today = Math.floor(at / 86_400);20 if (today === day) return;21 day = today;22 bytesToday = 0;23}242526export function attachmentBytesToday(at: number): number {27 rollDay(at);28 return bytesToday;29}303132const IMAGES: [type: string, ext: string, magic: (head: string) => boolean][] = [33 ["image/png", "png", (head) => head.startsWith("\x89PNG\r\n\x1a\n")],34 ["image/jpeg", "jpg", (head) => head.startsWith("\xff\xd8\xff")],35 ["image/gif", "gif", (head) => head.startsWith("GIF87a") || head.startsWith("GIF89a")],36 ["image/webp", "webp", (head) => head.startsWith("RIFF") && head.slice(8, 12) === "WEBP"],37];38export const FILE_EXTENSIONS: Record<string, string> = {39 ...Object.fromEntries(IMAGES.map(([type, ext]) => [type, ext])),40 "text/plain": "txt",41};4243export type Upload = { name: string; type: string; data: Uint8Array };44type StoredFile = { name: string; type: string; data: Uint8Array<ArrayBuffer> };4546export type Attachment = {47 id: number;48 entry_id: number | null;49 name: string;50 type: string;51 size: number;52 53 head: Uint8Array | null;54};555657export async function readUploads(files: File[]): Promise<Upload[] | string> {58 if (files.length > FILES_PER_POST) return `Attach at most ${FILES_PER_POST} files.`;59 const uploads: Upload[] = [];60 for (const file of files) {61 const data = new Uint8Array(await file.arrayBuffer());62 63 const name = (file.name.split(/[\\/]/).pop() ?? "").replace(/\p{Cc}/gu, "").slice(0, 100);64 const head = Buffer.from(data.subarray(0, 12)).toString("latin1");65 const image = IMAGES.find(([, , magic]) => magic(head));66 if (image) {67 if (data.length > IMAGE_BYTES) return `${name} is over 8 MB.`;68 69 70 const stem = name.replace(/\.\w+$/, "");71 uploads.push({ name: `${stem || "screenshot"}.${image[1]}`, type: image[0], data });72 continue;73 }74 if (!/\.(txt|log)$/i.test(name)) {75 return `${name || "A file"} isn't a PNG, JPEG, GIF or WebP picture, or a .txt or .log file.`;76 }77 if (data.length > LOG_BYTES) return `${name} is over 2 MB.`;78 try {79 new TextDecoder("utf-8", { fatal: true }).decode(data);80 } catch {81 return `${name} isn't UTF-8 text.`;82 }83 uploads.push({ name, type: "text/plain", data });84 }85 return uploads;86}878889export function fileBytesSince(db: Database, ipHash: string, since: number): number {90 const row = db91 .query<{ n: number | null }, [string, number]>(92 "SELECT SUM(size) AS n FROM issue_files WHERE ip_hash = ? AND created_at > ?",93 )94 .get(ipHash, since);95 return row?.n ?? 0;96}979899export function attachFiles(100 db: Database,101 issueId: number,102 entryId: number | null,103 uploads: Upload[],104 ipHash: string,105 at: number,106): void {107 const insert = db.query(108 `INSERT INTO issue_files (issue_id, entry_id, name, type, size, data, ip_hash, created_at)109VALUES (?, ?, ?, ?, ?, ?, ?, ?)`,110 );111 112 113 rollDay(at);114 bytesToday += uploads.reduce((sum, upload) => sum + upload.data.length, 0);115 db.transaction(() => {116 for (const upload of uploads) {117 insert.run(118 issueId,119 entryId,120 upload.name,121 upload.type,122 upload.data.length,123 upload.data,124 ipHash,125 at,126 );127 }128 })();129}130131132export function issueAttachments(db: Database, issueId: number): Attachment[] {133 return db134 .query<Attachment, [number, number]>(135 `SELECT id, entry_id, name, type, size,136 CASE WHEN type = 'text/plain' THEN substr(data, 1, ?) END AS head137FROM issue_files138WHERE issue_id = ?139ORDER BY id`,140 )141 .all(PREVIEW_BYTES, issueId);142}143144145export function visibleFile(146 db: Database,147 repo: string,148 number: number,149 id: number,150): StoredFile | null {151 return db152 .query<StoredFile, [string, number, number]>(153 `SELECT f.name, f.type, f.data154FROM issue_files f155JOIN issues i ON i.id = f.issue_id156LEFT JOIN issue_entries e ON e.id = f.entry_id157WHERE i.repo = ? AND i.number = ? AND f.id = ? AND i.hidden = 0158 AND (f.entry_id IS NULL OR e.hidden = 0)`,159 )160 .get(repo, number, id);161}