Store document image uploads in SQLite
This commit is contained in:
@@ -20,7 +20,8 @@
|
||||
"react": "19.3.1",
|
||||
"react-dom": "19.3.1",
|
||||
"react-markdown": "10.1.0",
|
||||
"remark-gfm": "4.0.1"
|
||||
"remark-gfm": "4.0.1",
|
||||
"sharp": "0.35.5"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@tailwindcss/postcss": "4.3.3",
|
||||
@@ -33,7 +34,6 @@
|
||||
"eslint": "^9.39.5",
|
||||
"eslint-config-next": "16.4.3",
|
||||
"postcss": "8.5.31",
|
||||
"sharp": "0.35.5",
|
||||
"tailwindcss": "4.3.3",
|
||||
"typescript": "~5.9.3"
|
||||
}
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
import { createHash } from "node:crypto";
|
||||
import { openSiteDatabase } from "./site-database";
|
||||
|
||||
function openImages() {
|
||||
const db = openSiteDatabase();
|
||||
try {
|
||||
db.exec(`CREATE TABLE IF NOT EXISTS document_images (
|
||||
id TEXT PRIMARY KEY,
|
||||
bytes BLOB NOT NULL
|
||||
)`);
|
||||
return db;
|
||||
} catch (error) {
|
||||
db.close();
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
export function saveDocumentImage(bytes: Buffer) {
|
||||
const id = createHash("sha256").update(bytes).digest("hex");
|
||||
const db = openImages();
|
||||
try {
|
||||
db.prepare("INSERT INTO document_images (id, bytes) VALUES (?, ?) ON CONFLICT(id) DO NOTHING").run(id, bytes);
|
||||
return id;
|
||||
} finally {
|
||||
db.close();
|
||||
}
|
||||
}
|
||||
|
||||
export function readDocumentImage(id: string) {
|
||||
const db = openImages();
|
||||
try {
|
||||
const row = db.prepare("SELECT bytes FROM document_images WHERE id = ?").get(id) as
|
||||
| { bytes: Uint8Array }
|
||||
| undefined;
|
||||
return row ? Buffer.from(row.bytes) : undefined;
|
||||
} finally {
|
||||
db.close();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
import type { NextApiRequest, NextApiResponse } from "next";
|
||||
import { documentApiError } from "@/lib/documents-api";
|
||||
import { readDocumentImage } from "@/lib/document-images";
|
||||
|
||||
// The site proxy accepts a logged-in reader or a document API key on this route.
|
||||
export default function handler(request: NextApiRequest, response: NextApiResponse) {
|
||||
try {
|
||||
response.setHeader("Cache-Control", "private, no-store");
|
||||
response.setHeader("X-Content-Type-Options", "nosniff");
|
||||
if (request.method !== "GET" && request.method !== "HEAD") {
|
||||
response.setHeader("Allow", "GET, HEAD");
|
||||
return response.status(405).end();
|
||||
}
|
||||
const id = request.query.id;
|
||||
if (typeof id !== "string" || !/^[a-f0-9]{64}$/.test(id)) return response.status(404).end();
|
||||
const bytes = readDocumentImage(id);
|
||||
if (!bytes) return response.status(404).end();
|
||||
response.setHeader("Content-Type", "image/webp");
|
||||
response.setHeader("Content-Length", bytes.length);
|
||||
return request.method === "HEAD" ? response.status(200).end() : response.status(200).send(bytes);
|
||||
} catch (error) {
|
||||
return documentApiError(response, error);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
import type { NextApiRequest, NextApiResponse } from "next";
|
||||
import sharp from "sharp";
|
||||
import { authorizeDocuments, documentApiError } from "@/lib/documents-api";
|
||||
import { saveDocumentImage } from "@/lib/document-images";
|
||||
|
||||
const maxUploadBytes = 8 * 1024 * 1024;
|
||||
const maxStoredBytes = 2 * 1024 * 1024;
|
||||
const imageTypes = new Set(["image/png", "image/jpeg", "image/webp"]);
|
||||
const imageFormats = new Set(["png", "jpeg", "webp"]);
|
||||
|
||||
export const config = { api: { bodyParser: false } };
|
||||
|
||||
export default async function handler(request: NextApiRequest, response: NextApiResponse) {
|
||||
try {
|
||||
if (request.method !== "POST") {
|
||||
response.setHeader("Allow", "POST");
|
||||
return response.status(405).end();
|
||||
}
|
||||
if (!authorizeDocuments(request, response, true)) return;
|
||||
|
||||
const type = request.headers["content-type"]?.split(";")[0].trim().toLowerCase();
|
||||
if (!type || !imageTypes.has(type)) {
|
||||
return response.status(415).json({ error: "请上传 PNG、JPEG 或 WebP 图片" });
|
||||
}
|
||||
if (Number(request.headers["content-length"]) > maxUploadBytes) {
|
||||
return response.status(413).json({ error: "图片上传上限为 8 MiB" });
|
||||
}
|
||||
|
||||
const chunks: Buffer[] = [];
|
||||
let length = 0;
|
||||
for await (const chunk of request.iterator({ destroyOnReturn: false })) {
|
||||
const bytes = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
|
||||
length += bytes.length;
|
||||
if (length > maxUploadBytes) {
|
||||
return response.status(413).json({ error: "图片上传上限为 8 MiB" });
|
||||
}
|
||||
chunks.push(bytes);
|
||||
}
|
||||
|
||||
let encoded: Buffer;
|
||||
try {
|
||||
const input = sharp(Buffer.concat(chunks), { limitInputPixels: 25_000_000 });
|
||||
const { format, pages } = await input.metadata();
|
||||
if (!format || !imageFormats.has(format) || type !== `image/${format}` || (pages ?? 1) > 1) {
|
||||
return response.status(415).json({ error: "图片格式需与声明一致,且只支持静态图片" });
|
||||
}
|
||||
encoded = await input.rotate()
|
||||
.resize({ width: 2000, height: 4000, fit: "inside", withoutEnlargement: true })
|
||||
.webp({ quality: 85 })
|
||||
.toBuffer();
|
||||
} catch {
|
||||
return response.status(400).json({ error: "无法解码图片,或像素数量超过限制" });
|
||||
}
|
||||
if (encoded.length > maxStoredBytes) {
|
||||
return response.status(413).json({ error: "处理后的图片超过 2 MiB,请缩小后重试" });
|
||||
}
|
||||
|
||||
const id = saveDocumentImage(encoded);
|
||||
const url = `/api/documents/images/${id}`;
|
||||
return response.status(200).json({ id, url, contentType: "image/webp", size: encoded.length });
|
||||
} catch (error) {
|
||||
return documentApiError(response, error);
|
||||
}
|
||||
}
|
||||
@@ -23,6 +23,10 @@ import { collectionEntries, collectionLabel } from "@/lib/collections";
|
||||
import { Icon } from "@/components/Icon";
|
||||
import { headingsFor } from "@/lib/navigation";
|
||||
|
||||
function isZoomableFigure(source: string) {
|
||||
return source.startsWith("/figures/endor-") || /^\/api\/documents\/images\/[a-f0-9]{64}$/.test(source);
|
||||
}
|
||||
|
||||
type Props = { doc: Doc; docs: DocLink[] };
|
||||
const AICompanyResearch = dynamic(() => import("@/components/AICompanyResearch"));
|
||||
export const getServerSideProps: GetServerSideProps<Props> = async ({ params, res, resolvedUrl }) => {
|
||||
@@ -120,14 +124,14 @@ export default function DocPage({
|
||||
const slides = node?.children.flatMap((child) =>
|
||||
child.type === "element" && child.tagName === "img" &&
|
||||
typeof child.properties.src === "string" &&
|
||||
child.properties.src.startsWith("/figures/endor-")
|
||||
isZoomableFigure(child.properties.src)
|
||||
? [{ source: child.properties.src, alt: String(child.properties.alt ?? "") }]
|
||||
: [],
|
||||
) ?? [];
|
||||
const onlyImages = node?.children.every((child) =>
|
||||
(child.type === "element" && child.tagName === "img" &&
|
||||
typeof child.properties.src === "string" &&
|
||||
child.properties.src.startsWith("/figures/endor-")) ||
|
||||
isZoomableFigure(child.properties.src)) ||
|
||||
(child.type === "text" && child.value.trim() === ""),
|
||||
);
|
||||
if (slides.length > 1 && onlyImages) return <FigureGallery slides={slides} />;
|
||||
@@ -141,7 +145,7 @@ export default function DocPage({
|
||||
);
|
||||
},
|
||||
img: ({ src, alt }) =>
|
||||
typeof src === "string" && src.startsWith("/figures/endor-") ? (
|
||||
typeof src === "string" && isZoomableFigure(src) ? (
|
||||
<ArchitectureFigure source={src} alt={alt ?? "Endor 架构图"} />
|
||||
) : (
|
||||
// eslint-disable-next-line @next/next/no-img-element
|
||||
|
||||
Reference in New Issue
Block a user