Compare commits

..

16 Commits

Author SHA1 Message Date
Gitea Actions Bot 9fd6b44487 chore: bump version to 1.0.116 (backend + frontend) 2025-09-09 15:47:41 +00:00
paul 9fe10bcce2 feat(native): build frontend and serve SPA from backend (SERVE_FRONTEND); fix Cannot GET /admin on native installs
Mirror to GitHub / mirror (push) Successful in 42s
Test and Lint / backend-test (push) Successful in 1m33s
Test and Lint / frontend-test (push) Successful in 2m7s
Version and Release / version-bump (push) Successful in 1m0s
Version and Release / trigger-drone (push) Successful in 3s
2025-09-09 17:41:41 +02:00
Gitea Actions Bot f2abb40987 chore: bump version to 1.0.115 (backend + frontend) 2025-09-09 15:32:47 +00:00
paul 3697344cd0 fix(setup/native): handle forced updates safely by fetch+checkout/reset instead of pull; stable on rewritten histories
Mirror to GitHub / mirror (push) Successful in 38s
Test and Lint / backend-test (push) Successful in 1m29s
Test and Lint / frontend-test (push) Successful in 2m5s
Version and Release / version-bump (push) Successful in 1m0s
Version and Release / trigger-drone (push) Successful in 3s
2025-09-09 17:27:27 +02:00
Gitea Actions Bot 4aa0ff705f chore: bump version to 1.0.114 (backend + frontend) 2025-09-09 15:25:05 +00:00
paul dc482e614a fix(setup/native): Debian 12 compatibility (reliable RAM detection, sudo-less run_as_user, git safe.directory); ensure SQLite data dir; use user for migrate
Mirror to GitHub / mirror (push) Successful in 40s
Test and Lint / backend-test (push) Successful in 1m37s
Test and Lint / frontend-test (push) Successful in 2m8s
Version and Release / version-bump (push) Successful in 57s
Version and Release / trigger-drone (push) Successful in 3s
2025-09-09 17:19:03 +02:00
Gitea Actions Bot 448882cfef chore: bump version to 1.0.113 (backend + frontend) 2025-09-09 13:31:10 +00:00
paul 7f9cb33a40 chore(native): ensure SQLite data dir exists in setup and at runtime; keep native paths consistent under /opt/picpeak/app
Mirror to GitHub / mirror (push) Successful in 44s
Test and Lint / backend-test (push) Successful in 1m38s
Test and Lint / frontend-test (push) Successful in 2m3s
Version and Release / version-bump (push) Successful in 59s
Version and Release / trigger-drone (push) Successful in 3s
2025-09-09 15:25:04 +02:00
Gitea Actions Bot 798f6211e0 chore: bump version to 1.0.112 (backend + frontend) 2025-09-09 09:46:52 +00:00
paul b992b151d3 fix(native): correct setup paths to /opt/picpeak/app, update repo URL, add sqlite prod support; docs path fixes
Mirror to GitHub / mirror (push) Successful in 1m27s
Test and Lint / backend-test (push) Successful in 1m49s
Test and Lint / frontend-test (push) Successful in 2m9s
Version and Release / version-bump (push) Successful in 1m8s
Version and Release / trigger-drone (push) Successful in 3s
2025-09-09 11:25:41 +02:00
paul 87b8414e44 fix(setup/native): correct repo URL, paths, and systemd for native install; support sqlite in production knex config 2025-09-09 11:13:01 +02:00
paul ee13556c5c docs(readme): reflect new External Media reference mode and update roadmap (gallery feedback status)
Mirror to GitHub / mirror (push) Successful in 36s
Test and Lint / backend-test (push) Successful in 1m31s
Test and Lint / frontend-test (push) Successful in 2m14s
2025-09-06 10:16:08 +02:00
Gitea Actions Bot afeb35a446 chore: bump version to 1.0.111 (backend + frontend) 2025-09-06 07:22:38 +00:00
paul ab324f1928 fix(frontend): add missing externalMedia service and mount admin external-media routes; verify Vite build
Mirror to GitHub / mirror (push) Successful in 44s
Test and Lint / backend-test (push) Successful in 1m39s
Test and Lint / frontend-test (push) Successful in 2m16s
Version and Release / version-bump (push) Successful in 1m37s
Version and Release / trigger-drone (push) Successful in 3s
2025-09-06 09:15:49 +02:00
Gitea Actions Bot 78ab0ad2e9 chore: bump version to 1.0.110 (backend + frontend) 2025-09-05 22:06:43 +00:00
paul 49c77785e7 feat(admin): external media import modal + thumbnail fixes for reference events\n\n- Photos tab: replace inline external folder picker with a modal opened via "Import from External Folder" button next to "Upload Photos"; add info that all pictures in the selected folder will be imported.\n- Admin thumbnails: align list endpoint to /api/admin/photos/:eventId/photos and always return thumbnail_url to trigger on-demand generation; normalize external paths to avoid duplicated folder segments (e.g., individual/individual) that broke resolver; improve thumbnail logging.\n- Use authenticated image fetching on admin feedback pages to prevent 401s in automation.\n- i18n: add backup.external.warning strings; complete German backup/restore coverage; add common keys (notSet, of, up, select, selected).\n- Docs: add Local (npm) setup for EXTERNAL_MEDIA_ROOT in deployment guide.\n\nRefs #17 – gallery feature request: https://github.com/the-luap/picpeak/issues/17
Mirror to GitHub / mirror (push) Successful in 45s
Test and Lint / backend-test (push) Successful in 1m42s
Test and Lint / frontend-test (push) Failing after 1m50s
Version and Release / version-bump (push) Successful in 1m1s
Version and Release / trigger-drone (push) Successful in 3s
2025-09-05 23:44:30 +02:00
24 changed files with 1068 additions and 107 deletions
+38
View File
@@ -71,6 +71,7 @@ If you need to customize the application or the pre-built images aren't availabl
- [Reverse Proxy Setup](#reverse-proxy-setup)
- [Maintenance](#maintenance)
- [Troubleshooting](#troubleshooting)
- [External Media Library](#external-media-library)
## Prerequisites
@@ -111,6 +112,43 @@ If you need to customize the application or the pre-built images aren't availabl
docker compose -f docker-compose.production.yml logs -f
```
## External Media Library
PicPeak can reference an existing, readonly media library mounted into the backend container. This avoids copying originals into PicPeak storage.
- Map your host library path to the container as readonly in `docker-compose.production.yml`:
- Add volume under `backend`: `- ${EXTERNAL_MEDIA}:/external-media:ro`
- Add backend env: `EXTERNAL_MEDIA_ROOT=/external-media`
- In `.env`, set:
- `EXTERNAL_MEDIA=/mnt/photos` (example host path)
- `EXTERNAL_MEDIA_ROOT=/external-media`
Usage:
- In Admin → Events, set “Source Mode” to “Reference (external folder)”, select a folder under `/external-media`, then import to index and generate thumbnails. Originals stay in your library.
Backups and Archives:
- Backups only include data under `STORAGE_PATH` and exclude external originals. The backup manifest includes `metadata.external_references = { excluded: true, events: N, photos: M }` and the Admin UI surfaces a warning.
- Archiving reference events creates a manifestonly ZIP and deletes thumbnails for that event. External originals are never moved or deleted.
Local (npm) setup (no Docker):
1. Create or choose a folder that contains your external originals, e.g. `/Users/you/Pictures/picpeak-external` (macOS/Linux) or `C:\\Pictures\\picpeak-external` (Windows).
2. In `backend/.env` (or your shell), set:
- `EXTERNAL_MEDIA_ROOT=/absolute/path/to/picpeak-external`
- Ensure `STORAGE_PATH` points to your PicPeak storage (defaults to `./storage`).
3. Start services from source:
- Backend: `cd backend && npm install && npm run migrate && JWT_SECRET=... npm start`
- Frontend: `cd frontend && npm install && npm run dev` (or build + serve)
4. In Admin → Events:
- Create an event, set “Source Mode” to “Reference (external folder)”.
- Use the folder picker to browse under your `EXTERNAL_MEDIA_ROOT` and select the subfolder to reference.
- Click “Import from selected folder” to index files and generate thumbnails on demand.
Notes:
- PicPeak only reads from `EXTERNAL_MEDIA_ROOT`; it never modifies or deletes your originals there.
- Thumbnails are generated under `STORAGE_PATH/thumbnails` and are included in backups; originals in `EXTERNAL_MEDIA_ROOT` are excluded.
- On Windows, use absolute paths (e.g., `C:\\Photos\\Library`) for `EXTERNAL_MEDIA_ROOT`.
### Method 2: Building from Source
1. **Clone the repository**
+6 -2
View File
@@ -28,6 +28,7 @@ Unlike expensive SaaS solutions, PicPeak gives you:
### For Photographers
- 📁 **Drag & Drop Upload** - Simply drop photos into folders
- 🔗 **External Media (Reference Mode)** - Browse and import from a readonly external folder library without copying originals
-**Auto-Expiring Galleries** - Set expiration dates (default: 30 days)
- 🔐 **Password Protection** - Secure client galleries
- 📧 **Automated Emails** - Creation confirmations and expiration warnings
@@ -45,6 +46,7 @@ Unlike expensive SaaS solutions, PicPeak gives you:
### Technical Excellence
- 🐳 **Docker Ready** - Deploy in minutes
- 🔄 **Auto-Processing** - Automatic thumbnail generation
- 🗂️ **Reference Library Support** - Point PicPeak at `EXTERNAL_MEDIA_ROOT` to reference existing originals, index quickly, and generate thumbnails on demand
- 💾 **Smart Storage** - Automatic archiving of expired galleries
- 🛡️ **Security First** - JWT auth, rate limiting, CORS protection
- 📈 **Scalable** - From small studios to large agencies
@@ -73,6 +75,7 @@ docker-compose up -d
## 📖 Documentation
- 📘 [**Deployment Guide**](DEPLOYMENT_GUIDE.md) - Detailed installation instructions
- Includes the new [External Media Library](DEPLOYMENT_GUIDE.md#external-media-library) reference mode
- 🤝 [**Contributing**](CONTRIBUTING.md) - How to contribute
- 📜 [**License**](LICENSE) - MIT License
- 🔒 [**Security**](SECURITY.md) - Security policies
@@ -192,9 +195,10 @@ These features are currently in beta testing and may have limited functionality
| Feature | Description | Priority | Status |
|---------|-------------|----------|---------|
| **Backup & Restore** | Comprehensive backup system with S3/MinIO support, automated scheduling, and safe restore functionality | High | ✅ Implemented |
| **External Media Library (Reference Mode)** | Use an external folder library as a readonly source with import and ondemand thumbnail generation | High | ✅ Implemented |
| **Gallery Templates** | Additional gallery layouts and themes (masonry, slideshow, story-style) for different event types | Medium | 🔄 Open |
| **Face Recognition** | AI-powered face detection to help guests find their photos and create automatic person-based albums | Low | 🔄 Open |
| **Gallery Feedback** | Allow guests to like, rate, and comment on photos with admin notifications and moderation | Medium | ✅ Implemented (not tested) |
| **Gallery Feedback** | Allow guests to like, rate, and comment on photos with admin notifications and moderation | Medium | ✅ Implemented |
| **Video Support** | Upload and display videos alongside photos in galleries with streaming support | Low | 🔄 Open |
| **Multiple Administrators** | Support for multiple admin accounts with role-based permissions and activity tracking | Low | 📋 Planned |
@@ -233,4 +237,4 @@ PicPeak is released under the [MIT License](LICENSE). Use it freely for personal
<a href="https://github.com/the-luap/picpeak">GitHub</a> •
<a href="DEPLOYMENT_GUIDE.md">Documentation</a> •
<a href="https://github.com/the-luap/picpeak/issues">Support</a>
</p>
</p>
+9 -9
View File
@@ -8,7 +8,7 @@ This guide provides easy installation instructions for PicPeak on Linux servers
```bash
# Download and run the unified setup script
curl -fsSL https://raw.githubusercontent.com/yourusername/wedding-photo-sharing/main/scripts/setup.sh -o setup.sh && \
curl -fsSL https://raw.githubusercontent.com/the-luap/picpeak/main/scripts/setup.sh -o setup.sh && \
chmod +x setup.sh && \
sudo ./setup.sh
```
@@ -305,9 +305,9 @@ docker compose restart
```
### Native Configuration
Edit `/opt/picpeak/backend/.env`:
Edit `/opt/picpeak/app/backend/.env`:
```bash
sudo nano /opt/picpeak/backend/.env
sudo nano /opt/picpeak/app/backend/.env
sudo systemctl restart picpeak-backend
```
@@ -369,7 +369,7 @@ tar -czf photos-backup.tar.gz storage/events/
#### Native:
```bash
# Database backup
sudo cp /opt/picpeak/backend/database.sqlite /backup/database-$(date +%Y%m%d).sqlite
sudo cp /opt/picpeak/app/backend/data/photo_sharing.db /backup/database-$(date +%Y%m%d).sqlite
# Photos backup
sudo tar -czf /backup/photos-$(date +%Y%m%d).tar.gz /opt/picpeak/events/
@@ -446,7 +446,7 @@ ls -la ~/picpeak/storage/events/
docker exec picpeak-backend node scripts/reset-admin-password.js
# Native
cd /opt/picpeak/backend
cd /opt/picpeak/app/backend
sudo -u picpeak node scripts/reset-admin-password.js
```
@@ -458,11 +458,11 @@ sudo -u picpeak node scripts/reset-admin-password.js
- Installation: `/tmp/picpeak-setup-*.log`
2. **Documentation:**
- [Full Documentation](https://github.com/yourusername/wedding-photo-sharing)
- [Full Documentation](https://github.com/the-luap/picpeak)
- [Deployment Guide](./DEPLOYMENT_GUIDE.md)
3. **Support:**
- [GitHub Issues](https://github.com/yourusername/wedding-photo-sharing/issues)
- [GitHub Issues](https://github.com/the-luap/picpeak/issues)
- Include: Error messages, system info (`uname -a`), installation method
## 🔒 Security Best Practices
@@ -498,7 +498,7 @@ services:
### Native Optimization
```bash
# Increase Node.js memory
echo "NODE_OPTIONS=--max-old-space-size=2048" >> /opt/picpeak/backend/.env
echo "NODE_OPTIONS=--max-old-space-size=2048" >> /opt/picpeak/app/backend/.env
sudo systemctl restart picpeak-backend
```
@@ -540,4 +540,4 @@ sudo ./setup.sh --native \
---
**PicPeak Setup v1.0** | [Documentation](https://github.com/yourusername/wedding-photo-sharing) | [Support](https://github.com/yourusername/wedding-photo-sharing/issues)
**PicPeak Setup v1.0** | [Documentation](https://github.com/the-luap/picpeak) | [Support](https://github.com/the-luap/picpeak/issues)
+32 -24
View File
@@ -26,29 +26,37 @@ const config = {
production: {
client: process.env.DATABASE_CLIENT || 'pg',
connection: {
host: process.env.DB_HOST || 'db',
port: process.env.DB_PORT || 5432,
user: process.env.DB_USER || 'picpeak',
password: process.env.DB_PASSWORD,
database: process.env.DB_NAME || 'picpeak',
ssl: process.env.DB_SSL === 'true' ? { rejectUnauthorized: false } : false,
// Connection stability settings
connectionTimeoutMillis: 30000,
idleTimeoutMillis: 30000,
keepAlive: true,
keepAliveInitialDelayMillis: 0
},
pool: {
min: 5,
max: 25,
acquireTimeoutMillis: 60000,
createTimeoutMillis: 60000,
idleTimeoutMillis: 30000,
reapIntervalMillis: 1000,
createRetryIntervalMillis: 200,
propagateCreateError: false
},
// Support both Postgres and SQLite in production based on DATABASE_CLIENT
connection: (process.env.DATABASE_CLIENT || 'pg') === 'pg'
? {
host: process.env.DB_HOST || 'db',
port: process.env.DB_PORT || 5432,
user: process.env.DB_USER || 'picpeak',
password: process.env.DB_PASSWORD,
database: process.env.DB_NAME || 'picpeak',
ssl: process.env.DB_SSL === 'true' ? { rejectUnauthorized: false } : false,
// Connection stability settings
connectionTimeoutMillis: 30000,
idleTimeoutMillis: 30000,
keepAlive: true,
keepAliveInitialDelayMillis: 0
}
: {
filename: path.join(__dirname, process.env.DATABASE_PATH || './data/photo_sharing.db')
},
useNullAsDefault: (process.env.DATABASE_CLIENT || 'pg') !== 'pg',
pool: (process.env.DATABASE_CLIENT || 'pg') === 'pg'
? {
min: 5,
max: 25,
acquireTimeoutMillis: 60000,
createTimeoutMillis: 60000,
idleTimeoutMillis: 30000,
reapIntervalMillis: 1000,
createRetryIntervalMillis: 200,
propagateCreateError: false
}
: undefined,
migrations: {
directory: './migrations'
},
@@ -56,4 +64,4 @@ const config = {
}
};
module.exports = config[process.env.NODE_ENV || 'development'];
module.exports = config[process.env.NODE_ENV || 'development'];
@@ -0,0 +1,54 @@
/**
* Migration 041: Add external media reference support
* - events.source_mode: 'managed' | 'reference'
* - events.external_path: relative path under external media root
* - photos.source_origin: 'managed' | 'external'
* - photos.external_relpath: relative path within event.external_path
*/
const { addColumnIfNotExists } = require('../helpers');
exports.up = async function(knex) {
console.log('Running migration: 041_add_external_media');
// events.source_mode (default 'managed')
await addColumnIfNotExists(knex, 'events', 'source_mode', (table) => {
table.string('source_mode').notNullable().defaultTo('managed');
});
// events.external_path (nullable)
await addColumnIfNotExists(knex, 'events', 'external_path', (table) => {
table.text('external_path');
});
// photos.source_origin (default 'managed')
await addColumnIfNotExists(knex, 'photos', 'source_origin', (table) => {
table.string('source_origin').notNullable().defaultTo('managed');
});
// photos.external_relpath (nullable)
await addColumnIfNotExists(knex, 'photos', 'external_relpath', (table) => {
table.text('external_relpath');
});
// Helpful index for queries
try {
if (knex.client.config.client === 'pg') {
await knex.raw("CREATE INDEX IF NOT EXISTS photos_event_source_idx ON photos (event_id, source_origin)");
} else {
await knex.schema.alterTable('photos', (table) => {
table.index(['event_id', 'source_origin'], 'photos_event_source_idx');
});
}
} catch (e) {
console.log('Index creation skipped or failed (may already exist):', e.message);
}
console.log('Migration 041_add_external_media completed');
};
exports.down = async function(knex) {
console.log('Rollback: 041_add_external_media');
// Keep columns (safe rollback not removing data). Intentionally no-op.
};
+2 -2
View File
@@ -1,12 +1,12 @@
{
"name": "picpeak-backend",
"version": "1.0.109",
"version": "1.0.116",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "picpeak-backend",
"version": "1.0.109",
"version": "1.0.116",
"dependencies": {
"@aws-sdk/client-s3": "^3.850.0",
"@aws-sdk/lib-storage": "^3.850.0",
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "picpeak-backend",
"version": "1.0.109",
"version": "1.0.116",
"description": "Backend for PicPeak event photo sharing platform",
"main": "server.js",
"scripts": {
+20 -1
View File
@@ -12,6 +12,7 @@ logger.info('Server starting up', {
timestamp: new Date().toISOString()
});
const fs = require('fs');
const express = require('express');
const helmet = require('helmet');
const cors = require('cors');
@@ -143,6 +144,7 @@ const secureStatic = require('./src/middleware/secureStatic');
// Get storage path from environment or use default
const storagePath = process.env.STORAGE_PATH || path.join(__dirname, '../storage');
process.env.EXTERNAL_MEDIA_ROOT = process.env.EXTERNAL_MEDIA_ROOT || '/external-media';
// Static file serving for photos (protected)
app.use('/photos', require('./src/middleware/photoAuth'), setCorsHeaders, secureStatic(path.join(storagePath, 'events/active')));
@@ -199,7 +201,8 @@ app.get('/health', async (req, res) => {
// Routes
app.use('/api/auth', authRoutes);
app.use('/api/events', eventRoutes);
app.use('/api/events', eventRoutes);
app.use('/api/admin/external-media', require('./src/routes/adminExternalMedia'));
// Gallery routes - main routes first, then feedback routes
app.use('/api/gallery', galleryRoutes);
app.use('/api/gallery', require('./src/routes/galleryFeedback'));
@@ -217,6 +220,22 @@ app.use('/api/public', require('./src/routes/publicCMS'));
app.use('/api/images', require('./src/routes/protectedImages'));
app.use('/api/secure-images', secureImagesRoutes);
// Optional: Serve built frontend (native installs)
try {
const serveFrontend = process.env.SERVE_FRONTEND === 'true';
const frontendDir = process.env.FRONTEND_DIR || path.join(__dirname, '../frontend/dist');
if (serveFrontend && fs.existsSync(frontendDir)) {
logger.info(`Serving frontend from ${frontendDir}`);
app.use(express.static(frontendDir));
// SPA fallback for non-API routes
app.get([ '/', '/admin', '/admin/*', '/gallery/*' ], (req, res) => {
res.sendFile(path.join(frontendDir, 'index.html'));
});
}
} catch (e) {
logger.warn('Failed to enable frontend static serving', { error: e.message });
}
// Error handling middleware
app.use((err, req, res, next) => {
console.error('EXPRESS ERROR HANDLER:', err);
+22 -1
View File
@@ -1,7 +1,28 @@
const fs = require('fs');
const path = require('path');
const knex = require('knex');
const knexConfig = require('../../knexfile');
const logger = require('../utils/logger');
// Ensure SQLite directory exists when using file-based DB (native installs)
try {
const isPostgres = knexConfig && knexConfig.client === 'pg';
if (!isPostgres && knexConfig && knexConfig.connection) {
const filename = typeof knexConfig.connection === 'object'
? knexConfig.connection.filename
: (typeof knexConfig.connection === 'string' ? knexConfig.connection : null);
if (filename && typeof filename === 'string') {
const dir = path.dirname(filename);
if (dir && dir !== '.') {
fs.mkdirSync(dir, { recursive: true });
}
}
}
} catch (e) {
// Non-fatal: log and continue; SQLite will fail later if still missing
try { logger.warn('SQLite directory ensure failed', { error: e.message }); } catch (_) {}
}
// Create database connection with built-in retry logic
const db = knex(knexConfig);
@@ -312,4 +333,4 @@ async function logActivity(activityType, metadata = {}, eventId = null, actor =
}
}
module.exports = { db, initializeDatabase, logActivity, withRetry };
module.exports = { db, initializeDatabase, logActivity, withRetry };
+112
View File
@@ -0,0 +1,112 @@
const express = require('express');
const path = require('path');
const fs = require('fs').promises;
const { adminAuth } = require('../middleware/auth');
const { list, resolveExternalPath, getExternalMediaRoot } = require('../services/externalMediaService');
const { db, logActivity } = require('../database/db');
const router = express.Router();
// GET /api/admin/external-media/list?path=relative/dir
router.get('/list', adminAuth, async (req, res) => {
try {
const relPath = (req.query.path || '').replace(/^\/+/, '');
const result = await list(relPath);
res.json(result);
} catch (error) {
res.status(400).json({ error: 'Invalid path', details: error.message });
}
});
// Helper to recursively collect files under a directory, filtered by image extensions
async function walkDir(dir, baseDir) {
const results = [];
const entries = await fs.readdir(dir, { withFileTypes: true });
for (const e of entries) {
if (e.name.startsWith('.')) continue;
const full = path.join(dir, e.name);
if (e.isDirectory()) {
results.push(...await walkDir(full, baseDir));
} else if (e.isFile()) {
const ext = path.extname(e.name).toLowerCase();
if (['.jpg', '.jpeg', '.png', '.webp'].includes(ext)) {
const rel = path.relative(baseDir, full);
results.push({ full, rel, name: e.name });
}
}
}
return results;
}
// POST /api/admin/events/:id/import-external
// Body: { external_path: string, recursive?: boolean, map?: { individual?: string, collages?: string } }
router.post('/events/:id/import-external', adminAuth, async (req, res) => {
try {
const eventId = parseInt(req.params.id);
const { external_path, recursive = true, map = { individual: 'individual', collages: 'collages' } } = req.body || {};
if (!external_path) return res.status(400).json({ error: 'external_path is required' });
// Load event
const event = await db('events').where('id', eventId).first();
if (!event) return res.status(404).json({ error: 'Event not found' });
const baseAbs = resolveExternalPath({ external_path }, '');
// Collect files
const files = recursive ? await walkDir(baseAbs, baseAbs) : (await fs.readdir(baseAbs, { withFileTypes: true }))
.filter(e => e.isFile())
.map(e => ({ full: path.join(baseAbs, e.name), rel: e.name, name: e.name }))
.filter(f => ['.jpg', '.jpeg', '.png', '.webp'].includes(path.extname(f.name).toLowerCase()));
let imported = 0;
let skipped = 0;
// Insert photos
for (const f of files) {
// Infer type by subfolder names
const segs = f.rel.split(path.sep);
let type = 'individual';
if (segs[0] === map.collages) type = 'collage';
if (segs[0] === map.individual) type = 'individual';
try {
// Check if already exists (by external_relpath)
const exists = await db('photos')
.where({ event_id: eventId, external_relpath: f.rel })
.first();
if (exists) { skipped++; continue; }
const stats = await fs.stat(f.full);
const inserted = await db('photos')
.insert({
event_id: eventId,
filename: f.name,
// Keep path as a hint for legacy code but not used for resolution in external mode
path: path.join(event.slug, f.name),
thumbnail_path: null,
type,
size_bytes: stats.size,
source_origin: 'external',
external_relpath: f.rel
})
.returning('id');
imported += (inserted?.length ? 1 : 0);
} catch (e) {
skipped++;
}
}
// Update event fields
await db('events').where('id', eventId).update({ source_mode: 'reference', external_path });
// Queue thumbnail generation lazily by reading thumbnails via ensure endpoint as needed
await logActivity('external_import_completed', { event_id: eventId, imported, skipped, external_path }, eventId, { type: 'admin' });
res.json({ imported, skipped, thumbnailsQueued: 0 });
} catch (error) {
res.status(500).json({ error: 'Failed to import external media', details: error.message });
}
});
module.exports = router;
+11 -7
View File
@@ -606,8 +606,9 @@ router.get('/:eventId/photos/:photoId/download', adminAuth, async (req, res) =>
return res.status(404).json({ error: 'Photo not found' });
}
const storagePath = getStoragePath();
const filePath = path.join(storagePath, 'events/active', photo.path);
const { resolvePhotoFilePath } = require('../services/photoResolver');
const event = await db('events').where('id', eventId).first();
const filePath = resolvePhotoFilePath(event, photo);
// Check if file exists
try {
@@ -684,8 +685,10 @@ router.get('/:eventId/photos', adminAuth, async (req, res) => {
photos: photos.map(photo => ({
id: photo.id,
filename: photo.filename,
url: `/admin/events/${eventId}/photo/${photo.id}`,
thumbnail_url: photo.thumbnail_path ? `/admin/events/${eventId}/thumbnail/${photo.id}` : null,
// Use the correct admin photos router base for serving images
url: `/admin/photos/${eventId}/photo/${photo.id}`,
// Always expose a thumbnail URL; backend will generate on demand if missing
thumbnail_url: `/admin/photos/${eventId}/thumbnail/${photo.id}`,
type: photo.type,
category_id: photo.type,
category_name: photo.type === 'individual' ? 'Individual Photos' : 'Collages',
@@ -719,8 +722,9 @@ router.get('/:eventId/photo/:photoId', adminAuth, async (req, res) => {
return res.status(404).json({ error: 'Photo not found' });
}
const storagePath = getStoragePath();
const filePath = path.join(storagePath, 'events/active', photo.path);
const { resolvePhotoFilePath } = require('../services/photoResolver');
const event = await db('events').where('id', eventId).first();
const filePath = resolvePhotoFilePath(event, photo);
// Check if file exists
try {
@@ -802,4 +806,4 @@ router.get('/:eventId/debug', adminAuth, async (req, res) => {
}
});
module.exports = router;
module.exports = router;
@@ -0,0 +1,67 @@
const fs = require('fs').promises;
const path = require('path');
const { safePathJoin } = require('../utils/fileSecurityUtils');
function getExternalMediaRoot() {
return process.env.EXTERNAL_MEDIA_ROOT || '/external-media';
}
function isUnderRoot(p) {
const root = path.resolve(getExternalMediaRoot());
const resolved = path.resolve(p);
return resolved === root || resolved.startsWith(root + path.sep);
}
async function list(relativePath = '') {
const root = getExternalMediaRoot();
// Normalize and ensure safe join under root
const targetDir = safePathJoin(root, relativePath || '.');
const entries = [];
try {
const dirents = await fs.readdir(targetDir, { withFileTypes: true });
for (const d of dirents) {
// Skip hidden files and directories
if (d.name.startsWith('.')) continue;
const full = path.join(targetDir, d.name);
const stat = await fs.stat(full).catch(() => null);
if (!stat) continue;
if (d.isDirectory()) {
entries.push({ name: d.name, type: 'dir' });
} else if (d.isFile()) {
const ext = path.extname(d.name).toLowerCase();
if (['.jpg', '.jpeg', '.png', '.webp'].includes(ext)) {
entries.push({ name: d.name, type: 'file', size: stat.size, mtime: stat.mtime });
}
}
}
} catch (e) {
// Propagate errors for caller to handle (e.g., invalid path)
throw e;
}
const rootResolved = path.resolve(root);
const currentResolved = path.resolve(targetDir);
const canNavigateUp = currentResolved !== rootResolved;
// Return normalized relative path from root
const relFromRoot = path.relative(rootResolved, currentResolved);
return { path: relFromRoot, entries, canNavigateUp };
}
function resolveExternalPath(event, relpath) {
const root = getExternalMediaRoot();
const base = event?.external_path ? path.join(event.external_path) : '';
const combined = base ? path.join(base, relpath || '') : (relpath || '');
return safePathJoin(root, combined);
}
module.exports = {
getExternalMediaRoot,
isUnderRoot,
list,
resolveExternalPath,
};
+14 -3
View File
@@ -132,7 +132,8 @@ async function generateThumbnail(imagePath, options = {}) {
return path.relative(getStoragePath(), thumbnailPath);
} catch (error) {
logger.error(`Failed to generate thumbnail for ${filename}:`, error.message);
const msg = (error && error.message) ? error.message : String(error);
logger.error(`Failed to generate thumbnail for ${filename}: ${msg}`);
// Clean up any partially created file
try {
@@ -171,8 +172,18 @@ async function isThumbnailValid(thumbnailPath) {
* Regenerate thumbnail if it's broken or missing
*/
async function ensureThumbnail(photo) {
const storagePath = getStoragePath();
const originalPath = path.join(storagePath, 'events/active', photo.path);
const { db } = require('../database/db');
const { resolvePhotoFilePath } = require('./photoResolver');
let originalPath;
try {
const event = await db('events').where('id', photo.event_id).first();
originalPath = resolvePhotoFilePath(event, photo);
logger.info(`Ensuring thumbnail for photo ${photo.id} from source: ${originalPath}`);
} catch (e) {
const msg = (e && e.message) ? e.message : String(e);
logger.error(`Failed to resolve original path for thumbnail (photo ${photo.id}): ${msg}`);
return null;
}
// Check if thumbnail exists and is valid
if (photo.thumbnail_path) {
+44
View File
@@ -0,0 +1,44 @@
const path = require('path');
const { resolveExternalPath } = require('./externalMediaService');
const getStoragePath = () => process.env.STORAGE_PATH || path.join(__dirname, '../../../storage');
/**
* Resolve absolute photo file path based on event + photo origin
* Managed: storage/events/active + photo.path (legacy variants supported)
* External reference: EXTERNAL_MEDIA_ROOT + event.external_path + photo.external_relpath
*/
function resolvePhotoFilePath(event, photo) {
if (!event || !photo) throw new Error('resolvePhotoFilePath requires event and photo');
const mode = (event.source_mode || photo.source_origin || 'managed');
if (mode === 'reference' || photo.source_origin === 'external') {
if (!photo.external_relpath) {
throw new Error('Missing external_relpath for external photo');
}
// Normalize duplicate leaf segments (e.g., event.external_path ends with 'individual'
// and external_relpath starts with 'individual/') to avoid double segment like
// '/external-media/.../individual/individual/file.jpg'
let rel = photo.external_relpath;
try {
const lastSeg = path.basename(event.external_path || '');
const firstSeg = rel.split(path.sep)[0];
if (lastSeg && firstSeg && lastSeg === firstSeg) {
rel = rel.split(path.sep).slice(1).join(path.sep) || '';
}
} catch (_) {
// ignore normalization errors
}
return resolveExternalPath(event, rel);
}
const storagePath = getStoragePath();
if (photo.path && photo.path.startsWith('events/active/')) {
return path.join(storagePath, photo.path);
}
return path.join(storagePath, 'events/active', photo.path || '');
}
module.exports = {
resolvePhotoFilePath,
};
+2 -2
View File
@@ -1,12 +1,12 @@
{
"name": "picpeak-frontend",
"version": "1.0.109",
"version": "1.0.116",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "picpeak-frontend",
"version": "1.0.109",
"version": "1.0.116",
"dependencies": {
"@tanstack/react-query": "^5.0.0",
"@tiptap/extension-character-count": "^2.26.1",
+1 -1
View File
@@ -1,7 +1,7 @@
{
"name": "picpeak-frontend",
"private": true,
"version": "1.0.109",
"version": "1.0.116",
"type": "module",
"scripts": {
"dev": "vite",
@@ -15,6 +15,7 @@ import { parseISO } from 'date-fns';
import { toast } from 'react-toastify';
import { Card, Loading, Button } from '../common';
import { AdminAuthenticatedImage } from './AdminAuthenticatedImage';
import { feedbackService } from '../../services/feedback.service';
import { useLocalizedDate } from '../../hooks/useLocalizedDate';
@@ -129,15 +130,13 @@ export const FeedbackModerationPanel: React.FC<FeedbackModerationPanelProps> = (
<p className="mt-1 text-sm text-neutral-700">{item.comment_text || item.comment}</p>
{item.photo_id && (
<div className="mt-2 flex items-center gap-2">
<img
src={`/api/admin/photos/${eventId}/thumbnail/${item.photo_id}`}
alt={item.filename || 'Photo'}
className="w-16 h-16 object-cover rounded"
onError={(e) => {
// Hide image if thumbnail fails to load
(e.target as HTMLImageElement).style.display = 'none';
}}
/>
<div className="w-16 h-16 overflow-hidden rounded">
<AdminAuthenticatedImage
src={`/api/admin/photos/${eventId}/thumbnail/${item.photo_id}`}
alt={item.filename || 'Photo'}
className="w-16 h-16 object-cover rounded"
/>
</div>
<p className="text-xs text-neutral-500">
{t('feedback.onPhoto', 'On photo')}: {item.filename || item.photo_filename || `#${item.photo_id}`}
</p>
@@ -218,4 +217,4 @@ export const FeedbackModerationPanel: React.FC<FeedbackModerationPanelProps> = (
);
};
FeedbackModerationPanel.displayName = 'FeedbackModerationPanel';
FeedbackModerationPanel.displayName = 'FeedbackModerationPanel';
+346 -1
View File
@@ -36,6 +36,11 @@
"customize": "Anpassen",
"hide": "Ausblenden",
"unknown": "Unbekannt",
"notSet": "Nicht festgelegt",
"of": "von",
"up": "Nach oben",
"select": "Auswählen",
"selected": "Ausgewählt",
"chunk": "Teil"
},
"upload": {
@@ -50,6 +55,10 @@
"uploadFailed": "Upload fehlgeschlagen",
"someFilesFailed": "Einige Dateien konnten nicht hochgeladen werden",
"uploadPhotos": "Fotos hochladen",
"importExternal": "Aus externem Ordner importieren",
"externalImportInfo": "Alle Bilder aus dem ausgewählten Ordner werden importiert.",
"selectExternalFolder": "Externen Ordner unter /external-media auswählen",
"importFromSelectedFolder": "Ausgewählten Ordner importieren",
"maxFilesReached": "Maximal 500 Dateien erlaubt",
"someFilesSkipped": "Einige Dateien wurden übersprungen (500 Dateien Limit)",
"tooManyFiles": "Maximal 500 Dateien können gleichzeitig hochgeladen werden",
@@ -66,6 +75,342 @@
"backup": "Backup & Wiederherstellung",
"cmsPages": "CMS-Seiten"
},
"backup": {
"external": {
"warning": {
"title": "Externe Medien ausgeschlossen",
"body": "Diese Installation referenziert Fotos aus /external-media. Diese Originale sind von Backups ausgeschlossen. Thumbnails und Datenbank werden weiterhin gesichert."
}
},
"title": "Backup-Verwaltung",
"subtitle": "System-Backups verwalten, automatische Backups konfigurieren und aus früheren Backups wiederherstellen.",
"tabs": {
"dashboard": "Dashboard",
"configuration": "Konfiguration",
"history": "Backup-Verlauf",
"restore": "Wiederherstellen"
},
"status": {
"inProgress": "Backup wird ausgeführt...",
"lastBackup": "Letztes Backup",
"noBackups": "Keine Backups gefunden",
"nextBackup": "Nächstes Backup",
"notScheduled": "Nicht geplant",
"enabled": "Aktiviert",
"disabled": "Deaktiviert"
},
"actions": {
"runBackupNow": "Backup jetzt starten",
"starting": "Starte...",
"running": "Läuft...",
"testConnection": "Verbindung testen",
"save": "Konfiguration speichern",
"delete": "Löschen",
"view": "Details anzeigen",
"download": "Herunterladen",
"refresh": "Aktualisieren"
},
"dashboard": {
"backupHealth": "Backup-Gesundheit",
"health": {
"title": "Backup-Gesundheit"
},
"healthMessages": {
"noBackups": "Keine Backups gefunden",
"lastBackupFailed": "Letztes Backup fehlgeschlagen",
"upToDate": "Backup ist aktuell",
"recent": "Backup ist kürzlich",
"gettingOld": "Backup wird alt",
"outdated": "Backup ist veraltet"
},
"stats": {
"totalBackups": "Gesamt-Backups",
"backupSize": "Backup-Größe",
"lastDuration": "Letzte Dauer",
"backupStatus": "Backup-Status",
"last": "Letztes",
"files": "Dateien",
"minutes": "{{count}}m",
"active": "Aktiv",
"inactive": "Inaktiv",
"noBackupsYet": "Noch keine Backups"
},
"recentActivity": {
"title": "Letzte Backup-Aktivitäten"
},
"notConfigured": {
"title": "Backup nicht konfiguriert",
"message": "Bitte konfigurieren Sie die Backup-Einstellungen im Tab \"Konfiguration\", bevor Sie Backups ausführen."
},
"coverage": {
"title": "Backup-Abdeckung",
"database": "Datenbank",
"photos": "Fotos",
"archives": "Archive",
"systemFiles": "Systemdateien",
"included": "Enthalten",
"excluded": "Ausgeschlossen",
"optional": "Optional"
},
"storageDestination": "Speicherziel",
"nextScheduledBackup": "Nächstes geplantes Backup",
"backupType": "{{type}}-Backup",
"noDestinationSet": "Kein Ziel gesetzt"
},
"configuration": {
"enableBackup": "Automatische Backups aktivieren",
"enableBackupHelp": "Backups automatisch gemäß Zeitplan erstellen",
"destinationType": "Backup-Ziel",
"destinationTypes": {
"local": {
"name": "Lokaler Speicher",
"description": "Backups auf dem lokalen Dateisystem speichern"
},
"rsync": {
"name": "Remote-Server (Rsync)",
"description": "Backups per SSH/Rsync auf einen entfernten Server synchronisieren"
},
"s3": {
"name": "S3-kompatibler Speicher",
"description": "Backups in Amazon S3 oder kompatiblen Objektspeicher ablegen"
}
},
"fields": {
"destinationPath": "Zielpfad",
"destinationPathHelp": "Lokaler Verzeichnispfad für Backups",
"destinationPathPlaceholder": "/pfad/zum/backup/verzeichnis",
"rsyncHost": "Remote Host",
"rsyncHostPlaceholder": "backup.example.com",
"rsyncUser": "Benutzer",
"rsyncUserPlaceholder": "backupuser",
"rsyncPath": "Remote-Pfad",
"rsyncPathPlaceholder": "/pfad/auf/server",
"rsyncSshKey": "SSH-Schlüssel",
"rsyncSshKeyPlaceholder": "Privater SSH-Schlüssel (PEM)",
"rsyncSshKeyHelp": "Fügen Sie den privaten SSH-Schlüssel im PEM-Format ein.",
"s3Endpoint": "S3-Endpunkt-URL",
"s3EndpointHelp": "z. B. https://s3.amazonaws.com oder Ihr MinIO-Endpunkt",
"s3Bucket": "Bucket-Name",
"s3Region": "Region",
"s3AccessKey": "Access Key ID",
"s3SecretKey": "Secret Access Key"
},
"schedule": {
"title": "Zeitplan",
"scheduleType": "Zeitplantyp",
"customCron": "Eigener Cron-Ausdruck",
"customCronHelp": "Cron-Ausdruck für benutzerdefinierten Zeitplan",
"retention": "Aufbewahrung (Tage)",
"retentionHelp": "Anzahl der Tage, nach denen alte Backups automatisch gelöscht werden"
},
"whatToBackup": {
"title": "Was soll gesichert werden",
"database": "Datenbank",
"databaseHelp": "Datenbank (Einstellungen, Events, Benutzer)",
"photos": "Fotos",
"photosHelp": "Aktive Galeriefotos sichern",
"archives": "Archive",
"archivesHelp": "Archivierte ZIP-Dateien",
"thumbnails": "Thumbnails",
"thumbnailsHelp": "Generierte Vorschaubilder"
},
"advancedOptions": {
"title": "Erweiterte Optionen",
"compression": "Kompression",
"compressionHelp": "Backups komprimieren, um Speicherplatz zu sparen",
"encryption": "Verschlüsselung",
"encryptionHelp": "Backups mit einer Passphrase verschlüsseln",
"encryptionPassphrase": "Verschlüsselungs-Passphrase",
"encryptionPassphraseHelp": "Passphrase zum Verschlüsseln/Entschlüsseln der Backups"
},
"savingSettings": "Einstellungen werden gespeichert...",
"saveSettings": "Einstellungen speichern"
},
"history": {
"columns": {
"status": "Status",
"dateTime": "Datum & Uhrzeit",
"type": "Typ",
"size": "Größe",
"duration": "Dauer",
"actions": "Aktionen"
},
"details": "Details",
"statistics": "Statistiken",
"errors": "Fehler",
"backupDetails": {
"backupId": "Backup-ID",
"startTime": "Startzeit",
"endTime": "Endzeit",
"destination": "Ziel",
"filesProcessed": "Verarbeitete Dateien",
"totalSize": "Gesamtgröße",
"compressionRatio": "Kompressionsrate",
"errorLog": "Fehlerprotokoll",
"noErrors": "Keine Fehler aufgetreten"
},
"pagination": {
"showing": "Zeige {{from}}{{to}} von {{total}} Backups",
"previous": "Zurück",
"next": "Weiter"
},
"filter": {
"allStatus": "Alle Status",
"completed": "Abgeschlossen",
"failed": "Fehlgeschlagen",
"running": "Läuft",
"partial": "Teilweise"
},
"noBackupsFound": "Keine Backups gefunden",
"backupsWillAppear": "Backups erscheinen hier, sobald sie erstellt wurden",
"messages": {
"deleteSuccess": "Backup erfolgreich gelöscht"
}
},
"restore": {
"steps": {
"selectSource": "Quelle auswählen",
"chooseBackup": "Backup wählen",
"restoreOptions": "Wiederherstellungsoptionen",
"reviewConfirm": "Prüfen & Bestätigen",
"progress": "Fortschritt"
},
"source": {
"title": "Backup-Quelle auswählen",
"subtitle": "Wählen Sie, woher das Backup wiederhergestellt werden soll",
"local": {
"name": "Lokales Backup",
"description": "Vom lokalen Dateisystem wiederherstellen"
},
"s3": {
"name": "S3-Speicher",
"description": "Aus S3-Bucket wiederherstellen"
},
"upload": {
"name": "Backup hochladen",
"description": "Eine Backup-Datei hochladen",
"comingSoon": "Upload-Funktion folgt in Kürze"
},
"configuration": {
"s3": "S3-Konfiguration",
"endpoint": "S3-Endpunkt-URL",
"bucket": "Bucket-Name",
"accessKey": "Access Key ID",
"secretKey": "Secret Access Key"
}
},
"backup": {
"title": "Backup zum Wiederherstellen wählen",
"subtitle": "Aus verfügbaren Backups auswählen",
"noBackupsFound": "Keine Backups in der gewählten Quelle gefunden",
"encrypted": "Verschlüsseltes Backup",
"encryptedMessage": "Zum Wiederherstellen dieses Backups wird die Verschlüsselungs-Passphrase benötigt.",
"enterPassphrase": "Verschlüsselungs-Passphrase eingeben",
"at": "um"
},
"restoreTypes": {
"full": {
"name": "Vollständige Wiederherstellung",
"description": "Alles wiederherstellen (Datenbank, Fotos und Archive)",
"warning": "Dies ersetzt alle aktuellen Daten"
},
"database": {
"name": "Nur Datenbank",
"description": "Nur die Datenbank wiederherstellen (Einstellungen, Events, Benutzer)",
"warning": "Aktuelle Datenbank wird ersetzt"
},
"files": {
"name": "Nur Dateien",
"description": "Nur Fotos und Archive wiederherstellen",
"warning": "Vorhandene Dateien können überschrieben werden"
},
"selective": {
"name": "Selektive Wiederherstellung",
"description": "Bestimmte Elemente zur Wiederherstellung auswählen",
"warning": "Es werden nur ausgewählte Elemente wiederhergestellt"
}
},
"options": {
"title": "Wiederherstellungsoptionen",
"subtitle": "Auswählen, was wiederhergestellt werden soll",
"additionalOptions": {
"title": "Zusätzliche Optionen",
"skipPreBackup": "Vorab-Backup überspringen",
"skipPreBackupHelp": "Standardmäßig wird vor der Wiederherstellung ein Backup erstellt. Aktivieren, um dies zu überspringen.",
"force": "Wiederherstellung erzwingen",
"forceHelp": "Sicherheitsprüfungen und Warnungen überschreiben (mit Vorsicht verwenden)"
}
},
"confirmation": {
"title": "Prüfen & Bestätigen",
"subtitle": "Bitte prüfen Sie Ihre Wiederherstellungskonfiguration",
"validation": {
"passed": "Validierung bestanden",
"failed": "Validierung fehlgeschlagen",
"checking": "Wiederherstellungskonfiguration wird geprüft..."
},
"spaceCheck": {
"title": "Speicherplatz",
"required": "Erforderlich",
"available": "Verfügbar",
"insufficient": "Nicht genügend Speicherplatz"
},
"summary": {
"title": "Zusammenfassung",
"source": "Quelle",
"backupDate": "Backup-Datum",
"restoreType": "Art der Wiederherstellung",
"preBackup": "Vorab-Backup",
"enabled": "Aktiviert",
"skipped": "Übersprungen"
},
"warning": {
"title": "Wichtiger Hinweis",
"message": "Diese Wiederherstellung ersetzt bestehende Daten. Stellen Sie sicher, dass Sie ein aktuelles Backup haben. Dieser Vorgang kann nicht rückgängig gemacht werden."
}
},
"progress": {
"title": "Fortschritt der Wiederherstellung",
"inProgress": "Wiederherstellung läuft...",
"completed": "Wiederherstellung abgeschlossen",
"overallProgress": "Gesamtfortschritt",
"current": "Aktuell",
"statusDetails": "Statusdetails",
"restoreLogs": "Wiederherstellungs-Logs",
"steps": {
"completed": "Abgeschlossen",
"running": "Läuft",
"failed": "Fehlgeschlagen",
"pending": "Ausstehend"
},
"success": {
"title": "Wiederherstellung erfolgreich abgeschlossen",
"message": "Ihre Daten wurden wiederhergestellt. Bitte prüfen Sie, ob alles korrekt funktioniert."
}
},
"actions": {
"back": "Zurück",
"next": "Weiter",
"startRestore": "Wiederherstellung starten",
"starting": "Starte...",
"validating": "Validiere...",
"startNewRestore": "Neue Wiederherstellung starten"
},
"messages": {
"restoreStarted": "Wiederherstellung erfolgreich gestartet"
}
},
"messages": {
"backupStarted": "Backup erfolgreich gestartet",
"backupFailed": "Backup konnte nicht gestartet werden",
"configUpdated": "Backup-Konfiguration aktualisiert",
"configUpdateFailed": "Konfiguration konnte nicht aktualisiert werden",
"backupDeleted": "Backup erfolgreich gelöscht",
"deleteFailed": "Backup konnte nicht gelöscht werden",
"testEmailSent": "Verbindung erfolgreich getestet!",
"testEmailFailed": "Verbindungstest fehlgeschlagen"
}
},
"archives": {
"title": "Archive",
"subtitle": "Archivierte Fotogalerien verwalten",
@@ -1437,4 +1782,4 @@
"poweredBy": "Bereitgestellt von PicPeak",
"devModeHint": "Entwicklungsmodus: E-Mail: admin@example.com, Passwort: admin123"
}
}
}
+16 -1
View File
@@ -36,6 +36,11 @@
"customize": "Customize",
"hide": "Hide",
"unknown": "Unknown",
"notSet": "Not set",
"of": "of",
"up": "Up",
"select": "Select",
"selected": "Selected",
"chunk": "Chunk"
},
"upload": {
@@ -50,6 +55,10 @@
"uploadFailed": "Upload failed",
"someFilesFailed": "Some files failed to upload",
"uploadPhotos": "Upload Photos",
"importExternal": "Import from External Folder",
"externalImportInfo": "All pictures from the selected folder will be imported.",
"selectExternalFolder": "Select external folder under /external-media",
"importFromSelectedFolder": "Import from selected folder",
"maxFilesReached": "Maximum 500 files allowed",
"someFilesSkipped": "Some files were skipped (500 file limit)",
"tooManyFiles": "Maximum 500 files can be uploaded at once",
@@ -973,6 +982,12 @@
"pageUpdated": "Page updated successfully"
},
"backup": {
"external": {
"warning": {
"title": "External media excluded",
"body": "This installation references photos from /external-media. These originals are excluded from backups. Thumbnails and database are still backed up."
}
},
"title": "Backup Management",
"subtitle": "Manage system backups, configure automated backups, and restore from previous backups.",
"tabs": {
@@ -1496,4 +1511,4 @@
"poweredBy": "Powered by PicPeak",
"devModeHint": "Development Mode: Use email: admin@example.com, password: admin123"
}
}
}
@@ -28,9 +28,68 @@ import { EventCategoryManager, AdminPhotoGrid, AdminPhotoViewer, PhotoFilters, P
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { eventsService } from '../../services/events.service';
import { archiveService } from '../../services/archive.service';
import { externalMediaService } from '../../services/externalMedia.service';
import { photosService, AdminPhoto } from '../../services/photos.service';
import { feedbackService, FeedbackSettings as FeedbackSettingsType } from '../../services/feedback.service';
import { ThemeConfig, GALLERY_THEME_PRESETS } from '../../types/theme.types';
import { useTranslation } from 'react-i18next';
const ExternalFolderPicker: React.FC<{ value: string; onChange: (p: string) => void }> = ({ value, onChange }) => {
const { t } = useTranslation();
const [entries, setEntries] = useState<{ path: string; entries: any[]; canNavigateUp: boolean } | null>(null);
const [loading, setLoading] = useState(false);
const [currentPath, setCurrentPath] = useState<string>(value || '');
const load = async (p: string) => {
try {
setLoading(true);
const res = await externalMediaService.list(p);
setEntries(res);
setCurrentPath(res.path);
} finally {
setLoading(false);
}
};
useEffect(() => { load(currentPath || ''); }, []);
const navigateUp = () => {
if (!entries?.canNavigateUp) return;
const parts = (entries.path || '').split('/').filter(Boolean);
parts.pop();
load(parts.join('/'));
};
return (
<div className="mt-2 border rounded-lg p-3">
<div className="flex items-center justify-between mb-2">
<div className="text-sm text-neutral-600">/external-media/{entries?.path || ''}</div>
<div className="flex gap-2">
<button className="text-sm underline" onClick={navigateUp} disabled={!entries?.canNavigateUp}>{t('common.up', 'Up')}</button>
<button className="text-sm underline" onClick={() => onChange(entries?.path || '')}>{t('common.select', 'Select')}</button>
</div>
</div>
{loading ? (
<div className="text-sm text-neutral-500">{t('common.loading', 'Loading...')}</div>
) : (
<div className="grid grid-cols-2 md:grid-cols-3 gap-2">
{entries?.entries?.filter((e: any) => e.type === 'dir').map((e: any) => (
<button
key={e.name}
onClick={() => load([entries?.path, e.name].filter(Boolean).join('/'))}
className="px-3 py-2 border rounded text-left hover:bg-neutral-50"
>
📁 {e.name}
</button>
))}
</div>
)}
{value && (
<div className="mt-2 text-xs text-neutral-600">{t('common.selected', 'Selected')}: /external-media/{value}</div>
)}
</div>
);
};
export const EventDetailsPage: React.FC = () => {
const { id } = useParams<{ id: string }>();
@@ -67,7 +126,10 @@ export const EventDetailsPage: React.FC = () => {
});
const [copiedLink, setCopiedLink] = useState(false);
const [showPhotoUpload, setShowPhotoUpload] = useState(false);
const [showExternalImport, setShowExternalImport] = useState(false);
const [activeTab, setActiveTab] = useState<'overview' | 'photos' | 'categories'>('overview');
const [externalPath, setExternalPath] = useState<string>('');
const [importing, setImporting] = useState<boolean>(false);
const [selectedPhoto, setSelectedPhoto] = useState<{ photo: AdminPhoto; index: number } | null>(null);
const [showPasswordReset, setShowPasswordReset] = useState(false);
const [currentTheme, setCurrentTheme] = useState<ThemeConfig | null>(null);
@@ -598,6 +660,15 @@ export const EventDetailsPage: React.FC = () => {
</div>
) : (
<dl className="space-y-4">
<div>
<dt className="text-sm font-medium text-neutral-500">Source Mode</dt>
<dd className="mt-1 text-sm text-neutral-900">
{event.source_mode === 'reference' ? 'Reference (external folder)' : 'Managed (upload)'}
{event.source_mode === 'reference' && event.external_path ? (
<span className="text-neutral-500 ml-2">/external-media/{event.external_path}</span>
) : null}
</dd>
</div>
<div>
<dt className="text-sm font-medium text-neutral-500">{t('events.welcomeMessage')}</dt>
<dd className="mt-1 text-sm text-neutral-900">
@@ -951,6 +1022,17 @@ export const EventDetailsPage: React.FC = () => {
>
{t('events.uploadPhotos')}
</Button>
{event.source_mode === 'reference' && (
<div className="ml-3">
<Button
variant="outline"
size="sm"
onClick={() => setShowExternalImport(true)}
>
{t('events.importExternal', 'Import from External Folder')}
</Button>
</div>
)}
</div>
{/* Photo Grid */}
@@ -1024,6 +1106,59 @@ export const EventDetailsPage: React.FC = () => {
/>
)}
{/* External Import Modal */}
{showExternalImport && (
<div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4">
<Card className="max-w-2xl w-full">
<div className="flex items-center justify-between mb-4">
<h2 className="text-xl font-semibold text-neutral-900">{t('events.importExternal', 'Import from External Folder')}</h2>
<button onClick={() => setShowExternalImport(false)} className="text-neutral-400 hover:text-neutral-600">
<X className="w-5 h-5" />
</button>
</div>
<div className="mb-3 text-sm text-neutral-700">
{t('events.externalImportInfo', 'All pictures from the selected folder will be imported.')}
</div>
<div className="mb-2 text-sm text-neutral-700">
{t('events.selectExternalFolder', 'Select external folder under /external-media')}
</div>
<ExternalFolderPicker value={externalPath || event.external_path || ''} onChange={setExternalPath} />
<div className="mt-4 flex justify-end gap-2">
<Button variant="outline" onClick={() => setShowExternalImport(false)}>
{t('common.cancel')}
</Button>
<Button
variant="primary"
isLoading={importing}
onClick={async () => {
try {
setImporting(true);
const selected = externalPath || event.external_path || '';
if (!selected) {
toast.error(t('errors.somethingWentWrong', 'Something went wrong'));
return;
}
await externalMediaService.importEvent(parseInt(id!), selected, { recursive: true });
toast.success(t('toast.saveSuccess'));
queryClient.invalidateQueries({ queryKey: ['admin-event', id] });
queryClient.invalidateQueries({ queryKey: ['admin-event-photos', id] });
setShowExternalImport(false);
} catch (e: any) {
toast.error(e?.response?.data?.error || 'Import failed');
} finally {
setImporting(false);
}
}}
>
{t('events.importFromSelectedFolder', 'Import from selected folder')}
</Button>
</div>
</Card>
</div>
)}
</div>
);
};
+9 -10
View File
@@ -20,6 +20,7 @@ import { toast } from 'react-toastify';
import { format } from 'date-fns';
import { Button, Card, Loading } from '../../components/common';
import { AdminAuthenticatedImage } from '../../components/admin/AdminAuthenticatedImage';
import { FeedbackSettings } from '../../components/admin';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { eventsService } from '../../services/events.service';
@@ -251,15 +252,13 @@ export const EventFeedbackPage: React.FC = () => {
<Card key={item.id} className="overflow-hidden">
<div className="p-4 flex items-start gap-4">
{item.photo_id && (
<img
src={`/api/admin/photos/${eventId}/thumbnail/${item.photo_id}`}
alt={item.filename || 'Photo'}
className="w-16 h-16 object-cover rounded"
onError={(e) => {
// Hide image if thumbnail fails to load
(e.target as HTMLImageElement).style.display = 'none';
}}
/>
<div className="w-16 h-16 overflow-hidden rounded">
<AdminAuthenticatedImage
src={`/api/admin/photos/${eventId}/thumbnail/${item.photo_id}`}
alt={item.filename || 'Photo'}
className="w-16 h-16 object-cover rounded"
/>
</div>
)}
<div className="flex-1">
<div className="flex items-start justify-between">
@@ -528,4 +527,4 @@ export const EventFeedbackPage: React.FC = () => {
)}
</div>
);
};
};
@@ -0,0 +1,22 @@
import { api } from '../config/api';
export interface ExternalEntry { name: string; type: 'dir' | 'file'; size?: number; mtime?: string }
export const externalMediaService = {
async list(pathRel: string = ''): Promise<{ path: string; entries: ExternalEntry[]; canNavigateUp: boolean }> {
const params = new URLSearchParams();
if (pathRel) params.set('path', pathRel);
const res = await api.get(`/admin/external-media/list?${params.toString()}`);
return res.data;
},
async importEvent(eventId: number, externalPath: string, options?: { recursive?: boolean; map?: { individual?: string; collages?: string } }): Promise<{ imported: number; skipped: number; thumbnailsQueued: number }> {
const res = await api.post(`/admin/external-media/events/${eventId}/import-external`, {
external_path: externalPath,
recursive: options?.recursive ?? true,
map: options?.map
});
return res.data;
}
}
+3 -2
View File
@@ -45,7 +45,8 @@ class PhotosService {
}
const queryString = params.toString();
const url = `/admin/events/${eventId}/photos${queryString ? `?${queryString}` : ''}`;
// Use admin photos router for listing to ensure URL alignment with media/thumbnail endpoints
const url = `/admin/photos/${eventId}/photos${queryString ? `?${queryString}` : ''}`;
const response = await api.get(url);
@@ -96,4 +97,4 @@ class PhotosService {
}
}
export const photosService = new PhotosService();
export const photosService = new PhotosService();
+93 -30
View File
@@ -13,7 +13,7 @@ IFS=$'\n\t'
# Script configuration
readonly SCRIPT_VERSION="2.0.0"
readonly APP_NAME="PicPeak"
readonly REPO_URL="https://github.com/yourusername/wedding-photo-sharing"
readonly REPO_URL="https://github.com/the-luap/picpeak.git"
readonly NODE_VERSION="20"
readonly MIN_RAM_DOCKER=2048
readonly MIN_RAM_NATIVE=1024
@@ -61,6 +61,23 @@ UNINSTALL_MODE=false
# Helper Functions
################################################################################
# Run a command as the application user, even if sudo is not available
run_as_user() {
local cmd="$*"
if [[ "$(id -u)" -ne 0 ]]; then
# Already non-root; just run
bash -lc "$cmd"
return $?
fi
if command_exists sudo; then
sudo -H -u "$NATIVE_APP_USER" bash -lc "$cmd"
elif command_exists runuser; then
runuser -u "$NATIVE_APP_USER" -- bash -lc "$cmd"
else
su -s /bin/bash - "$NATIVE_APP_USER" -c "$cmd"
fi
}
print_banner() {
echo -e "${PURPLE}"
echo "╔════════════════════════════════════════════════════════════════════════╗"
@@ -110,11 +127,16 @@ generate_jwt_secret() {
}
get_available_ram_mb() {
if command_exists free; then
free -m | awk '/^Mem:/{print $2}'
else
echo "0"
# Prefer /proc/meminfo (always available on Linux), fallback to free(1)
if [[ -r /proc/meminfo ]]; then
awk '/^MemTotal:/ { printf "%d\n", $2/1024 }' /proc/meminfo
return
fi
if command_exists free; then
free -m | awk '/^Mem:/ {print $2}'
return
fi
echo "0"
}
get_available_disk_gb() {
@@ -551,21 +573,48 @@ setup_native_installation() {
# Create application directory
log_step "Creating application directory..."
mkdir -p "$NATIVE_APP_DIR"/{backend,events/{active,archived},logs,config}
mkdir -p "$NATIVE_APP_DIR"/{app,events/{active,archived},logs,config}
chown -R $NATIVE_APP_USER:$NATIVE_APP_USER "$NATIVE_APP_DIR"
# Clone repository
log_step "Downloading PicPeak..."
if [[ -d "$NATIVE_APP_DIR/backend/.git" ]]; then
cd "$NATIVE_APP_DIR/backend"
git pull
if [[ -d "$NATIVE_APP_DIR/app/.git" ]]; then
cd "$NATIVE_APP_DIR/app"
# Ensure correct remote and update even if history was rewritten
run_as_user "git config --global --add safe.directory $NATIVE_APP_DIR/app" || true
run_as_user "git remote set-url origin $REPO_URL" || true
run_as_user "git fetch --all --prune" || true
# Prefer checking out remote main and hard resetting to avoid merge prompts
if ! run_as_user "git checkout -B main origin/main"; then
run_as_user "git checkout main" || true
run_as_user "git reset --hard origin/main"
fi
else
git clone "$REPO_URL" "$NATIVE_APP_DIR/backend"
run_as_user "git clone $REPO_URL $NATIVE_APP_DIR/app" || {
run_as_user "git config --global --add safe.directory $NATIVE_APP_DIR/app"
run_as_user "git clone $REPO_URL $NATIVE_APP_DIR/app"
}
fi
# Install dependencies
log_step "Installing dependencies..."
cd "$NATIVE_APP_DIR/backend"
# The repository root contains both backend/ and frontend/
# Install backend production dependencies
cd "$NATIVE_APP_DIR/app/backend"
npm install --production
# Ensure SQLite data directory exists for native installs
mkdir -p "$NATIVE_APP_DIR/app/backend/data"
# Build frontend for native serving
log_step "Building frontend..."
if [[ -d "$NATIVE_APP_DIR/app/frontend" ]]; then
cd "$NATIVE_APP_DIR/app/frontend"
# Try ci (faster/clean) then fallback to install
run_as_user "npm ci --include=dev" || run_as_user "npm install"
run_as_user "npm run build"
else
log_warn "Frontend directory not found; admin UI will not be served by backend"
fi
# Generate secrets
local jwt_secret=$(generate_jwt_secret)
@@ -573,7 +622,7 @@ setup_native_installation() {
# Create .env file
log_step "Creating configuration..."
cat > "$NATIVE_APP_DIR/backend/.env" <<EOF
cat > "$NATIVE_APP_DIR/app/backend/.env" <<EOF
# PicPeak Native Configuration
# Generated: $(date)
@@ -587,11 +636,12 @@ ADMIN_USERNAME=admin
ADMIN_PASSWORD=$ADMIN_PASSWORD
ADMIN_EMAIL=$ADMIN_EMAIL
# Database
DATABASE_PATH=$NATIVE_APP_DIR/backend/database.sqlite
# Database (native uses SQLite by default)
DATABASE_CLIENT=sqlite3
DATABASE_PATH=$NATIVE_APP_DIR/app/backend/data/photo_sharing.db
# Storage
PHOTOS_DIR=$NATIVE_APP_DIR/events
# Storage root (thumbnails/uploads live under this path)
STORAGE_PATH=$NATIVE_APP_DIR
# Email
SMTP_ENABLED=${SMTP_HOST:+true}
@@ -614,16 +664,20 @@ DEFAULT_EXPIRY_DAYS=30
# Logging
LOG_DIR=$NATIVE_APP_DIR/logs
LOG_LEVEL=info
# Frontend serving (native installs)
SERVE_FRONTEND=true
FRONTEND_DIR=$NATIVE_APP_DIR/app/frontend/dist
EOF
# Set permissions
chown -R $NATIVE_APP_USER:$NATIVE_APP_USER "$NATIVE_APP_DIR"
chmod 600 "$NATIVE_APP_DIR/backend/.env"
chmod 600 "$NATIVE_APP_DIR/app/backend/.env"
# Run database migrations
log_step "Initializing database..."
cd "$NATIVE_APP_DIR/backend"
sudo -u $NATIVE_APP_USER npm run migrate
cd "$NATIVE_APP_DIR/app/backend"
run_as_user "npm run migrate"
# Create systemd services
create_systemd_services
@@ -654,7 +708,7 @@ After=network.target
[Service]
Type=simple
User=$NATIVE_APP_USER
WorkingDirectory=$NATIVE_APP_DIR/backend
WorkingDirectory=$NATIVE_APP_DIR/app/backend
Environment="NODE_ENV=production"
ExecStart=/usr/bin/node server.js
Restart=always
@@ -675,7 +729,7 @@ After=network.target picpeak-backend.service
[Service]
Type=simple
User=$NATIVE_APP_USER
WorkingDirectory=$NATIVE_APP_DIR/backend
WorkingDirectory=$NATIVE_APP_DIR/app/backend
Environment="NODE_ENV=production"
ExecStart=/usr/bin/node src/services/workerManager.js
Restart=always
@@ -878,8 +932,8 @@ print_success_message() {
echo
echo "📚 Documentation:"
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo "Setup Guide: https://github.com/yourusername/wedding-photo-sharing/blob/main/SIMPLE_SETUP.md"
echo "Full Docs: https://github.com/yourusername/wedding-photo-sharing"
echo "Setup Guide: https://github.com/the-luap/picpeak/blob/main/SIMPLE_SETUP.md"
echo "Full Docs: https://github.com/the-luap/picpeak"
echo
echo -e "${GREEN}✨ Setup complete! Visit the admin panel to start creating galleries.${NC}"
}
@@ -935,17 +989,26 @@ update_native_installation() {
systemctl stop picpeak-backend picpeak-workers
# Backup current configuration
cp "$NATIVE_APP_DIR/backend/.env" "$NATIVE_APP_DIR/backend/.env.backup-$(date +%Y%m%d-%H%M%S)"
if [[ -f "$NATIVE_APP_DIR/app/backend/.env" ]]; then
cp "$NATIVE_APP_DIR/app/backend/.env" "$NATIVE_APP_DIR/app/backend/.env.backup-$(date +%Y%m%d-%H%M%S)"
fi
# Pull latest code
cd "$NATIVE_APP_DIR/backend"
sudo -u $NATIVE_APP_USER git pull
cd "$NATIVE_APP_DIR/app"
run_as_user "git config --global --add safe.directory $NATIVE_APP_DIR/app" || true
run_as_user "git remote set-url origin $REPO_URL" || true
run_as_user "git fetch --all --prune"
if ! run_as_user "git checkout -B main origin/main"; then
run_as_user "git checkout main" || true
run_as_user "git reset --hard origin/main"
fi
# Update dependencies
sudo -u $NATIVE_APP_USER npm install --production
# Update backend dependencies
cd "$NATIVE_APP_DIR/app/backend"
run_as_user "npm install --production"
# Run migrations
sudo -u $NATIVE_APP_USER npm run migrate
run_as_user "npm run migrate"
# Restart services
systemctl start picpeak-backend picpeak-workers
@@ -1181,4 +1244,4 @@ main() {
}
# Run main function
main "$@"
main "$@"