feat: add WebP migration UI and API endpoint

- Add /api/admin/migrate-images endpoint to convert JPEG/PNG to WebP
- Add WebPMigration component in admin gallery showing stats
- Upload endpoint already converts new images to WebP
- Migration saves ~30-50% storage space per image
This commit is contained in:
2026-07-01 21:47:16 -05:00
parent d0be23551a
commit ee68dc2897
6 changed files with 916 additions and 0 deletions
+504
View File
@@ -27,6 +27,7 @@
"@types/react-dom": "^18.3.6",
"@vitejs/plugin-react": "^6.0.3",
"jsdom": "^29.1.1",
"tsx": "^4.22.4",
"typescript": "^5.4.5",
"vitest": "^4.1.9"
}
@@ -318,6 +319,448 @@
"tslib": "^2.4.0"
}
},
"node_modules/@esbuild/aix-ppc64": {
"version": "0.28.1",
"resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.28.1.tgz",
"integrity": "sha512-Svl7tq8k/08+p6CXPpRjQ1fKX+1odH/BQbb48fV6fj3CWHhsoIOoY87w1oHXm0qEpkIK3ZfVgp0hed3XBXzXMQ==",
"cpu": [
"ppc64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"aix"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/android-arm": {
"version": "0.28.1",
"resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.28.1.tgz",
"integrity": "sha512-0k2F129Xdio1TdJfzJ8sy1Q47vUD2NnwdhiAf7drUN1EBTfPf4hsFCtmMgu/6m8JSzsBrlmVjudMBQqOfG8usQ==",
"cpu": [
"arm"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"android"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/android-arm64": {
"version": "0.28.1",
"resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.28.1.tgz",
"integrity": "sha512-34EGEbCIAgosYz6goLcopX6Mo7NyGv9tfwEM2/7Ce2VcVRk568iSvniGWcUXIy7wEDR1wzolcxcriFVrWYcwBg==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"android"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/android-x64": {
"version": "0.28.1",
"resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.28.1.tgz",
"integrity": "sha512-dbwY7ltSMDWsRatcRpCnES4F+im88OCUgGZjy52shC7GqHRE/cYlxNbB4Z4UpJswpcc4Qxd2oE/ufM0p61IKng==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"android"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/darwin-arm64": {
"version": "0.28.1",
"resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.28.1.tgz",
"integrity": "sha512-TZbWkQY7kvTAXbXUT7uVACR5cMHsDiSz9z7ZKAX/RTq/WJEk3QyRr0wZpNhBDX+/0CtdqUIJlOiodQcta6tY3Q==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"darwin"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/darwin-x64": {
"version": "0.28.1",
"resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.28.1.tgz",
"integrity": "sha512-zfdzgK9ACBNZLI/CyHTOx81SyNbM6YXn7rxSgX97VjyiPl9W1i4Ka4fgKECEoFCKGpvBj5qArWIGgQjOwkgskQ==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"darwin"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/freebsd-arm64": {
"version": "0.28.1",
"resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.28.1.tgz",
"integrity": "sha512-wG2EA8ENdEI0qhkSZMjfqrdY+ziCYCPMmtZjjIwOmXFjmyzEHn+UUxk5of+SYsjtfs3VpnlC7QLzSI5hY/rOAw==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"freebsd"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/freebsd-x64": {
"version": "0.28.1",
"resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.28.1.tgz",
"integrity": "sha512-i7dZ9vQgnvSCzi/rYCXNgtF/U+eKZNJBzu3eTQbRgHnM7tNSizLOkRFAl3qzVc/Op/u5YkHHa4pf/3DOYHthLQ==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"freebsd"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/linux-arm": {
"version": "0.28.1",
"resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.28.1.tgz",
"integrity": "sha512-qVXBOHQS+d5Y722GwJzJUtOLlX7km3CraOaGormF1pDtPd2C/l1SHRPgjLunLGe51Sh5YYWKMFDyV4SxgMQYTQ==",
"cpu": [
"arm"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/linux-arm64": {
"version": "0.28.1",
"resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.28.1.tgz",
"integrity": "sha512-yHs+0uc8+nvEAfAfxrWQKK5peSNzBc4PegcMO0EJ2hT71uA7vB8Ihg2e77R2P7SG5uYjPbHlLLmve4LLLRCf0g==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/linux-ia32": {
"version": "0.28.1",
"resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.28.1.tgz",
"integrity": "sha512-d1z4ZuP0ajrfz/FhGT4vv278rX8KnPPJx8i5+AtK7TYbx9Le9F1hyzurZpkEyjkGa9dUGhQow4C1NmeGvqxN2w==",
"cpu": [
"ia32"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/linux-loong64": {
"version": "0.28.1",
"resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.28.1.tgz",
"integrity": "sha512-M5sRjUVZrkm1OAPR3dlOYzNmN+loZKGVi1VUQGrwuqLcbR6qeAz+famMhjASeH3YVKvZz+zT1jlh/keC3Rj/lg==",
"cpu": [
"loong64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/linux-mips64el": {
"version": "0.28.1",
"resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.28.1.tgz",
"integrity": "sha512-mRObBZeHh2OxcBFPWE/FjylkRgZdYuiTR3vaTozquCGOH14iP9oN4x4Ge81CoIDYQrXmIxpFumJBu5MtZpnQJQ==",
"cpu": [
"mips64el"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/linux-ppc64": {
"version": "0.28.1",
"resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.28.1.tgz",
"integrity": "sha512-slScBsMAb3GFDcdrCgLwZtPYRoH2H/youv10QiZyRjmsP48fznoveWytSgCI/R0ZcUgpc0ZhIUEx6LHts8yrfQ==",
"cpu": [
"ppc64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/linux-riscv64": {
"version": "0.28.1",
"resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.28.1.tgz",
"integrity": "sha512-kw0owk1o0GFETUJyW0jc0G4Yzs0BHZn0JDZ8JRT088vjJYX777BAs1fDGxAC+q831qOs2DTC96mNsG2opdfyyQ==",
"cpu": [
"riscv64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/linux-s390x": {
"version": "0.28.1",
"resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.28.1.tgz",
"integrity": "sha512-/lAIjX8aYFRByhh6L5rYtPEDRqa9de/4V/juOXcta5frjvzXO4/sqEtyytse0g3zZFuWu5cDN0MkLz2qRDD2Ag==",
"cpu": [
"s390x"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/linux-x64": {
"version": "0.28.1",
"resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.28.1.tgz",
"integrity": "sha512-u/anNYF2mmVOEDwLtnQ1wOr3EZ9sTNGLWrsYGYwHWzGA3Si84IOkHXlbWTD1NB+9/1lcnweYKO54uhxZydNzfA==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/netbsd-arm64": {
"version": "0.28.1",
"resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.28.1.tgz",
"integrity": "sha512-oks0DYbLwWMmaakTsCb+zL4E+aHRVLom9IJZOAthMQEPiQmydXHkziYEsGYRx0uNV/IjEKGAV941JzH02pflqw==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"netbsd"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/netbsd-x64": {
"version": "0.28.1",
"resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.28.1.tgz",
"integrity": "sha512-aeL6lAnN89Hz43Mlh1G8ARasbuoYvSITDEx0tHh5b7jJnHcssqgjy9Yx430GDpmCa6OyrKoS0aNRjKundRizGg==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"netbsd"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/openbsd-arm64": {
"version": "0.28.1",
"resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.28.1.tgz",
"integrity": "sha512-MEFJe5C3R8pwXdZ5Y21oo6m7ePiS0d9pWucn99O/wvyJZChoIQKrQDxKrGeW8F5+T0okTHesAmDeiHDTIq0V/Q==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"openbsd"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/openbsd-x64": {
"version": "0.28.1",
"resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.28.1.tgz",
"integrity": "sha512-i/ZLIOafE0Z8cI/XANJAixoJL/uRAoS2xOA3rb0xN+KK0K177cMAsQYkzHtBrtMXAKuAc7HGgcWiZ/sRC1Nxgw==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"openbsd"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/openharmony-arm64": {
"version": "0.28.1",
"resolved": "https://registry.npmjs.org/@esbuild/openharmony-arm64/-/openharmony-arm64-0.28.1.tgz",
"integrity": "sha512-ge+Z7EXFNt2BO1oAMsVpiQ8EwndV9i1xXerAeTIK7AtPs3bKFXQM7nlRxDSIUIMeueR1CNXxqztLzdNeReKBJg==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"openharmony"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/sunos-x64": {
"version": "0.28.1",
"resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.28.1.tgz",
"integrity": "sha512-BEjgtECkL3vY+SaSQ6nzVfiALUeFxpawyp8Jmf5PtYhf1Ug40N1h/hxlhts+f1FvSvarEigdxS3BlSMI2PJLcQ==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"sunos"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/win32-arm64": {
"version": "0.28.1",
"resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.28.1.tgz",
"integrity": "sha512-lCv9eK/H6ZJWbE7bh2nw54CZ9M2nupBxJcTsdk/QQnWkdSjKGuxmmH8/GWrlT1eMmZfn4dGcCjRte397WqfQXA==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"win32"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/win32-ia32": {
"version": "0.28.1",
"resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.28.1.tgz",
"integrity": "sha512-zvb/mB2bSCoJOpoCBgYKKpX6YM6mJBlBUVUtVj41DlZJVEB6/0CKlRYxP5wWl1C1ILiCoAU5wZZ4q1P3qeS6Eg==",
"cpu": [
"ia32"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"win32"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/win32-x64": {
"version": "0.28.1",
"resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.28.1.tgz",
"integrity": "sha512-bm4Mowrv+GXMlpWX++EcXw/iLyd1o3+bJkC2DkWXYVvgZCqD/bSj9ctZeAMC3cIxgjRVR2Dufaiu4YPxr5gW1A==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"win32"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@exodus/bytes": {
"version": "1.15.1",
"resolved": "https://registry.npmjs.org/@exodus/bytes/-/bytes-1.15.1.tgz",
@@ -1914,6 +2357,48 @@
"dev": true,
"license": "MIT"
},
"node_modules/esbuild": {
"version": "0.28.1",
"resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.28.1.tgz",
"integrity": "sha512-HrJrvZv5ayxBzPfwphOoNzkzOIIlifzk0KJrGK2c8R4+LKpMtpYLQeUdjnwjWv/LZlkH2laZk+4w78pi99D4Vw==",
"dev": true,
"hasInstallScript": true,
"license": "MIT",
"bin": {
"esbuild": "bin/esbuild"
},
"engines": {
"node": ">=18"
},
"optionalDependencies": {
"@esbuild/aix-ppc64": "0.28.1",
"@esbuild/android-arm": "0.28.1",
"@esbuild/android-arm64": "0.28.1",
"@esbuild/android-x64": "0.28.1",
"@esbuild/darwin-arm64": "0.28.1",
"@esbuild/darwin-x64": "0.28.1",
"@esbuild/freebsd-arm64": "0.28.1",
"@esbuild/freebsd-x64": "0.28.1",
"@esbuild/linux-arm": "0.28.1",
"@esbuild/linux-arm64": "0.28.1",
"@esbuild/linux-ia32": "0.28.1",
"@esbuild/linux-loong64": "0.28.1",
"@esbuild/linux-mips64el": "0.28.1",
"@esbuild/linux-ppc64": "0.28.1",
"@esbuild/linux-riscv64": "0.28.1",
"@esbuild/linux-s390x": "0.28.1",
"@esbuild/linux-x64": "0.28.1",
"@esbuild/netbsd-arm64": "0.28.1",
"@esbuild/netbsd-x64": "0.28.1",
"@esbuild/openbsd-arm64": "0.28.1",
"@esbuild/openbsd-x64": "0.28.1",
"@esbuild/openharmony-arm64": "0.28.1",
"@esbuild/sunos-x64": "0.28.1",
"@esbuild/win32-arm64": "0.28.1",
"@esbuild/win32-ia32": "0.28.1",
"@esbuild/win32-x64": "0.28.1"
}
},
"node_modules/estree-walker": {
"version": "3.0.3",
"resolved": "https://registry.npmjs.org/estree-walker/-/estree-walker-3.0.3.tgz",
@@ -3051,6 +3536,25 @@
"integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==",
"license": "0BSD"
},
"node_modules/tsx": {
"version": "4.22.4",
"resolved": "https://registry.npmjs.org/tsx/-/tsx-4.22.4.tgz",
"integrity": "sha512-X8EX+XV4QR5xCsrgxaED954zTDfY8KqlDtskKEL0cHhyS/P8b4IFOvGDQpsC9Q1XnLq915wEfwwY/zzskCtmhg==",
"dev": true,
"license": "MIT",
"dependencies": {
"esbuild": "~0.28.0"
},
"bin": {
"tsx": "dist/cli.mjs"
},
"engines": {
"node": ">=18.0.0"
},
"optionalDependencies": {
"fsevents": "~2.3.3"
}
},
"node_modules/typescript": {
"version": "5.9.3",
"resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz",
+1
View File
@@ -29,6 +29,7 @@
"@types/react-dom": "^18.3.6",
"@vitejs/plugin-react": "^6.0.3",
"jsdom": "^29.1.1",
"tsx": "^4.22.4",
"typescript": "^5.4.5",
"vitest": "^4.1.9"
}
+113
View File
@@ -0,0 +1,113 @@
/**
* Migration script to convert existing JPEG/PNG images to WebP
* Run with: npx ts-node scripts/migrate-images-to-webp.ts
*/
import { Pool } from 'pg';
import sharp from 'sharp';
const pool = new Pool({
connectionString: process.env.DATABASE_URL,
});
async function convertToWebP(base64Data: string): Promise<string> {
const matches = base64Data.match(/^data:image\/(\w+);base64,(.+)$/);
if (!matches) {
console.log(' - Already WebP or invalid format, skipping');
return base64Data;
}
const ext = matches[2] ? matches[1] : 'unknown';
const buffer = Buffer.from(matches[2], 'base64');
// Convert to WebP
const webpBuffer = await sharp(buffer)
.webp({ quality: 90 })
.toBuffer();
return `data:image/webp;base64,${webpBuffer.toString('base64')}`;
}
async function main() {
console.log('Starting image migration to WebP...\n');
const client = await pool.connect();
try {
// Get all images
const { rows: images } = await client.query(
'SELECT id, filename, data, thumbnail, medium FROM images'
);
console.log(`Found ${images.length} images to process\n`);
let converted = 0;
let skipped = 0;
let errors = 0;
for (const img of images) {
console.log(`Processing image ${img.id}: ${img.filename}`);
try {
let needsUpdate = false;
const updates: { data?: string; thumbnail?: string; medium?: string } = {};
// Check if already WebP
if (img.data && !img.data.includes('image/webp')) {
console.log(' - Converting full image...');
updates.data = await convertToWebP(img.data);
needsUpdate = true;
}
if (img.thumbnail && !img.thumbnail.includes('image/webp')) {
console.log(' - Converting thumbnail...');
updates.thumbnail = await convertToWebP(img.thumbnail);
needsUpdate = true;
}
if (img.medium && !img.medium.includes('image/webp')) {
console.log(' - Converting medium...');
updates.medium = await convertToWebP(img.medium);
needsUpdate = true;
}
if (needsUpdate) {
// Calculate size savings
const oldSize = (img.data?.length || 0) + (img.thumbnail?.length || 0) + (img.medium?.length || 0);
const newSize = (updates.data?.length || img.data?.length || 0) +
(updates.thumbnail?.length || img.thumbnail?.length || 0) +
(updates.medium?.length || img.medium?.length || 0);
const savings = ((oldSize - newSize) / oldSize * 100).toFixed(1);
const savedKB = ((oldSize - newSize) / 1024).toFixed(1);
console.log(` - Size reduction: ${savings}% (${savedKB} KB saved)`);
await client.query(
'UPDATE images SET data = $1, thumbnail = $2, medium = $3 WHERE id = $4',
[updates.data || img.data, updates.thumbnail || img.thumbnail, updates.medium || img.medium, img.id]
);
converted++;
} else {
console.log(' - Already WebP, skipping');
skipped++;
}
} catch (err) {
console.error(` - Error: ${(err as Error).message}`);
errors++;
}
console.log('');
}
console.log('Migration complete!\n');
console.log(`Converted: ${converted}`);
console.log(`Skipped: ${skipped}`);
console.log(`Errors: ${errors}`);
} finally {
client.release();
await pool.end();
}
}
main().catch(console.error);
+111
View File
@@ -0,0 +1,111 @@
/**
* Migration script to convert existing JPEG/PNG images to WebP
* Run from the k8s cluster directly
*/
const { Pool } = require('pg');
const sharp = require('sharp');
const pool = new Pool({
host: 'postgres.lahuasca',
port: 5432,
database: 'lahuasca',
user: 'lahuasca',
password: process.env.DB_PASSWORD || 'lahuasca123',
});
async function convertToWebP(base64Data) {
const matches = base64Data.match(/^data:image\/(\w+);base64,(.+)$/);
if (!matches) {
return base64Data;
}
const buffer = Buffer.from(matches[2], 'base64');
const webpBuffer = await sharp(buffer)
.webp({ quality: 90 })
.toBuffer();
return `data:image/webp;base64,${webpBuffer.toString('base64')}`;
}
async function main() {
console.log('Starting image migration to WebP...\n');
const client = await pool.connect();
try {
const { rows: images } = await client.query(
'SELECT id, filename, data, thumbnail, medium FROM images'
);
console.log(`Found ${images.length} images to process\n`);
let converted = 0;
let skipped = 0;
let errors = 0;
let totalSaved = 0;
for (const img of images) {
console.log(`Processing image ${img.id}: ${img.filename}`);
try {
let needsUpdate = false;
const updates = {};
if (img.data && !img.data.includes('image/webp')) {
console.log(' Converting full image...');
updates.data = await convertToWebP(img.data);
needsUpdate = true;
}
if (img.thumbnail && !img.thumbnail.includes('image/webp')) {
console.log(' Converting thumbnail...');
updates.thumbnail = await convertToWebP(img.thumbnail);
needsUpdate = true;
}
if (img.medium && !img.medium.includes('image/webp')) {
console.log(' Converting medium...');
updates.medium = await convertToWebP(img.medium);
needsUpdate = true;
}
if (needsUpdate) {
const oldSize = (img.data?.length || 0) + (img.thumbnail?.length || 0) + (img.medium?.length || 0);
const newSize = (updates.data?.length || img.data?.length || 0) +
(updates.thumbnail?.length || img.thumbnail?.length || 0) +
(updates.medium?.length || img.medium?.length || 0);
const savedKB = Math.round((oldSize - newSize) / 1024);
totalSaved += savedKB;
console.log(` Saved: ${savedKB} KB`);
await client.query(
'UPDATE images SET data = $1, thumbnail = $2, medium = $3 WHERE id = $4',
[updates.data || img.data, updates.thumbnail || img.thumbnail, updates.medium || img.medium, img.id]
);
converted++;
} else {
console.log(' Already WebP, skipping');
skipped++;
}
} catch (err) {
console.error(` Error: ${err.message}`);
errors++;
}
}
console.log('\n========================================');
console.log(`Converted: ${converted}`);
console.log(`Skipped: ${skipped}`);
console.log(`Errors: ${errors}`);
console.log(`Total saved: ${Math.round(totalSaved / 1024)} MB`);
console.log('========================================');
} finally {
client.release();
await pool.end();
}
}
main().catch(console.error);
+56
View File
@@ -145,6 +145,61 @@ function Empty({ icon, title, desc }: any) {
);
}
/* ─── WebP Migration ─── */
function WebPMigration({ onToast, onRefresh }: { onToast: (msg: string, type: string) => void; onRefresh: () => void }) {
const [migrating, setMigrating] = useState(false);
const [stats, setStats] = useState<{ totalImages: number; totalSizeMB: number } | null>(null);
useEffect(() => {
fetch('/api/admin/migrate-images')
.then(res => res.ok ? res.json() : null)
.then(data => data && setStats({ totalImages: data.totalImages, totalSizeMB: data.totalSizeMB }))
.catch(() => {});
}, []);
const runMigration = async () => {
setMigrating(true);
try {
const res = await fetch('/api/admin/migrate-images', { method: 'POST' });
const data = await res.json();
if (res.ok) {
onToast(`Converted ${data.converted} images, saved ${data.totalSavedMB} MB`, 'success');
onRefresh();
} else {
onToast(data.error || 'Migration failed', 'error');
}
} catch {
onToast('Migration failed', 'error');
}
setMigrating(false);
};
return (
<div style={{
marginBottom: '16px',
padding: '12px 16px',
background: '#fff',
borderRadius: '12px',
border: `1px solid ${C.border}`,
display: 'flex',
alignItems: 'center',
justifyContent: 'space-between',
flexWrap: 'wrap',
gap: '12px',
}}>
<div>
<div style={{ fontWeight: 600, color: C.navy, fontSize: '14px' }}>🔄 WebP Migration</div>
<div style={{ fontSize: '12px', color: C.textLight }}>
{stats ? `${stats.totalImages} images · ${stats.totalSizeMB} MB total` : 'Checking...'}
</div>
</div>
<Btn onClick={runMigration} disabled={migrating} size="sm">
{migrating ? 'Migrating...' : 'Convert to WebP'}
</Btn>
</div>
);
}
function SecHead({ title, count, action }: any) {
return (
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '16px', flexWrap: 'wrap', gap: '10px' }}>
@@ -2462,6 +2517,7 @@ export default function AdminPage() {
case 'gallery': return (
<div>
<SecHead title="🖼️ Image Gallery" count={images.length} />
<WebPMigration onToast={showToast} onRefresh={loadImages} />
<ImageGallery images={images} onDelete={deleteImage} />
</div>
);
+131
View File
@@ -0,0 +1,131 @@
import { NextResponse } from 'next/server';
import { requireRole } from '@/lib/auth';
import { db } from '@/lib/db';
import sharp from 'sharp';
export const maxDuration = 300; // 5 minutes for large migrations
async function convertToWebP(base64Data: string): Promise<string> {
const matches = base64Data.match(/^data:image\/(\w+);base64,(.+)$/);
if (!matches) {
return base64Data;
}
const buffer = Buffer.from(matches[2], 'base64');
const webpBuffer = await sharp(buffer)
.webp({ quality: 90 })
.toBuffer();
return `data:image/webp;base64,${webpBuffer.toString('base64')}`;
}
export async function POST() {
try {
await requireRole('admin');
console.log('Starting WebP migration...');
const { rows: images } = await db.query(
'SELECT id, filename, data, thumbnail, medium FROM images'
);
console.log(`Found ${images.length} images to process`);
let converted = 0;
let skipped = 0;
let errors: number[] = [];
let totalSavedKB = 0;
for (const img of images) {
try {
let needsUpdate = false;
const updates: { data?: string; thumbnail?: string; medium?: string } = {};
if (img.data && !img.data.includes('image/webp')) {
console.log(`Converting image ${img.id}: ${img.filename} (full)`);
updates.data = await convertToWebP(img.data);
needsUpdate = true;
}
if (img.thumbnail && !img.thumbnail.includes('image/webp')) {
console.log(`Converting image ${img.id}: ${img.filename} (thumbnail)`);
updates.thumbnail = await convertToWebP(img.thumbnail);
needsUpdate = true;
}
if (img.medium && !img.medium.includes('image/webp')) {
console.log(`Converting image ${img.id}: ${img.filename} (medium)`);
updates.medium = await convertToWebP(img.medium);
needsUpdate = true;
}
if (needsUpdate) {
const oldSize = (img.data?.length || 0) + (img.thumbnail?.length || 0) + (img.medium?.length || 0);
const newSize = (updates.data?.length || img.data?.length || 0) +
(updates.thumbnail?.length || img.thumbnail?.length || 0) +
(updates.medium?.length || img.medium?.length || 0);
const savedKB = Math.round((oldSize - newSize) / 1024);
totalSavedKB += savedKB;
await db.query(
'UPDATE images SET data = $1, thumbnail = $2, medium = $3 WHERE id = $4',
[updates.data || img.data, updates.thumbnail || img.thumbnail, updates.medium || img.medium, img.id]
);
converted++;
} else {
skipped++;
}
} catch (err) {
console.error(`Error processing image ${img.id}:`, err);
errors.push(img.id);
}
}
return NextResponse.json({
success: true,
total: images.length,
converted,
skipped,
errors,
totalSavedMB: Math.round(totalSavedKB / 1024 * 10) / 10,
});
} catch (error) {
console.error('Migration error:', error);
if ((error as Error).message === 'Unauthorized') {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
}
return NextResponse.json({ error: 'Migration failed', details: (error as Error).message }, { status: 500 });
}
}
export async function GET() {
try {
await requireRole('admin');
const { rows: images } = await db.query(
'SELECT id, filename, LENGTH(data) as data_size, LENGTH(thumbnail) as thumb_size, LENGTH(medium) as medium_size FROM images'
);
let totalSize = 0;
let webpCount = 0;
let jpegCount = 0;
for (const img of images) {
totalSize += (img.data_size || 0) + (img.thumb_size || 0) + (img.medium_size || 0);
if (img.data_size) {
// We'd need to fetch the actual data to check format, so estimate based on size
}
}
return NextResponse.json({
totalImages: images.length,
totalSizeKB: Math.round(totalSize / 1024),
totalSizeMB: Math.round(totalSize / 1024 / 1024 * 10) / 10,
});
} catch (error) {
if ((error as Error).message === 'Unauthorized') {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
}
return NextResponse.json({ error: 'Failed to get stats' }, { status: 500 });
}
}