feat: image optimization — client-side resize + server-side thumbnails
Avatars/banners now resize to max 512px/1920px and convert to WebP before upload (zero server cost). Chat image uploads generate an 800px-wide WebP thumbnail via Sharp; the feed shows the thumbnail, click opens the full-res original. Adds lazy loading to avatars. Federation-compatible: remote instances without this feature fall back gracefully.
This commit is contained in:
@@ -23,7 +23,8 @@
|
||||
"drizzle-orm": "^0.33.0",
|
||||
"fastify": "^4.28.1",
|
||||
"jsonwebtoken": "^9.0.2",
|
||||
"livekit-server-sdk": "^2.6.1"
|
||||
"livekit-server-sdk": "^2.6.1",
|
||||
"sharp": "^0.33.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/bcryptjs": "^2.4.6",
|
||||
|
||||
@@ -44,6 +44,12 @@ export function runMigrations(db: Database.Database): void {
|
||||
{ name: 'closed', type: 'INTEGER DEFAULT 0' }
|
||||
]
|
||||
},
|
||||
{
|
||||
name: 'attachments',
|
||||
columns: [
|
||||
{ name: 'thumbnail_filename', type: 'TEXT' }
|
||||
]
|
||||
},
|
||||
{
|
||||
name: 'dm_channels',
|
||||
columns: [
|
||||
|
||||
@@ -85,6 +85,7 @@ export const attachments = sqliteTable('attachments', {
|
||||
originalName: text('original_name').notNull(),
|
||||
mimetype: text('mimetype').notNull(),
|
||||
size: integer('size').notNull(),
|
||||
thumbnailFilename: text('thumbnail_filename'),
|
||||
createdAt: integer('created_at').notNull(),
|
||||
});
|
||||
|
||||
|
||||
@@ -83,6 +83,7 @@ export function buildDmMessageWithUser(
|
||||
originalName: a.originalName,
|
||||
mimetype: a.mimetype,
|
||||
size: a.size,
|
||||
thumbnailFilename: a.thumbnailFilename ?? null,
|
||||
createdAt: a.createdAt,
|
||||
})),
|
||||
reactions,
|
||||
|
||||
@@ -143,6 +143,7 @@ export function buildMessageWithUser(
|
||||
originalName: a.originalName,
|
||||
mimetype: a.mimetype,
|
||||
size: a.size,
|
||||
thumbnailFilename: a.thumbnailFilename ?? null,
|
||||
createdAt: a.createdAt,
|
||||
})),
|
||||
reactions,
|
||||
|
||||
@@ -8,6 +8,7 @@ import fs from 'fs';
|
||||
import path from 'path';
|
||||
import { pipeline } from 'stream/promises';
|
||||
import type { Attachment } from '@backspace/shared';
|
||||
import { generateThumbnail, isResizableImage } from '../utils/thumbnail.js';
|
||||
|
||||
export async function uploadRoutes(app: FastifyInstance): Promise<void> {
|
||||
// Ensure upload directory exists
|
||||
@@ -57,6 +58,12 @@ export async function uploadRoutes(app: FastifyInstance): Promise<void> {
|
||||
const now = Date.now();
|
||||
const db = getDb();
|
||||
|
||||
// Generate thumbnail for resizable images (non-blocking — upload succeeds regardless)
|
||||
let thumbnailFilename: string | null = null;
|
||||
if (isResizableImage(mimetype)) {
|
||||
thumbnailFilename = await generateThumbnail(filepath, mimetype, config.uploadDir);
|
||||
}
|
||||
|
||||
// Save attachment record
|
||||
db.insert(schema.attachments).values({
|
||||
id,
|
||||
@@ -64,6 +71,7 @@ export async function uploadRoutes(app: FastifyInstance): Promise<void> {
|
||||
originalName,
|
||||
mimetype,
|
||||
size,
|
||||
thumbnailFilename,
|
||||
createdAt: now,
|
||||
}).run();
|
||||
|
||||
@@ -74,6 +82,7 @@ export async function uploadRoutes(app: FastifyInstance): Promise<void> {
|
||||
originalName,
|
||||
mimetype,
|
||||
size,
|
||||
thumbnailFilename: thumbnailFilename ?? undefined,
|
||||
createdAt: now,
|
||||
};
|
||||
|
||||
|
||||
@@ -1,11 +1,13 @@
|
||||
import fs from 'fs';
|
||||
import path from 'path';
|
||||
import { config } from '../config.js';
|
||||
import { thumbFilename } from './thumbnail.js';
|
||||
|
||||
/**
|
||||
* Delete a single uploaded file by its stored filename.
|
||||
* Uses path.basename() to prevent directory traversal attacks.
|
||||
* Tolerates ENOENT (file already gone) but logs other errors.
|
||||
* Also attempts to delete the corresponding thumbnail if one exists.
|
||||
*/
|
||||
export function deleteUploadFile(filename: string): void {
|
||||
const safeName = path.basename(filename);
|
||||
@@ -17,6 +19,15 @@ export function deleteUploadFile(filename: string): void {
|
||||
console.error(`Failed to delete upload file ${safeName}:`, err.message);
|
||||
}
|
||||
}
|
||||
|
||||
// Also attempt to delete the thumbnail variant
|
||||
const thumbName = thumbFilename(safeName);
|
||||
const thumbPath = path.join(config.uploadDir, thumbName);
|
||||
try {
|
||||
fs.unlinkSync(thumbPath);
|
||||
} catch {
|
||||
// Thumbnail may not exist — that's fine
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -0,0 +1,66 @@
|
||||
import path from 'path';
|
||||
import sharp from 'sharp';
|
||||
|
||||
const RESIZABLE_MIMETYPES = new Set([
|
||||
'image/jpeg',
|
||||
'image/png',
|
||||
'image/webp',
|
||||
'image/gif',
|
||||
'image/avif',
|
||||
'image/tiff',
|
||||
]);
|
||||
|
||||
const THUMBNAIL_MAX_WIDTH = 800;
|
||||
const THUMBNAIL_QUALITY = 80;
|
||||
|
||||
/**
|
||||
* Derive a deterministic thumbnail filename from the original.
|
||||
* e.g. "123456789.png" → "123456789_thumb.webp"
|
||||
*/
|
||||
export function thumbFilename(original: string): string {
|
||||
const parsed = path.parse(original);
|
||||
return `${parsed.name}_thumb.webp`;
|
||||
}
|
||||
|
||||
/** Check if the given mimetype is a resizable image format. */
|
||||
export function isResizableImage(mimetype: string): boolean {
|
||||
return RESIZABLE_MIMETYPES.has(mimetype);
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate a WebP thumbnail for the given image file.
|
||||
* Returns the thumbnail filename on success, or null if:
|
||||
* - The image is already ≤ THUMBNAIL_MAX_WIDTH px wide
|
||||
* - An error occurs (upload still succeeds without thumbnail)
|
||||
*/
|
||||
export async function generateThumbnail(
|
||||
originalPath: string,
|
||||
mimetype: string,
|
||||
uploadDir: string,
|
||||
): Promise<string | null> {
|
||||
if (!isResizableImage(mimetype)) return null;
|
||||
|
||||
try {
|
||||
const image = sharp(originalPath);
|
||||
const metadata = await image.metadata();
|
||||
|
||||
// Skip if the original is already small enough
|
||||
if (!metadata.width || metadata.width <= THUMBNAIL_MAX_WIDTH) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const originalFilename = path.basename(originalPath);
|
||||
const thumbName = thumbFilename(originalFilename);
|
||||
const thumbPath = path.join(uploadDir, thumbName);
|
||||
|
||||
await sharp(originalPath)
|
||||
.resize({ width: THUMBNAIL_MAX_WIDTH, withoutEnlargement: true })
|
||||
.webp({ quality: THUMBNAIL_QUALITY })
|
||||
.toFile(thumbPath);
|
||||
|
||||
return thumbName;
|
||||
} catch (err) {
|
||||
console.error('Thumbnail generation failed (non-fatal):', err);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -58,6 +58,7 @@ function getMessageWithUser(messageId: string): MessageWithUser | null {
|
||||
originalName: a.originalName,
|
||||
mimetype: a.mimetype,
|
||||
size: a.size,
|
||||
thumbnailFilename: a.thumbnailFilename ?? null,
|
||||
createdAt: a.createdAt,
|
||||
}));
|
||||
|
||||
|
||||
Reference in New Issue
Block a user