Add HEIC to JPEG conversion and image resizing support; update dependencies and Dockerfile

This commit is contained in:
denshooter
2026-02-22 00:17:08 +01:00
parent bf070ec47f
commit eb28501b2e
11 changed files with 481 additions and 43 deletions
+133 -26
View File
@@ -1187,34 +1187,141 @@ export default function AdminPage() {
{timelineContributions
.filter(c => c.type === 'timeline')
.sort((a, b) => new Date(b.created_at).getTime() - new Date(a.created_at).getTime())
.map(c => (
<div key={`tc-${c.id}`} className={`rounded-lg p-3 border flex items-center justify-between ${
c.status === 'flagged' ? 'bg-red-50 border-red-200' :
c.status === 'approved' ? 'bg-green-50/50 border-green-200' :
c.status === 'rejected' ? 'bg-red-50/30 border-red-100' :
'bg-amber-50 border-amber-200'
}`}>
<div className="flex-1 min-w-0">
<div className="flex items-center gap-2 flex-wrap">
<span className="font-lora text-sm text-warm-brown font-medium">{c.title || 'Ohne Titel'}</span>
{c.year && <span className="text-warm-gold text-xs">{c.day ? `${c.day}.` : ''}{c.month ? `${c.month}.` : ''}{c.year}</span>}
{c.status === 'flagged' && <span className="text-xs px-1.5 py-0.5 bg-red-200 text-red-800 rounded-full">🚩</span>}
{c.status === 'approved' && <span className="text-xs px-1.5 py-0.5 bg-green-200 text-green-800 rounded-full"></span>}
{c.status === 'rejected' && <span className="text-xs px-1.5 py-0.5 bg-red-100 text-red-600 rounded-full"></span>}
</div>
<p className="text-warm-brown-light/60 text-xs truncate">{c.name} {c.content ? `· ${c.content}` : ''}</p>
</div>
<div className="flex gap-1 ml-2">
{(c.status === 'pending' || c.status === 'flagged') && (
<>
<button onClick={async () => { await fetch(`/api/contributions/${c.id}`, { method: 'PUT', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ status: 'approved' }) }); loadData() }} className="p-1.5 text-green-600 hover:text-green-700" title="Freigeben"><Eye size={13} /></button>
<button onClick={async () => { await fetch(`/api/contributions/${c.id}`, { method: 'PUT', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ status: 'rejected' }) }); loadData() }} className="p-1.5 text-red-400 hover:text-red-500" title="Ablehnen"><X size={13} /></button>
</>
.map(c => {
const isEditing = editingContribution?.id === c.id
return (
<div key={`tc-${c.id}`} className={`rounded-lg p-3 border ${
c.status === 'flagged' ? 'bg-red-50 border-red-200' :
c.status === 'approved' ? 'bg-green-50/50 border-green-200' :
c.status === 'rejected' ? 'bg-red-50/30 border-red-100' :
'bg-amber-50 border-amber-200'
}`}>
{isEditing ? (
<div className="space-y-2">
<div className="grid grid-cols-3 gap-2">
<input
type="text"
value={editingContribution.day || ''}
onChange={(e) => setEditingContribution({ ...editingContribution, day: e.target.value })}
placeholder="Tag"
className="px-2 py-1.5 rounded border border-warm-border bg-white text-warm-brown text-xs"
/>
<input
type="text"
value={editingContribution.month || ''}
onChange={(e) => setEditingContribution({ ...editingContribution, month: e.target.value })}
placeholder="Monat"
className="px-2 py-1.5 rounded border border-warm-border bg-white text-warm-brown text-xs"
/>
<input
type="text"
value={editingContribution.year || ''}
onChange={(e) => setEditingContribution({ ...editingContribution, year: e.target.value })}
placeholder="Jahr"
className="px-2 py-1.5 rounded border border-warm-border bg-white text-warm-brown text-xs"
/>
</div>
<input
type="text"
value={editingContribution.title || ''}
onChange={(e) => setEditingContribution({ ...editingContribution, title: e.target.value })}
placeholder="Titel"
className="w-full px-2 py-1.5 rounded border border-warm-border bg-white text-warm-brown text-xs"
/>
<input
type="text"
value={editingContribution.location || ''}
onChange={(e) => setEditingContribution({ ...editingContribution, location: e.target.value })}
placeholder="Ort (optional)"
className="w-full px-2 py-1.5 rounded border border-warm-border bg-white text-warm-brown text-xs"
/>
<textarea
value={editingContribution.content || ''}
onChange={(e) => setEditingContribution({ ...editingContribution, content: e.target.value })}
placeholder="Beschreibung (optional)"
rows={2}
className="w-full px-2 py-1.5 rounded border border-warm-border bg-white text-warm-brown text-xs resize-none"
/>
<div className="flex items-center gap-2">
<input
type="text"
value={editingContribution.name || ''}
onChange={(e) => setEditingContribution({ ...editingContribution, name: e.target.value })}
placeholder="Name des Einreichers"
className="flex-1 px-2 py-1.5 rounded border border-warm-border bg-white text-warm-brown text-xs"
/>
<button
onClick={() => setEditingContribution({ ...editingContribution, name: '' })}
title="Namen entfernen (wird nicht angezeigt)"
className="px-2 py-1.5 rounded border border-warm-border bg-white text-warm-brown-light hover:text-red-500 text-xs transition-colors"
>
Name verbergen
</button>
</div>
<div className="flex gap-2">
<button
onClick={async () => {
await fetch(`/api/contributions/${editingContribution.id}`, {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
name: editingContribution.name,
type: editingContribution.type,
year: editingContribution.year,
month: editingContribution.month,
day: editingContribution.day,
title: editingContribution.title,
content: editingContribution.content,
location: editingContribution.location,
media_filenames: editingContribution.media_filenames,
status: editingContribution.status,
}),
})
setEditingContribution(null)
loadData()
}}
className="px-3 py-1.5 bg-warm-gold text-white rounded text-xs hover:bg-amber-600 transition-colors"
>
Speichern
</button>
<button
onClick={() => setEditingContribution(null)}
className="px-3 py-1.5 bg-warm-brown-light/20 text-warm-brown rounded text-xs hover:bg-warm-brown-light/30 transition-colors"
>
Abbrechen
</button>
</div>
</div>
) : (
<div className="flex items-center justify-between">
<div className="flex-1 min-w-0">
<div className="flex items-center gap-2 flex-wrap">
<span className="font-lora text-sm text-warm-brown font-medium">{c.title || 'Ohne Titel'}</span>
{c.year && <span className="text-warm-gold text-xs">{c.day ? `${c.day}.` : ''}{c.month ? `${c.month}.` : ''}{c.year}</span>}
{c.status === 'flagged' && <span className="text-xs px-1.5 py-0.5 bg-red-200 text-red-800 rounded-full">🚩</span>}
{c.status === 'approved' && <span className="text-xs px-1.5 py-0.5 bg-green-200 text-green-800 rounded-full"></span>}
{c.status === 'rejected' && <span className="text-xs px-1.5 py-0.5 bg-red-100 text-red-600 rounded-full"></span>}
</div>
<p className="text-warm-brown-light/60 text-xs truncate">
{c.name ? c.name : <span className="italic text-warm-brown-light/40">Kein Name</span>}
{c.content ? ` · ${c.content}` : ''}
</p>
</div>
<div className="flex gap-1 ml-2">
<button onClick={() => setEditingContribution(c)} className="p-1.5 text-amber-700 hover:text-amber-500" title="Bearbeiten"><Edit2 size={13} /></button>
{(c.status === 'pending' || c.status === 'flagged') && (
<>
<button onClick={async () => { await fetch(`/api/contributions/${c.id}`, { method: 'PUT', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ status: 'approved' }) }); loadData() }} className="p-1.5 text-green-600 hover:text-green-700" title="Freigeben"><Eye size={13} /></button>
<button onClick={async () => { await fetch(`/api/contributions/${c.id}`, { method: 'PUT', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ status: 'rejected' }) }); loadData() }} className="p-1.5 text-red-400 hover:text-red-500" title="Ablehnen"><X size={13} /></button>
</>
)}
<button onClick={async () => { if (confirm('Löschen?')) { await fetch(`/api/contributions/${c.id}`, { method: 'DELETE' }); loadData() } }} className="p-1.5 text-red-400/60 hover:text-red-500" title="Löschen"><Trash2 size={13} /></button>
</div>
</div>
)}
<button onClick={async () => { if (confirm('Löschen?')) { await fetch(`/api/contributions/${c.id}`, { method: 'DELETE' }); loadData() } }} className="p-1.5 text-red-400/60 hover:text-red-500" title="Löschen"><Trash2 size={13} /></button>
</div>
</div>
))}
)
})}
</div>
</div>
)}
+79 -2
View File
@@ -1,6 +1,7 @@
import { NextRequest, NextResponse } from 'next/server'
import fs from 'fs'
import path from 'path'
import sharp from 'sharp'
export const runtime = 'nodejs'
@@ -40,8 +41,84 @@ export async function GET(
return NextResponse.json({ error: 'Not found' }, { status: 404 })
}
const ext = path.extname(filePath).toLowerCase()
const contentType = MIME[ext] || 'application/octet-stream'
let ext = path.extname(filePath).toLowerCase()
let contentType = MIME[ext] || 'application/octet-stream'
let fileToSendPath = filePath
// 1. Handle HEIC/HEIF conversion (to JPEG)
// If it's HEIC, we want to work with the converted JPEG version for serving or resizing
if (ext === '.heic' || ext === '.heif') {
const jpegPath = filePath.replace(/\.(heic|heif)$/i, '.jpg')
if (fs.existsSync(jpegPath)) {
fileToSendPath = jpegPath
ext = '.jpg'
contentType = 'image/jpeg'
} else {
try {
const converted = await sharp(fs.readFileSync(filePath)).jpeg({ quality: 90 }).toBuffer()
fs.writeFileSync(jpegPath, converted)
fileToSendPath = jpegPath
ext = '.jpg'
contentType = 'image/jpeg'
} catch {
// Conversion failed — keep original path (will likely fail to display in non-Apple browsers)
}
}
}
// 2. Handle Resizing (only for images, if width requested)
const widthParam = request.nextUrl.searchParams.get('w')
const allowedWidths = [200, 400, 600, 800, 1200, 1600]
if (widthParam && contentType.startsWith('image/') && !contentType.includes('gif')) {
const targetWidth = parseInt(widthParam, 10)
if (allowedWidths.includes(targetWidth)) {
// Construct resized filename: original.jpg -> original_w800.jpg
const dir = path.dirname(fileToSendPath)
const name = path.basename(fileToSendPath, ext)
const resizedPath = path.join(dir, `${name}_w${targetWidth}${ext}`)
if (fs.existsSync(resizedPath)) {
fileToSendPath = resizedPath
} else {
try {
let transformer = sharp(fs.readFileSync(fileToSendPath))
.resize(targetWidth, null, { withoutEnlargement: true })
if (ext === '.jpg' || ext === '.jpeg') {
transformer = transformer.jpeg({ quality: 80 })
} else if (ext === '.png') {
transformer = transformer.png({ quality: 80 })
} else if (ext === '.webp') {
transformer = transformer.webp({ quality: 80 })
}
const resizedBuffer = await transformer.toBuffer()
fs.writeFileSync(resizedPath, resizedBuffer)
fileToSendPath = resizedPath
} catch (e) {
// Resize failed (maybe corrupt image), serve original
console.error('Resize failed:', e)
}
}
}
}
// If we changed the file path (HEIC conversion or resizing), update stats
if (fileToSendPath !== filePath) {
const stat = fs.statSync(fileToSendPath)
const buffer = fs.readFileSync(fileToSendPath)
return new NextResponse(buffer as unknown as ReadableStream, {
headers: {
'Content-Type': contentType,
'Content-Length': String(stat.size),
'Cache-Control': 'public, max-age=31536000, immutable',
},
})
}
const stat = fs.statSync(filePath)
// Range requests for video/audio seeking
+16 -2
View File
@@ -4,6 +4,7 @@ import path from 'path'
import { cookies } from 'next/headers'
import { createHash, randomUUID } from 'crypto'
import { getDb } from '@/lib/db'
import sharp from 'sharp'
export const runtime = 'nodejs'
export const maxDuration = 60
@@ -95,7 +96,7 @@ export async function POST(req: NextRequest) {
for (const file of filesToProcess) {
let mimeType = file.type?.toLowerCase() || ''
const ext = path.extname(file.name).toLowerCase()
let ext = path.extname(file.name).toLowerCase()
if (!mimeType && (ext === '.heic' || ext === '.heif')) {
mimeType = 'image/heic'
@@ -106,9 +107,22 @@ export async function POST(req: NextRequest) {
continue // Skip unsupported files
}
let buffer: Buffer = Buffer.from(await file.arrayBuffer())
// Convert HEIC/HEIF to JPEG so all browsers can display it
if (mimeType === 'image/heic' || mimeType === 'image/heif') {
try {
const converted = await sharp(buffer).jpeg({ quality: 90 }).toBuffer()
buffer = converted as unknown as Buffer
ext = '.jpg'
mimeType = 'image/jpeg'
} catch {
// Conversion failed — keep original HEIC (will only display on Apple devices)
}
}
const filename = `${folder}/${randomUUID()}${ext || '.bin'}`
const filePath = path.join(DATA_DIR, 'uploads', filename)
const buffer = Buffer.from(await file.arrayBuffer())
// Check for duplicate
const existingFile = await findDuplicate(buffer, folder)
+8 -1
View File
@@ -21,8 +21,15 @@ const lora = Lora({
export const dynamic = 'force-dynamic'
let metadataBase: URL
try {
metadataBase = new URL(process.env.NEXT_PUBLIC_URL || 'http://localhost:3000')
} catch {
metadataBase = new URL('http://localhost:3000')
}
export const metadata: Metadata = {
metadataBase: new URL(process.env.NEXT_PUBLIC_URL || 'http://localhost:3000'),
metadataBase,
title: 'In Erinnerung an Maria Malejka',
description:
'Eine liebevolle Gedenkseite für Maria Malejka · 29. November 1945 10. Februar 2026',
+2 -2
View File
@@ -31,7 +31,7 @@ export default function PhotoGallery({ photos }: { photos: MediaItem[] }) {
className="relative aspect-square overflow-hidden rounded-xl shadow-md hover:shadow-xl transition-shadow duration-300 group"
>
<img
src={`/api/files/${photo.filename}`}
src={`/api/files/${photo.filename}?w=400`}
alt={photo.caption || 'Maria Malejka'}
className="w-full h-full object-cover group-hover:scale-105 transition-transform duration-700"
loading="lazy"
@@ -91,7 +91,7 @@ export default function PhotoGallery({ photos }: { photos: MediaItem[] }) {
onClick={(e) => e.stopPropagation()}
>
<img
src={`/api/files/${photos[lightboxIndex].filename}`}
src={`/api/files/${photos[lightboxIndex].filename}?w=1200`}
alt={photos[lightboxIndex].caption || ''}
className="max-h-[78vh] max-w-full object-contain rounded-lg"
/>
+5 -4
View File
@@ -95,9 +95,10 @@ export default function TimelineSection({ entries }: TimelineSectionProps) {
{photos.slice(0, 2).map((filename, i) => (
<img
key={i}
src={`/api/files/${filename.trim()}`}
src={`/api/files/${filename.trim()}?w=600`}
alt=""
className="w-full max-h-40 object-contain rounded-lg bg-warm-brown/5"
className="w-full max-h-40 object-cover rounded-lg"
loading="lazy"
/>
))}
</div>
@@ -219,9 +220,9 @@ export default function TimelineSection({ entries }: TimelineSectionProps) {
{selectedEntry.media_filenames.split(',').map((filename, i) => (
<img
key={i}
src={`/api/files/${filename.trim()}`}
src={`/api/files/${filename.trim()}?w=1200`}
alt=""
className="w-full object-contain rounded-lg bg-warm-brown/5"
className="w-full object-contain rounded-xl"
/>
))}
</div>