Compare commits
24 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| ad9c6d63d3 | |||
| 8c77b30de6 | |||
| e51347d0a1 | |||
| 71e7179145 | |||
| bda76ff513 | |||
| 097ce2c205 | |||
| 1d8be3d840 | |||
| aebb8e66cb | |||
| ed2a278da2 | |||
| db2f5da66a | |||
| 19f8facc49 | |||
| b03760ab01 | |||
| 526dcd8dfc | |||
| 5b2561b6f1 | |||
| 3a6d06192a | |||
| 4b64b80b20 | |||
| ff89f96e31 | |||
| 465f997752 | |||
| 6948aaa92a | |||
| 4c7b49a5f6 | |||
| 6368f1027f | |||
| d64e7d08de | |||
| eb3751cb52 | |||
| 9fda54bd06 |
@@ -209,6 +209,7 @@ These features are currently in beta testing and may have limited functionality
|
|||||||
| **Gallery Feedback** | Allow guests to like, rate, and comment on photos with admin notifications and moderation | Medium | ✅ Implemented |
|
| **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 |
|
| **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 |
|
| **Multiple Administrators** | Support for multiple admin accounts with role-based permissions and activity tracking | Low | 📋 Planned |
|
||||||
|
| **Filtering & Export Options** | Add filters to show only rated, liked, or marked photos and export filtered selections for Capture One or Lightroom workflows | Low | 🔄 Open |
|
||||||
|
|
||||||
**Status Legend:** ✅ Implemented | 🚧 In Progress | 🔄 Open | 📋 Planned
|
**Status Legend:** ✅ Implemented | 🚧 In Progress | 🔄 Open | 📋 Planned
|
||||||
|
|
||||||
|
|||||||
@@ -292,6 +292,7 @@ sudo systemctl stop picpeak-backend picpeak-workers
|
|||||||
sudo systemctl restart picpeak-backend picpeak-workers
|
sudo systemctl restart picpeak-backend picpeak-workers
|
||||||
|
|
||||||
# Update PicPeak
|
# Update PicPeak
|
||||||
|
# (reruns migrations to pick up schema fixes for native installs)
|
||||||
sudo ./setup.sh --update
|
sudo ./setup.sh --update
|
||||||
```
|
```
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,51 @@
|
|||||||
|
const logger = require('../../src/utils/logger');
|
||||||
|
|
||||||
|
async function ensureColumn(knex, tableName, columnName, alterFn) {
|
||||||
|
const exists = await knex.schema.hasColumn(tableName, columnName);
|
||||||
|
if (!exists) {
|
||||||
|
logger.info(`Adding column ${tableName}.${columnName}`);
|
||||||
|
await knex.schema.table(tableName, alterFn);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
exports.up = async function(knex) {
|
||||||
|
await ensureColumn(knex, 'events', 'host_name', (table) => {
|
||||||
|
table.string('host_name');
|
||||||
|
});
|
||||||
|
|
||||||
|
await ensureColumn(knex, 'events', 'allow_user_uploads', (table) => {
|
||||||
|
table.boolean('allow_user_uploads').defaultTo(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
await ensureColumn(knex, 'events', 'upload_category_id', (table) => {
|
||||||
|
table.integer('upload_category_id');
|
||||||
|
});
|
||||||
|
|
||||||
|
await ensureColumn(knex, 'events', 'allow_downloads', (table) => {
|
||||||
|
table.boolean('allow_downloads').defaultTo(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
await ensureColumn(knex, 'events', 'disable_right_click', (table) => {
|
||||||
|
table.boolean('disable_right_click').defaultTo(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
await ensureColumn(knex, 'events', 'watermark_downloads', (table) => {
|
||||||
|
table.boolean('watermark_downloads').defaultTo(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
await ensureColumn(knex, 'events', 'watermark_text', (table) => {
|
||||||
|
table.text('watermark_text');
|
||||||
|
});
|
||||||
|
|
||||||
|
await ensureColumn(knex, 'events', 'hero_photo_id', (table) => {
|
||||||
|
table.integer('hero_photo_id').references('id').inTable('photos').onDelete('SET NULL');
|
||||||
|
});
|
||||||
|
|
||||||
|
await ensureColumn(knex, 'photos', 'uploaded_by', (table) => {
|
||||||
|
table.string('uploaded_by').defaultTo('admin');
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
exports.down = async function() {
|
||||||
|
// Non destructive migration; no rollback
|
||||||
|
};
|
||||||
Generated
+30
-7
@@ -1,21 +1,22 @@
|
|||||||
{
|
{
|
||||||
"name": "picpeak-backend",
|
"name": "picpeak-backend",
|
||||||
"version": "1.0.124",
|
"version": "1.0.129",
|
||||||
"lockfileVersion": 3,
|
"lockfileVersion": 3,
|
||||||
"requires": true,
|
"requires": true,
|
||||||
"packages": {
|
"packages": {
|
||||||
"": {
|
"": {
|
||||||
"name": "picpeak-backend",
|
"name": "picpeak-backend",
|
||||||
"version": "1.0.124",
|
"version": "1.0.129",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@aws-sdk/client-s3": "^3.850.0",
|
"@aws-sdk/client-s3": "^3.850.0",
|
||||||
"@aws-sdk/lib-storage": "^3.850.0",
|
"@aws-sdk/lib-storage": "^3.850.0",
|
||||||
"@aws-sdk/s3-request-presigner": "^3.850.0",
|
"@aws-sdk/s3-request-presigner": "^3.850.0",
|
||||||
"adm-zip": "^0.5.16",
|
"adm-zip": "^0.5.16",
|
||||||
"archiver": "^5.3.1",
|
"archiver": "^5.3.1",
|
||||||
"axios": "^1.10.0",
|
"axios": "^1.12.2",
|
||||||
"bcrypt": "6.0.0",
|
"bcrypt": "6.0.0",
|
||||||
"chokidar": "4.0.3",
|
"chokidar": "4.0.3",
|
||||||
|
"cookie-parser": "^1.4.7",
|
||||||
"cors": "^2.8.5",
|
"cors": "^2.8.5",
|
||||||
"dotenv": "^16.0.3",
|
"dotenv": "^16.0.3",
|
||||||
"express": "^4.18.2",
|
"express": "^4.18.2",
|
||||||
@@ -3889,13 +3890,13 @@
|
|||||||
"license": "MIT"
|
"license": "MIT"
|
||||||
},
|
},
|
||||||
"node_modules/axios": {
|
"node_modules/axios": {
|
||||||
"version": "1.10.0",
|
"version": "1.12.2",
|
||||||
"resolved": "https://registry.npmjs.org/axios/-/axios-1.10.0.tgz",
|
"resolved": "https://registry.npmjs.org/axios/-/axios-1.12.2.tgz",
|
||||||
"integrity": "sha512-/1xYAC4MP/HEG+3duIhFr4ZQXR4sQXOIe+o6sdqzeykGLx6Upp/1p8MHqhINOvGeP7xyNHe7tsiJByc4SSVUxw==",
|
"integrity": "sha512-vMJzPewAlRyOgxV2dU0Cuz2O8zzzx9VYtbJOaBgXFeLc4IV/Eg50n4LowmehOOR61S8ZMpc2K5Sa7g6A4jfkUw==",
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"follow-redirects": "^1.15.6",
|
"follow-redirects": "^1.15.6",
|
||||||
"form-data": "^4.0.0",
|
"form-data": "^4.0.4",
|
||||||
"proxy-from-env": "^1.1.0"
|
"proxy-from-env": "^1.1.0"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
@@ -4727,6 +4728,28 @@
|
|||||||
"node": ">= 0.6"
|
"node": ">= 0.6"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/cookie-parser": {
|
||||||
|
"version": "1.4.7",
|
||||||
|
"resolved": "https://registry.npmjs.org/cookie-parser/-/cookie-parser-1.4.7.tgz",
|
||||||
|
"integrity": "sha512-nGUvgXnotP3BsjiLX2ypbQnWoGUPIIfHQNZkkC668ntrzGWEZVW70HDEB1qnNGMicPje6EttlIgzo51YSwNQGw==",
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"cookie": "0.7.2",
|
||||||
|
"cookie-signature": "1.0.6"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">= 0.8.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/cookie-parser/node_modules/cookie": {
|
||||||
|
"version": "0.7.2",
|
||||||
|
"resolved": "https://registry.npmjs.org/cookie/-/cookie-0.7.2.tgz",
|
||||||
|
"integrity": "sha512-yki5XnKuf750l50uGTllt6kKILY4nQ1eNIQatoXEByZ5dWgnKqbnqmTrBE5B4N7lrMJKQ2ytWMiTO2o0v6Ew/w==",
|
||||||
|
"license": "MIT",
|
||||||
|
"engines": {
|
||||||
|
"node": ">= 0.6"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/cookie-signature": {
|
"node_modules/cookie-signature": {
|
||||||
"version": "1.0.6",
|
"version": "1.0.6",
|
||||||
"resolved": "https://registry.npmjs.org/cookie-signature/-/cookie-signature-1.0.6.tgz",
|
"resolved": "https://registry.npmjs.org/cookie-signature/-/cookie-signature-1.0.6.tgz",
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "picpeak-backend",
|
"name": "picpeak-backend",
|
||||||
"version": "1.0.124",
|
"version": "1.0.129",
|
||||||
"description": "Backend for PicPeak event photo sharing platform",
|
"description": "Backend for PicPeak event photo sharing platform",
|
||||||
"main": "server.js",
|
"main": "server.js",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
@@ -17,9 +17,10 @@
|
|||||||
"@aws-sdk/s3-request-presigner": "^3.850.0",
|
"@aws-sdk/s3-request-presigner": "^3.850.0",
|
||||||
"adm-zip": "^0.5.16",
|
"adm-zip": "^0.5.16",
|
||||||
"archiver": "^5.3.1",
|
"archiver": "^5.3.1",
|
||||||
"axios": "^1.10.0",
|
"axios": "^1.12.2",
|
||||||
"bcrypt": "6.0.0",
|
"bcrypt": "6.0.0",
|
||||||
"chokidar": "4.0.3",
|
"chokidar": "4.0.3",
|
||||||
|
"cookie-parser": "^1.4.7",
|
||||||
"cors": "^2.8.5",
|
"cors": "^2.8.5",
|
||||||
"dotenv": "^16.0.3",
|
"dotenv": "^16.0.3",
|
||||||
"express": "^4.18.2",
|
"express": "^4.18.2",
|
||||||
|
|||||||
+31
-3
@@ -26,6 +26,11 @@ const { startScheduledBackups } = require('./src/services/databaseBackup');
|
|||||||
const { maintenanceMiddleware } = require('./src/middleware/maintenance');
|
const { maintenanceMiddleware } = require('./src/middleware/maintenance');
|
||||||
const { sessionTimeoutMiddleware } = require('./src/middleware/sessionTimeout');
|
const { sessionTimeoutMiddleware } = require('./src/middleware/sessionTimeout');
|
||||||
const { createRateLimiter, createAuthRateLimiter } = require('./src/services/rateLimitService');
|
const { createRateLimiter, createAuthRateLimiter } = require('./src/services/rateLimitService');
|
||||||
|
const cookieParser = require('cookie-parser');
|
||||||
|
const {
|
||||||
|
getAdminTokenFromRequest,
|
||||||
|
getGalleryTokenFromRequest,
|
||||||
|
} = require('./src/utils/tokenUtils');
|
||||||
|
|
||||||
// Import routes
|
// Import routes
|
||||||
const authRoutes = require('./src/routes/auth-enhanced');
|
const authRoutes = require('./src/routes/auth-enhanced');
|
||||||
@@ -47,14 +52,18 @@ app.set('trust proxy', 'loopback, linklocal, uniquelocal');
|
|||||||
const enableHsts = process.env.ENABLE_HSTS === 'true';
|
const enableHsts = process.env.ENABLE_HSTS === 'true';
|
||||||
const cspDirectives = {
|
const cspDirectives = {
|
||||||
defaultSrc: ["'self'"],
|
defaultSrc: ["'self'"],
|
||||||
scriptSrc: ["'self'", "'unsafe-inline'"], // Required for React
|
scriptSrc: [
|
||||||
|
"'self'",
|
||||||
|
'https://www.google.com',
|
||||||
|
'https://www.gstatic.com'
|
||||||
|
],
|
||||||
styleSrc: ["'self'", "'unsafe-inline'", "https:"], // Required for styled components
|
styleSrc: ["'self'", "'unsafe-inline'", "https:"], // Required for styled components
|
||||||
imgSrc: ["'self'", "data:", "https:", "blob:"], // Allow data URLs and external images
|
imgSrc: ["'self'", "data:", "https:", "blob:"], // Allow data URLs and external images
|
||||||
connectSrc: ["'self'"], // API connections
|
connectSrc: ["'self'", 'https://www.google.com', 'https://www.gstatic.com'], // API connections
|
||||||
fontSrc: ["'self'", "https:", "data:"], // Web fonts
|
fontSrc: ["'self'", "https:", "data:"], // Web fonts
|
||||||
objectSrc: ["'none'"], // Disable plugins
|
objectSrc: ["'none'"], // Disable plugins
|
||||||
mediaSrc: ["'self'"], // Audio/video
|
mediaSrc: ["'self'"], // Audio/video
|
||||||
frameSrc: ["'none'"], // Disable iframes
|
frameSrc: ["'self'", 'https://www.google.com'],
|
||||||
};
|
};
|
||||||
// Only upgrade insecure requests when HSTS explicitly enabled (HTTPS deployment)
|
// Only upgrade insecure requests when HSTS explicitly enabled (HTTPS deployment)
|
||||||
if (enableHsts) {
|
if (enableHsts) {
|
||||||
@@ -62,6 +71,25 @@ if (enableHsts) {
|
|||||||
cspDirectives.upgradeInsecureRequests = [];
|
cspDirectives.upgradeInsecureRequests = [];
|
||||||
}
|
}
|
||||||
|
|
||||||
|
app.use(cookieParser());
|
||||||
|
|
||||||
|
app.use((req, res, next) => {
|
||||||
|
if (!req.headers.authorization) {
|
||||||
|
const slugMatch = req.path.match(/\/api\/(?:gallery|secure-images)\/([^\/]+)/);
|
||||||
|
const slug = slugMatch ? slugMatch[1] : req.requestedSlug;
|
||||||
|
const galleryToken = getGalleryTokenFromRequest(req, slug);
|
||||||
|
const adminToken = getAdminTokenFromRequest(req);
|
||||||
|
|
||||||
|
if (galleryToken) {
|
||||||
|
req.headers.authorization = `Bearer ${galleryToken}`;
|
||||||
|
} else if (adminToken) {
|
||||||
|
req.headers.authorization = `Bearer ${adminToken}`;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
next();
|
||||||
|
});
|
||||||
|
|
||||||
app.use(helmet({
|
app.use(helmet({
|
||||||
contentSecurityPolicy: {
|
contentSecurityPolicy: {
|
||||||
// Avoid helmet adding defaults like upgrade-insecure-requests when not desired
|
// Avoid helmet adding defaults like upgrade-insecure-requests when not desired
|
||||||
|
|||||||
+151
-2
@@ -75,6 +75,13 @@ async function initializeDatabase() {
|
|||||||
table.boolean('is_archived').defaultTo(false);
|
table.boolean('is_archived').defaultTo(false);
|
||||||
table.string('archive_path');
|
table.string('archive_path');
|
||||||
table.datetime('archived_at');
|
table.datetime('archived_at');
|
||||||
|
table.boolean('allow_user_uploads').defaultTo(false);
|
||||||
|
table.integer('upload_category_id');
|
||||||
|
table.boolean('allow_downloads').defaultTo(true);
|
||||||
|
table.boolean('disable_right_click').defaultTo(false);
|
||||||
|
table.boolean('watermark_downloads').defaultTo(false);
|
||||||
|
table.text('watermark_text');
|
||||||
|
table.integer('hero_photo_id').references('id').inTable('photos').onDelete('SET NULL');
|
||||||
});
|
});
|
||||||
} else {
|
} else {
|
||||||
// Check if color_theme needs to be updated to TEXT type
|
// Check if color_theme needs to be updated to TEXT type
|
||||||
@@ -104,11 +111,39 @@ async function initializeDatabase() {
|
|||||||
archive_path TEXT,
|
archive_path TEXT,
|
||||||
archived_at DATETIME,
|
archived_at DATETIME,
|
||||||
allow_user_uploads BOOLEAN DEFAULT 0,
|
allow_user_uploads BOOLEAN DEFAULT 0,
|
||||||
upload_category_id INTEGER
|
upload_category_id INTEGER,
|
||||||
|
allow_downloads BOOLEAN DEFAULT 1,
|
||||||
|
disable_right_click BOOLEAN DEFAULT 0,
|
||||||
|
watermark_downloads BOOLEAN DEFAULT 0,
|
||||||
|
watermark_text TEXT,
|
||||||
|
hero_photo_id INTEGER
|
||||||
)
|
)
|
||||||
`);
|
`);
|
||||||
|
|
||||||
await db.raw('INSERT INTO events_new SELECT * FROM events');
|
const pragmaRows = await db.raw("PRAGMA table_info('events')");
|
||||||
|
const existingColumns = pragmaRows.map(row => row.name);
|
||||||
|
const selectColumns = existingColumns.map((col) => {
|
||||||
|
switch (col) {
|
||||||
|
case 'allow_user_uploads':
|
||||||
|
return "COALESCE(allow_user_uploads, 0) as allow_user_uploads";
|
||||||
|
case 'upload_category_id':
|
||||||
|
return "upload_category_id";
|
||||||
|
case 'allow_downloads':
|
||||||
|
return "COALESCE(allow_downloads, 1) as allow_downloads";
|
||||||
|
case 'disable_right_click':
|
||||||
|
return "COALESCE(disable_right_click, 0) as disable_right_click";
|
||||||
|
case 'watermark_downloads':
|
||||||
|
return "COALESCE(watermark_downloads, 0) as watermark_downloads";
|
||||||
|
case 'watermark_text':
|
||||||
|
return 'watermark_text';
|
||||||
|
case 'hero_photo_id':
|
||||||
|
return 'hero_photo_id';
|
||||||
|
default:
|
||||||
|
return col;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
await db.raw(`INSERT INTO events_new (${existingColumns.join(', ')}) SELECT ${selectColumns.join(', ')} FROM events`);
|
||||||
await db.raw('DROP TABLE events');
|
await db.raw('DROP TABLE events');
|
||||||
await db.raw('ALTER TABLE events_new RENAME TO events');
|
await db.raw('ALTER TABLE events_new RENAME TO events');
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
@@ -129,6 +164,7 @@ async function initializeDatabase() {
|
|||||||
table.string('thumbnail_path');
|
table.string('thumbnail_path');
|
||||||
table.string('type').notNullable(); // 'collage' or 'individual'
|
table.string('type').notNullable(); // 'collage' or 'individual'
|
||||||
table.integer('size_bytes');
|
table.integer('size_bytes');
|
||||||
|
table.string('uploaded_by').defaultTo('admin');
|
||||||
table.datetime('uploaded_at').defaultTo(db.fn.now());
|
table.datetime('uploaded_at').defaultTo(db.fn.now());
|
||||||
table.integer('view_count').defaultTo(0);
|
table.integer('view_count').defaultTo(0);
|
||||||
table.integer('download_count').defaultTo(0);
|
table.integer('download_count').defaultTo(0);
|
||||||
@@ -159,11 +195,24 @@ async function initializeDatabase() {
|
|||||||
table.string('email_type').notNullable(); // 'creation', 'warning', 'expiration', 'archive_complete'
|
table.string('email_type').notNullable(); // 'creation', 'warning', 'expiration', 'archive_complete'
|
||||||
table.json('email_data');
|
table.json('email_data');
|
||||||
table.string('status').defaultTo('pending'); // 'pending', 'sent', 'failed'
|
table.string('status').defaultTo('pending'); // 'pending', 'sent', 'failed'
|
||||||
|
table.datetime('created_at').defaultTo(db.fn.now());
|
||||||
table.datetime('scheduled_at').defaultTo(db.fn.now());
|
table.datetime('scheduled_at').defaultTo(db.fn.now());
|
||||||
table.datetime('sent_at');
|
table.datetime('sent_at');
|
||||||
table.text('error_message');
|
table.text('error_message');
|
||||||
table.integer('retry_count').defaultTo(0);
|
table.integer('retry_count').defaultTo(0);
|
||||||
});
|
});
|
||||||
|
} else {
|
||||||
|
const hasCreatedAt = await db.schema.hasColumn('email_queue', 'created_at');
|
||||||
|
if (!hasCreatedAt) {
|
||||||
|
await db.schema.alterTable('email_queue', (table) => {
|
||||||
|
table.datetime('created_at').defaultTo(db.fn.now());
|
||||||
|
});
|
||||||
|
try {
|
||||||
|
await db('email_queue').whereNull('created_at').update({ created_at: db.fn.now() });
|
||||||
|
} catch (updateError) {
|
||||||
|
logger.debug('Email queue created_at backfill skipped', { error: updateError.message });
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Admin users table
|
// Admin users table
|
||||||
@@ -181,6 +230,7 @@ async function initializeDatabase() {
|
|||||||
table.datetime('updated_at').defaultTo(db.fn.now());
|
table.datetime('updated_at').defaultTo(db.fn.now());
|
||||||
table.datetime('last_login');
|
table.datetime('last_login');
|
||||||
table.string('last_login_ip');
|
table.string('last_login_ip');
|
||||||
|
table.string('language', 2).defaultTo('en');
|
||||||
});
|
});
|
||||||
} else {
|
} else {
|
||||||
// Check if updated_at column exists
|
// Check if updated_at column exists
|
||||||
@@ -216,6 +266,13 @@ async function initializeDatabase() {
|
|||||||
table.string('last_login_ip');
|
table.string('last_login_ip');
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const hasLanguage = await db.schema.hasColumn('admin_users', 'language');
|
||||||
|
if (!hasLanguage) {
|
||||||
|
await db.schema.table('admin_users', (table) => {
|
||||||
|
table.string('language', 2).defaultTo('en');
|
||||||
|
});
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Token revocation tables
|
// Token revocation tables
|
||||||
@@ -292,6 +349,18 @@ async function initializeDatabase() {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const defaultLanguageSetting = await db('app_settings')
|
||||||
|
.where('setting_key', 'default_language')
|
||||||
|
.first();
|
||||||
|
if (!defaultLanguageSetting) {
|
||||||
|
await db('app_settings').insert({
|
||||||
|
setting_key: 'default_language',
|
||||||
|
setting_value: JSON.stringify('en'),
|
||||||
|
setting_type: 'general',
|
||||||
|
updated_at: new Date(),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
// Activity logs table
|
// Activity logs table
|
||||||
const hasActivityLogsTable = await db.schema.hasTable('activity_logs');
|
const hasActivityLogsTable = await db.schema.hasTable('activity_logs');
|
||||||
if (!hasActivityLogsTable) {
|
if (!hasActivityLogsTable) {
|
||||||
@@ -315,6 +384,86 @@ async function initializeDatabase() {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
await ensureGlobalCategories();
|
||||||
|
}
|
||||||
|
|
||||||
|
// Ensure photo categories exist for new deployments
|
||||||
|
async function ensureGlobalCategories() {
|
||||||
|
const hasPhotoCategoriesTable = await db.schema.hasTable('photo_categories');
|
||||||
|
if (!hasPhotoCategoriesTable) {
|
||||||
|
await db.schema.createTable('photo_categories', (table) => {
|
||||||
|
table.increments('id').primary();
|
||||||
|
table.string('name', 100).notNullable();
|
||||||
|
table.string('slug', 100).notNullable();
|
||||||
|
table.boolean('is_global').defaultTo(true);
|
||||||
|
table.integer('event_id').references('id').inTable('events').onDelete('CASCADE');
|
||||||
|
table.timestamp('created_at').defaultTo(db.fn.now());
|
||||||
|
table.unique(['slug', 'event_id']);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
const hasCategoryIdColumn = await db.schema.hasColumn('photos', 'category_id');
|
||||||
|
if (!hasCategoryIdColumn) {
|
||||||
|
await db.schema.alterTable('photos', (table) => {
|
||||||
|
table.integer('category_id').references('id').inTable('photo_categories');
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
const hasCmsPagesTable = await db.schema.hasTable('cms_pages');
|
||||||
|
if (!hasCmsPagesTable) {
|
||||||
|
await db.schema.createTable('cms_pages', (table) => {
|
||||||
|
table.increments('id').primary();
|
||||||
|
table.string('slug', 100).unique().notNullable();
|
||||||
|
table.text('title_en');
|
||||||
|
table.text('title_de');
|
||||||
|
table.text('content_en');
|
||||||
|
table.text('content_de');
|
||||||
|
table.timestamp('updated_at').defaultTo(db.fn.now());
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
const categoryCountRow = await db('photo_categories').count({ count: 'id' }).first();
|
||||||
|
const categoryCount = categoryCountRow ? Number(categoryCountRow.count) : 0;
|
||||||
|
if (categoryCount === 0) {
|
||||||
|
const defaultCategories = [
|
||||||
|
{ name: 'Ceremony', slug: 'ceremony', is_global: true },
|
||||||
|
{ name: 'Reception', slug: 'reception', is_global: true },
|
||||||
|
{ name: 'Portraits', slug: 'portraits', is_global: true },
|
||||||
|
{ name: 'Group Photos', slug: 'group-photos', is_global: true },
|
||||||
|
{ name: 'Details', slug: 'details', is_global: true },
|
||||||
|
{ name: 'Party', slug: 'party', is_global: true },
|
||||||
|
];
|
||||||
|
|
||||||
|
await db('photo_categories').insert(defaultCategories);
|
||||||
|
}
|
||||||
|
|
||||||
|
const cmsPages = await db('cms_pages').select('slug');
|
||||||
|
const existingSlugs = cmsPages.map((page) => page.slug);
|
||||||
|
const defaultPages = [
|
||||||
|
{
|
||||||
|
slug: 'impressum',
|
||||||
|
title_en: 'Legal Notice',
|
||||||
|
title_de: 'Impressum',
|
||||||
|
content_en: '<h2>Legal Notice</h2><p>Please edit this content in the admin panel.</p>',
|
||||||
|
content_de: '<h2>Impressum</h2><p>Bitte bearbeiten Sie diesen Inhalt im Admin-Panel.</p>',
|
||||||
|
updated_at: new Date(),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
slug: 'datenschutz',
|
||||||
|
title_en: 'Privacy Policy',
|
||||||
|
title_de: 'Datenschutzerklärung',
|
||||||
|
content_en: '<h2>Privacy Policy</h2><p>Please edit this content in the admin panel.</p>',
|
||||||
|
content_de: '<h2>Datenschutzerklärung</h2><p>Bitte bearbeiten Sie diesen Inhalt im Admin-Panel.</p>',
|
||||||
|
updated_at: new Date(),
|
||||||
|
},
|
||||||
|
];
|
||||||
|
|
||||||
|
for (const page of defaultPages) {
|
||||||
|
if (!existingSlugs.includes(page.slug)) {
|
||||||
|
await db('cms_pages').insert(page);
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Helper function to log activities
|
// Helper function to log activities
|
||||||
|
|||||||
@@ -3,13 +3,14 @@ const { db } = require('../database/db');
|
|||||||
const { formatBoolean } = require('../utils/dbCompat');
|
const { formatBoolean } = require('../utils/dbCompat');
|
||||||
const { isTokenRevoked } = require('../utils/tokenRevocation');
|
const { isTokenRevoked } = require('../utils/tokenRevocation');
|
||||||
const logger = require('../utils/logger');
|
const logger = require('../utils/logger');
|
||||||
|
const { getAdminTokenFromRequest, getGalleryTokenFromRequest } = require('../utils/tokenUtils');
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Enhanced admin authentication middleware with revocation checking
|
* Enhanced admin authentication middleware with revocation checking
|
||||||
*/
|
*/
|
||||||
async function adminAuth(req, res, next) {
|
async function adminAuth(req, res, next) {
|
||||||
try {
|
try {
|
||||||
const token = req.headers.authorization?.split(' ')[1];
|
const token = getAdminTokenFromRequest(req);
|
||||||
if (!token) {
|
if (!token) {
|
||||||
return res.status(401).json({ error: 'No token provided' });
|
return res.status(401).json({ error: 'No token provided' });
|
||||||
}
|
}
|
||||||
@@ -97,7 +98,8 @@ async function adminAuth(req, res, next) {
|
|||||||
*/
|
*/
|
||||||
async function galleryAuth(req, res, next) {
|
async function galleryAuth(req, res, next) {
|
||||||
try {
|
try {
|
||||||
const token = req.headers.authorization?.split(' ')[1];
|
const slug = req.params?.slug || req.requestedSlug;
|
||||||
|
const token = getGalleryTokenFromRequest(req, slug);
|
||||||
if (!token) {
|
if (!token) {
|
||||||
return res.status(401).json({ error: 'No token provided' });
|
return res.status(401).json({ error: 'No token provided' });
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ const jwt = require('jsonwebtoken');
|
|||||||
const { db } = require('../database/db');
|
const { db } = require('../database/db');
|
||||||
const { formatBoolean } = require('../utils/dbCompat');
|
const { formatBoolean } = require('../utils/dbCompat');
|
||||||
const logger = require('../utils/logger');
|
const logger = require('../utils/logger');
|
||||||
|
const { getAdminTokenFromRequest, getGalleryTokenFromRequest } = require('../utils/tokenUtils');
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Enhanced admin authentication middleware
|
* Enhanced admin authentication middleware
|
||||||
@@ -9,7 +10,7 @@ const logger = require('../utils/logger');
|
|||||||
*/
|
*/
|
||||||
async function adminAuth(req, res, next) {
|
async function adminAuth(req, res, next) {
|
||||||
try {
|
try {
|
||||||
const token = req.headers.authorization?.split(' ')[1];
|
const token = getAdminTokenFromRequest(req);
|
||||||
if (!token) {
|
if (!token) {
|
||||||
return res.status(401).json({ error: 'No token provided' });
|
return res.status(401).json({ error: 'No token provided' });
|
||||||
}
|
}
|
||||||
@@ -89,7 +90,8 @@ async function adminAuth(req, res, next) {
|
|||||||
*/
|
*/
|
||||||
async function galleryAuth(req, res, next) {
|
async function galleryAuth(req, res, next) {
|
||||||
try {
|
try {
|
||||||
const token = req.headers.authorization?.split(' ')[1];
|
const slug = req.params?.slug || req.requestedSlug;
|
||||||
|
const token = getGalleryTokenFromRequest(req, slug);
|
||||||
if (!token) {
|
if (!token) {
|
||||||
return res.status(401).json({ error: 'No token provided' });
|
return res.status(401).json({ error: 'No token provided' });
|
||||||
}
|
}
|
||||||
@@ -151,7 +153,8 @@ async function galleryAuth(req, res, next) {
|
|||||||
*/
|
*/
|
||||||
async function photoAuth(req, res, next) {
|
async function photoAuth(req, res, next) {
|
||||||
try {
|
try {
|
||||||
const token = req.headers.authorization?.split(' ')[1];
|
const slug = req.params?.slug || req.requestedSlug;
|
||||||
|
const token = getAdminTokenFromRequest(req) || getGalleryTokenFromRequest(req, slug);
|
||||||
if (!token) {
|
if (!token) {
|
||||||
return res.status(401).json({ error: 'Authentication required' });
|
return res.status(401).json({ error: 'Authentication required' });
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,10 +2,11 @@ const jwt = require('jsonwebtoken');
|
|||||||
const { db } = require('../database/db');
|
const { db } = require('../database/db');
|
||||||
const { formatBoolean } = require('../utils/dbCompat');
|
const { formatBoolean } = require('../utils/dbCompat');
|
||||||
const logger = require('../utils/logger');
|
const logger = require('../utils/logger');
|
||||||
|
const { getAdminTokenFromRequest } = require('../utils/tokenUtils');
|
||||||
|
|
||||||
async function adminAuth(req, res, next) {
|
async function adminAuth(req, res, next) {
|
||||||
try {
|
try {
|
||||||
const token = req.headers.authorization?.split(' ')[1];
|
const token = getAdminTokenFromRequest(req);
|
||||||
if (!token) {
|
if (!token) {
|
||||||
const clientIp = req.headers['x-forwarded-for']?.split(',')[0]?.trim() ||
|
const clientIp = req.headers['x-forwarded-for']?.split(',')[0]?.trim() ||
|
||||||
req.headers['x-real-ip'] ||
|
req.headers['x-real-ip'] ||
|
||||||
|
|||||||
@@ -1,17 +1,17 @@
|
|||||||
const jwt = require('jsonwebtoken');
|
const jwt = require('jsonwebtoken');
|
||||||
const { db, withRetry } = require('../database/db');
|
const { db, withRetry } = require('../database/db');
|
||||||
const { formatBoolean } = require('../utils/dbCompat');
|
const { formatBoolean } = require('../utils/dbCompat');
|
||||||
|
const { getGalleryTokenFromRequest } = require('../utils/tokenUtils');
|
||||||
|
|
||||||
// Middleware to verify gallery access
|
// Middleware to verify gallery access
|
||||||
async function verifyGalleryAccess(req, res, next) {
|
async function verifyGalleryAccess(req, res, next) {
|
||||||
try {
|
try {
|
||||||
const authHeader = req.headers.authorization;
|
const requestedSlug = req.params.slug || req.requestedSlug;
|
||||||
const token = authHeader?.split(' ')[1];
|
const token = getGalleryTokenFromRequest(req, requestedSlug);
|
||||||
if (!token) {
|
if (!token) {
|
||||||
return res.status(401).json({ error: 'No token provided' });
|
return res.status(401).json({ error: 'No token provided' });
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
// Try to verify with issuer first, fallback to no issuer for backward compatibility
|
// Try to verify with issuer first, fallback to no issuer for backward compatibility
|
||||||
let decoded;
|
let decoded;
|
||||||
try {
|
try {
|
||||||
@@ -29,8 +29,6 @@ async function verifyGalleryAccess(req, res, next) {
|
|||||||
console.log('[verifyGalleryAccess] Token decoded successfully, eventId:', decoded.eventId);
|
console.log('[verifyGalleryAccess] Token decoded successfully, eventId:', decoded.eventId);
|
||||||
|
|
||||||
// If we have a slug in the URL params or from pre-middleware, verify it matches
|
// If we have a slug in the URL params or from pre-middleware, verify it matches
|
||||||
const requestedSlug = req.params.slug || req.requestedSlug;
|
|
||||||
|
|
||||||
let event;
|
let event;
|
||||||
if (requestedSlug) {
|
if (requestedSlug) {
|
||||||
// Verify by slug and ensure it matches the token's event
|
// Verify by slug and ensure it matches the token's event
|
||||||
@@ -84,7 +82,7 @@ async function verifyGalleryAccess(req, res, next) {
|
|||||||
next();
|
next();
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('Error verifying gallery access:', error);
|
console.error('Error verifying gallery access:', error);
|
||||||
res.status(401).json({ error: 'Invalid token', details: error.message });
|
res.status(401).json({ error: 'Invalid token' });
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ const bcrypt = require('bcrypt');
|
|||||||
const jwt = require('jsonwebtoken');
|
const jwt = require('jsonwebtoken');
|
||||||
const { db } = require('../database/db');
|
const { db } = require('../database/db');
|
||||||
const { formatBoolean } = require('../utils/dbCompat');
|
const { formatBoolean } = require('../utils/dbCompat');
|
||||||
|
const { getGalleryTokenFromRequest } = require('../utils/tokenUtils');
|
||||||
|
|
||||||
async function photoAuth(req, res, next) {
|
async function photoAuth(req, res, next) {
|
||||||
try {
|
try {
|
||||||
@@ -20,9 +21,9 @@ async function photoAuth(req, res, next) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// First check for JWT token (from gallery access)
|
// First check for JWT token (from gallery access)
|
||||||
const authHeader = req.headers.authorization;
|
const tokenFromRequest = getGalleryTokenFromRequest(req, eventSlug);
|
||||||
if (authHeader && authHeader.startsWith('Bearer ')) {
|
if (tokenFromRequest) {
|
||||||
const token = authHeader.replace('Bearer ', '');
|
const token = tokenFromRequest;
|
||||||
try {
|
try {
|
||||||
// Try to verify with issuer first, fallback to no issuer for backward compatibility
|
// Try to verify with issuer first, fallback to no issuer for backward compatibility
|
||||||
let decoded;
|
let decoded;
|
||||||
@@ -88,7 +89,7 @@ async function photoAuth(req, res, next) {
|
|||||||
// Check for password header (legacy support)
|
// Check for password header (legacy support)
|
||||||
const password = req.headers['x-gallery-password'];
|
const password = req.headers['x-gallery-password'];
|
||||||
|
|
||||||
if (!password && !authHeader) {
|
if (!password && !tokenFromRequest) {
|
||||||
return res.status(401).json({ error: 'Authentication required' });
|
return res.status(401).json({ error: 'Authentication required' });
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
const jwt = require('jsonwebtoken');
|
const jwt = require('jsonwebtoken');
|
||||||
const { db } = require('../database/db');
|
const { db } = require('../database/db');
|
||||||
|
const { getAdminTokenFromRequest } = require('../utils/tokenUtils');
|
||||||
|
|
||||||
// In-memory session tracking (in production, use Redis)
|
// In-memory session tracking (in production, use Redis)
|
||||||
const sessions = new Map();
|
const sessions = new Map();
|
||||||
@@ -67,11 +68,7 @@ async function getSessionTimeout() {
|
|||||||
|
|
||||||
async function sessionTimeoutMiddleware(req, res, next) {
|
async function sessionTimeoutMiddleware(req, res, next) {
|
||||||
// Skip for non-authenticated routes
|
// Skip for non-authenticated routes
|
||||||
if (!req.headers.authorization) {
|
const token = getAdminTokenFromRequest(req);
|
||||||
return next();
|
|
||||||
}
|
|
||||||
|
|
||||||
const token = req.headers.authorization.split(' ')[1];
|
|
||||||
if (!token) {
|
if (!token) {
|
||||||
return next();
|
return next();
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -221,7 +221,11 @@ router.post('/test-connection', adminAuth, async (req, res) => {
|
|||||||
await fs.access(config.path, fs.constants.W_OK);
|
await fs.access(config.path, fs.constants.W_OK);
|
||||||
res.json({ success: true, message: 'Local path is writable' });
|
res.json({ success: true, message: 'Local path is writable' });
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
res.json({ success: false, message: 'Cannot write to local path: ' + error.message });
|
logger.warn('Local backup path not writable', {
|
||||||
|
path: config.path,
|
||||||
|
error: error.message
|
||||||
|
});
|
||||||
|
res.json({ success: false, message: 'Cannot write to local path. Check server logs for details.' });
|
||||||
}
|
}
|
||||||
break;
|
break;
|
||||||
|
|
||||||
@@ -243,7 +247,11 @@ router.post('/test-connection', adminAuth, async (req, res) => {
|
|||||||
const { stdout } = await execAsync(testCommand);
|
const { stdout } = await execAsync(testCommand);
|
||||||
res.json({ success: true, message: 'Rsync connection successful' });
|
res.json({ success: true, message: 'Rsync connection successful' });
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
res.json({ success: false, message: 'Rsync connection failed: ' + error.message });
|
logger.warn('Rsync connection test failed', {
|
||||||
|
destination: config.host || config.destination,
|
||||||
|
error: error.message
|
||||||
|
});
|
||||||
|
res.json({ success: false, message: 'Rsync connection failed. Check server logs for details.' });
|
||||||
}
|
}
|
||||||
break;
|
break;
|
||||||
|
|
||||||
@@ -274,7 +282,7 @@ router.get('/manifest/:backupRunId', adminAuth, async (req, res) => {
|
|||||||
});
|
});
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
logger.error('Failed to get backup manifest:', error);
|
logger.error('Failed to get backup manifest:', error);
|
||||||
res.status(404).json({ error: error.message || 'Backup manifest not found' });
|
res.status(404).json({ error: 'Backup manifest not found' });
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -327,7 +335,7 @@ router.get('/manifest/:backupRunId/download', adminAuth, async (req, res) => {
|
|||||||
}
|
}
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
logger.error('Failed to download backup manifest:', error);
|
logger.error('Failed to download backup manifest:', error);
|
||||||
res.status(404).json({ error: error.message || 'Backup manifest not found' });
|
res.status(404).json({ error: 'Backup manifest not found' });
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -344,7 +352,7 @@ router.get('/manifests/:backupId', adminAuth, async (req, res) => {
|
|||||||
});
|
});
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
logger.error('Failed to get backup manifest:', error);
|
logger.error('Failed to get backup manifest:', error);
|
||||||
res.status(404).json({ error: error.message || 'Backup manifest not found' });
|
res.status(404).json({ error: 'Backup manifest not found' });
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -375,7 +383,7 @@ router.get('/manifests/:backupId/download', adminAuth, async (req, res) => {
|
|||||||
}
|
}
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
logger.error('Failed to download backup manifest:', error);
|
logger.error('Failed to download backup manifest:', error);
|
||||||
res.status(404).json({ error: error.message || 'Backup manifest not found' });
|
res.status(404).json({ error: 'Backup manifest not found' });
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -436,7 +444,7 @@ router.get('/s3/buckets', adminAuth, async (req, res) => {
|
|||||||
});
|
});
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
logger.error('Failed to list S3 buckets:', error);
|
logger.error('Failed to list S3 buckets:', error);
|
||||||
res.status(500).json({ error: 'Failed to list S3 buckets: ' + error.message });
|
res.status(500).json({ error: 'Failed to list S3 buckets' });
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -473,7 +481,7 @@ router.get('/s3/files', adminAuth, async (req, res) => {
|
|||||||
});
|
});
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
logger.error('Failed to list S3 files:', error);
|
logger.error('Failed to list S3 files:', error);
|
||||||
res.status(500).json({ error: 'Failed to list S3 files: ' + error.message });
|
res.status(500).json({ error: 'Failed to list S3 files' });
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -535,7 +543,7 @@ router.delete('/s3/cleanup', adminAuth, async (req, res) => {
|
|||||||
});
|
});
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
logger.error('Failed to cleanup S3 backups:', error);
|
logger.error('Failed to cleanup S3 backups:', error);
|
||||||
res.status(500).json({ error: 'Failed to cleanup S3 backups: ' + error.message });
|
res.status(500).json({ error: 'Failed to cleanup S3 backups' });
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -587,7 +595,7 @@ router.post('/s3/test-upload', adminAuth, async (req, res) => {
|
|||||||
});
|
});
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
logger.error('S3 upload test failed:', error);
|
logger.error('S3 upload test failed:', error);
|
||||||
res.status(500).json({ error: 'S3 upload test failed: ' + error.message });
|
res.status(500).json({ error: 'S3 upload test failed' });
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -675,7 +683,7 @@ router.get('/download/:backupId', adminAuth, async (req, res) => {
|
|||||||
}
|
}
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
logger.error('Failed to download backup:', error);
|
logger.error('Failed to download backup:', error);
|
||||||
res.status(500).json({ error: 'Failed to download backup: ' + error.message });
|
res.status(500).json({ error: 'Failed to download backup' });
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -744,7 +752,7 @@ router.get('/checksums', adminAuth, async (req, res) => {
|
|||||||
});
|
});
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
logger.error('Failed to get file checksums:', error);
|
logger.error('Failed to get file checksums:', error);
|
||||||
res.status(500).json({ error: 'Failed to get file checksums: ' + error.message });
|
res.status(500).json({ error: 'Failed to get file checksums' });
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -847,7 +855,7 @@ router.post('/estimate', adminAuth, async (req, res) => {
|
|||||||
});
|
});
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
logger.error('Failed to estimate backup size:', error);
|
logger.error('Failed to estimate backup size:', error);
|
||||||
res.status(500).json({ error: 'Failed to estimate backup size: ' + error.message });
|
res.status(500).json({ error: 'Failed to estimate backup size' });
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -945,10 +953,11 @@ async function validateManifestData(manifestData) {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
|
logger.error('Manifest validation error', { error: error.message });
|
||||||
return {
|
return {
|
||||||
valid: false,
|
valid: false,
|
||||||
error: `Validation error: ${error.message}`,
|
error: 'Validation error encountered while processing manifest',
|
||||||
details: { error: error.message }
|
details: { hint: 'See server logs for diagnostic details.' }
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -515,13 +515,11 @@ router.delete('/:id', adminAuth, async (req, res) => {
|
|||||||
// Provide more specific error messages
|
// Provide more specific error messages
|
||||||
if (error.message && error.message.includes('foreign key constraint')) {
|
if (error.message && error.message.includes('foreign key constraint')) {
|
||||||
res.status(500).json({
|
res.status(500).json({
|
||||||
error: 'Cannot delete event due to existing references. Please contact support.',
|
error: 'Cannot delete event due to existing references. Please contact support.'
|
||||||
details: error.message
|
|
||||||
});
|
});
|
||||||
} else {
|
} else {
|
||||||
res.status(500).json({
|
res.status(500).json({
|
||||||
error: 'Failed to delete event',
|
error: 'Failed to delete event'
|
||||||
details: process.env.NODE_ENV === 'development' ? error.message : undefined
|
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -780,7 +778,7 @@ router.post('/bulk-archive', adminAuth, [
|
|||||||
results.failed.push({
|
results.failed.push({
|
||||||
id: event.id,
|
id: event.id,
|
||||||
name: event.event_name,
|
name: event.event_name,
|
||||||
error: error.message
|
error: 'Failed to archive event. Check server logs for details.'
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ const fs = require('fs').promises;
|
|||||||
const { adminAuth } = require('../middleware/auth');
|
const { adminAuth } = require('../middleware/auth');
|
||||||
const { list, resolveExternalPath, getExternalMediaRoot } = require('../services/externalMediaService');
|
const { list, resolveExternalPath, getExternalMediaRoot } = require('../services/externalMediaService');
|
||||||
const { db, logActivity } = require('../database/db');
|
const { db, logActivity } = require('../database/db');
|
||||||
|
const logger = require('../utils/logger');
|
||||||
|
|
||||||
const router = express.Router();
|
const router = express.Router();
|
||||||
|
|
||||||
@@ -14,7 +15,11 @@ router.get('/list', adminAuth, async (req, res) => {
|
|||||||
const result = await list(relPath);
|
const result = await list(relPath);
|
||||||
res.json(result);
|
res.json(result);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
res.status(400).json({ error: 'Invalid path', details: error.message });
|
logger.warn('Invalid external media path requested', {
|
||||||
|
path: req.query.path,
|
||||||
|
error: error.message
|
||||||
|
});
|
||||||
|
res.status(400).json({ error: 'Invalid external media path' });
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -104,9 +109,13 @@ router.post('/events/:id/import-external', adminAuth, async (req, res) => {
|
|||||||
|
|
||||||
res.json({ imported, skipped, thumbnailsQueued: 0 });
|
res.json({ imported, skipped, thumbnailsQueued: 0 });
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
res.status(500).json({ error: 'Failed to import external media', details: error.message });
|
logger.error('External media import failed', {
|
||||||
|
eventId: req.params.id,
|
||||||
|
externalPath: req.body?.external_path,
|
||||||
|
error: error.message
|
||||||
|
});
|
||||||
|
res.status(500).json({ error: 'Failed to import external media' });
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
module.exports = router;
|
module.exports = router;
|
||||||
|
|
||||||
|
|||||||
@@ -368,7 +368,7 @@ router.post('/word-filters',
|
|||||||
res.json({ success: true });
|
res.json({ success: true });
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
if (error.message === 'Word filter already exists') {
|
if (error.message === 'Word filter already exists') {
|
||||||
return res.status(409).json({ error: error.message });
|
return res.status(409).json({ error: 'Word filter already exists' });
|
||||||
}
|
}
|
||||||
logger.error('Error adding word filter:', error);
|
logger.error('Error adding word filter:', error);
|
||||||
res.status(500).json({ error: 'Failed to add word filter' });
|
res.status(500).json({ error: 'Failed to add word filter' });
|
||||||
|
|||||||
@@ -802,7 +802,8 @@ router.get('/:eventId/debug', adminAuth, async (req, res) => {
|
|||||||
storagePath: getStoragePath()
|
storagePath: getStoragePath()
|
||||||
});
|
});
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
res.status(500).json({ error: error.message });
|
console.error('Error fetching admin photo debug data:', error);
|
||||||
|
res.status(500).json({ error: 'Failed to fetch photo debug data' });
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
@@ -82,7 +82,7 @@ router.post('/validate', [
|
|||||||
logger.error('Restore validation failed:', error);
|
logger.error('Restore validation failed:', error);
|
||||||
res.status(400).json({
|
res.status(400).json({
|
||||||
success: false,
|
success: false,
|
||||||
error: error.message,
|
error: 'Restore validation failed',
|
||||||
logs: restoreService.restoreLog
|
logs: restoreService.restoreLog
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -162,7 +162,7 @@ router.post('/start', [
|
|||||||
logger.error('Failed to start restore:', error);
|
logger.error('Failed to start restore:', error);
|
||||||
res.status(500).json({
|
res.status(500).json({
|
||||||
success: false,
|
success: false,
|
||||||
error: error.message
|
error: 'Failed to start restore operation'
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ const fs = require('fs').promises;
|
|||||||
const path = require('path');
|
const path = require('path');
|
||||||
const os = require('os');
|
const os = require('os');
|
||||||
const { formatBoolean } = require('../utils/dbCompat');
|
const { formatBoolean } = require('../utils/dbCompat');
|
||||||
|
const logger = require('../utils/logger');
|
||||||
const router = express.Router();
|
const router = express.Router();
|
||||||
|
|
||||||
// Get system version
|
// Get system version
|
||||||
@@ -208,10 +209,14 @@ router.get('/database', adminAuth, async (req, res) => {
|
|||||||
});
|
});
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
// Table might not exist
|
// Table might not exist
|
||||||
|
logger.warn('Failed to retrieve table info', {
|
||||||
|
table,
|
||||||
|
error: error.message
|
||||||
|
});
|
||||||
tableInfo.push({
|
tableInfo.push({
|
||||||
name: table,
|
name: table,
|
||||||
rows: 0,
|
rows: 0,
|
||||||
error: error.message
|
error: 'Unable to retrieve table details'
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -14,6 +14,14 @@ const {
|
|||||||
} = require('../utils/authSecurity');
|
} = require('../utils/authSecurity');
|
||||||
const { endSession } = require('../middleware/sessionTimeout');
|
const { endSession } = require('../middleware/sessionTimeout');
|
||||||
const logger = require('../utils/logger');
|
const logger = require('../utils/logger');
|
||||||
|
const {
|
||||||
|
setAdminAuthCookie,
|
||||||
|
clearAdminAuthCookie,
|
||||||
|
setGalleryAuthCookies,
|
||||||
|
clearGalleryAuthCookies,
|
||||||
|
getAdminTokenFromRequest,
|
||||||
|
getGalleryTokenFromRequest,
|
||||||
|
} = require('../utils/tokenUtils');
|
||||||
const router = express.Router();
|
const router = express.Router();
|
||||||
|
|
||||||
// Admin login with enhanced security
|
// Admin login with enhanced security
|
||||||
@@ -92,6 +100,8 @@ router.post('/admin/login', [
|
|||||||
issuer: 'picpeak-auth'
|
issuer: 'picpeak-auth'
|
||||||
});
|
});
|
||||||
|
|
||||||
|
setAdminAuthCookie(res, token);
|
||||||
|
|
||||||
res.json({
|
res.json({
|
||||||
token,
|
token,
|
||||||
user: {
|
user: {
|
||||||
@@ -110,13 +120,14 @@ router.post('/admin/login', [
|
|||||||
// Logout endpoint
|
// Logout endpoint
|
||||||
router.post('/logout', async (req, res) => {
|
router.post('/logout', async (req, res) => {
|
||||||
try {
|
try {
|
||||||
const token = req.headers.authorization?.split(' ')[1];
|
const adminToken = getAdminTokenFromRequest(req);
|
||||||
|
const galleryToken = getGalleryTokenFromRequest(req);
|
||||||
|
const token = adminToken || galleryToken;
|
||||||
|
|
||||||
if (token) {
|
if (token) {
|
||||||
// End the session
|
// End the session
|
||||||
endSession(token);
|
endSession(token);
|
||||||
|
|
||||||
// Log the logout
|
|
||||||
try {
|
try {
|
||||||
const decoded = jwt.verify(token, process.env.JWT_SECRET);
|
const decoded = jwt.verify(token, process.env.JWT_SECRET);
|
||||||
logger.info('User logged out', {
|
logger.info('User logged out', {
|
||||||
@@ -124,9 +135,21 @@ router.post('/logout', async (req, res) => {
|
|||||||
username: decoded.username,
|
username: decoded.username,
|
||||||
type: decoded.type
|
type: decoded.type
|
||||||
});
|
});
|
||||||
|
|
||||||
|
if (decoded.type === 'admin') {
|
||||||
|
clearAdminAuthCookie(res);
|
||||||
|
} else if (decoded.type === 'gallery') {
|
||||||
|
clearGalleryAuthCookies(res, decoded.eventSlug);
|
||||||
|
}
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
// Token might be invalid, but still process logout
|
// Token might be invalid, but still process logout and clear cookies
|
||||||
|
clearAdminAuthCookie(res);
|
||||||
|
clearGalleryAuthCookies(res);
|
||||||
}
|
}
|
||||||
|
} else {
|
||||||
|
// No token found, but ensure cookies are cleared
|
||||||
|
clearAdminAuthCookie(res);
|
||||||
|
clearGalleryAuthCookies(res);
|
||||||
}
|
}
|
||||||
|
|
||||||
res.json({ message: 'Logged out successfully' });
|
res.json({ message: 'Logged out successfully' });
|
||||||
@@ -210,6 +233,8 @@ router.post('/gallery/verify', [
|
|||||||
issuer: 'picpeak-auth'
|
issuer: 'picpeak-auth'
|
||||||
});
|
});
|
||||||
|
|
||||||
|
setGalleryAuthCookies(res, token, event.slug);
|
||||||
|
|
||||||
res.json({
|
res.json({
|
||||||
token,
|
token,
|
||||||
event: {
|
event: {
|
||||||
@@ -230,10 +255,89 @@ router.post('/gallery/verify', [
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// Share link authentication (token-based)
|
||||||
|
router.post('/gallery/share-login', [
|
||||||
|
body('slug').notEmpty().trim(),
|
||||||
|
body('token').notEmpty()
|
||||||
|
], async (req, res) => {
|
||||||
|
try {
|
||||||
|
const errors = validationResult(req);
|
||||||
|
if (!errors.isEmpty()) {
|
||||||
|
return res.status(400).json({ errors: errors.array() });
|
||||||
|
}
|
||||||
|
|
||||||
|
const { slug, token } = req.body;
|
||||||
|
const ipAddress = req.ip || req.connection.remoteAddress;
|
||||||
|
const userAgent = req.headers['user-agent'] || '';
|
||||||
|
|
||||||
|
const event = await db('events')
|
||||||
|
.where({ slug, is_active: formatBoolean(true), is_archived: formatBoolean(false) })
|
||||||
|
.first();
|
||||||
|
|
||||||
|
if (!event) {
|
||||||
|
return res.status(404).json({ error: 'Gallery not found' });
|
||||||
|
}
|
||||||
|
|
||||||
|
let expectedToken = event.share_link;
|
||||||
|
if (expectedToken && expectedToken.includes('/')) {
|
||||||
|
expectedToken = expectedToken.split('/').pop();
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!expectedToken || token !== expectedToken) {
|
||||||
|
return res.status(401).json({ error: 'Invalid or expired share link' });
|
||||||
|
}
|
||||||
|
|
||||||
|
const jwtToken = jwt.sign({
|
||||||
|
eventId: event.id,
|
||||||
|
eventSlug: event.slug,
|
||||||
|
type: 'gallery',
|
||||||
|
ip: ipAddress,
|
||||||
|
loginTime: Date.now()
|
||||||
|
}, process.env.JWT_SECRET, {
|
||||||
|
expiresIn: '24h',
|
||||||
|
issuer: 'picpeak-auth'
|
||||||
|
});
|
||||||
|
|
||||||
|
await trackSuccessfulLogin(`gallery:${slug}:share`, ipAddress, userAgent);
|
||||||
|
setGalleryAuthCookies(res, jwtToken, event.slug);
|
||||||
|
|
||||||
|
res.json({
|
||||||
|
token: jwtToken,
|
||||||
|
event: {
|
||||||
|
id: event.id,
|
||||||
|
event_name: event.event_name,
|
||||||
|
event_type: event.event_type,
|
||||||
|
event_date: event.event_date,
|
||||||
|
welcome_message: event.welcome_message,
|
||||||
|
color_theme: event.color_theme,
|
||||||
|
expires_at: event.expires_at,
|
||||||
|
allow_user_uploads: event.allow_user_uploads,
|
||||||
|
upload_category_id: event.upload_category_id
|
||||||
|
}
|
||||||
|
});
|
||||||
|
} catch (error) {
|
||||||
|
logger.error('Share link authentication error:', error);
|
||||||
|
res.status(500).json({ error: 'Share link login failed' });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// Gallery logout to clear cookies
|
||||||
|
router.post('/gallery/logout', async (req, res) => {
|
||||||
|
try {
|
||||||
|
const { slug } = req.body || {};
|
||||||
|
clearGalleryAuthCookies(res, slug);
|
||||||
|
res.json({ message: 'Logged out successfully' });
|
||||||
|
} catch (error) {
|
||||||
|
logger.error('Gallery logout error:', error);
|
||||||
|
res.status(500).json({ error: 'Logout failed' });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
// Get current session info
|
// Get current session info
|
||||||
router.get('/session', async (req, res) => {
|
router.get('/session', async (req, res) => {
|
||||||
try {
|
try {
|
||||||
const token = req.headers.authorization?.split(' ')[1];
|
const { slug } = req.query;
|
||||||
|
const token = getAdminTokenFromRequest(req) || getGalleryTokenFromRequest(req, slug);
|
||||||
|
|
||||||
if (!token) {
|
if (!token) {
|
||||||
return res.status(401).json({ error: 'No token provided' });
|
return res.status(401).json({ error: 'No token provided' });
|
||||||
@@ -250,7 +354,9 @@ router.get('/session', async (req, res) => {
|
|||||||
valid: true,
|
valid: true,
|
||||||
type: decoded.type,
|
type: decoded.type,
|
||||||
expiresIn: Math.floor(remainingTime),
|
expiresIn: Math.floor(remainingTime),
|
||||||
user: decoded.username || decoded.eventSlug
|
user: decoded.username || decoded.eventSlug,
|
||||||
|
eventSlug: decoded.eventSlug,
|
||||||
|
adminUsername: decoded.username
|
||||||
});
|
});
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
res.json({
|
res.json({
|
||||||
|
|||||||
+118
-37
@@ -37,7 +37,7 @@ router.get('/:slug/verify-token/:token', async (req, res) => {
|
|||||||
res.json({ valid: true });
|
res.json({ valid: true });
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('Error verifying token:', error);
|
console.error('Error verifying token:', error);
|
||||||
res.status(500).json({ error: 'Failed to verify token', details: error.message });
|
res.status(500).json({ error: 'Failed to verify token' });
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -90,7 +90,7 @@ router.get('/:slug/info', async (req, res) => {
|
|||||||
});
|
});
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('Error fetching gallery info:', error);
|
console.error('Error fetching gallery info:', error);
|
||||||
res.status(500).json({ error: 'Failed to fetch gallery info', details: error.message });
|
res.status(500).json({ error: 'Failed to fetch gallery info' });
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -107,30 +107,39 @@ router.get('/:slug/photos', verifyGalleryAccess, async (req, res) => {
|
|||||||
.select('photos.*')
|
.select('photos.*')
|
||||||
.orderBy('photos.uploaded_at', 'desc');
|
.orderBy('photos.uploaded_at', 'desc');
|
||||||
|
|
||||||
// Apply filtering if requested
|
// Apply filtering if requested (global, based on aggregate counts)
|
||||||
if (filter && guest_id) {
|
if (filter) {
|
||||||
let filters = {};
|
const f = String(filter).toLowerCase();
|
||||||
|
const parts = f.split(',').map(s => s.trim());
|
||||||
|
const include = new Set();
|
||||||
|
|
||||||
// Parse filter parameter
|
// Helper to include IDs for a predicate
|
||||||
if (filter === 'liked') {
|
const includeBy = (predicate) => {
|
||||||
filters.liked = true;
|
photos.forEach(p => { if (predicate(p)) include.add(p.id); });
|
||||||
} else if (filter === 'favorited') {
|
};
|
||||||
filters.favorited = true;
|
|
||||||
} else if (filter === 'liked,favorited' || filter === 'favorited,liked') {
|
if (parts.includes('liked')) {
|
||||||
filters.liked = true;
|
includeBy(p => (p.like_count || 0) > 0);
|
||||||
filters.favorited = true;
|
}
|
||||||
filters.operator = 'OR';
|
if (parts.includes('favorited')) {
|
||||||
|
includeBy(p => (p.favorite_count || 0) > 0);
|
||||||
|
}
|
||||||
|
if (parts.includes('rated')) {
|
||||||
|
includeBy(p => (p.average_rating || 0) > 0);
|
||||||
|
}
|
||||||
|
if (parts.includes('commented')) {
|
||||||
|
// Query commented photo IDs
|
||||||
|
const commented = await db('photo_feedback')
|
||||||
|
.where({ event_id: req.event.id, feedback_type: 'comment', is_approved: true, is_hidden: false })
|
||||||
|
.groupBy('photo_id')
|
||||||
|
.select('photo_id');
|
||||||
|
const commentedIds = new Set(commented.map(c => c.photo_id));
|
||||||
|
includeBy(p => commentedIds.has(p.id));
|
||||||
}
|
}
|
||||||
|
|
||||||
// Get filtered photo IDs
|
if (include.size > 0) {
|
||||||
const filteredPhotoIds = await feedbackService.getFilteredPhotos(
|
photos = photos.filter(p => include.has(p.id));
|
||||||
req.event.id,
|
}
|
||||||
guest_id,
|
|
||||||
filters
|
|
||||||
);
|
|
||||||
|
|
||||||
// Filter photos to only include those with feedback
|
|
||||||
photos = photos.filter(photo => filteredPhotoIds.includes(photo.id));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Then get comment counts separately
|
// Then get comment counts separately
|
||||||
@@ -230,7 +239,7 @@ router.get('/:slug/photos', verifyGalleryAccess, async (req, res) => {
|
|||||||
});
|
});
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('Error fetching photos:', error);
|
console.error('Error fetching photos:', error);
|
||||||
res.status(500).json({ error: 'Failed to fetch photos', details: error.message });
|
res.status(500).json({ error: 'Failed to fetch photos' });
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -384,6 +393,87 @@ router.get('/:slug/download-all', verifyGalleryAccess, async (req, res) => {
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// Download selected photos as ZIP
|
||||||
|
router.post('/:slug/download-selected', verifyGalleryAccess, async (req, res) => {
|
||||||
|
try {
|
||||||
|
// Check if downloads are allowed for this event
|
||||||
|
if (req.event.allow_downloads === false) {
|
||||||
|
return res.status(403).json({ error: 'Downloads are disabled for this gallery' });
|
||||||
|
}
|
||||||
|
|
||||||
|
const ids = Array.isArray(req.body?.photo_ids) ? req.body.photo_ids : [];
|
||||||
|
if (!ids.length) {
|
||||||
|
return res.status(400).json({ error: 'photo_ids is required (non-empty array)' });
|
||||||
|
}
|
||||||
|
|
||||||
|
// Clean IDs
|
||||||
|
const photoIds = ids
|
||||||
|
.map((v) => parseInt(v, 10))
|
||||||
|
.filter((v) => Number.isInteger(v))
|
||||||
|
.slice(0, 500);
|
||||||
|
|
||||||
|
if (photoIds.length === 0) {
|
||||||
|
return res.status(400).json({ error: 'No valid photo IDs provided' });
|
||||||
|
}
|
||||||
|
|
||||||
|
// Fetch photos
|
||||||
|
const photos = await db('photos')
|
||||||
|
.where('photos.event_id', req.event.id)
|
||||||
|
.whereIn('photos.id', photoIds)
|
||||||
|
.select('photos.*')
|
||||||
|
.orderBy('photos.uploaded_at', 'desc');
|
||||||
|
|
||||||
|
if (photos.length === 0) {
|
||||||
|
return res.status(404).json({ error: 'No photos found for selected IDs' });
|
||||||
|
}
|
||||||
|
|
||||||
|
const archiveName = `${req.event.slug}-selected.zip`;
|
||||||
|
res.setHeader('Content-Type', 'application/zip');
|
||||||
|
res.setHeader('Content-Disposition', `attachment; filename="${archiveName}"`);
|
||||||
|
|
||||||
|
const archive = archiver('zip', { zlib: { level: 5 } });
|
||||||
|
archive.on('error', (err) => {
|
||||||
|
console.error('Zip error:', err);
|
||||||
|
try { res.status(500).end(); } catch (e) {}
|
||||||
|
});
|
||||||
|
archive.pipe(res);
|
||||||
|
|
||||||
|
const { resolvePhotoFilePath } = require('../services/photoResolver');
|
||||||
|
const fs = require('fs');
|
||||||
|
// Check watermark settings similar to download-all
|
||||||
|
const watermarkSettings = await watermarkService.getWatermarkSettings();
|
||||||
|
for (const photo of photos) {
|
||||||
|
try {
|
||||||
|
const filePath = resolvePhotoFilePath(req.event, photo);
|
||||||
|
if (filePath && fs.existsSync(filePath)) {
|
||||||
|
const name = photo.filename || `photo-${photo.id}.jpg`;
|
||||||
|
if (watermarkSettings && watermarkSettings.enabled) {
|
||||||
|
// Apply watermark like download-all
|
||||||
|
const watermarkedBuffer = await watermarkService.applyWatermark(filePath, watermarkSettings);
|
||||||
|
archive.append(watermarkedBuffer, { name });
|
||||||
|
} else {
|
||||||
|
archive.file(filePath, { name });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
// skip missing/inaccessible files
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
await archive.finalize();
|
||||||
|
|
||||||
|
await db('access_logs').insert({
|
||||||
|
event_id: req.event.id,
|
||||||
|
ip_address: req.ip,
|
||||||
|
user_agent: req.headers['user-agent'],
|
||||||
|
action: 'download_selected'
|
||||||
|
});
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error in download-selected:', error);
|
||||||
|
res.status(500).json({ error: 'Failed to download selected photos' });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
|
||||||
// View single photo (with watermark if enabled)
|
// View single photo (with watermark if enabled)
|
||||||
router.get('/:slug/photo/:photoId',
|
router.get('/:slug/photo/:photoId',
|
||||||
@@ -413,18 +503,9 @@ router.get('/:slug/photo/:photoId',
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
// Photo path should be in storage/events/active directory
|
// Resolve the absolute file path for this photo, supporting both managed and external reference modes
|
||||||
// Handle both legacy paths (just slug/filename) and new paths (events/active/slug/filename)
|
const { resolvePhotoFilePath } = require('../services/photoResolver');
|
||||||
const storagePath = getStoragePath();
|
const filePath = resolvePhotoFilePath(req.event, photo);
|
||||||
|
|
||||||
let filePath;
|
|
||||||
if (photo.path.startsWith('events/active/')) {
|
|
||||||
// New format: path already includes events/active/ prefix
|
|
||||||
filePath = path.join(storagePath, photo.path);
|
|
||||||
} else {
|
|
||||||
// Legacy format: path is just slug/filename
|
|
||||||
filePath = path.join(storagePath, 'events/active', photo.path);
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
// Log access - temporarily disabled for debugging
|
// Log access - temporarily disabled for debugging
|
||||||
@@ -466,7 +547,7 @@ router.get('/:slug/photo/:photoId',
|
|||||||
photoId: req.params.photoId,
|
photoId: req.params.photoId,
|
||||||
eventId: req.event?.id
|
eventId: req.event?.id
|
||||||
});
|
});
|
||||||
res.status(500).json({ error: 'Failed to serve photo', details: error.message });
|
res.status(500).json({ error: 'Failed to serve photo' });
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ const rateLimit = require('express-rate-limit');
|
|||||||
const jwt = require('jsonwebtoken');
|
const jwt = require('jsonwebtoken');
|
||||||
const { db } = require('../database/db');
|
const { db } = require('../database/db');
|
||||||
const logger = require('../utils/logger');
|
const logger = require('../utils/logger');
|
||||||
|
const { getAdminTokenFromRequest, getGalleryTokenFromRequest } = require('../utils/tokenUtils');
|
||||||
|
|
||||||
// Cache for rate limit settings
|
// Cache for rate limit settings
|
||||||
let settingsCache = null;
|
let settingsCache = null;
|
||||||
@@ -95,12 +96,9 @@ function clearSettingsCache() {
|
|||||||
*/
|
*/
|
||||||
function isAuthenticated(req) {
|
function isAuthenticated(req) {
|
||||||
try {
|
try {
|
||||||
const authHeader = req.headers.authorization;
|
const slugMatch = req.path.match(/\/api\/(?:gallery|secure-images)\/([^\/]+)/);
|
||||||
if (!authHeader || !authHeader.startsWith('Bearer ')) {
|
const slug = slugMatch ? slugMatch[1] : req.requestedSlug;
|
||||||
return false;
|
const token = getAdminTokenFromRequest(req) || getGalleryTokenFromRequest(req, slug);
|
||||||
}
|
|
||||||
|
|
||||||
const token = authHeader.substring(7);
|
|
||||||
const decoded = jwt.verify(token, process.env.JWT_SECRET);
|
const decoded = jwt.verify(token, process.env.JWT_SECRET);
|
||||||
|
|
||||||
// Check if token is valid
|
// Check if token is valid
|
||||||
|
|||||||
@@ -0,0 +1,129 @@
|
|||||||
|
const ADMIN_COOKIE_NAME = 'admin_token';
|
||||||
|
const GALLERY_COOKIE_NAME = 'gallery_token';
|
||||||
|
const GALLERY_COOKIE_PREFIX = 'gallery_token_';
|
||||||
|
|
||||||
|
const DEFAULT_MAX_AGE_MS = 24 * 60 * 60 * 1000; // 24 hours
|
||||||
|
|
||||||
|
const secureCookie = (() => {
|
||||||
|
if (typeof process.env.COOKIE_SECURE === 'string') {
|
||||||
|
return process.env.COOKIE_SECURE.toLowerCase() === 'true';
|
||||||
|
}
|
||||||
|
// Default to false so native HTTP installs stay functional. Operators can
|
||||||
|
// opt-in via COOKIE_SECURE=true when serving behind HTTPS.
|
||||||
|
return false;
|
||||||
|
})();
|
||||||
|
const sameSiteDefault = process.env.COOKIE_SAMESITE || 'Lax';
|
||||||
|
const cookieDomain = process.env.COOKIE_DOMAIN;
|
||||||
|
|
||||||
|
function buildCookieBaseOptions() {
|
||||||
|
const options = {
|
||||||
|
httpOnly: true,
|
||||||
|
secure: secureCookie,
|
||||||
|
sameSite: sameSiteDefault,
|
||||||
|
path: '/',
|
||||||
|
};
|
||||||
|
|
||||||
|
if (cookieDomain) {
|
||||||
|
options.domain = cookieDomain;
|
||||||
|
}
|
||||||
|
|
||||||
|
return options;
|
||||||
|
}
|
||||||
|
|
||||||
|
function buildCookieOptionsWithExpiry(maxAgeMs = DEFAULT_MAX_AGE_MS) {
|
||||||
|
return {
|
||||||
|
...buildCookieBaseOptions(),
|
||||||
|
maxAge: maxAgeMs,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function sanitizeSlugForCookie(slug = '') {
|
||||||
|
return String(slug).replace(/[^A-Za-z0-9_-]/g, '_');
|
||||||
|
}
|
||||||
|
|
||||||
|
function setAdminAuthCookie(res, token) {
|
||||||
|
if (!token) return;
|
||||||
|
res.cookie(ADMIN_COOKIE_NAME, token, buildCookieOptionsWithExpiry());
|
||||||
|
}
|
||||||
|
|
||||||
|
function clearAdminAuthCookie(res) {
|
||||||
|
res.clearCookie(ADMIN_COOKIE_NAME, buildCookieBaseOptions());
|
||||||
|
}
|
||||||
|
|
||||||
|
function setGalleryAuthCookies(res, token, slug) {
|
||||||
|
if (!token) return;
|
||||||
|
const options = buildCookieOptionsWithExpiry();
|
||||||
|
res.cookie(GALLERY_COOKIE_NAME, token, options);
|
||||||
|
if (slug) {
|
||||||
|
const cookieName = `${GALLERY_COOKIE_PREFIX}${sanitizeSlugForCookie(slug)}`;
|
||||||
|
res.cookie(cookieName, token, options);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function clearGalleryAuthCookies(res, slug) {
|
||||||
|
const baseOptions = buildCookieBaseOptions();
|
||||||
|
res.clearCookie(GALLERY_COOKIE_NAME, baseOptions);
|
||||||
|
|
||||||
|
const cookies = res.req?.cookies || {};
|
||||||
|
|
||||||
|
if (slug) {
|
||||||
|
const cookieName = `${GALLERY_COOKIE_PREFIX}${sanitizeSlugForCookie(slug)}`;
|
||||||
|
res.clearCookie(cookieName, baseOptions);
|
||||||
|
} else {
|
||||||
|
Object.keys(cookies).forEach((name) => {
|
||||||
|
if (name.startsWith(GALLERY_COOKIE_PREFIX)) {
|
||||||
|
res.clearCookie(name, baseOptions);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function getAdminTokenFromRequest(req) {
|
||||||
|
const header = req.headers?.authorization;
|
||||||
|
if (header && header.startsWith('Bearer ')) {
|
||||||
|
return header.substring(7);
|
||||||
|
}
|
||||||
|
return req.cookies?.[ADMIN_COOKIE_NAME] || null;
|
||||||
|
}
|
||||||
|
|
||||||
|
function getGalleryTokenFromRequest(req, slug) {
|
||||||
|
const header = req.headers?.authorization;
|
||||||
|
if (header && header.startsWith('Bearer ')) {
|
||||||
|
return header.substring(7);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!req.cookies) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (slug) {
|
||||||
|
const cookieName = `${GALLERY_COOKIE_PREFIX}${sanitizeSlugForCookie(slug)}`;
|
||||||
|
if (req.cookies[cookieName]) {
|
||||||
|
return req.cookies[cookieName];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (req.cookies[GALLERY_COOKIE_NAME]) {
|
||||||
|
return req.cookies[GALLERY_COOKIE_NAME];
|
||||||
|
}
|
||||||
|
|
||||||
|
const prefixed = Object.keys(req.cookies).find((name) => name.startsWith(GALLERY_COOKIE_PREFIX));
|
||||||
|
if (prefixed) {
|
||||||
|
return req.cookies[prefixed];
|
||||||
|
}
|
||||||
|
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = {
|
||||||
|
ADMIN_COOKIE_NAME,
|
||||||
|
GALLERY_COOKIE_NAME,
|
||||||
|
GALLERY_COOKIE_PREFIX,
|
||||||
|
sanitizeSlugForCookie,
|
||||||
|
setAdminAuthCookie,
|
||||||
|
clearAdminAuthCookie,
|
||||||
|
setGalleryAuthCookies,
|
||||||
|
clearGalleryAuthCookies,
|
||||||
|
getAdminTokenFromRequest,
|
||||||
|
getGalleryTokenFromRequest,
|
||||||
|
};
|
||||||
@@ -11,6 +11,7 @@ services:
|
|||||||
- JWT_SECRET=${JWT_SECRET}
|
- JWT_SECRET=${JWT_SECRET}
|
||||||
- ADMIN_USERNAME=${ADMIN_USERNAME:-admin}
|
- ADMIN_USERNAME=${ADMIN_USERNAME:-admin}
|
||||||
- ADMIN_EMAIL=${ADMIN_EMAIL:-admin@example.com}
|
- ADMIN_EMAIL=${ADMIN_EMAIL:-admin@example.com}
|
||||||
|
- ADMIN_PASSWORD=${ADMIN_PASSWORD}
|
||||||
- DATABASE_CLIENT=pg
|
- DATABASE_CLIENT=pg
|
||||||
- DATABASE_URL=postgresql://${DB_USER}:${DB_PASSWORD}@postgres:5432/${DB_NAME}
|
- DATABASE_URL=postgresql://${DB_USER}:${DB_PASSWORD}@postgres:5432/${DB_NAME}
|
||||||
- DB_TYPE=postgresql
|
- DB_TYPE=postgresql
|
||||||
@@ -19,6 +20,7 @@ services:
|
|||||||
- DB_USER=${DB_USER}
|
- DB_USER=${DB_USER}
|
||||||
- DB_PASSWORD=${DB_PASSWORD}
|
- DB_PASSWORD=${DB_PASSWORD}
|
||||||
- DB_NAME=${DB_NAME}
|
- DB_NAME=${DB_NAME}
|
||||||
|
- EXTERNAL_MEDIA_ROOT=${EXTERNAL_MEDIA_ROOT:-/app/storage/external-media}
|
||||||
- SMTP_HOST=${SMTP_HOST}
|
- SMTP_HOST=${SMTP_HOST}
|
||||||
- SMTP_PORT=${SMTP_PORT}
|
- SMTP_PORT=${SMTP_PORT}
|
||||||
- SMTP_SECURE=${SMTP_SECURE:-false}
|
- SMTP_SECURE=${SMTP_SECURE:-false}
|
||||||
|
|||||||
Generated
+36
-47
@@ -1,12 +1,12 @@
|
|||||||
{
|
{
|
||||||
"name": "picpeak-frontend",
|
"name": "picpeak-frontend",
|
||||||
"version": "1.0.124",
|
"version": "1.0.128",
|
||||||
"lockfileVersion": 3,
|
"lockfileVersion": 3,
|
||||||
"requires": true,
|
"requires": true,
|
||||||
"packages": {
|
"packages": {
|
||||||
"": {
|
"": {
|
||||||
"name": "picpeak-frontend",
|
"name": "picpeak-frontend",
|
||||||
"version": "1.0.124",
|
"version": "1.0.128",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@tanstack/react-query": "^5.0.0",
|
"@tanstack/react-query": "^5.0.0",
|
||||||
"@tiptap/extension-character-count": "^2.26.1",
|
"@tiptap/extension-character-count": "^2.26.1",
|
||||||
@@ -20,14 +20,14 @@
|
|||||||
"@types/dompurify": "^3.0.5",
|
"@types/dompurify": "^3.0.5",
|
||||||
"@types/lodash": "^4.17.20",
|
"@types/lodash": "^4.17.20",
|
||||||
"@types/react-google-recaptcha": "^2.1.9",
|
"@types/react-google-recaptcha": "^2.1.9",
|
||||||
"axios": "^1.3.2",
|
"axios": "^1.12.2",
|
||||||
"clsx": "^2.0.0",
|
"clsx": "^2.0.0",
|
||||||
"date-fns": "4.1.0",
|
"date-fns": "4.1.0",
|
||||||
"dompurify": "^3.2.6",
|
"dompurify": "^3.2.6",
|
||||||
"i18next": "^25.3.1",
|
"i18next": "^25.3.1",
|
||||||
"i18next-browser-languagedetector": "^8.2.0",
|
"i18next-browser-languagedetector": "^8.2.0",
|
||||||
"i18next-http-backend": "^3.0.2",
|
"i18next-http-backend": "^3.0.2",
|
||||||
"js-cookie": "^3.0.5",
|
"linkifyjs": "^4.3.2",
|
||||||
"lodash": "^4.17.21",
|
"lodash": "^4.17.21",
|
||||||
"lowlight": "^2.9.0",
|
"lowlight": "^2.9.0",
|
||||||
"lucide-react": "0.525.0",
|
"lucide-react": "0.525.0",
|
||||||
@@ -44,7 +44,6 @@
|
|||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@eslint/js": "^9.29.0",
|
"@eslint/js": "^9.29.0",
|
||||||
"@types/js-cookie": "^3.0.6",
|
|
||||||
"@types/react": "^18.3.12",
|
"@types/react": "^18.3.12",
|
||||||
"@types/react-dom": "^18.3.1",
|
"@types/react-dom": "^18.3.1",
|
||||||
"@vitejs/plugin-react": "^4.5.2",
|
"@vitejs/plugin-react": "^4.5.2",
|
||||||
@@ -57,7 +56,7 @@
|
|||||||
"tailwindcss": "^3.3.0",
|
"tailwindcss": "^3.3.0",
|
||||||
"typescript": "~5.8.3",
|
"typescript": "~5.8.3",
|
||||||
"typescript-eslint": "^8.34.1",
|
"typescript-eslint": "^8.34.1",
|
||||||
"vite": "^7.0.0"
|
"vite": "^7.1.6"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/@alloc/quick-lru": {
|
"node_modules/@alloc/quick-lru": {
|
||||||
@@ -2014,13 +2013,6 @@
|
|||||||
"@types/unist": "^2"
|
"@types/unist": "^2"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/@types/js-cookie": {
|
|
||||||
"version": "3.0.6",
|
|
||||||
"resolved": "https://registry.npmjs.org/@types/js-cookie/-/js-cookie-3.0.6.tgz",
|
|
||||||
"integrity": "sha512-wkw9yd1kEXOPnvEeEV1Go1MmxtBJL0RR79aOTAApecWFVu7w0NNXNqhcWgvw2YgZDYadliXkl14pa3WXw5jlCQ==",
|
|
||||||
"dev": true,
|
|
||||||
"license": "MIT"
|
|
||||||
},
|
|
||||||
"node_modules/@types/json-schema": {
|
"node_modules/@types/json-schema": {
|
||||||
"version": "7.0.15",
|
"version": "7.0.15",
|
||||||
"resolved": "https://registry.npmjs.org/@types/json-schema/-/json-schema-7.0.15.tgz",
|
"resolved": "https://registry.npmjs.org/@types/json-schema/-/json-schema-7.0.15.tgz",
|
||||||
@@ -2549,13 +2541,13 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/axios": {
|
"node_modules/axios": {
|
||||||
"version": "1.10.0",
|
"version": "1.12.2",
|
||||||
"resolved": "https://registry.npmjs.org/axios/-/axios-1.10.0.tgz",
|
"resolved": "https://registry.npmjs.org/axios/-/axios-1.12.2.tgz",
|
||||||
"integrity": "sha512-/1xYAC4MP/HEG+3duIhFr4ZQXR4sQXOIe+o6sdqzeykGLx6Upp/1p8MHqhINOvGeP7xyNHe7tsiJByc4SSVUxw==",
|
"integrity": "sha512-vMJzPewAlRyOgxV2dU0Cuz2O8zzzx9VYtbJOaBgXFeLc4IV/Eg50n4LowmehOOR61S8ZMpc2K5Sa7g6A4jfkUw==",
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"follow-redirects": "^1.15.6",
|
"follow-redirects": "^1.15.6",
|
||||||
"form-data": "^4.0.0",
|
"form-data": "^4.0.4",
|
||||||
"proxy-from-env": "^1.1.0"
|
"proxy-from-env": "^1.1.0"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
@@ -3903,15 +3895,6 @@
|
|||||||
"jiti": "bin/jiti.js"
|
"jiti": "bin/jiti.js"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/js-cookie": {
|
|
||||||
"version": "3.0.5",
|
|
||||||
"resolved": "https://registry.npmjs.org/js-cookie/-/js-cookie-3.0.5.tgz",
|
|
||||||
"integrity": "sha512-cEiJEAEoIbWfCZYKWhVwFuvPX1gETRYPw6LlaTKoxD3s2AkXzkCjnp6h0V77ozyqj0jakteJ4YqDJT830+lVGw==",
|
|
||||||
"license": "MIT",
|
|
||||||
"engines": {
|
|
||||||
"node": ">=14"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"node_modules/js-tokens": {
|
"node_modules/js-tokens": {
|
||||||
"version": "4.0.0",
|
"version": "4.0.0",
|
||||||
"resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz",
|
"resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz",
|
||||||
@@ -4032,9 +4015,9 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/linkifyjs": {
|
"node_modules/linkifyjs": {
|
||||||
"version": "4.3.1",
|
"version": "4.3.2",
|
||||||
"resolved": "https://registry.npmjs.org/linkifyjs/-/linkifyjs-4.3.1.tgz",
|
"resolved": "https://registry.npmjs.org/linkifyjs/-/linkifyjs-4.3.2.tgz",
|
||||||
"integrity": "sha512-DRSlB9DKVW04c4SUdGvKK5FR6be45lTU9M76JnngqPeeGDqPwYc0zdUErtsNVMtxPXgUWV4HbXbnC4sNyBxkYg==",
|
"integrity": "sha512-NT1CJtq3hHIreOianA8aSXn6Cw0JzYOuDQbOrSPe7gqFnCpKP++MQe3ODgO3oh2GJFORkAAdqredOa60z63GbA==",
|
||||||
"license": "MIT"
|
"license": "MIT"
|
||||||
},
|
},
|
||||||
"node_modules/locate-path": {
|
"node_modules/locate-path": {
|
||||||
@@ -5524,14 +5507,14 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/tinyglobby": {
|
"node_modules/tinyglobby": {
|
||||||
"version": "0.2.14",
|
"version": "0.2.15",
|
||||||
"resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.14.tgz",
|
"resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.15.tgz",
|
||||||
"integrity": "sha512-tX5e7OM1HnYr2+a2C/4V0htOcSQcoSTH9KgJnVvNm5zm/cyEWKJ7j7YutsH9CxMdtOkkLFy2AHrMci9IM8IPZQ==",
|
"integrity": "sha512-j2Zq4NyQYG5XMST4cbs02Ak8iJUdxRM0XI5QyxXuZOzKOINmWurp3smXu3y5wDcJrptwpSjgXHzIQxR0omXljQ==",
|
||||||
"dev": true,
|
"dev": true,
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"fdir": "^6.4.4",
|
"fdir": "^6.5.0",
|
||||||
"picomatch": "^4.0.2"
|
"picomatch": "^4.0.3"
|
||||||
},
|
},
|
||||||
"engines": {
|
"engines": {
|
||||||
"node": ">=12.0.0"
|
"node": ">=12.0.0"
|
||||||
@@ -5541,11 +5524,14 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/tinyglobby/node_modules/fdir": {
|
"node_modules/tinyglobby/node_modules/fdir": {
|
||||||
"version": "6.4.6",
|
"version": "6.5.0",
|
||||||
"resolved": "https://registry.npmjs.org/fdir/-/fdir-6.4.6.tgz",
|
"resolved": "https://registry.npmjs.org/fdir/-/fdir-6.5.0.tgz",
|
||||||
"integrity": "sha512-hiFoqpyZcfNm1yc4u8oWCf9A2c4D3QjCrks3zmoVKVxpQRzmPNar1hUJcBG2RQHvEVGDN+Jm81ZheVLAQMK6+w==",
|
"integrity": "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==",
|
||||||
"dev": true,
|
"dev": true,
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
|
"engines": {
|
||||||
|
"node": ">=12.0.0"
|
||||||
|
},
|
||||||
"peerDependencies": {
|
"peerDependencies": {
|
||||||
"picomatch": "^3 || ^4"
|
"picomatch": "^3 || ^4"
|
||||||
},
|
},
|
||||||
@@ -5731,18 +5717,18 @@
|
|||||||
"license": "MIT"
|
"license": "MIT"
|
||||||
},
|
},
|
||||||
"node_modules/vite": {
|
"node_modules/vite": {
|
||||||
"version": "7.0.5",
|
"version": "7.1.6",
|
||||||
"resolved": "https://registry.npmjs.org/vite/-/vite-7.0.5.tgz",
|
"resolved": "https://registry.npmjs.org/vite/-/vite-7.1.6.tgz",
|
||||||
"integrity": "sha512-1mncVwJxy2C9ThLwz0+2GKZyEXuC3MyWtAAlNftlZZXZDP3AJt5FmwcMit/IGGaNZ8ZOB2BNO/HFUB+CpN0NQw==",
|
"integrity": "sha512-SRYIB8t/isTwNn8vMB3MR6E+EQZM/WG1aKmmIUCfDXfVvKfc20ZpamngWHKzAmmu9ppsgxsg4b2I7c90JZudIQ==",
|
||||||
"dev": true,
|
"dev": true,
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"esbuild": "^0.25.0",
|
"esbuild": "^0.25.0",
|
||||||
"fdir": "^6.4.6",
|
"fdir": "^6.5.0",
|
||||||
"picomatch": "^4.0.2",
|
"picomatch": "^4.0.3",
|
||||||
"postcss": "^8.5.6",
|
"postcss": "^8.5.6",
|
||||||
"rollup": "^4.40.0",
|
"rollup": "^4.43.0",
|
||||||
"tinyglobby": "^0.2.14"
|
"tinyglobby": "^0.2.15"
|
||||||
},
|
},
|
||||||
"bin": {
|
"bin": {
|
||||||
"vite": "bin/vite.js"
|
"vite": "bin/vite.js"
|
||||||
@@ -5806,11 +5792,14 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/vite/node_modules/fdir": {
|
"node_modules/vite/node_modules/fdir": {
|
||||||
"version": "6.4.6",
|
"version": "6.5.0",
|
||||||
"resolved": "https://registry.npmjs.org/fdir/-/fdir-6.4.6.tgz",
|
"resolved": "https://registry.npmjs.org/fdir/-/fdir-6.5.0.tgz",
|
||||||
"integrity": "sha512-hiFoqpyZcfNm1yc4u8oWCf9A2c4D3QjCrks3zmoVKVxpQRzmPNar1hUJcBG2RQHvEVGDN+Jm81ZheVLAQMK6+w==",
|
"integrity": "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==",
|
||||||
"dev": true,
|
"dev": true,
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
|
"engines": {
|
||||||
|
"node": ">=12.0.0"
|
||||||
|
},
|
||||||
"peerDependencies": {
|
"peerDependencies": {
|
||||||
"picomatch": "^3 || ^4"
|
"picomatch": "^3 || ^4"
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
{
|
{
|
||||||
"name": "picpeak-frontend",
|
"name": "picpeak-frontend",
|
||||||
"private": true,
|
"private": true,
|
||||||
"version": "1.0.124",
|
"version": "1.0.128",
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"dev": "vite",
|
"dev": "vite",
|
||||||
@@ -23,14 +23,14 @@
|
|||||||
"@types/dompurify": "^3.0.5",
|
"@types/dompurify": "^3.0.5",
|
||||||
"@types/lodash": "^4.17.20",
|
"@types/lodash": "^4.17.20",
|
||||||
"@types/react-google-recaptcha": "^2.1.9",
|
"@types/react-google-recaptcha": "^2.1.9",
|
||||||
"axios": "^1.3.2",
|
"axios": "^1.12.2",
|
||||||
"clsx": "^2.0.0",
|
"clsx": "^2.0.0",
|
||||||
"date-fns": "4.1.0",
|
"date-fns": "4.1.0",
|
||||||
"dompurify": "^3.2.6",
|
"dompurify": "^3.2.6",
|
||||||
"i18next": "^25.3.1",
|
"i18next": "^25.3.1",
|
||||||
"i18next-browser-languagedetector": "^8.2.0",
|
"i18next-browser-languagedetector": "^8.2.0",
|
||||||
"i18next-http-backend": "^3.0.2",
|
"i18next-http-backend": "^3.0.2",
|
||||||
"js-cookie": "^3.0.5",
|
"linkifyjs": "^4.3.2",
|
||||||
"lodash": "^4.17.21",
|
"lodash": "^4.17.21",
|
||||||
"lowlight": "^2.9.0",
|
"lowlight": "^2.9.0",
|
||||||
"lucide-react": "0.525.0",
|
"lucide-react": "0.525.0",
|
||||||
@@ -47,7 +47,6 @@
|
|||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@eslint/js": "^9.29.0",
|
"@eslint/js": "^9.29.0",
|
||||||
"@types/js-cookie": "^3.0.6",
|
|
||||||
"@types/react": "^18.3.12",
|
"@types/react": "^18.3.12",
|
||||||
"@types/react-dom": "^18.3.1",
|
"@types/react-dom": "^18.3.1",
|
||||||
"@vitejs/plugin-react": "^4.5.2",
|
"@vitejs/plugin-react": "^4.5.2",
|
||||||
@@ -60,6 +59,6 @@
|
|||||||
"tailwindcss": "^3.3.0",
|
"tailwindcss": "^3.3.0",
|
||||||
"typescript": "~5.8.3",
|
"typescript": "~5.8.3",
|
||||||
"typescript-eslint": "^8.34.1",
|
"typescript-eslint": "^8.34.1",
|
||||||
"vite": "^7.0.0"
|
"vite": "^7.1.6"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,9 +1,9 @@
|
|||||||
import React, { useEffect } from 'react';
|
import React, { useEffect, useState } from 'react';
|
||||||
import { useLocation } from 'react-router-dom';
|
import { useLocation } from 'react-router-dom';
|
||||||
import { useQuery } from '@tanstack/react-query';
|
import { useQuery } from '@tanstack/react-query';
|
||||||
import { MaintenanceMode } from './MaintenanceMode';
|
import { MaintenanceMode } from './MaintenanceMode';
|
||||||
import { useMaintenanceMode } from '../contexts/MaintenanceContext';
|
import { useMaintenanceMode } from '../contexts/MaintenanceContext';
|
||||||
import { setMaintenanceModeCallback, api, getAuthToken } from '../config/api';
|
import { setMaintenanceModeCallback, api } from '../config/api';
|
||||||
|
|
||||||
interface MaintenanceWrapperProps {
|
interface MaintenanceWrapperProps {
|
||||||
children: React.ReactNode;
|
children: React.ReactNode;
|
||||||
@@ -12,10 +12,38 @@ interface MaintenanceWrapperProps {
|
|||||||
export const MaintenanceWrapper: React.FC<MaintenanceWrapperProps> = ({ children }) => {
|
export const MaintenanceWrapper: React.FC<MaintenanceWrapperProps> = ({ children }) => {
|
||||||
const location = useLocation();
|
const location = useLocation();
|
||||||
const { isMaintenanceMode, setMaintenanceMode } = useMaintenanceMode();
|
const { isMaintenanceMode, setMaintenanceMode } = useMaintenanceMode();
|
||||||
|
const [hasAdminSession, setHasAdminSession] = useState(false);
|
||||||
|
|
||||||
// Check if current route is admin route
|
// Check if current route is admin route
|
||||||
const isAdminRoute = location.pathname.startsWith('/admin');
|
const isAdminRoute = location.pathname.startsWith('/admin');
|
||||||
const hasAdminAuth = !!getAuthToken(true);
|
|
||||||
|
useEffect(() => {
|
||||||
|
let isMounted = true;
|
||||||
|
|
||||||
|
const checkAdminSession = async () => {
|
||||||
|
if (!isAdminRoute) {
|
||||||
|
setHasAdminSession(false);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const response = await api.get<{ valid: boolean; type: string }>('/auth/session');
|
||||||
|
if (isMounted) {
|
||||||
|
setHasAdminSession(Boolean(response.data?.valid && response.data.type === 'admin'));
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
if (isMounted) {
|
||||||
|
setHasAdminSession(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
checkAdminSession();
|
||||||
|
|
||||||
|
return () => {
|
||||||
|
isMounted = false;
|
||||||
|
};
|
||||||
|
}, [isAdminRoute]);
|
||||||
|
|
||||||
// Register the maintenance mode callback
|
// Register the maintenance mode callback
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
@@ -37,7 +65,7 @@ export const MaintenanceWrapper: React.FC<MaintenanceWrapperProps> = ({ children
|
|||||||
} catch (error: any) {
|
} catch (error: any) {
|
||||||
if (error.response?.status === 503) {
|
if (error.response?.status === 503) {
|
||||||
// Only set maintenance mode for non-admin routes or unauthenticated admin routes
|
// Only set maintenance mode for non-admin routes or unauthenticated admin routes
|
||||||
if (!isAdminRoute || !hasAdminAuth) {
|
if (!isAdminRoute || !hasAdminSession) {
|
||||||
setMaintenanceMode(true);
|
setMaintenanceMode(true);
|
||||||
return { maintenance: true };
|
return { maintenance: true };
|
||||||
}
|
}
|
||||||
@@ -47,11 +75,11 @@ export const MaintenanceWrapper: React.FC<MaintenanceWrapperProps> = ({ children
|
|||||||
},
|
},
|
||||||
staleTime: 30000, // Check every 30 seconds
|
staleTime: 30000, // Check every 30 seconds
|
||||||
retry: false, // Don't retry on failure
|
retry: false, // Don't retry on failure
|
||||||
enabled: (!isAdminRoute || !hasAdminAuth) && !isMaintenanceMode, // Don't check if already in maintenance
|
enabled: (!isAdminRoute || !hasAdminSession) && !isMaintenanceMode, // Don't check if already in maintenance
|
||||||
});
|
});
|
||||||
|
|
||||||
// Show maintenance page if in maintenance mode and not on admin route with auth
|
// Show maintenance page if in maintenance mode and not on admin route with auth
|
||||||
if (isMaintenanceMode && (!isAdminRoute || !hasAdminAuth)) {
|
if (isMaintenanceMode && (!isAdminRoute || !hasAdminSession)) {
|
||||||
return <MaintenanceMode />;
|
return <MaintenanceMode />;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -71,8 +71,8 @@ export const AdminHeader: React.FC<AdminHeaderProps> = ({ onMenuClick }) => {
|
|||||||
<header className="sticky top-0 z-30 bg-white border-b border-neutral-200">
|
<header className="sticky top-0 z-30 bg-white border-b border-neutral-200">
|
||||||
<div className="px-4 sm:px-6 lg:px-8">
|
<div className="px-4 sm:px-6 lg:px-8">
|
||||||
<div className="flex items-center justify-between h-16">
|
<div className="flex items-center justify-between h-16">
|
||||||
{/* Left side - Menu button and Date */}
|
{/* Left side - Menu button, Logo, and Date */}
|
||||||
<div className="flex items-center gap-3">
|
<div className="flex items-center gap-3 min-w-0">
|
||||||
<button
|
<button
|
||||||
onClick={onMenuClick}
|
onClick={onMenuClick}
|
||||||
className="lg:hidden text-neutral-500 hover:text-neutral-700"
|
className="lg:hidden text-neutral-500 hover:text-neutral-700"
|
||||||
@@ -80,26 +80,20 @@ export const AdminHeader: React.FC<AdminHeaderProps> = ({ onMenuClick }) => {
|
|||||||
<Menu className="w-6 h-6" />
|
<Menu className="w-6 h-6" />
|
||||||
</button>
|
</button>
|
||||||
|
|
||||||
{/* Date display - hidden on small screens */}
|
{/* PicPeak logo - sticky to the left on all sizes */}
|
||||||
<div className="hidden xl:block">
|
<div className="flex items-center gap-2">
|
||||||
|
<img src="/picpeak-kamera-transparent.png" alt="PicPeak" className="h-8 w-auto object-contain" />
|
||||||
|
<span className="text-xl sm:text-2xl" style={{ fontFamily: 'Poppins, sans-serif', fontWeight: 600, color: '#145346' }}>PicPeak</span>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Date display - hidden on smaller screens */}
|
||||||
|
<div className="hidden xl:block pl-3 border-l border-neutral-200 ml-1">
|
||||||
<p className="text-base text-neutral-700">
|
<p className="text-base text-neutral-700">
|
||||||
{format(new Date(), 'PPPP')}
|
{format(new Date(), 'PPPP')}
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Center - Logo and PicPeak text - hidden on small screens to prevent overlap */}
|
|
||||||
<div className="hidden lg:flex absolute left-1/2 transform -translate-x-1/2 items-center gap-3">
|
|
||||||
<img src="/picpeak-kamera-transparent.png" alt="PicPeak" className="h-10 w-auto object-contain" />
|
|
||||||
<span className="text-2xl" style={{ fontFamily: 'Poppins, sans-serif', fontWeight: 600, color: '#145346' }}>PicPeak</span>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* Mobile Logo - shown only on small screens */}
|
|
||||||
<div className="flex lg:hidden items-center gap-2 mx-auto">
|
|
||||||
<img src="/picpeak-kamera-transparent.png" alt="PicPeak" className="h-8 w-auto object-contain" />
|
|
||||||
<span className="text-xl" style={{ fontFamily: 'Poppins, sans-serif', fontWeight: 600, color: '#145346' }}>PicPeak</span>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* Right side actions */}
|
{/* Right side actions */}
|
||||||
<div className="flex items-center gap-3">
|
<div className="flex items-center gap-3">
|
||||||
{/* Language Selector */}
|
{/* Language Selector */}
|
||||||
|
|||||||
@@ -29,7 +29,10 @@ export const AdminPhotoGrid: React.FC<AdminPhotoGridProps> = ({
|
|||||||
if (e) {
|
if (e) {
|
||||||
e.stopPropagation();
|
e.stopPropagation();
|
||||||
}
|
}
|
||||||
|
// Auto-enable selection mode when selecting via checkbox
|
||||||
|
if (!isSelectionMode) {
|
||||||
|
setIsSelectionMode(true);
|
||||||
|
}
|
||||||
const newSelected = new Set(selectedPhotos);
|
const newSelected = new Set(selectedPhotos);
|
||||||
if (newSelected.has(photoId)) {
|
if (newSelected.has(photoId)) {
|
||||||
newSelected.delete(photoId);
|
newSelected.delete(photoId);
|
||||||
@@ -126,7 +129,7 @@ export const AdminPhotoGrid: React.FC<AdminPhotoGridProps> = ({
|
|||||||
{isSelectionMode ? 'Cancel Selection' : 'Select Photos'}
|
{isSelectionMode ? 'Cancel Selection' : 'Select Photos'}
|
||||||
</Button>
|
</Button>
|
||||||
|
|
||||||
{isSelectionMode && (
|
{(isSelectionMode || selectedPhotos.size > 0) && (
|
||||||
<>
|
<>
|
||||||
<Button
|
<Button
|
||||||
variant="ghost"
|
variant="ghost"
|
||||||
@@ -167,25 +170,32 @@ export const AdminPhotoGrid: React.FC<AdminPhotoGridProps> = ({
|
|||||||
return (
|
return (
|
||||||
<div
|
<div
|
||||||
key={photo.id}
|
key={photo.id}
|
||||||
|
data-testid={`admin-photo-tile-${photo.id}`}
|
||||||
className={`relative group cursor-pointer rounded-lg overflow-hidden bg-neutral-100 transition-opacity ${
|
className={`relative group cursor-pointer rounded-lg overflow-hidden bg-neutral-100 transition-opacity ${
|
||||||
isSelectionMode ? 'ring-2 ring-offset-2 ' + (selectedPhotos.has(photo.id) ? 'ring-primary-500' : 'ring-transparent') : ''
|
isSelectionMode ? 'ring-2 ring-offset-2 ' + (selectedPhotos.has(photo.id) ? 'ring-primary-500' : 'ring-transparent') : ''
|
||||||
} ${isDeleting ? 'opacity-50' : ''}`}
|
} ${isDeleting ? 'opacity-50' : ''}`}
|
||||||
onClick={() => !isDeleting && (isSelectionMode ? handlePhotoSelect(photo.id) : onPhotoClick(photo, index))}
|
onClick={() => !isDeleting && onPhotoClick(photo, index)}
|
||||||
>
|
>
|
||||||
{/* Selection Checkbox */}
|
{/* Selection Checkbox (top-right) */}
|
||||||
{isSelectionMode && (
|
<button
|
||||||
<div className="absolute top-2 left-2 z-10">
|
type="button"
|
||||||
<div className={`w-6 h-6 rounded border-2 flex items-center justify-center ${
|
aria-label={`Select ${photo.filename}`}
|
||||||
selectedPhotos.has(photo.id)
|
role="checkbox"
|
||||||
? 'bg-primary-500 border-primary-500'
|
aria-checked={selectedPhotos.has(photo.id)}
|
||||||
: 'bg-white/80 border-neutral-300'
|
data-testid={`admin-photo-checkbox-${photo.id}`}
|
||||||
}`}>
|
className={`absolute top-2 right-2 z-20 transition-opacity ${
|
||||||
{selectedPhotos.has(photo.id) && (
|
selectedPhotos.has(photo.id) ? 'opacity-100' : 'opacity-0 group-hover:opacity-100'
|
||||||
<Check className="w-4 h-4 text-white" />
|
}`}
|
||||||
)}
|
onClick={(e) => handlePhotoSelect(photo.id, e)}
|
||||||
</div>
|
>
|
||||||
|
<div className={`w-6 h-6 rounded border-2 flex items-center justify-center ${
|
||||||
|
selectedPhotos.has(photo.id)
|
||||||
|
? 'bg-primary-600 border-primary-600'
|
||||||
|
: 'bg-white/90 border-white'
|
||||||
|
}`}>
|
||||||
|
{selectedPhotos.has(photo.id) && <Check className="w-4 h-4 text-white" />}
|
||||||
</div>
|
</div>
|
||||||
)}
|
</button>
|
||||||
|
|
||||||
{/* Thumbnail */}
|
{/* Thumbnail */}
|
||||||
<div className="aspect-square">
|
<div className="aspect-square">
|
||||||
@@ -238,30 +248,30 @@ export const AdminPhotoGrid: React.FC<AdminPhotoGridProps> = ({
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Category Badge */}
|
{/* Category Badge - move to top-left and prevent overlap with select checkbox */}
|
||||||
{photo.category_name && (
|
{photo.category_name && (
|
||||||
<div className="absolute top-2 right-2">
|
<div className="absolute left-2 top-2 pointer-events-none">
|
||||||
<span className="px-2 py-1 text-xs font-medium bg-white/90 text-neutral-700 rounded">
|
<span className="px-2 py-1 text-xs font-medium bg-white/90 text-neutral-700 rounded max-w-[70%] whitespace-nowrap overflow-hidden text-ellipsis">
|
||||||
{photo.category_name}
|
{photo.category_name}
|
||||||
</span>
|
</span>
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{/* Feedback Indicators */}
|
{/* Feedback Indicators (moved to bottom-right to avoid covering category) */}
|
||||||
{(photo.comment_count > 0 || photo.average_rating > 0 || photo.like_count > 0) && (
|
{(photo.comment_count > 0 || photo.average_rating > 0 || photo.like_count > 0) && (
|
||||||
<div className="absolute top-2 left-2 flex gap-1 z-10" style={{ left: isSelectionMode ? '40px' : '8px' }}>
|
<div className="absolute bottom-2 right-2 flex items-center gap-1 z-10">
|
||||||
{photo.comment_count > 0 && (
|
|
||||||
<div className="bg-white/90 backdrop-blur-sm rounded-full px-2 py-1 flex items-center gap-1" title={`${photo.comment_count} comments`}>
|
|
||||||
<MessageSquare className="w-3.5 h-3.5 text-primary-600" fill="currentColor" />
|
|
||||||
<span className="text-xs font-medium text-neutral-700">{photo.comment_count}</span>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
{photo.average_rating > 0 && (
|
{photo.average_rating > 0 && (
|
||||||
<div className="bg-white/90 backdrop-blur-sm rounded-full px-2 py-1 flex items-center gap-1" title={`Rating: ${Number(photo.average_rating).toFixed(1)}`}>
|
<div className="bg-white/90 backdrop-blur-sm rounded-full px-2 py-1 flex items-center gap-1" title={`Rating: ${Number(photo.average_rating).toFixed(1)}`}>
|
||||||
<Star className="w-3.5 h-3.5 text-yellow-500" fill="currentColor" />
|
<Star className="w-3.5 h-3.5 text-yellow-500" fill="currentColor" />
|
||||||
<span className="text-xs font-medium text-neutral-700">{Number(photo.average_rating).toFixed(1)}</span>
|
<span className="text-xs font-medium text-neutral-700">{Number(photo.average_rating).toFixed(1)}</span>
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
{photo.comment_count > 0 && (
|
||||||
|
<div className="bg-white/90 backdrop-blur-sm rounded-full px-2 py-1 flex items-center gap-1" title={`${photo.comment_count} comments`}>
|
||||||
|
<MessageSquare className="w-3.5 h-3.5 text-primary-600" fill="currentColor" />
|
||||||
|
<span className="text-xs font-medium text-neutral-700">{photo.comment_count}</span>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -132,7 +132,7 @@ export const FeedbackModerationPanel: React.FC<FeedbackModerationPanelProps> = (
|
|||||||
<div className="mt-2 flex items-center gap-2">
|
<div className="mt-2 flex items-center gap-2">
|
||||||
<div className="w-16 h-16 overflow-hidden rounded">
|
<div className="w-16 h-16 overflow-hidden rounded">
|
||||||
<AdminAuthenticatedImage
|
<AdminAuthenticatedImage
|
||||||
src={`/api/admin/photos/${eventId}/thumbnail/${item.photo_id}`}
|
src={`/admin/photos/${eventId}/thumbnail/${item.photo_id}`}
|
||||||
alt={item.filename || 'Photo'}
|
alt={item.filename || 'Photo'}
|
||||||
className="w-16 h-16 object-cover rounded"
|
className="w-16 h-16 object-cover rounded"
|
||||||
/>
|
/>
|
||||||
|
|||||||
@@ -1,5 +1,4 @@
|
|||||||
import React, { useState, useEffect } from 'react';
|
import React, { useState, useEffect } from 'react';
|
||||||
import { getAuthToken } from '../../config/api';
|
|
||||||
import { buildResourceUrl } from '../../utils/url';
|
import { buildResourceUrl } from '../../utils/url';
|
||||||
|
|
||||||
interface AuthenticatedImageProps extends React.ImgHTMLAttributes<HTMLImageElement> {
|
interface AuthenticatedImageProps extends React.ImgHTMLAttributes<HTMLImageElement> {
|
||||||
@@ -25,33 +24,12 @@ export const AuthenticatedImage: React.FC<AuthenticatedImageProps> = ({
|
|||||||
let objectUrl: string | null = null;
|
let objectUrl: string | null = null;
|
||||||
|
|
||||||
// Determine which token to use based on context
|
// Determine which token to use based on context
|
||||||
let token: string | undefined;
|
|
||||||
|
|
||||||
if (isGallery) {
|
|
||||||
// For gallery images, get the gallery-specific token
|
|
||||||
const pathParts = window.location.pathname.split('/');
|
|
||||||
if (pathParts[1] === 'gallery' && pathParts[2]) {
|
|
||||||
const gallerySlug = pathParts[2];
|
|
||||||
token = localStorage.getItem(`gallery_token_${gallerySlug}`) || undefined;
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
// For admin images, use the admin token
|
|
||||||
token = getAuthToken(true);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!src) {
|
if (!src) {
|
||||||
setImageSrc(fallbackSrc || '');
|
setImageSrc(fallbackSrc || '');
|
||||||
setIsLoading(false);
|
setIsLoading(false);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!token) {
|
|
||||||
// No auth token - use fallback
|
|
||||||
setImageSrc(fallbackSrc || '');
|
|
||||||
setIsLoading(false);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
setIsLoading(true);
|
setIsLoading(true);
|
||||||
setError(false);
|
setError(false);
|
||||||
|
|
||||||
@@ -71,9 +49,7 @@ export const AuthenticatedImage: React.FC<AuthenticatedImageProps> = ({
|
|||||||
|
|
||||||
// Fetch authenticated image
|
// Fetch authenticated image
|
||||||
const response = await fetch(fullImageUrl, {
|
const response = await fetch(fullImageUrl, {
|
||||||
headers: {
|
credentials: 'include'
|
||||||
'Authorization': `Bearer ${token}`
|
|
||||||
}
|
|
||||||
});
|
});
|
||||||
|
|
||||||
if (!response.ok) {
|
if (!response.ok) {
|
||||||
|
|||||||
@@ -1,18 +1,19 @@
|
|||||||
import React from 'react';
|
import React from 'react';
|
||||||
import { Heart, Star } from 'lucide-react';
|
import { Heart, Star, MessageSquare } from 'lucide-react';
|
||||||
import { Button } from '../common';
|
import { Button } from '../common';
|
||||||
import { useTranslation } from 'react-i18next';
|
import { useTranslation } from 'react-i18next';
|
||||||
|
|
||||||
export type FilterType = 'all' | 'liked' | 'favorited';
|
export type FilterType = 'all' | 'liked' | 'rated' | 'commented';
|
||||||
|
|
||||||
interface GalleryFilterProps {
|
interface GalleryFilterProps {
|
||||||
currentFilter: FilterType;
|
currentFilter: FilterType;
|
||||||
onFilterChange: (filter: FilterType) => void;
|
onFilterChange: (filter: FilterType) => void;
|
||||||
feedbackEnabled: boolean;
|
feedbackEnabled: boolean;
|
||||||
likeCount?: number;
|
likeCount?: number;
|
||||||
favoriteCount?: number;
|
ratedCount?: number;
|
||||||
className?: string;
|
className?: string;
|
||||||
isMobile?: boolean;
|
isMobile?: boolean;
|
||||||
|
variant?: 'default' | 'compact';
|
||||||
}
|
}
|
||||||
|
|
||||||
export const GalleryFilter: React.FC<GalleryFilterProps> = ({
|
export const GalleryFilter: React.FC<GalleryFilterProps> = ({
|
||||||
@@ -20,9 +21,10 @@ export const GalleryFilter: React.FC<GalleryFilterProps> = ({
|
|||||||
onFilterChange,
|
onFilterChange,
|
||||||
feedbackEnabled,
|
feedbackEnabled,
|
||||||
likeCount = 0,
|
likeCount = 0,
|
||||||
favoriteCount = 0,
|
ratedCount = 0,
|
||||||
className = '',
|
className = '',
|
||||||
isMobile = false
|
isMobile = false,
|
||||||
|
variant = 'default'
|
||||||
}) => {
|
}) => {
|
||||||
const { t } = useTranslation();
|
const { t } = useTranslation();
|
||||||
|
|
||||||
@@ -30,6 +32,57 @@ export const GalleryFilter: React.FC<GalleryFilterProps> = ({
|
|||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Compact icon-only vertical variant (used in sidebar and tight spaces)
|
||||||
|
if (variant === 'compact') {
|
||||||
|
return (
|
||||||
|
<div className={`${className}`}>
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
<span className="text-sm text-neutral-700 whitespace-nowrap">
|
||||||
|
{t('gallery.feedbackFilter', 'Feedback Filter')}
|
||||||
|
</span>
|
||||||
|
<div className="flex items-center gap-1">
|
||||||
|
<Button
|
||||||
|
variant={currentFilter === 'all' ? 'primary' : 'outline'}
|
||||||
|
size="sm"
|
||||||
|
onClick={() => onFilterChange('all')}
|
||||||
|
className="p-1 w-8 h-8 flex items-center justify-center"
|
||||||
|
aria-label={t('gallery.all', 'All')}
|
||||||
|
>
|
||||||
|
<svg viewBox="0 0 24 24" className="w-3.5 h-3.5 text-current"><path d="M3 3h8v8H3V3zm10 0h8v8h-8V3zM3 13h8v8H3v-8zm10 8v-8h8v8h-8z"/></svg>
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
variant={currentFilter === 'liked' ? 'primary' : 'outline'}
|
||||||
|
size="sm"
|
||||||
|
onClick={() => onFilterChange('liked')}
|
||||||
|
className="p-1 w-8 h-8 flex items-center justify-center"
|
||||||
|
aria-label={t('feedback.likes', 'Likes')}
|
||||||
|
>
|
||||||
|
<Heart className="w-3.5 h-3.5" />
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
variant={currentFilter === 'rated' ? 'primary' : 'outline'}
|
||||||
|
size="sm"
|
||||||
|
onClick={() => onFilterChange('rated')}
|
||||||
|
className="p-1 w-8 h-8 flex items-center justify-center"
|
||||||
|
aria-label={t('gallery.rated', 'Rated')}
|
||||||
|
>
|
||||||
|
<Star className="w-3.5 h-3.5" />
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
variant={currentFilter === 'commented' ? 'primary' : 'outline'}
|
||||||
|
size="sm"
|
||||||
|
onClick={() => onFilterChange('commented')}
|
||||||
|
className="p-1 w-8 h-8 flex items-center justify-center"
|
||||||
|
aria-label={t('gallery.commented', 'Commented')}
|
||||||
|
>
|
||||||
|
<MessageSquare className="w-3.5 h-3.5" />
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className={`${className}`}>
|
<div className={`${className}`}>
|
||||||
{/* Mobile-optimized vertical layout */}
|
{/* Mobile-optimized vertical layout */}
|
||||||
@@ -59,13 +112,13 @@ export const GalleryFilter: React.FC<GalleryFilterProps> = ({
|
|||||||
</Button>
|
</Button>
|
||||||
|
|
||||||
<Button
|
<Button
|
||||||
variant={currentFilter === 'favorited' ? 'primary' : 'outline'}
|
variant={currentFilter === 'rated' ? 'primary' : 'outline'}
|
||||||
size="sm"
|
size="sm"
|
||||||
onClick={() => onFilterChange('favorited')}
|
onClick={() => onFilterChange('rated')}
|
||||||
className="text-xs flex-1 min-w-[80px] flex items-center justify-center gap-1"
|
className="text-xs flex-1 min-w-[80px] flex items-center justify-center gap-1"
|
||||||
>
|
>
|
||||||
<Star className="w-3 h-3" />
|
<Star className="w-3 h-3" />
|
||||||
<span>{favoriteCount > 0 ? favoriteCount : t('gallery.favorites', 'Favorites')}</span>
|
<span>{ratedCount > 0 ? ratedCount : t('gallery.rated', 'Rated')}</span>
|
||||||
</Button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
@@ -101,19 +154,29 @@ export const GalleryFilter: React.FC<GalleryFilterProps> = ({
|
|||||||
</Button>
|
</Button>
|
||||||
|
|
||||||
<Button
|
<Button
|
||||||
variant={currentFilter === 'favorited' ? 'primary' : 'outline'}
|
variant={currentFilter === 'rated' ? 'primary' : 'outline'}
|
||||||
size="sm"
|
size="sm"
|
||||||
onClick={() => onFilterChange('favorited')}
|
onClick={() => onFilterChange('rated')}
|
||||||
className="text-xs sm:text-sm flex items-center gap-1"
|
className="text-xs sm:text-sm flex items-center gap-1"
|
||||||
>
|
>
|
||||||
<Star className="w-3 h-3 sm:w-4 sm:h-4" />
|
<Star className="w-3 h-3 sm:w-4 sm:h-4" />
|
||||||
<span className="hidden sm:inline">{t('gallery.favorited', 'Favorites')}</span>
|
<span className="hidden sm:inline">{t('gallery.rated', 'Rated')}</span>
|
||||||
{favoriteCount > 0 && (
|
{ratedCount > 0 && (
|
||||||
<span className="bg-primary-100 text-primary-700 px-1.5 rounded">
|
<span className="bg-primary-100 text-primary-700 px-1.5 rounded">
|
||||||
{favoriteCount}
|
{ratedCount}
|
||||||
</span>
|
</span>
|
||||||
)}
|
)}
|
||||||
</Button>
|
</Button>
|
||||||
|
|
||||||
|
<Button
|
||||||
|
variant={currentFilter === 'commented' ? 'primary' : 'outline'}
|
||||||
|
size="sm"
|
||||||
|
onClick={() => onFilterChange('commented')}
|
||||||
|
className="text-xs sm:text-sm flex items-center gap-1"
|
||||||
|
>
|
||||||
|
<MessageSquare className="w-3 h-3 sm:w-4 sm:h-4" />
|
||||||
|
<span className="hidden sm:inline">{t('gallery.commented', 'Commented')}</span>
|
||||||
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|||||||
@@ -33,7 +33,7 @@ interface GallerySidebarProps {
|
|||||||
filterType?: FilterType;
|
filterType?: FilterType;
|
||||||
onFilterChange?: (filter: FilterType) => void;
|
onFilterChange?: (filter: FilterType) => void;
|
||||||
likeCount?: number;
|
likeCount?: number;
|
||||||
favoriteCount?: number;
|
ratedCount?: number;
|
||||||
}
|
}
|
||||||
|
|
||||||
export const GallerySidebar: React.FC<GallerySidebarProps> = ({
|
export const GallerySidebar: React.FC<GallerySidebarProps> = ({
|
||||||
@@ -64,7 +64,7 @@ export const GallerySidebar: React.FC<GallerySidebarProps> = ({
|
|||||||
filterType = 'all',
|
filterType = 'all',
|
||||||
onFilterChange,
|
onFilterChange,
|
||||||
likeCount = 0,
|
likeCount = 0,
|
||||||
favoriteCount = 0
|
ratedCount = 0
|
||||||
}) => {
|
}) => {
|
||||||
const { t } = useTranslation();
|
const { t } = useTranslation();
|
||||||
const sidebarRef = useRef<HTMLDivElement>(null);
|
const sidebarRef = useRef<HTMLDivElement>(null);
|
||||||
@@ -114,7 +114,7 @@ export const GallerySidebar: React.FC<GallerySidebarProps> = ({
|
|||||||
<div
|
<div
|
||||||
ref={sidebarRef}
|
ref={sidebarRef}
|
||||||
className={`
|
className={`
|
||||||
fixed top-0 left-0 h-full bg-white shadow-xl z-50 transition-transform duration-300 ease-in-out
|
fixed top-0 left-0 h-full bg-white shadow-xl z-50 transition-transform duration-300 ease-in-out flex flex-col
|
||||||
${isMobile ? 'w-full max-w-sm' : 'w-80'}
|
${isMobile ? 'w-full max-w-sm' : 'w-80'}
|
||||||
${isOpen ? 'translate-x-0' : '-translate-x-full'}
|
${isOpen ? 'translate-x-0' : '-translate-x-full'}
|
||||||
`}
|
`}
|
||||||
@@ -223,8 +223,9 @@ export const GallerySidebar: React.FC<GallerySidebarProps> = ({
|
|||||||
}}
|
}}
|
||||||
feedbackEnabled={feedbackEnabled}
|
feedbackEnabled={feedbackEnabled}
|
||||||
likeCount={likeCount}
|
likeCount={likeCount}
|
||||||
favoriteCount={favoriteCount}
|
ratedCount={ratedCount}
|
||||||
className="w-full"
|
className="w-full"
|
||||||
|
variant="compact"
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|||||||
@@ -22,6 +22,7 @@ import { Upload, Menu } from 'lucide-react';
|
|||||||
import { galleryService } from '../../services/gallery.service';
|
import { galleryService } from '../../services/gallery.service';
|
||||||
import { feedbackService } from '../../services/feedback.service';
|
import { feedbackService } from '../../services/feedback.service';
|
||||||
import { useWatermarkSettings } from '../../hooks/useWatermarkSettings';
|
import { useWatermarkSettings } from '../../hooks/useWatermarkSettings';
|
||||||
|
import type { Photo } from '../../types';
|
||||||
|
|
||||||
interface GalleryViewProps {
|
interface GalleryViewProps {
|
||||||
slug: string;
|
slug: string;
|
||||||
@@ -58,6 +59,7 @@ export const GalleryView: React.FC<GalleryViewProps> = ({ slug, event }) => {
|
|||||||
const [protectionLevel, setProtectionLevel] = useState<'basic' | 'standard' | 'enhanced' | 'maximum'>('standard');
|
const [protectionLevel, setProtectionLevel] = useState<'basic' | 'standard' | 'enhanced' | 'maximum'>('standard');
|
||||||
const [filterType, setFilterType] = useState<FilterType>('all');
|
const [filterType, setFilterType] = useState<FilterType>('all');
|
||||||
const [guestId, setGuestId] = useState<string>('');
|
const [guestId, setGuestId] = useState<string>('');
|
||||||
|
const [staticHeroPhoto, setStaticHeroPhoto] = useState<Photo | null>(null);
|
||||||
|
|
||||||
// Generate a unique guest ID for this session
|
// Generate a unique guest ID for this session
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
@@ -167,6 +169,23 @@ export const GalleryView: React.FC<GalleryViewProps> = ({ slug, event }) => {
|
|||||||
}
|
}
|
||||||
}, [settingsData]);
|
}, [settingsData]);
|
||||||
|
|
||||||
|
// Determine a stable hero photo from the initial (unfiltered) load
|
||||||
|
useEffect(() => {
|
||||||
|
if (!staticHeroPhoto && data?.photos && filterType === 'all') {
|
||||||
|
let hero: Photo | null = null;
|
||||||
|
const heroId = data?.event?.hero_photo_id || null;
|
||||||
|
if (heroId) {
|
||||||
|
hero = data.photos.find(p => p.id === heroId) || null;
|
||||||
|
}
|
||||||
|
if (!hero && data.photos.length > 0) {
|
||||||
|
hero = data.photos[0];
|
||||||
|
}
|
||||||
|
if (hero) {
|
||||||
|
setStaticHeroPhoto(hero);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}, [data?.photos, data?.event?.hero_photo_id, filterType, staticHeroPhoto]);
|
||||||
|
|
||||||
// Apply theme when settings are loaded
|
// Apply theme when settings are loaded
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (settingsData && data?.event) {
|
if (settingsData && data?.event) {
|
||||||
@@ -247,6 +266,21 @@ export const GalleryView: React.FC<GalleryViewProps> = ({ slug, event }) => {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Apply feedback filter
|
||||||
|
switch (filterType) {
|
||||||
|
case 'liked':
|
||||||
|
photos = photos.filter(photo => (photo.like_count || 0) > 0);
|
||||||
|
break;
|
||||||
|
case 'rated':
|
||||||
|
photos = photos.filter(photo => (photo.average_rating || 0) > 0 || (photo.total_ratings || 0) > 0);
|
||||||
|
break;
|
||||||
|
case 'commented':
|
||||||
|
photos = photos.filter(photo => (photo.comment_count || 0) > 0);
|
||||||
|
break;
|
||||||
|
default:
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
// Apply sorting
|
// Apply sorting
|
||||||
photos.sort((a, b) => {
|
photos.sort((a, b) => {
|
||||||
switch (sortBy) {
|
switch (sortBy) {
|
||||||
@@ -279,7 +313,7 @@ export const GalleryView: React.FC<GalleryViewProps> = ({ slug, event }) => {
|
|||||||
}
|
}
|
||||||
|
|
||||||
return photos;
|
return photos;
|
||||||
}, [data?.photos, selectedCategoryId, searchTerm, sortBy, watermarkEnabled, slug]);
|
}, [data?.photos, selectedCategoryId, searchTerm, sortBy, watermarkEnabled, slug, filterType]);
|
||||||
|
|
||||||
// Check if downloads are allowed (both event setting and not expired)
|
// Check if downloads are allowed (both event setting and not expired)
|
||||||
const allowDownloads = !isExpired && (data?.event?.allow_downloads === true);
|
const allowDownloads = !isExpired && (data?.event?.allow_downloads === true);
|
||||||
@@ -440,7 +474,7 @@ export const GalleryView: React.FC<GalleryViewProps> = ({ slug, event }) => {
|
|||||||
filterType={filterType}
|
filterType={filterType}
|
||||||
onFilterChange={setFilterType}
|
onFilterChange={setFilterType}
|
||||||
likeCount={data?.photos?.filter(p => p.like_count > 0).length || 0}
|
likeCount={data?.photos?.filter(p => p.like_count > 0).length || 0}
|
||||||
favoriteCount={data?.photos?.filter(p => p.favorite_count > 0).length || 0}
|
ratedCount={data?.photos?.filter(p => (p.total_ratings || 0) > 0).length || 0}
|
||||||
/>
|
/>
|
||||||
) : null}
|
) : null}
|
||||||
|
|
||||||
@@ -531,8 +565,6 @@ export const GalleryView: React.FC<GalleryViewProps> = ({ slug, event }) => {
|
|||||||
feedbackEnabled={feedbackEnabled}
|
feedbackEnabled={feedbackEnabled}
|
||||||
currentFilter={filterType}
|
currentFilter={filterType}
|
||||||
onFilterChange={setFilterType}
|
onFilterChange={setFilterType}
|
||||||
likeCount={data?.photos?.filter(p => p.like_count > 0).length || 0}
|
|
||||||
favoriteCount={data?.photos?.filter(p => p.favorite_count > 0).length || 0}
|
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
) : null}
|
) : null}
|
||||||
@@ -543,7 +575,16 @@ export const GalleryView: React.FC<GalleryViewProps> = ({ slug, event }) => {
|
|||||||
photos={filteredPhotos}
|
photos={filteredPhotos}
|
||||||
slug={slug}
|
slug={slug}
|
||||||
categoryId={selectedCategoryId}
|
categoryId={selectedCategoryId}
|
||||||
|
onFeedbackChange={() => refetch()}
|
||||||
|
heroPhotoOverride={staticHeroPhoto}
|
||||||
feedbackEnabled={feedbackEnabled}
|
feedbackEnabled={feedbackEnabled}
|
||||||
|
feedbackOptions={{
|
||||||
|
allowLikes: !!feedbackSettings?.allow_likes,
|
||||||
|
allowFavorites: !!feedbackSettings?.allow_favorites,
|
||||||
|
allowRatings: !!feedbackSettings?.allow_ratings,
|
||||||
|
allowComments: !!feedbackSettings?.allow_comments,
|
||||||
|
requireNameEmail: !!feedbackSettings?.require_name_email,
|
||||||
|
}}
|
||||||
isSelectionMode={isSelectionMode}
|
isSelectionMode={isSelectionMode}
|
||||||
selectedPhotos={selectedPhotos}
|
selectedPhotos={selectedPhotos}
|
||||||
onSelectionChange={setSelectedPhotos}
|
onSelectionChange={setSelectedPhotos}
|
||||||
|
|||||||
@@ -4,7 +4,6 @@ import { feedbackService } from '../../services/feedback.service';
|
|||||||
import { PhotoRating } from './PhotoRating';
|
import { PhotoRating } from './PhotoRating';
|
||||||
import { PhotoLikes } from './PhotoLikes';
|
import { PhotoLikes } from './PhotoLikes';
|
||||||
import { PhotoComments } from './PhotoComments';
|
import { PhotoComments } from './PhotoComments';
|
||||||
import { PhotoFavorites } from './PhotoFavorites';
|
|
||||||
import { Skeleton } from '../common';
|
import { Skeleton } from '../common';
|
||||||
import type { FeedbackSettings } from '../../services/feedback.service';
|
import type { FeedbackSettings } from '../../services/feedback.service';
|
||||||
|
|
||||||
@@ -43,18 +42,14 @@ export const PhotoFeedback: React.FC<PhotoFeedbackProps> = ({
|
|||||||
// Local state for optimistic updates
|
// Local state for optimistic updates
|
||||||
const [currentRating, setCurrentRating] = useState(0);
|
const [currentRating, setCurrentRating] = useState(0);
|
||||||
const [isLiked, setIsLiked] = useState(false);
|
const [isLiked, setIsLiked] = useState(false);
|
||||||
const [isFavorited, setIsFavorited] = useState(false);
|
|
||||||
const [likeCount, setLikeCount] = useState(0);
|
const [likeCount, setLikeCount] = useState(0);
|
||||||
const [favoriteCount, setFavoriteCount] = useState(0);
|
|
||||||
|
|
||||||
// Update local state when data loads
|
// Update local state when data loads
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (feedbackData) {
|
if (feedbackData) {
|
||||||
setCurrentRating(feedbackData.my_feedback.rating || 0);
|
setCurrentRating(feedbackData.my_feedback.rating || 0);
|
||||||
setIsLiked(feedbackData.my_feedback.liked);
|
setIsLiked(feedbackData.my_feedback.liked);
|
||||||
setIsFavorited(feedbackData.my_feedback.favorited);
|
|
||||||
setLikeCount(feedbackData.summary.like_count);
|
setLikeCount(feedbackData.summary.like_count);
|
||||||
setFavoriteCount(feedbackData.summary.favorite_count);
|
|
||||||
}
|
}
|
||||||
}, [feedbackData]);
|
}, [feedbackData]);
|
||||||
|
|
||||||
@@ -70,12 +65,6 @@ export const PhotoFeedback: React.FC<PhotoFeedbackProps> = ({
|
|||||||
if (onFeedbackUpdate) onFeedbackUpdate();
|
if (onFeedbackUpdate) onFeedbackUpdate();
|
||||||
};
|
};
|
||||||
|
|
||||||
const handleFavoriteChange = (favorited: boolean) => {
|
|
||||||
setIsFavorited(favorited);
|
|
||||||
setFavoriteCount(prev => favorited ? prev + 1 : Math.max(0, prev - 1));
|
|
||||||
if (onFeedbackUpdate) onFeedbackUpdate();
|
|
||||||
};
|
|
||||||
|
|
||||||
if (settingsLoading) {
|
if (settingsLoading) {
|
||||||
return (
|
return (
|
||||||
<div className={`space-y-3 ${className}`}>
|
<div className={`space-y-3 ${className}`}>
|
||||||
@@ -90,7 +79,7 @@ export const PhotoFeedback: React.FC<PhotoFeedbackProps> = ({
|
|||||||
}
|
}
|
||||||
|
|
||||||
const hasAnyFeedbackType = settings.allow_ratings || settings.allow_likes ||
|
const hasAnyFeedbackType = settings.allow_ratings || settings.allow_likes ||
|
||||||
settings.allow_comments || settings.allow_favorites;
|
settings.allow_comments;
|
||||||
|
|
||||||
if (!hasAnyFeedbackType) {
|
if (!hasAnyFeedbackType) {
|
||||||
return null;
|
return null;
|
||||||
@@ -113,7 +102,7 @@ export const PhotoFeedback: React.FC<PhotoFeedbackProps> = ({
|
|||||||
)}
|
)}
|
||||||
|
|
||||||
{/* Action Buttons */}
|
{/* Action Buttons */}
|
||||||
{(settings.allow_likes || settings.allow_favorites) && (
|
{settings.allow_likes && (
|
||||||
<div className="flex items-center gap-2">
|
<div className="flex items-center gap-2">
|
||||||
{settings.allow_likes && (
|
{settings.allow_likes && (
|
||||||
<PhotoLikes
|
<PhotoLikes
|
||||||
@@ -126,17 +115,6 @@ export const PhotoFeedback: React.FC<PhotoFeedbackProps> = ({
|
|||||||
onLikeChange={handleLikeChange}
|
onLikeChange={handleLikeChange}
|
||||||
/>
|
/>
|
||||||
)}
|
)}
|
||||||
{settings.allow_favorites && (
|
|
||||||
<PhotoFavorites
|
|
||||||
photoId={photoId}
|
|
||||||
gallerySlug={gallerySlug}
|
|
||||||
isFavorited={isFavorited}
|
|
||||||
favoriteCount={favoriteCount}
|
|
||||||
isEnabled={true}
|
|
||||||
requireNameEmail={settings.require_name_email || false}
|
|
||||||
onFavoriteChange={handleFavoriteChange}
|
|
||||||
/>
|
|
||||||
)}
|
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
import React, { useState } from 'react';
|
import React, { useState } from 'react';
|
||||||
import { Search, SortAsc, Grid, Heart, Star } from 'lucide-react';
|
import { Search, SortAsc, Grid, Heart, Star, MessageSquare } from 'lucide-react';
|
||||||
import { useTranslation } from 'react-i18next';
|
import { useTranslation } from 'react-i18next';
|
||||||
import { Button, Input } from '../common';
|
import { Button, Input } from '../common';
|
||||||
import type { FilterType } from './GalleryFilter';
|
import type { FilterType } from './GalleryFilter';
|
||||||
@@ -32,8 +32,6 @@ interface PhotoFilterBarProps {
|
|||||||
feedbackEnabled?: boolean;
|
feedbackEnabled?: boolean;
|
||||||
currentFilter?: FilterType;
|
currentFilter?: FilterType;
|
||||||
onFilterChange?: (filter: FilterType) => void;
|
onFilterChange?: (filter: FilterType) => void;
|
||||||
likeCount?: number;
|
|
||||||
favoriteCount?: number;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export const PhotoFilterBar: React.FC<PhotoFilterBarProps> = ({
|
export const PhotoFilterBar: React.FC<PhotoFilterBarProps> = ({
|
||||||
@@ -49,8 +47,6 @@ export const PhotoFilterBar: React.FC<PhotoFilterBarProps> = ({
|
|||||||
feedbackEnabled = false,
|
feedbackEnabled = false,
|
||||||
currentFilter = 'all',
|
currentFilter = 'all',
|
||||||
onFilterChange,
|
onFilterChange,
|
||||||
likeCount = 0,
|
|
||||||
favoriteCount = 0,
|
|
||||||
}) => {
|
}) => {
|
||||||
const { t } = useTranslation();
|
const { t } = useTranslation();
|
||||||
const [showSortMenu, setShowSortMenu] = useState(false);
|
const [showSortMenu, setShowSortMenu] = useState(false);
|
||||||
@@ -143,6 +139,7 @@ export const PhotoFilterBar: React.FC<PhotoFilterBarProps> = ({
|
|||||||
{/* Categories Row */}
|
{/* Categories Row */}
|
||||||
{categories && categories.length > 0 && (
|
{categories && categories.length > 0 && (
|
||||||
<div className="flex items-start lg:items-center justify-between flex-col lg:flex-row gap-3">
|
<div className="flex items-start lg:items-center justify-between flex-col lg:flex-row gap-3">
|
||||||
|
{/* Categories: keep in a horizontal scroll container */}
|
||||||
<div className="w-full overflow-x-auto pb-2 lg:pb-0">
|
<div className="w-full overflow-x-auto pb-2 lg:pb-0">
|
||||||
<div className="flex items-center gap-2 min-w-max">
|
<div className="flex items-center gap-2 min-w-max">
|
||||||
<Button
|
<Button
|
||||||
@@ -170,81 +167,104 @@ export const PhotoFilterBar: React.FC<PhotoFilterBarProps> = ({
|
|||||||
</Button>
|
</Button>
|
||||||
);
|
);
|
||||||
})}
|
})}
|
||||||
|
|
||||||
{/* Feedback Filter - Inline on desktop, below on mobile/tablet */}
|
|
||||||
{feedbackEnabled && onFilterChange && (
|
|
||||||
<>
|
|
||||||
{/* Desktop: Divider and inline filter - only on larger screens */}
|
|
||||||
<div className="hidden lg:flex items-center gap-2 ml-2 pl-2 border-l border-neutral-300">
|
|
||||||
<span className="text-sm text-neutral-600 whitespace-nowrap">{t('gallery.feedbackFilter')}:</span>
|
|
||||||
<Button
|
|
||||||
variant={currentFilter === 'all' ? 'primary' : 'outline'}
|
|
||||||
size="sm"
|
|
||||||
onClick={() => onFilterChange('all')}
|
|
||||||
className="text-xs sm:text-sm"
|
|
||||||
>
|
|
||||||
{t('gallery.all')}
|
|
||||||
</Button>
|
|
||||||
<Button
|
|
||||||
variant={currentFilter === 'liked' ? 'primary' : 'outline'}
|
|
||||||
size="sm"
|
|
||||||
onClick={() => onFilterChange('liked')}
|
|
||||||
className="text-xs sm:text-sm flex items-center gap-1"
|
|
||||||
>
|
|
||||||
<Heart className="w-3 h-3" />
|
|
||||||
{likeCount > 0 && <span>{likeCount}</span>}
|
|
||||||
</Button>
|
|
||||||
<Button
|
|
||||||
variant={currentFilter === 'favorited' ? 'primary' : 'outline'}
|
|
||||||
size="sm"
|
|
||||||
onClick={() => onFilterChange('favorited')}
|
|
||||||
className="text-xs sm:text-sm flex items-center gap-1"
|
|
||||||
>
|
|
||||||
<Star className="w-3 h-3" />
|
|
||||||
{favoriteCount > 0 && <span>{favoriteCount}</span>}
|
|
||||||
</Button>
|
|
||||||
</div>
|
|
||||||
</>
|
|
||||||
)}
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
{/* Desktop: compact horizontal feedback filter with headline (icons only) */}
|
||||||
|
{feedbackEnabled && onFilterChange && (
|
||||||
|
<div className="hidden lg:flex items-center gap-2 mx-2 flex-shrink-0">
|
||||||
|
<span className="text-sm text-neutral-600 whitespace-nowrap">
|
||||||
|
{t('gallery.feedbackFilter', 'Feedback Filter')}
|
||||||
|
</span>
|
||||||
|
<div className="flex items-center gap-1">
|
||||||
|
<Button
|
||||||
|
variant={currentFilter === 'all' ? 'primary' : 'outline'}
|
||||||
|
size="sm"
|
||||||
|
onClick={() => onFilterChange('all')}
|
||||||
|
className="p-1 w-8 h-8 flex items-center justify-center"
|
||||||
|
aria-label={t('gallery.all', 'All')}
|
||||||
|
>
|
||||||
|
<Grid className="w-3.5 h-3.5" />
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
variant={currentFilter === 'liked' ? 'primary' : 'outline'}
|
||||||
|
size="sm"
|
||||||
|
onClick={() => onFilterChange('liked')}
|
||||||
|
className="p-1 w-8 h-8 flex items-center justify-center"
|
||||||
|
aria-label={t('feedback.likes', 'Likes')}
|
||||||
|
>
|
||||||
|
<Heart className="w-3.5 h-3.5" />
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
variant={currentFilter === 'rated' ? 'primary' : 'outline'}
|
||||||
|
size="sm"
|
||||||
|
onClick={() => onFilterChange('rated')}
|
||||||
|
className="p-1 w-8 h-8 flex items-center justify-center"
|
||||||
|
aria-label={t('gallery.rated', 'Rated')}
|
||||||
|
>
|
||||||
|
<Star className="w-3.5 h-3.5" />
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
variant={currentFilter === 'commented' ? 'primary' : 'outline'}
|
||||||
|
size="sm"
|
||||||
|
onClick={() => onFilterChange('commented')}
|
||||||
|
className="p-1 w-8 h-8 flex items-center justify-center"
|
||||||
|
aria-label={t('gallery.commented', 'Commented')}
|
||||||
|
>
|
||||||
|
<MessageSquare className="w-3.5 h-3.5" />
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
<p className="text-xs md:text-sm text-neutral-600 flex-shrink-0 ml-auto">
|
<p className="text-xs md:text-sm text-neutral-600 flex-shrink-0 ml-auto">
|
||||||
{photoCount} {photoCount === 1 ? t('common.photo') : t('common.photos')}
|
{photoCount} {photoCount === 1 ? t('common.photo') : t('common.photos')}
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{/* Mobile/Tablet: Feedback Filter below categories */}
|
{/* Mobile/Tablet: compact horizontal icons with headline below categories */}
|
||||||
{feedbackEnabled && onFilterChange && (
|
{feedbackEnabled && onFilterChange && (
|
||||||
<div className="flex lg:hidden items-center gap-2">
|
<div className="flex lg:hidden items-center gap-2">
|
||||||
<span className="text-xs text-neutral-600">{t('gallery.feedbackFilter')}:</span>
|
<span className="text-xs text-neutral-600 whitespace-nowrap">
|
||||||
<div className="flex gap-1 flex-1">
|
{t('gallery.feedbackFilter', 'Feedback Filter')}
|
||||||
|
</span>
|
||||||
|
<div className="flex items-center gap-1">
|
||||||
<Button
|
<Button
|
||||||
variant={currentFilter === 'all' ? 'primary' : 'outline'}
|
variant={currentFilter === 'all' ? 'primary' : 'outline'}
|
||||||
size="sm"
|
size="sm"
|
||||||
onClick={() => onFilterChange('all')}
|
onClick={() => onFilterChange('all')}
|
||||||
className="text-xs flex-1"
|
className="p-1 w-8 h-8 flex items-center justify-center"
|
||||||
|
aria-label={t('gallery.all', 'All')}
|
||||||
>
|
>
|
||||||
{t('gallery.all')}
|
<Grid className="w-3.5 h-3.5" />
|
||||||
</Button>
|
</Button>
|
||||||
<Button
|
<Button
|
||||||
variant={currentFilter === 'liked' ? 'primary' : 'outline'}
|
variant={currentFilter === 'liked' ? 'primary' : 'outline'}
|
||||||
size="sm"
|
size="sm"
|
||||||
onClick={() => onFilterChange('liked')}
|
onClick={() => onFilterChange('liked')}
|
||||||
className="text-xs flex-1 flex items-center justify-center gap-1"
|
className="p-1 w-8 h-8 flex items-center justify-center"
|
||||||
|
aria-label={t('feedback.likes', 'Likes')}
|
||||||
>
|
>
|
||||||
<Heart className="w-3 h-3" />
|
<Heart className="w-3.5 h-3.5" />
|
||||||
{likeCount > 0 && <span>{likeCount}</span>}
|
|
||||||
</Button>
|
</Button>
|
||||||
<Button
|
<Button
|
||||||
variant={currentFilter === 'favorited' ? 'primary' : 'outline'}
|
variant={currentFilter === 'rated' ? 'primary' : 'outline'}
|
||||||
size="sm"
|
size="sm"
|
||||||
onClick={() => onFilterChange('favorited')}
|
onClick={() => onFilterChange('rated')}
|
||||||
className="text-xs flex-1 flex items-center justify-center gap-1"
|
className="p-1 w-8 h-8 flex items-center justify-center"
|
||||||
|
aria-label={t('gallery.rated', 'Rated')}
|
||||||
>
|
>
|
||||||
<Star className="w-3 h-3" />
|
<Star className="w-3.5 h-3.5" />
|
||||||
{favoriteCount > 0 && <span>{favoriteCount}</span>}
|
</Button>
|
||||||
|
<Button
|
||||||
|
variant={currentFilter === 'commented' ? 'primary' : 'outline'}
|
||||||
|
size="sm"
|
||||||
|
onClick={() => onFilterChange('commented')}
|
||||||
|
className="p-1 w-8 h-8 flex items-center justify-center"
|
||||||
|
aria-label={t('gallery.commented', 'Commented')}
|
||||||
|
>
|
||||||
|
<MessageSquare className="w-3.5 h-3.5" />
|
||||||
</Button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -95,35 +95,17 @@ export const PhotoGrid: React.FC<PhotoGridProps> = ({
|
|||||||
|
|
||||||
const handleDownloadSelected = async () => {
|
const handleDownloadSelected = async () => {
|
||||||
if (selectedPhotos.size === 0) return;
|
if (selectedPhotos.size === 0) return;
|
||||||
|
const ids = Array.from(selectedPhotos);
|
||||||
const selectedPhotosList = photos.filter(p => selectedPhotos.has(p.id));
|
toastify.info(t('gallery.downloading', { count: ids.length }));
|
||||||
|
|
||||||
toastify.info(t('gallery.downloading', { count: selectedPhotos.size }));
|
|
||||||
|
|
||||||
// Download each selected photo
|
|
||||||
const downloadPromises = selectedPhotosList.map(photo =>
|
|
||||||
galleryService.downloadPhoto(slug, photo.id, photo.filename)
|
|
||||||
.catch(err => {
|
|
||||||
// Download failed - error handled by UI
|
|
||||||
return null;
|
|
||||||
})
|
|
||||||
);
|
|
||||||
|
|
||||||
try {
|
try {
|
||||||
await Promise.all(downloadPromises);
|
await galleryService.downloadSelectedPhotos(slug, ids);
|
||||||
toastify.success(t('gallery.downloadedPhotos', { count: selectedPhotos.size }));
|
analyticsService.trackGalleryEvent('bulk_download_selected', { gallery: slug, photo_count: ids.length });
|
||||||
|
|
||||||
// Track bulk download
|
|
||||||
analyticsService.trackGalleryEvent('bulk_download', {
|
|
||||||
gallery: slug,
|
|
||||||
photo_count: selectedPhotos.size
|
|
||||||
});
|
|
||||||
|
|
||||||
// Clear selection after download
|
|
||||||
setSelectedPhotos(new Set());
|
|
||||||
setIsSelectionMode(false);
|
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
toastify.error(t('gallery.downloadError'));
|
toastify.error(t('gallery.downloadError'));
|
||||||
|
} finally {
|
||||||
|
setSelectedPhotos(new Set());
|
||||||
|
setIsSelectionMode(false);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -316,7 +298,7 @@ const PhotoThumbnail: React.FC<PhotoThumbnailProps> = ({
|
|||||||
)}
|
)}
|
||||||
|
|
||||||
{/* Overlay on hover/tap - Always visible on mobile for better UX */}
|
{/* Overlay on hover/tap - Always visible on mobile for better UX */}
|
||||||
<div className="absolute inset-0 bg-black/40 opacity-0 group-hover:opacity-100 sm:opacity-0 sm:group-hover:opacity-100 transition-opacity duration-200 rounded-lg flex items-center justify-center gap-2">
|
<div className="absolute inset-0 bg-black/40 opacity-100 md:opacity-0 md:group-hover:opacity-100 transition-opacity duration-200 rounded-lg flex items-center justify-center gap-2">
|
||||||
{!isSelectionMode && (
|
{!isSelectionMode && (
|
||||||
<>
|
<>
|
||||||
<button
|
<button
|
||||||
|
|||||||
@@ -25,6 +25,9 @@ interface PhotoGridWithLayoutsProps {
|
|||||||
photos: Photo[];
|
photos: Photo[];
|
||||||
slug: string;
|
slug: string;
|
||||||
categoryId?: number | null;
|
categoryId?: number | null;
|
||||||
|
// When provided, the hero layout will use this photo
|
||||||
|
// instead of deriving from the filtered photo list.
|
||||||
|
heroPhotoOverride?: Photo | null;
|
||||||
isSelectionMode?: boolean;
|
isSelectionMode?: boolean;
|
||||||
selectedPhotos?: Set<number>;
|
selectedPhotos?: Set<number>;
|
||||||
onSelectionChange?: (photos: Set<number>) => void;
|
onSelectionChange?: (photos: Set<number>) => void;
|
||||||
@@ -38,15 +41,26 @@ interface PhotoGridWithLayoutsProps {
|
|||||||
allowDownloads?: boolean;
|
allowDownloads?: boolean;
|
||||||
protectionLevel?: 'basic' | 'standard' | 'enhanced' | 'maximum';
|
protectionLevel?: 'basic' | 'standard' | 'enhanced' | 'maximum';
|
||||||
useEnhancedProtection?: boolean;
|
useEnhancedProtection?: boolean;
|
||||||
|
feedbackOptions?: {
|
||||||
|
allowLikes?: boolean;
|
||||||
|
allowFavorites?: boolean;
|
||||||
|
allowRatings?: boolean;
|
||||||
|
allowComments?: boolean;
|
||||||
|
requireNameEmail?: boolean;
|
||||||
|
};
|
||||||
|
onFeedbackChange?: () => void;
|
||||||
}
|
}
|
||||||
|
|
||||||
export const PhotoGridWithLayouts: React.FC<PhotoGridWithLayoutsProps> = ({
|
export const PhotoGridWithLayouts: React.FC<PhotoGridWithLayoutsProps> = ({
|
||||||
photos,
|
photos,
|
||||||
slug,
|
slug,
|
||||||
categoryId,
|
categoryId,
|
||||||
|
heroPhotoOverride,
|
||||||
isSelectionMode: parentSelectionMode,
|
isSelectionMode: parentSelectionMode,
|
||||||
selectedPhotos: parentSelectedPhotos,
|
selectedPhotos: parentSelectedPhotos,
|
||||||
feedbackEnabled,
|
feedbackEnabled,
|
||||||
|
feedbackOptions,
|
||||||
|
onFeedbackChange,
|
||||||
allowDownloads = true,
|
allowDownloads = true,
|
||||||
protectionLevel = 'standard',
|
protectionLevel = 'standard',
|
||||||
useEnhancedProtection = false,
|
useEnhancedProtection = false,
|
||||||
@@ -61,6 +75,7 @@ export const PhotoGridWithLayouts: React.FC<PhotoGridWithLayoutsProps> = ({
|
|||||||
const { t } = useTranslation();
|
const { t } = useTranslation();
|
||||||
const { theme } = useTheme();
|
const { theme } = useTheme();
|
||||||
const [selectedPhotoIndex, setSelectedPhotoIndex] = useState<number | null>(null);
|
const [selectedPhotoIndex, setSelectedPhotoIndex] = useState<number | null>(null);
|
||||||
|
const [openFeedbackInitially, setOpenFeedbackInitially] = useState<boolean>(false);
|
||||||
const [localSelectedPhotos, setLocalSelectedPhotos] = useState<Set<number>>(new Set());
|
const [localSelectedPhotos, setLocalSelectedPhotos] = useState<Set<number>>(new Set());
|
||||||
const [localSelectionMode, setLocalSelectionMode] = useState(false);
|
const [localSelectionMode, setLocalSelectionMode] = useState(false);
|
||||||
const downloadPhotoMutation = useDownloadPhoto();
|
const downloadPhotoMutation = useDownloadPhoto();
|
||||||
@@ -77,10 +92,24 @@ export const PhotoGridWithLayouts: React.FC<PhotoGridWithLayoutsProps> = ({
|
|||||||
}, [categoryId]);
|
}, [categoryId]);
|
||||||
|
|
||||||
const handlePhotoClick = (index: number) => {
|
const handlePhotoClick = (index: number) => {
|
||||||
|
setOpenFeedbackInitially(false);
|
||||||
|
setSelectedPhotoIndex(index);
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleOpenWithFeedback = (index: number) => {
|
||||||
|
setOpenFeedbackInitially(true);
|
||||||
setSelectedPhotoIndex(index);
|
setSelectedPhotoIndex(index);
|
||||||
};
|
};
|
||||||
|
|
||||||
const handlePhotoSelect = (photoId: number) => {
|
const handlePhotoSelect = (photoId: number) => {
|
||||||
|
// Auto-enable selection mode when selecting via checkbox
|
||||||
|
if (!isSelectionMode) {
|
||||||
|
if (parentToggleSelectionMode) {
|
||||||
|
parentToggleSelectionMode();
|
||||||
|
} else {
|
||||||
|
setLocalSelectionMode(true);
|
||||||
|
}
|
||||||
|
}
|
||||||
const newSelected = new Set(selectedPhotos);
|
const newSelected = new Set(selectedPhotos);
|
||||||
if (newSelected.has(photoId)) {
|
if (newSelected.has(photoId)) {
|
||||||
newSelected.delete(photoId);
|
newSelected.delete(photoId);
|
||||||
@@ -114,39 +143,21 @@ export const PhotoGridWithLayouts: React.FC<PhotoGridWithLayoutsProps> = ({
|
|||||||
|
|
||||||
const handleDownloadSelected = async () => {
|
const handleDownloadSelected = async () => {
|
||||||
if (selectedPhotos.size === 0) return;
|
if (selectedPhotos.size === 0) return;
|
||||||
|
const ids = Array.from(selectedPhotos);
|
||||||
const selectedPhotosList = photos.filter(p => selectedPhotos.has(p.id));
|
toastify.info(t('gallery.downloading', { count: ids.length }));
|
||||||
|
|
||||||
toastify.info(t('gallery.downloading', { count: selectedPhotos.size }));
|
|
||||||
|
|
||||||
// Download each selected photo
|
|
||||||
const downloadPromises = selectedPhotosList.map(photo =>
|
|
||||||
galleryService.downloadPhoto(slug, photo.id, photo.filename)
|
|
||||||
.catch(err => {
|
|
||||||
// Download failed - error handled by UI
|
|
||||||
return null;
|
|
||||||
})
|
|
||||||
);
|
|
||||||
|
|
||||||
try {
|
try {
|
||||||
await Promise.all(downloadPromises);
|
await galleryService.downloadSelectedPhotos(slug, ids);
|
||||||
toastify.success(t('gallery.downloadedPhotos', { count: selectedPhotos.size }));
|
analyticsService.trackGalleryEvent('bulk_download_selected', { gallery: slug, photo_count: ids.length });
|
||||||
|
} catch (error) {
|
||||||
// Track bulk download
|
toastify.error(t('gallery.downloadError'));
|
||||||
analyticsService.trackGalleryEvent('bulk_download', {
|
} finally {
|
||||||
gallery: slug,
|
|
||||||
photo_count: selectedPhotos.size
|
|
||||||
});
|
|
||||||
|
|
||||||
// Clear selection after download
|
|
||||||
setSelectedPhotos(new Set());
|
setSelectedPhotos(new Set());
|
||||||
if (parentToggleSelectionMode) {
|
if (parentToggleSelectionMode) {
|
||||||
parentToggleSelectionMode();
|
parentToggleSelectionMode();
|
||||||
} else {
|
} else {
|
||||||
setLocalSelectionMode(false);
|
setLocalSelectionMode(false);
|
||||||
}
|
}
|
||||||
} catch (error) {
|
|
||||||
toastify.error(t('gallery.downloadError'));
|
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -166,7 +177,10 @@ export const PhotoGridWithLayouts: React.FC<PhotoGridWithLayoutsProps> = ({
|
|||||||
photos,
|
photos,
|
||||||
slug,
|
slug,
|
||||||
onPhotoClick: handlePhotoClick,
|
onPhotoClick: handlePhotoClick,
|
||||||
|
onOpenPhotoWithFeedback: handleOpenWithFeedback,
|
||||||
|
onFeedbackChange: onFeedbackChange,
|
||||||
onDownload: handleDownload,
|
onDownload: handleDownload,
|
||||||
|
heroPhotoOverride,
|
||||||
selectedPhotos,
|
selectedPhotos,
|
||||||
allowDownloads,
|
allowDownloads,
|
||||||
protectionLevel,
|
protectionLevel,
|
||||||
@@ -178,6 +192,7 @@ export const PhotoGridWithLayouts: React.FC<PhotoGridWithLayoutsProps> = ({
|
|||||||
eventDate,
|
eventDate,
|
||||||
expiresAt,
|
expiresAt,
|
||||||
feedbackEnabled,
|
feedbackEnabled,
|
||||||
|
feedbackOptions,
|
||||||
};
|
};
|
||||||
|
|
||||||
let LayoutComponent;
|
let LayoutComponent;
|
||||||
@@ -275,6 +290,7 @@ export const PhotoGridWithLayouts: React.FC<PhotoGridWithLayoutsProps> = ({
|
|||||||
allowDownloads={allowDownloads}
|
allowDownloads={allowDownloads}
|
||||||
protectionLevel={protectionLevel}
|
protectionLevel={protectionLevel}
|
||||||
useEnhancedProtection={useEnhancedProtection}
|
useEnhancedProtection={useEnhancedProtection}
|
||||||
|
initialShowFeedback={openFeedbackInitially}
|
||||||
/>
|
/>
|
||||||
)}
|
)}
|
||||||
</>
|
</>
|
||||||
|
|||||||
@@ -1,10 +1,12 @@
|
|||||||
import React, { useState, useEffect } from 'react';
|
import React, { useState, useEffect } from 'react';
|
||||||
import { useDevToolsProtection } from '../../hooks/useDevToolsProtection';
|
import { useDevToolsProtection } from '../../hooks/useDevToolsProtection';
|
||||||
import { X, ChevronLeft, ChevronRight, Download, ZoomIn, ZoomOut, MessageSquare } from 'lucide-react';
|
import { X, ChevronLeft, ChevronRight, Download, ZoomIn, ZoomOut, MessageSquare, Heart, Star } from 'lucide-react';
|
||||||
import type { Photo } from '../../types';
|
import type { Photo } from '../../types';
|
||||||
import { useDownloadPhoto } from '../../hooks/useGallery';
|
import { useDownloadPhoto } from '../../hooks/useGallery';
|
||||||
import { AuthenticatedImage } from '../common';
|
import { AuthenticatedImage } from '../common';
|
||||||
import { PhotoFeedback } from './PhotoFeedback';
|
import { PhotoFeedback } from './PhotoFeedback';
|
||||||
|
import { feedbackService } from '../../services/feedback.service';
|
||||||
|
import { FeedbackIdentityModal } from './FeedbackIdentityModal';
|
||||||
|
|
||||||
interface PhotoLightboxProps {
|
interface PhotoLightboxProps {
|
||||||
photos: Photo[];
|
photos: Photo[];
|
||||||
@@ -15,6 +17,7 @@ interface PhotoLightboxProps {
|
|||||||
allowDownloads?: boolean;
|
allowDownloads?: boolean;
|
||||||
protectionLevel?: 'basic' | 'standard' | 'enhanced' | 'maximum';
|
protectionLevel?: 'basic' | 'standard' | 'enhanced' | 'maximum';
|
||||||
useEnhancedProtection?: boolean;
|
useEnhancedProtection?: boolean;
|
||||||
|
initialShowFeedback?: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
export const PhotoLightbox: React.FC<PhotoLightboxProps> = ({
|
export const PhotoLightbox: React.FC<PhotoLightboxProps> = ({
|
||||||
@@ -26,6 +29,7 @@ export const PhotoLightbox: React.FC<PhotoLightboxProps> = ({
|
|||||||
allowDownloads = true,
|
allowDownloads = true,
|
||||||
protectionLevel = 'standard',
|
protectionLevel = 'standard',
|
||||||
useEnhancedProtection = false,
|
useEnhancedProtection = false,
|
||||||
|
initialShowFeedback = false,
|
||||||
}) => {
|
}) => {
|
||||||
const [currentIndex, setCurrentIndex] = useState(initialIndex);
|
const [currentIndex, setCurrentIndex] = useState(initialIndex);
|
||||||
const [zoom, setZoom] = useState(1);
|
const [zoom, setZoom] = useState(1);
|
||||||
@@ -33,7 +37,28 @@ export const PhotoLightbox: React.FC<PhotoLightboxProps> = ({
|
|||||||
const [dragStart, setDragStart] = useState({ x: 0, y: 0 });
|
const [dragStart, setDragStart] = useState({ x: 0, y: 0 });
|
||||||
const [dragOffset, setDragOffset] = useState({ x: 0, y: 0 });
|
const [dragOffset, setDragOffset] = useState({ x: 0, y: 0 });
|
||||||
const [touchDistance, setTouchDistance] = useState<number | null>(null);
|
const [touchDistance, setTouchDistance] = useState<number | null>(null);
|
||||||
const [showFeedback, setShowFeedback] = useState(false);
|
const [showFeedback, setShowFeedback] = useState(initialShowFeedback);
|
||||||
|
const [isSmallScreen, setIsSmallScreen] = useState<boolean>(typeof window !== 'undefined' ? window.innerWidth < 640 : false);
|
||||||
|
const [feedbackSettings, setFeedbackSettings] = useState<{
|
||||||
|
feedback_enabled?: boolean;
|
||||||
|
allow_likes?: boolean;
|
||||||
|
allow_ratings?: boolean;
|
||||||
|
require_name_email?: boolean;
|
||||||
|
} | null>(null);
|
||||||
|
const [myLiked, setMyLiked] = useState<boolean>(false);
|
||||||
|
const [myRating, setMyRating] = useState<number>(0);
|
||||||
|
const [likeCount, setLikeCount] = useState<number>(0);
|
||||||
|
const [avgRating, setAvgRating] = useState<number>(0);
|
||||||
|
const [totalRatings, setTotalRatings] = useState<number>(0);
|
||||||
|
const [savedIdentity, setSavedIdentity] = useState<{ name: string; email: string } | null>(null);
|
||||||
|
const [showIdentityModal, setShowIdentityModal] = useState(false);
|
||||||
|
const [pendingAction, setPendingAction] = useState<null | { type: 'like' | 'rating'; rating?: number }>(null);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const onResize = () => setIsSmallScreen(window.innerWidth < 640);
|
||||||
|
window.addEventListener('resize', onResize);
|
||||||
|
return () => window.removeEventListener('resize', onResize);
|
||||||
|
}, []);
|
||||||
|
|
||||||
const downloadPhotoMutation = useDownloadPhoto();
|
const downloadPhotoMutation = useDownloadPhoto();
|
||||||
const currentPhoto = photos[currentIndex];
|
const currentPhoto = photos[currentIndex];
|
||||||
@@ -111,6 +136,81 @@ export const PhotoLightbox: React.FC<PhotoLightboxProps> = ({
|
|||||||
};
|
};
|
||||||
}, [currentIndex]);
|
}, [currentIndex]);
|
||||||
|
|
||||||
|
// Load feedback settings once
|
||||||
|
useEffect(() => {
|
||||||
|
let mounted = true;
|
||||||
|
(async () => {
|
||||||
|
try {
|
||||||
|
const settings = await feedbackService.getGalleryFeedbackSettings(slug);
|
||||||
|
if (mounted) setFeedbackSettings(settings as any);
|
||||||
|
} catch {
|
||||||
|
// ignore
|
||||||
|
}
|
||||||
|
})();
|
||||||
|
return () => { mounted = false; };
|
||||||
|
}, [slug]);
|
||||||
|
|
||||||
|
// Load my feedback for the current photo
|
||||||
|
useEffect(() => {
|
||||||
|
let mounted = true;
|
||||||
|
(async () => {
|
||||||
|
try {
|
||||||
|
if (!feedbackSettings?.feedback_enabled) return;
|
||||||
|
const data = await feedbackService.getPhotoFeedback(slug, String(currentPhoto.id));
|
||||||
|
if (!mounted) return;
|
||||||
|
setMyLiked(!!data.my_feedback.liked);
|
||||||
|
setMyRating(data.my_feedback.rating || 0);
|
||||||
|
setLikeCount(Number(data.summary?.like_count) || 0);
|
||||||
|
setAvgRating(Number(data.summary?.average_rating) || 0);
|
||||||
|
setTotalRatings(Number(data.summary?.total_ratings) || 0);
|
||||||
|
} catch {
|
||||||
|
// ignore
|
||||||
|
}
|
||||||
|
})();
|
||||||
|
return () => { mounted = false; };
|
||||||
|
}, [slug, currentPhoto.id, feedbackSettings?.feedback_enabled]);
|
||||||
|
|
||||||
|
const submitLike = async () => {
|
||||||
|
const needIdentity = feedbackSettings?.require_name_email && !savedIdentity;
|
||||||
|
if (needIdentity) {
|
||||||
|
setPendingAction({ type: 'like' });
|
||||||
|
setShowIdentityModal(true);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
await feedbackService.submitFeedback(slug, String(currentPhoto.id), {
|
||||||
|
feedback_type: 'like',
|
||||||
|
guest_name: savedIdentity?.name,
|
||||||
|
guest_email: savedIdentity?.email,
|
||||||
|
});
|
||||||
|
setMyLiked(prev => {
|
||||||
|
const next = !prev;
|
||||||
|
setLikeCount(c => Math.max(0, c + (next ? 1 : -1)));
|
||||||
|
return next;
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
const submitRating = async (value: number) => {
|
||||||
|
const needIdentity = feedbackSettings?.require_name_email && !savedIdentity;
|
||||||
|
if (needIdentity) {
|
||||||
|
setPendingAction({ type: 'rating', rating: value });
|
||||||
|
setShowIdentityModal(true);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
await feedbackService.submitFeedback(slug, String(currentPhoto.id), {
|
||||||
|
feedback_type: 'rating',
|
||||||
|
rating: value,
|
||||||
|
guest_name: savedIdentity?.name,
|
||||||
|
guest_email: savedIdentity?.email,
|
||||||
|
});
|
||||||
|
setMyRating(value);
|
||||||
|
// Refresh current summary to reflect average and totals
|
||||||
|
try {
|
||||||
|
const fresh = await feedbackService.getPhotoFeedback(slug, String(currentPhoto.id));
|
||||||
|
setAvgRating(Number(fresh.summary?.average_rating) || 0);
|
||||||
|
setTotalRatings(Number(fresh.summary?.total_ratings) || 0);
|
||||||
|
} catch {}
|
||||||
|
};
|
||||||
|
|
||||||
const goToPrevious = () => {
|
const goToPrevious = () => {
|
||||||
setCurrentIndex((prev) => (prev > 0 ? prev - 1 : photos.length - 1));
|
setCurrentIndex((prev) => (prev > 0 ? prev - 1 : photos.length - 1));
|
||||||
resetZoom();
|
resetZoom();
|
||||||
@@ -211,13 +311,17 @@ export const PhotoLightbox: React.FC<PhotoLightboxProps> = ({
|
|||||||
`fixed inset-0 bg-black z-50 flex items-center justify-center protected-image protection-${protectionLevel}` :
|
`fixed inset-0 bg-black z-50 flex items-center justify-center protected-image protection-${protectionLevel}` :
|
||||||
'fixed inset-0 bg-black z-50 flex items-center justify-center';
|
'fixed inset-0 bg-black z-50 flex items-center justify-center';
|
||||||
|
|
||||||
|
const desktopFeedbackWidth = 416; // 26rem; keep in sync with panel width
|
||||||
|
const isDesktopFeedback = showFeedback && !isSmallScreen;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className={lightboxClass}>
|
<div className={lightboxClass}>
|
||||||
{/* Close button */}
|
{/* Close button */}
|
||||||
<button
|
<button
|
||||||
onClick={onClose}
|
onClick={onClose}
|
||||||
className="absolute top-4 right-4 p-2 bg-white/10 hover:bg-white/20 rounded-full transition-colors z-20"
|
className="absolute top-4 p-2 bg-white/10 hover:bg-white/20 rounded-full transition-colors z-30"
|
||||||
aria-label="Close"
|
aria-label="Close"
|
||||||
|
style={{ right: isDesktopFeedback ? `${desktopFeedbackWidth + 16}px` : '1rem' }}
|
||||||
>
|
>
|
||||||
<X className="w-6 h-6 text-white" />
|
<X className="w-6 h-6 text-white" />
|
||||||
</button>
|
</button>
|
||||||
@@ -231,16 +335,22 @@ export const PhotoLightbox: React.FC<PhotoLightboxProps> = ({
|
|||||||
<ChevronLeft className="w-6 h-6 text-white" />
|
<ChevronLeft className="w-6 h-6 text-white" />
|
||||||
</button>
|
</button>
|
||||||
|
|
||||||
<button
|
{!showFeedback || !isSmallScreen ? (
|
||||||
onClick={goToNext}
|
<button
|
||||||
className="absolute right-4 top-1/2 -translate-y-1/2 p-2 bg-white/10 hover:bg-white/20 rounded-full transition-colors z-20"
|
onClick={goToNext}
|
||||||
aria-label="Next photo"
|
className="absolute top-1/2 -translate-y-1/2 p-2 bg-white/10 hover:bg-white/20 rounded-full transition-colors z-30"
|
||||||
>
|
aria-label="Next photo"
|
||||||
<ChevronRight className="w-6 h-6 text-white" />
|
style={{ right: isDesktopFeedback ? `${desktopFeedbackWidth + 16}px` : '1rem' }}
|
||||||
</button>
|
>
|
||||||
|
<ChevronRight className="w-6 h-6 text-white" />
|
||||||
|
</button>
|
||||||
|
) : null}
|
||||||
|
|
||||||
{/* Bottom toolbar */}
|
{/* Bottom toolbar */}
|
||||||
<div className="absolute bottom-0 left-0 right-0 bg-gradient-to-t from-black/80 to-transparent p-4 z-20">
|
<div
|
||||||
|
className="absolute bottom-0 left-0 bg-gradient-to-t from-black/80 to-transparent p-4 z-20"
|
||||||
|
style={{ right: isDesktopFeedback ? `${desktopFeedbackWidth}px` : 0 }}
|
||||||
|
>
|
||||||
<div className="max-w-4xl mx-auto flex items-center justify-between">
|
<div className="max-w-4xl mx-auto flex items-center justify-between">
|
||||||
<div className="text-white">
|
<div className="text-white">
|
||||||
<p className="text-sm opacity-75">
|
<p className="text-sm opacity-75">
|
||||||
@@ -281,6 +391,39 @@ export const PhotoLightbox: React.FC<PhotoLightboxProps> = ({
|
|||||||
</button>
|
</button>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
|
{/* Inline Like */}
|
||||||
|
{feedbackEnabled && feedbackSettings?.allow_likes && (
|
||||||
|
<div className="flex items-center gap-1">
|
||||||
|
<button
|
||||||
|
onClick={submitLike}
|
||||||
|
className={`p-2 rounded-full transition-colors ${myLiked ? 'bg-red-500/80 hover:bg-red-500' : 'bg-white/10 hover:bg-white/20'}`}
|
||||||
|
aria-label={myLiked ? 'Unlike photo' : 'Like photo'}
|
||||||
|
title={myLiked ? 'Unlike' : 'Like'}
|
||||||
|
>
|
||||||
|
<Heart className={`w-5 h-5 ${myLiked ? 'text-white' : 'text-white'}`} />
|
||||||
|
</button>
|
||||||
|
<span className="text-white text-xs min-w-[1.5rem] text-center select-none">{likeCount}</span>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* Inline Rating */}
|
||||||
|
{feedbackEnabled && feedbackSettings?.allow_ratings && (
|
||||||
|
<div className="flex items-center gap-1 ml-1" aria-label="Rate photo">
|
||||||
|
{[1,2,3,4,5].map((i) => (
|
||||||
|
<button
|
||||||
|
key={i}
|
||||||
|
onClick={() => submitRating(i)}
|
||||||
|
className="p-1"
|
||||||
|
aria-label={`Rate ${i} star${i>1?'s':''}`}
|
||||||
|
title={`Rate ${i}`}
|
||||||
|
>
|
||||||
|
<Star className={`w-5 h-5 ${myRating >= i ? 'text-yellow-400 fill-yellow-400' : 'text-white/70'}`} />
|
||||||
|
</button>
|
||||||
|
))}
|
||||||
|
<span className="text-white/90 text-xs ml-2 select-none">{avgRating.toFixed(1)} ({totalRatings})</span>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
{/* Feedback button with indicator */}
|
{/* Feedback button with indicator */}
|
||||||
{feedbackEnabled && (
|
{feedbackEnabled && (
|
||||||
<button
|
<button
|
||||||
@@ -305,7 +448,7 @@ export const PhotoLightbox: React.FC<PhotoLightboxProps> = ({
|
|||||||
|
|
||||||
{/* Image container */}
|
{/* Image container */}
|
||||||
<div
|
<div
|
||||||
className="absolute inset-0 flex items-center justify-center z-0"
|
className="absolute top-0 left-0 bottom-0 flex items-center justify-center z-0"
|
||||||
onClick={handleImageClick}
|
onClick={handleImageClick}
|
||||||
onMouseDown={handleMouseDown}
|
onMouseDown={handleMouseDown}
|
||||||
onMouseMove={handleMouseMove}
|
onMouseMove={handleMouseMove}
|
||||||
@@ -314,11 +457,15 @@ export const PhotoLightbox: React.FC<PhotoLightboxProps> = ({
|
|||||||
onTouchStart={handleTouchStart}
|
onTouchStart={handleTouchStart}
|
||||||
onTouchMove={handleTouchMove}
|
onTouchMove={handleTouchMove}
|
||||||
onTouchEnd={handleTouchEnd}
|
onTouchEnd={handleTouchEnd}
|
||||||
style={{ cursor: zoom > 1 ? (isDragging ? 'grabbing' : 'grab') : 'default' }}
|
style={{
|
||||||
|
cursor: zoom > 1 ? (isDragging ? 'grabbing' : 'grab') : 'default',
|
||||||
|
right: isDesktopFeedback ? `${desktopFeedbackWidth}px` : 0,
|
||||||
|
}}
|
||||||
>
|
>
|
||||||
<AuthenticatedImage
|
<AuthenticatedImage
|
||||||
src={currentPhoto.url}
|
src={currentPhoto.url}
|
||||||
alt={currentPhoto.filename}
|
alt={currentPhoto.filename}
|
||||||
|
fallbackSrc={currentPhoto.thumbnail_url || undefined}
|
||||||
className="max-w-full max-h-full object-contain select-none"
|
className="max-w-full max-h-full object-contain select-none"
|
||||||
style={{
|
style={{
|
||||||
transform: `scale(${zoom}) translate(${dragOffset.x / zoom}px, ${dragOffset.y / zoom}px)`,
|
transform: `scale(${zoom}) translate(${dragOffset.x / zoom}px, ${dragOffset.y / zoom}px)`,
|
||||||
@@ -369,7 +516,7 @@ export const PhotoLightbox: React.FC<PhotoLightboxProps> = ({
|
|||||||
|
|
||||||
{/* Feedback Panel */}
|
{/* Feedback Panel */}
|
||||||
{showFeedback && (
|
{showFeedback && (
|
||||||
<div className="absolute right-0 top-0 bottom-0 w-full sm:w-96 lg:w-[28rem] bg-white shadow-xl z-20 overflow-y-auto">
|
<div className="absolute right-0 top-0 bottom-0 w-full sm:w-[26rem] bg-white shadow-xl z-20 overflow-y-auto flex flex-col border-l border-neutral-200">
|
||||||
<div className="sticky top-0 bg-white border-b px-4 py-3 flex items-center justify-between">
|
<div className="sticky top-0 bg-white border-b px-4 py-3 flex items-center justify-between">
|
||||||
<h3 className="font-semibold text-neutral-900">Photo Feedback</h3>
|
<h3 className="font-semibold text-neutral-900">Photo Feedback</h3>
|
||||||
<button
|
<button
|
||||||
@@ -380,7 +527,7 @@ export const PhotoLightbox: React.FC<PhotoLightboxProps> = ({
|
|||||||
<X className="w-5 h-5" />
|
<X className="w-5 h-5" />
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
<div className="p-4">
|
<div className="p-4 flex-1 overflow-y-auto">
|
||||||
<PhotoFeedback
|
<PhotoFeedback
|
||||||
photoId={currentPhoto.id}
|
photoId={currentPhoto.id}
|
||||||
gallerySlug={slug}
|
gallerySlug={slug}
|
||||||
@@ -390,6 +537,34 @@ export const PhotoLightbox: React.FC<PhotoLightboxProps> = ({
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
|
{/* Identity Modal for required name/email */}
|
||||||
|
<FeedbackIdentityModal
|
||||||
|
isOpen={showIdentityModal}
|
||||||
|
onClose={() => { setShowIdentityModal(false); setPendingAction(null); }}
|
||||||
|
onSubmit={async (name, email) => {
|
||||||
|
setSavedIdentity({ name, email });
|
||||||
|
setShowIdentityModal(false);
|
||||||
|
if (pendingAction?.type === 'like') {
|
||||||
|
await feedbackService.submitFeedback(slug, String(currentPhoto.id), {
|
||||||
|
feedback_type: 'like',
|
||||||
|
guest_name: name,
|
||||||
|
guest_email: email,
|
||||||
|
});
|
||||||
|
setMyLiked(true);
|
||||||
|
} else if (pendingAction?.type === 'rating' && pendingAction.rating) {
|
||||||
|
await feedbackService.submitFeedback(slug, String(currentPhoto.id), {
|
||||||
|
feedback_type: 'rating',
|
||||||
|
rating: pendingAction.rating,
|
||||||
|
guest_name: name,
|
||||||
|
guest_email: email,
|
||||||
|
});
|
||||||
|
setMyRating(pendingAction.rating);
|
||||||
|
}
|
||||||
|
setPendingAction(null);
|
||||||
|
}}
|
||||||
|
feedbackType={pendingAction?.type === 'rating' ? 'rating' : 'like'}
|
||||||
|
/>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
@@ -10,4 +10,3 @@ export { PhotoFeedback } from './PhotoFeedback';
|
|||||||
export { PhotoRating } from './PhotoRating';
|
export { PhotoRating } from './PhotoRating';
|
||||||
export { PhotoLikes } from './PhotoLikes';
|
export { PhotoLikes } from './PhotoLikes';
|
||||||
export { PhotoComments } from './PhotoComments';
|
export { PhotoComments } from './PhotoComments';
|
||||||
export { PhotoFavorites } from './PhotoFavorites';
|
|
||||||
@@ -5,6 +5,10 @@ export interface BaseGalleryLayoutProps {
|
|||||||
photos: Photo[];
|
photos: Photo[];
|
||||||
slug: string;
|
slug: string;
|
||||||
onPhotoClick: (index: number) => void;
|
onPhotoClick: (index: number) => void;
|
||||||
|
// Optional: open the lightbox with feedback panel visible
|
||||||
|
onOpenPhotoWithFeedback?: (index: number) => void;
|
||||||
|
// Notify parent that feedback (like/favorite/rating/comment) changed
|
||||||
|
onFeedbackChange?: () => void;
|
||||||
onDownload: (photo: Photo, e: React.MouseEvent) => void;
|
onDownload: (photo: Photo, e: React.MouseEvent) => void;
|
||||||
selectedPhotos?: Set<number>;
|
selectedPhotos?: Set<number>;
|
||||||
isSelectionMode?: boolean;
|
isSelectionMode?: boolean;
|
||||||
@@ -17,6 +21,13 @@ export interface BaseGalleryLayoutProps {
|
|||||||
protectionLevel?: 'basic' | 'standard' | 'enhanced' | 'maximum';
|
protectionLevel?: 'basic' | 'standard' | 'enhanced' | 'maximum';
|
||||||
useEnhancedProtection?: boolean;
|
useEnhancedProtection?: boolean;
|
||||||
feedbackEnabled?: boolean;
|
feedbackEnabled?: boolean;
|
||||||
|
feedbackOptions?: {
|
||||||
|
allowLikes?: boolean;
|
||||||
|
allowFavorites?: boolean;
|
||||||
|
allowRatings?: boolean;
|
||||||
|
allowComments?: boolean;
|
||||||
|
requireNameEmail?: boolean;
|
||||||
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
export abstract class BaseGalleryLayout<T extends BaseGalleryLayoutProps = BaseGalleryLayoutProps> extends React.Component<T> {
|
export abstract class BaseGalleryLayout<T extends BaseGalleryLayoutProps = BaseGalleryLayoutProps> extends React.Component<T> {
|
||||||
|
|||||||
@@ -1,16 +1,20 @@
|
|||||||
import React, { useState, useEffect, useRef } from 'react';
|
import React, { useState, useEffect, useRef } from 'react';
|
||||||
import { ChevronLeft, ChevronRight, Download, Maximize2, Play, Pause } from 'lucide-react';
|
import { ChevronLeft, ChevronRight, Download, Maximize2, Play, Pause, Heart, MessageSquare } from 'lucide-react';
|
||||||
import { useTheme } from '../../../contexts/ThemeContext';
|
import { useTheme } from '../../../contexts/ThemeContext';
|
||||||
import { AuthenticatedImage, Button } from '../../common';
|
import { AuthenticatedImage, Button } from '../../common';
|
||||||
import type { BaseGalleryLayoutProps } from './BaseGalleryLayout';
|
import type { BaseGalleryLayoutProps } from './BaseGalleryLayout';
|
||||||
|
import { FeedbackIdentityModal } from '../../gallery/FeedbackIdentityModal';
|
||||||
|
import { feedbackService } from '../../../services/feedback.service';
|
||||||
|
|
||||||
export const CarouselGalleryLayout: React.FC<BaseGalleryLayoutProps> = ({
|
export const CarouselGalleryLayout: React.FC<BaseGalleryLayoutProps> = ({
|
||||||
photos,
|
photos,
|
||||||
|
slug,
|
||||||
onPhotoClick,
|
onPhotoClick,
|
||||||
|
onOpenPhotoWithFeedback,
|
||||||
onDownload,
|
onDownload,
|
||||||
allowDownloads = true,
|
allowDownloads = true,
|
||||||
// selectedPhotos = new Set(),
|
feedbackEnabled = false,
|
||||||
// isSelectionMode = false
|
feedbackOptions
|
||||||
}) => {
|
}) => {
|
||||||
const { theme } = useTheme();
|
const { theme } = useTheme();
|
||||||
const [currentIndex, setCurrentIndex] = useState(0);
|
const [currentIndex, setCurrentIndex] = useState(0);
|
||||||
@@ -59,6 +63,11 @@ export const CarouselGalleryLayout: React.FC<BaseGalleryLayoutProps> = ({
|
|||||||
if (photos.length === 0) return null;
|
if (photos.length === 0) return null;
|
||||||
|
|
||||||
const currentPhoto = photos[currentIndex];
|
const currentPhoto = photos[currentIndex];
|
||||||
|
const [showIdentityModal, setShowIdentityModal] = useState(false);
|
||||||
|
const [pendingAction, setPendingAction] = useState<null | { type: 'like'; photoId: number }>(null);
|
||||||
|
const [savedIdentity, setSavedIdentity] = useState<{ name: string; email: string } | null>(null);
|
||||||
|
const [likedIds, setLikedIds] = useState<Set<number>>(new Set());
|
||||||
|
const canQuickComment = Boolean(feedbackEnabled && feedbackOptions?.allowComments && onOpenPhotoWithFeedback);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="relative">
|
<div className="relative">
|
||||||
@@ -136,6 +145,44 @@ export const CarouselGalleryLayout: React.FC<BaseGalleryLayoutProps> = ({
|
|||||||
<Download className="w-5 h-5" />
|
<Download className="w-5 h-5" />
|
||||||
</Button>
|
</Button>
|
||||||
)}
|
)}
|
||||||
|
{feedbackOptions?.allowLikes && (
|
||||||
|
<Button
|
||||||
|
variant="ghost"
|
||||||
|
size="sm"
|
||||||
|
onClick={async () => {
|
||||||
|
if (feedbackOptions?.requireNameEmail && !savedIdentity) {
|
||||||
|
setPendingAction({ type: 'like', photoId: currentPhoto.id });
|
||||||
|
setShowIdentityModal(true);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
setLikedIds(prev => new Set(prev).add(currentPhoto.id));
|
||||||
|
try {
|
||||||
|
await feedbackService.submitFeedback(slug!, String(currentPhoto.id), {
|
||||||
|
feedback_type: 'like',
|
||||||
|
guest_name: savedIdentity?.name,
|
||||||
|
guest_email: savedIdentity?.email,
|
||||||
|
});
|
||||||
|
} catch (_) {}
|
||||||
|
}}
|
||||||
|
className={`hover:bg-white/20 ${likedIds.has(currentPhoto.id) ? 'text-red-400' : 'text-white'}`}
|
||||||
|
title="Like photo"
|
||||||
|
aria-pressed={likedIds.has(currentPhoto.id)}
|
||||||
|
>
|
||||||
|
<Heart className="w-5 h-5" />
|
||||||
|
</Button>
|
||||||
|
)}
|
||||||
|
{canQuickComment && (
|
||||||
|
<Button
|
||||||
|
variant="ghost"
|
||||||
|
size="sm"
|
||||||
|
onClick={() => { onOpenPhotoWithFeedback?.(currentIndex); }}
|
||||||
|
className="text-white hover:bg-white/20"
|
||||||
|
title="Comment"
|
||||||
|
aria-label="Comment on photo"
|
||||||
|
>
|
||||||
|
<MessageSquare className="w-5 h-5" />
|
||||||
|
</Button>
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
@@ -181,6 +228,24 @@ export const CarouselGalleryLayout: React.FC<BaseGalleryLayoutProps> = ({
|
|||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
|
<FeedbackIdentityModal
|
||||||
|
isOpen={showIdentityModal}
|
||||||
|
onClose={() => { setShowIdentityModal(false); setPendingAction(null); }}
|
||||||
|
onSubmit={async (name, email) => {
|
||||||
|
setSavedIdentity({ name, email });
|
||||||
|
setShowIdentityModal(false);
|
||||||
|
if (pendingAction) {
|
||||||
|
await feedbackService.submitFeedback(slug!, String(pendingAction.photoId), {
|
||||||
|
feedback_type: pendingAction.type,
|
||||||
|
guest_name: name,
|
||||||
|
guest_email: email,
|
||||||
|
});
|
||||||
|
setPendingAction(null);
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
feedbackType="like"
|
||||||
|
/>
|
||||||
|
|
||||||
<style>{`
|
<style>{`
|
||||||
@keyframes progress {
|
@keyframes progress {
|
||||||
from { width: 0%; }
|
from { width: 0%; }
|
||||||
|
|||||||
@@ -3,6 +3,8 @@ import { Download, Maximize2, Check, MessageSquare, Star, Heart } from 'lucide-r
|
|||||||
import { useInView } from 'react-intersection-observer';
|
import { useInView } from 'react-intersection-observer';
|
||||||
import { useTheme } from '../../../contexts/ThemeContext';
|
import { useTheme } from '../../../contexts/ThemeContext';
|
||||||
import { AuthenticatedImage } from '../../common';
|
import { AuthenticatedImage } from '../../common';
|
||||||
|
import { FeedbackIdentityModal } from '../../gallery/FeedbackIdentityModal';
|
||||||
|
import { feedbackService } from '../../../services/feedback.service';
|
||||||
import type { BaseGalleryLayoutProps } from './BaseGalleryLayout';
|
import type { BaseGalleryLayoutProps } from './BaseGalleryLayout';
|
||||||
import type { Photo } from '../../../types';
|
import type { Photo } from '../../../types';
|
||||||
|
|
||||||
@@ -12,12 +14,26 @@ interface GridPhotoProps {
|
|||||||
isSelectionMode: boolean;
|
isSelectionMode: boolean;
|
||||||
onClick: (e: React.MouseEvent) => void;
|
onClick: (e: React.MouseEvent) => void;
|
||||||
onDownload: (e: React.MouseEvent) => void;
|
onDownload: (e: React.MouseEvent) => void;
|
||||||
|
onToggleSelect: () => void;
|
||||||
animationType?: string;
|
animationType?: string;
|
||||||
allowDownloads?: boolean;
|
allowDownloads?: boolean;
|
||||||
slug?: string;
|
slug?: string;
|
||||||
protectionLevel?: 'basic' | 'standard' | 'enhanced' | 'maximum';
|
protectionLevel?: 'basic' | 'standard' | 'enhanced' | 'maximum';
|
||||||
useEnhancedProtection?: boolean;
|
useEnhancedProtection?: boolean;
|
||||||
feedbackEnabled?: boolean;
|
feedbackEnabled?: boolean;
|
||||||
|
feedbackOptions?: {
|
||||||
|
allowLikes?: boolean;
|
||||||
|
allowRatings?: boolean;
|
||||||
|
allowComments?: boolean;
|
||||||
|
requireNameEmail?: boolean;
|
||||||
|
};
|
||||||
|
savedIdentity?: { name: string; email: string } | null;
|
||||||
|
onRequireIdentity?: (action: 'like', photoId: number) => void;
|
||||||
|
onQuickComment?: () => void;
|
||||||
|
onFeedbackChange?: () => void;
|
||||||
|
// Immediate UI like state and callback
|
||||||
|
liked?: boolean;
|
||||||
|
onLikeSuccess?: () => void;
|
||||||
}
|
}
|
||||||
|
|
||||||
const GridPhoto: React.FC<GridPhotoProps> = ({
|
const GridPhoto: React.FC<GridPhotoProps> = ({
|
||||||
@@ -26,13 +42,22 @@ const GridPhoto: React.FC<GridPhotoProps> = ({
|
|||||||
isSelectionMode,
|
isSelectionMode,
|
||||||
onClick,
|
onClick,
|
||||||
onDownload,
|
onDownload,
|
||||||
|
onToggleSelect,
|
||||||
animationType = 'fade',
|
animationType = 'fade',
|
||||||
allowDownloads = true,
|
allowDownloads = true,
|
||||||
slug,
|
slug,
|
||||||
protectionLevel = 'standard',
|
protectionLevel = 'standard',
|
||||||
useEnhancedProtection = false,
|
useEnhancedProtection = false,
|
||||||
feedbackEnabled = false
|
feedbackEnabled = false,
|
||||||
|
feedbackOptions,
|
||||||
|
savedIdentity,
|
||||||
|
onRequireIdentity,
|
||||||
|
onQuickComment,
|
||||||
|
onFeedbackChange,
|
||||||
|
liked = false,
|
||||||
|
onLikeSuccess
|
||||||
}) => {
|
}) => {
|
||||||
|
// handled by parent layout; kept here for type completeness but not used
|
||||||
const { ref, inView } = useInView({
|
const { ref, inView } = useInView({
|
||||||
triggerOnce: true,
|
triggerOnce: true,
|
||||||
threshold: 0.1,
|
threshold: 0.1,
|
||||||
@@ -79,7 +104,7 @@ const GridPhoto: React.FC<GridPhotoProps> = ({
|
|||||||
}}
|
}}
|
||||||
/>
|
/>
|
||||||
|
|
||||||
<div className="absolute inset-0 bg-black/40 opacity-0 group-hover:opacity-100 transition-opacity duration-200 rounded-lg flex items-center justify-center gap-2">
|
<div className="absolute inset-0 bg-black/40 opacity-100 md:opacity-0 md:group-hover:opacity-100 transition-opacity duration-200 rounded-lg flex items-center justify-center gap-2">
|
||||||
{!isSelectionMode && (
|
{!isSelectionMode && (
|
||||||
<>
|
<>
|
||||||
<button
|
<button
|
||||||
@@ -101,44 +126,91 @@ const GridPhoto: React.FC<GridPhotoProps> = ({
|
|||||||
<Download className="w-5 h-5 text-neutral-800" />
|
<Download className="w-5 h-5 text-neutral-800" />
|
||||||
</button>
|
</button>
|
||||||
)}
|
)}
|
||||||
|
{onQuickComment && (
|
||||||
|
<button
|
||||||
|
className="p-2 bg-white/90 rounded-full hover:bg-white transition-colors"
|
||||||
|
onClick={(e) => { e.stopPropagation(); onQuickComment(); }}
|
||||||
|
aria-label="Comment on photo"
|
||||||
|
title="Comment"
|
||||||
|
>
|
||||||
|
<MessageSquare className="w-5 h-5 text-neutral-800" />
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
{/* Quick feedback actions */}
|
||||||
|
{feedbackOptions?.allowLikes && (
|
||||||
|
<button
|
||||||
|
className={`p-2 rounded-full transition-colors ${liked ? 'bg-red-500/90 hover:bg-red-500' : 'bg-white/90 hover:bg-white'}`}
|
||||||
|
onClick={async (e) => {
|
||||||
|
e.stopPropagation();
|
||||||
|
if (feedbackOptions?.requireNameEmail && !savedIdentity && onRequireIdentity) {
|
||||||
|
onRequireIdentity('like', photo.id);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
// Optimistic UI: mark as liked immediately
|
||||||
|
if (onLikeSuccess) onLikeSuccess();
|
||||||
|
try {
|
||||||
|
await feedbackService.submitFeedback(slug!, String(photo.id), {
|
||||||
|
feedback_type: 'like',
|
||||||
|
guest_name: savedIdentity?.name,
|
||||||
|
guest_email: savedIdentity?.email,
|
||||||
|
});
|
||||||
|
} catch (err) {
|
||||||
|
// Keep optimistic state; a refresh will reconcile
|
||||||
|
console.warn('Like submit failed, keeping optimistic UI', err);
|
||||||
|
}
|
||||||
|
if (onFeedbackChange) onFeedbackChange();
|
||||||
|
}}
|
||||||
|
aria-label="Like photo"
|
||||||
|
aria-pressed={liked}
|
||||||
|
title="Like"
|
||||||
|
>
|
||||||
|
<Heart className={`w-5 h-5 ${liked ? 'text-white fill-white' : 'text-neutral-800'}`} />
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
</>
|
</>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{isSelectionMode && (
|
{/* Selection Checkbox (visible on hover or when selected) */}
|
||||||
<div className={`absolute top-2 right-2 ${isSelected ? 'opacity-100' : 'opacity-0 group-hover:opacity-100'} transition-opacity`}>
|
<button
|
||||||
<div className={`w-6 h-6 rounded-full border-2 ${isSelected ? 'bg-primary-600 border-primary-600' : 'bg-white/80 border-white'} flex items-center justify-center transition-colors`}>
|
type="button"
|
||||||
{isSelected && <Check className="w-4 h-4 text-white" />}
|
aria-label={`Select ${photo.filename}`}
|
||||||
</div>
|
role="checkbox"
|
||||||
|
aria-checked={isSelected}
|
||||||
|
data-testid={`gallery-photo-checkbox-${photo.id}`}
|
||||||
|
className={`absolute top-2 right-2 z-20 transition-opacity ${
|
||||||
|
isSelected ? 'opacity-100' : 'opacity-0 group-hover:opacity-100'
|
||||||
|
}`}
|
||||||
|
onClick={(e) => { e.stopPropagation(); onToggleSelect(); }}
|
||||||
|
>
|
||||||
|
<div className={`w-6 h-6 rounded-full border-2 ${isSelected ? 'bg-primary-600 border-primary-600' : 'bg-white/90 border-white'} flex items-center justify-center transition-colors`}>
|
||||||
|
{isSelected && <Check className="w-4 h-4 text-white" />}
|
||||||
</div>
|
</div>
|
||||||
)}
|
</button>
|
||||||
|
|
||||||
{/* Feedback Indicators */}
|
{/* Feedback Indicators (always visible, bottom-left). Show like immediately when user liked */}
|
||||||
{feedbackEnabled && (photo.comment_count > 0 || photo.average_rating > 0 || photo.like_count > 0) && (
|
{(photo.comment_count > 0 || photo.average_rating > 0 || photo.like_count > 0 || liked) && (
|
||||||
<div className="absolute top-2 left-2 flex gap-1 z-10">
|
<div className={`absolute ${photo.type === 'collage' ? 'bottom-8' : 'bottom-2'} left-2 flex items-center gap-1 z-10`}>
|
||||||
{photo.comment_count > 0 && (
|
{(photo.like_count > 0 || liked) && (
|
||||||
<div className="bg-white/90 backdrop-blur-sm rounded-full px-2 py-1 flex items-center gap-1" title={`${photo.comment_count} comments`}>
|
<span className="inline-flex items-center justify-center w-6 h-6 rounded-full bg-white/90 backdrop-blur-sm" title="Liked">
|
||||||
<MessageSquare className="w-3.5 h-3.5 text-primary-600" fill="currentColor" />
|
<Heart className="w-3.5 h-3.5 text-red-500" fill="currentColor" />
|
||||||
<span className="text-xs font-medium text-neutral-700">{photo.comment_count}</span>
|
</span>
|
||||||
</div>
|
|
||||||
)}
|
)}
|
||||||
{photo.average_rating > 0 && (
|
{photo.average_rating > 0 && (
|
||||||
<div className="bg-white/90 backdrop-blur-sm rounded-full px-2 py-1 flex items-center gap-1" title={`Rating: ${Number(photo.average_rating).toFixed(1)}`}>
|
<span className="inline-flex items-center justify-center w-6 h-6 rounded-full bg-white/90 backdrop-blur-sm" title="Rated">
|
||||||
<Star className="w-3.5 h-3.5 text-yellow-500" fill="currentColor" />
|
<Star className="w-3.5 h-3.5 text-yellow-500" fill="currentColor" />
|
||||||
<span className="text-xs font-medium text-neutral-700">{Number(photo.average_rating).toFixed(1)}</span>
|
</span>
|
||||||
</div>
|
|
||||||
)}
|
)}
|
||||||
{photo.like_count > 0 && (
|
{photo.comment_count > 0 && (
|
||||||
<div className="bg-white/90 backdrop-blur-sm rounded-full px-2 py-1 flex items-center gap-1" title={`${photo.like_count} likes`}>
|
<span className="inline-flex items-center justify-center w-6 h-6 rounded-full bg-white/90 backdrop-blur-sm" title="Commented">
|
||||||
<Heart className="w-3.5 h-3.5 text-red-500" fill="currentColor" />
|
<MessageSquare className="w-3.5 h-3.5 text-primary-600" fill="currentColor" />
|
||||||
<span className="text-xs font-medium text-neutral-700">{photo.like_count}</span>
|
</span>
|
||||||
</div>
|
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{photo.type === 'collage' && (
|
{photo.type === 'collage' && (
|
||||||
<div className="absolute bottom-2 left-2">
|
<div className="absolute bottom-2 right-2">
|
||||||
<span className="px-2 py-1 bg-black/60 text-white text-xs rounded">
|
<span className="px-2 py-1 bg-black/60 text-white text-xs rounded">
|
||||||
Collage
|
Collage
|
||||||
</span>
|
</span>
|
||||||
@@ -156,6 +228,8 @@ export const GridGalleryLayout: React.FC<BaseGalleryLayoutProps> = ({
|
|||||||
photos,
|
photos,
|
||||||
slug,
|
slug,
|
||||||
onPhotoClick,
|
onPhotoClick,
|
||||||
|
onOpenPhotoWithFeedback,
|
||||||
|
onFeedbackChange,
|
||||||
onDownload,
|
onDownload,
|
||||||
selectedPhotos = new Set(),
|
selectedPhotos = new Set(),
|
||||||
isSelectionMode = false,
|
isSelectionMode = false,
|
||||||
@@ -163,7 +237,8 @@ export const GridGalleryLayout: React.FC<BaseGalleryLayoutProps> = ({
|
|||||||
allowDownloads = true,
|
allowDownloads = true,
|
||||||
protectionLevel = 'standard',
|
protectionLevel = 'standard',
|
||||||
useEnhancedProtection = false,
|
useEnhancedProtection = false,
|
||||||
feedbackEnabled = false
|
feedbackEnabled = false,
|
||||||
|
feedbackOptions
|
||||||
}) => {
|
}) => {
|
||||||
const { theme } = useTheme();
|
const { theme } = useTheme();
|
||||||
const gallerySettings = theme.gallerySettings || {};
|
const gallerySettings = theme.gallerySettings || {};
|
||||||
@@ -171,6 +246,11 @@ export const GridGalleryLayout: React.FC<BaseGalleryLayoutProps> = ({
|
|||||||
const spacing = gallerySettings.spacing || 'normal';
|
const spacing = gallerySettings.spacing || 'normal';
|
||||||
const animation = gallerySettings.photoAnimation || 'fade';
|
const animation = gallerySettings.photoAnimation || 'fade';
|
||||||
|
|
||||||
|
const [showIdentityModal, setShowIdentityModal] = React.useState(false);
|
||||||
|
const [pendingAction, setPendingAction] = React.useState<null | { type: 'like'; photoId: number }>(null);
|
||||||
|
const [likedPhotoIds, setLikedPhotoIds] = React.useState<Set<number>>(new Set());
|
||||||
|
const [savedIdentity, setSavedIdentity] = React.useState<{ name: string; email: string } | null>(null);
|
||||||
|
|
||||||
const spacingClass = spacing === 'tight' ? 'gap-2' : spacing === 'relaxed' ? 'gap-6' : 'gap-4';
|
const spacingClass = spacing === 'tight' ? 'gap-2' : spacing === 'relaxed' ? 'gap-6' : 'gap-4';
|
||||||
|
|
||||||
const gridClass = `grid ${spacingClass}
|
const gridClass = `grid ${spacingClass}
|
||||||
@@ -187,13 +267,8 @@ export const GridGalleryLayout: React.FC<BaseGalleryLayoutProps> = ({
|
|||||||
photo={photo}
|
photo={photo}
|
||||||
isSelected={selectedPhotos.has(photo.id)}
|
isSelected={selectedPhotos.has(photo.id)}
|
||||||
isSelectionMode={isSelectionMode}
|
isSelectionMode={isSelectionMode}
|
||||||
onClick={() => {
|
onClick={() => onPhotoClick(index)}
|
||||||
if (isSelectionMode && onPhotoSelect) {
|
onToggleSelect={() => onPhotoSelect && onPhotoSelect(photo.id)}
|
||||||
onPhotoSelect(photo.id);
|
|
||||||
} else {
|
|
||||||
onPhotoClick(index);
|
|
||||||
}
|
|
||||||
}}
|
|
||||||
onDownload={(e) => onDownload(photo, e)}
|
onDownload={(e) => onDownload(photo, e)}
|
||||||
animationType={animation}
|
animationType={animation}
|
||||||
allowDownloads={allowDownloads}
|
allowDownloads={allowDownloads}
|
||||||
@@ -201,8 +276,49 @@ export const GridGalleryLayout: React.FC<BaseGalleryLayoutProps> = ({
|
|||||||
protectionLevel={protectionLevel}
|
protectionLevel={protectionLevel}
|
||||||
useEnhancedProtection={useEnhancedProtection}
|
useEnhancedProtection={useEnhancedProtection}
|
||||||
feedbackEnabled={feedbackEnabled}
|
feedbackEnabled={feedbackEnabled}
|
||||||
|
feedbackOptions={feedbackOptions}
|
||||||
|
savedIdentity={savedIdentity}
|
||||||
|
onRequireIdentity={(action, photoId) => {
|
||||||
|
setPendingAction({ type: action, photoId });
|
||||||
|
setShowIdentityModal(true);
|
||||||
|
}}
|
||||||
|
onQuickComment={() => onOpenPhotoWithFeedback && onOpenPhotoWithFeedback(index)}
|
||||||
|
onFeedbackChange={onFeedbackChange}
|
||||||
|
liked={likedPhotoIds.has(photo.id)}
|
||||||
|
onLikeSuccess={() => {
|
||||||
|
setLikedPhotoIds((prev) => {
|
||||||
|
const next = new Set(prev);
|
||||||
|
next.add(photo.id);
|
||||||
|
return next;
|
||||||
|
});
|
||||||
|
}}
|
||||||
/>
|
/>
|
||||||
))}
|
))}
|
||||||
|
<FeedbackIdentityModal
|
||||||
|
isOpen={showIdentityModal}
|
||||||
|
onClose={() => { setShowIdentityModal(false); setPendingAction(null); }}
|
||||||
|
onSubmit={async (name, email) => {
|
||||||
|
setSavedIdentity({ name, email });
|
||||||
|
setShowIdentityModal(false);
|
||||||
|
if (pendingAction) {
|
||||||
|
await feedbackService.submitFeedback(slug, String(pendingAction.photoId), {
|
||||||
|
feedback_type: pendingAction.type,
|
||||||
|
guest_name: name,
|
||||||
|
guest_email: email,
|
||||||
|
});
|
||||||
|
// Immediately reflect like UI
|
||||||
|
if (pendingAction.type === 'like') {
|
||||||
|
setLikedPhotoIds((prev) => {
|
||||||
|
const next = new Set(prev);
|
||||||
|
next.add(pendingAction.photoId);
|
||||||
|
return next;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
setPendingAction(null);
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
feedbackType="like"
|
||||||
|
/>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
@@ -1,5 +1,5 @@
|
|||||||
import React, { useState, useEffect } from 'react';
|
import React, { useState, useEffect } from 'react';
|
||||||
import { Download, Maximize2, Check, ChevronDown, Calendar, Clock } from 'lucide-react';
|
import { Download, Maximize2, Check, ChevronDown, Calendar, Clock, Heart, MessageSquare } from 'lucide-react';
|
||||||
import { parseISO } from 'date-fns';
|
import { parseISO } from 'date-fns';
|
||||||
import { useTranslation } from 'react-i18next';
|
import { useTranslation } from 'react-i18next';
|
||||||
import { useLocalizedDate } from '../../../hooks/useLocalizedDate';
|
import { useLocalizedDate } from '../../../hooks/useLocalizedDate';
|
||||||
@@ -8,17 +8,23 @@ import { AuthenticatedImage } from '../../common';
|
|||||||
import type { BaseGalleryLayoutProps } from './BaseGalleryLayout';
|
import type { BaseGalleryLayoutProps } from './BaseGalleryLayout';
|
||||||
import type { Photo } from '../../../types';
|
import type { Photo } from '../../../types';
|
||||||
import { buildResourceUrl } from '../../../utils/url';
|
import { buildResourceUrl } from '../../../utils/url';
|
||||||
|
import { FeedbackIdentityModal } from '../../gallery/FeedbackIdentityModal';
|
||||||
|
import { feedbackService } from '../../../services/feedback.service';
|
||||||
|
|
||||||
interface HeroGalleryLayoutProps extends BaseGalleryLayoutProps {
|
interface HeroGalleryLayoutProps extends BaseGalleryLayoutProps {
|
||||||
eventName?: string;
|
eventName?: string;
|
||||||
eventLogo?: string | null;
|
eventLogo?: string | null;
|
||||||
eventDate?: string;
|
eventDate?: string;
|
||||||
expiresAt?: string;
|
expiresAt?: string;
|
||||||
|
// Use a static hero photo independent of current filter
|
||||||
|
heroPhotoOverride?: Photo | null;
|
||||||
}
|
}
|
||||||
|
|
||||||
export const HeroGalleryLayout: React.FC<HeroGalleryLayoutProps> = ({
|
export const HeroGalleryLayout: React.FC<HeroGalleryLayoutProps> = ({
|
||||||
photos,
|
photos,
|
||||||
|
slug,
|
||||||
onPhotoClick,
|
onPhotoClick,
|
||||||
|
onOpenPhotoWithFeedback,
|
||||||
onDownload,
|
onDownload,
|
||||||
selectedPhotos = new Set(),
|
selectedPhotos = new Set(),
|
||||||
isSelectionMode = false,
|
isSelectionMode = false,
|
||||||
@@ -27,15 +33,31 @@ export const HeroGalleryLayout: React.FC<HeroGalleryLayoutProps> = ({
|
|||||||
eventLogo,
|
eventLogo,
|
||||||
eventDate,
|
eventDate,
|
||||||
expiresAt,
|
expiresAt,
|
||||||
allowDownloads = true
|
heroPhotoOverride,
|
||||||
|
allowDownloads = true,
|
||||||
|
feedbackEnabled = false,
|
||||||
|
feedbackOptions
|
||||||
}) => {
|
}) => {
|
||||||
const { t } = useTranslation();
|
const { t } = useTranslation();
|
||||||
const { format } = useLocalizedDate();
|
const { format } = useLocalizedDate();
|
||||||
const { theme } = useTheme();
|
const { theme } = useTheme();
|
||||||
const [heroPhoto, setHeroPhoto] = useState<Photo | null>(null);
|
const [heroPhoto, setHeroPhoto] = useState<Photo | null>(null);
|
||||||
const [hasInitialized, setHasInitialized] = useState(false);
|
const [hasInitialized, setHasInitialized] = useState(false);
|
||||||
|
const [showIdentityModal, setShowIdentityModal] = useState(false);
|
||||||
|
const [pendingAction, setPendingAction] = useState<null | { type: 'like'; photoId: number }>(null);
|
||||||
|
const [savedIdentity, setSavedIdentity] = useState<{ name: string; email: string } | null>(null);
|
||||||
const gallerySettings = theme.gallerySettings || {};
|
const gallerySettings = theme.gallerySettings || {};
|
||||||
const overlayOpacity = gallerySettings.heroOverlayOpacity || 0.3;
|
const overlayOpacity = gallerySettings.heroOverlayOpacity || 0.3;
|
||||||
|
const [likedIds, setLikedIds] = useState<Set<number>>(new Set());
|
||||||
|
const canQuickComment = Boolean(feedbackEnabled && feedbackOptions?.allowComments && onOpenPhotoWithFeedback);
|
||||||
|
|
||||||
|
// If an override is provided, always use it and skip initialization logic
|
||||||
|
useEffect(() => {
|
||||||
|
if (heroPhotoOverride) {
|
||||||
|
setHeroPhoto(heroPhotoOverride);
|
||||||
|
setHasInitialized(true);
|
||||||
|
}
|
||||||
|
}, [heroPhotoOverride]);
|
||||||
|
|
||||||
// Reset initialization when heroImageId changes
|
// Reset initialization when heroImageId changes
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
@@ -46,14 +68,14 @@ export const HeroGalleryLayout: React.FC<HeroGalleryLayoutProps> = ({
|
|||||||
|
|
||||||
// Select hero photo (admin-selected or first photo only if gallery was empty)
|
// Select hero photo (admin-selected or first photo only if gallery was empty)
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
|
// When an override is provided, the effect above has already set the hero.
|
||||||
|
if (heroPhotoOverride) return;
|
||||||
|
|
||||||
if (photos.length > 0) {
|
if (photos.length > 0) {
|
||||||
const heroId = gallerySettings.heroImageId;
|
const heroId = gallerySettings.heroImageId;
|
||||||
// Process hero layout with provided photos
|
// If admin has selected a specific hero image, always use it when available
|
||||||
|
|
||||||
// If admin has selected a specific hero image, always use it
|
|
||||||
if (heroId) {
|
if (heroId) {
|
||||||
const adminSelectedHero = photos.find(p => p.id === heroId);
|
const adminSelectedHero = photos.find(p => p.id === heroId);
|
||||||
// Hero photo selected by admin
|
|
||||||
if (adminSelectedHero) {
|
if (adminSelectedHero) {
|
||||||
setHeroPhoto(adminSelectedHero);
|
setHeroPhoto(adminSelectedHero);
|
||||||
setHasInitialized(true);
|
setHasInitialized(true);
|
||||||
@@ -61,14 +83,13 @@ export const HeroGalleryLayout: React.FC<HeroGalleryLayoutProps> = ({
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Only auto-select first photo on initial load when gallery was empty
|
// Only auto-select first photo on initial load
|
||||||
// This prevents changing the hero when new photos are uploaded
|
|
||||||
if (!hasInitialized) {
|
if (!hasInitialized) {
|
||||||
setHeroPhoto(photos[0]);
|
setHeroPhoto(photos[0]);
|
||||||
setHasInitialized(true);
|
setHasInitialized(true);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}, [photos, gallerySettings.heroImageId, hasInitialized]);
|
}, [photos, gallerySettings.heroImageId, hasInitialized, heroPhotoOverride]);
|
||||||
|
|
||||||
if (!heroPhoto) return null;
|
if (!heroPhoto) return null;
|
||||||
|
|
||||||
@@ -76,11 +97,13 @@ export const HeroGalleryLayout: React.FC<HeroGalleryLayoutProps> = ({
|
|||||||
const remainingPhotos = photos;
|
const remainingPhotos = photos;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
|
<>
|
||||||
<div className="relative -mt-6">
|
<div className="relative -mt-6">
|
||||||
{/* Hero Section */}
|
{/* Hero Section */}
|
||||||
<div className="relative h-[60vh] sm:h-[70vh] lg:h-[80vh] -mx-4 sm:-mx-6 lg:-mx-8 mb-8">
|
<div className="relative h-[60vh] sm:h-[70vh] lg:h-[80vh] -mx-4 sm:-mx-6 lg:-mx-8 mb-8">
|
||||||
<AuthenticatedImage
|
<AuthenticatedImage
|
||||||
src={heroPhoto.url}
|
src={heroPhoto.url}
|
||||||
|
fallbackSrc={heroPhoto.thumbnail_url || undefined}
|
||||||
alt={heroPhoto.filename}
|
alt={heroPhoto.filename}
|
||||||
className="w-full h-full object-cover"
|
className="w-full h-full object-cover"
|
||||||
isGallery={true}
|
isGallery={true}
|
||||||
@@ -152,13 +175,7 @@ export const HeroGalleryLayout: React.FC<HeroGalleryLayoutProps> = ({
|
|||||||
<div
|
<div
|
||||||
key={photo.id}
|
key={photo.id}
|
||||||
className="relative group cursor-pointer aspect-square"
|
className="relative group cursor-pointer aspect-square"
|
||||||
onClick={() => {
|
onClick={() => onPhotoClick(actualIndex)}
|
||||||
if (isSelectionMode && onPhotoSelect) {
|
|
||||||
onPhotoSelect(photo.id);
|
|
||||||
} else {
|
|
||||||
onPhotoClick(actualIndex);
|
|
||||||
}
|
|
||||||
}}
|
|
||||||
>
|
>
|
||||||
<AuthenticatedImage
|
<AuthenticatedImage
|
||||||
src={photo.thumbnail_url || photo.url}
|
src={photo.thumbnail_url || photo.url}
|
||||||
@@ -194,15 +211,81 @@ export const HeroGalleryLayout: React.FC<HeroGalleryLayoutProps> = ({
|
|||||||
<Download className="w-5 h-5 text-neutral-800" />
|
<Download className="w-5 h-5 text-neutral-800" />
|
||||||
</button>
|
</button>
|
||||||
)}
|
)}
|
||||||
|
{feedbackOptions?.allowLikes && (
|
||||||
|
<button
|
||||||
|
className={`p-2 rounded-full transition-colors ${likedIds.has(photo.id) ? 'bg-red-500/90 hover:bg-red-500' : 'bg-white/90 hover:bg-white'}`}
|
||||||
|
onClick={async (e) => {
|
||||||
|
e.stopPropagation();
|
||||||
|
if (feedbackOptions?.requireNameEmail && !savedIdentity) {
|
||||||
|
setPendingAction({ type: 'like', photoId: photo.id });
|
||||||
|
setShowIdentityModal(true);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
setLikedIds(prev => new Set(prev).add(photo.id));
|
||||||
|
try {
|
||||||
|
await feedbackService.submitFeedback(slug!, String(photo.id), {
|
||||||
|
feedback_type: 'like',
|
||||||
|
guest_name: savedIdentity?.name,
|
||||||
|
guest_email: savedIdentity?.email,
|
||||||
|
});
|
||||||
|
} catch (_) {}
|
||||||
|
}}
|
||||||
|
aria-label="Like photo"
|
||||||
|
aria-pressed={likedIds.has(photo.id)}
|
||||||
|
title="Like"
|
||||||
|
>
|
||||||
|
<Heart className={`w-5 h-5 ${likedIds.has(photo.id) ? 'text-white fill-white' : 'text-neutral-800'}`} />
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
{canQuickComment && (
|
||||||
|
<button
|
||||||
|
className="p-2 bg-white/90 rounded-full hover:bg-white transition-colors"
|
||||||
|
onClick={(e) => { e.stopPropagation(); onOpenPhotoWithFeedback?.(actualIndex); }}
|
||||||
|
aria-label="Comment on photo"
|
||||||
|
title="Comment"
|
||||||
|
>
|
||||||
|
<MessageSquare className="w-5 h-5 text-neutral-800" />
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
</>
|
</>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{isSelectionMode && (
|
{/* Selection Checkbox (visible on hover or when selected) */}
|
||||||
<div className={`absolute top-2 right-2 ${selectedPhotos.has(photo.id) ? 'opacity-100' : 'opacity-0 group-hover:opacity-100'} transition-opacity`}>
|
<button
|
||||||
<div className={`w-6 h-6 rounded-full border-2 ${selectedPhotos.has(photo.id) ? 'bg-primary-600 border-primary-600' : 'bg-white/80 border-white'} flex items-center justify-center transition-colors`}>
|
type="button"
|
||||||
{selectedPhotos.has(photo.id) && <Check className="w-4 h-4 text-white" />}
|
aria-label={`Select ${photo.filename}`}
|
||||||
</div>
|
role="checkbox"
|
||||||
|
aria-checked={selectedPhotos.has(photo.id)}
|
||||||
|
data-testid={`gallery-photo-checkbox-${photo.id}`}
|
||||||
|
className={`absolute top-2 right-2 z-20 transition-opacity ${
|
||||||
|
selectedPhotos.has(photo.id) ? 'opacity-100' : 'opacity-0 group-hover:opacity-100'
|
||||||
|
}`}
|
||||||
|
onClick={(e) => { e.stopPropagation(); onPhotoSelect && onPhotoSelect(photo.id); }}
|
||||||
|
>
|
||||||
|
<div className={`w-6 h-6 rounded-full border-2 ${selectedPhotos.has(photo.id) ? 'bg-primary-600 border-primary-600' : 'bg-white/90 border-white'} flex items-center justify-center transition-colors`}>
|
||||||
|
{selectedPhotos.has(photo.id) && <Check className="w-4 h-4 text-white" />}
|
||||||
|
</div>
|
||||||
|
</button>
|
||||||
|
|
||||||
|
{/* Feedback indicators (always visible, bottom-left). Show like immediately when liked */}
|
||||||
|
{(photo.like_count > 0 || likedIds.has(photo.id) || (photo.average_rating || 0) > 0 || (photo.comment_count || 0) > 0) && (
|
||||||
|
<div className={`absolute ${photo.type === 'collage' ? 'bottom-8' : 'bottom-2'} left-2 flex items-center gap-1 z-20`}>
|
||||||
|
{(photo.like_count > 0 || likedIds.has(photo.id)) && (
|
||||||
|
<span className="inline-flex items-center justify-center w-6 h-6 rounded-full bg-white/90 backdrop-blur-sm" title="Liked">
|
||||||
|
<Heart className="w-3.5 h-3.5 text-red-500" fill="currentColor" />
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
{(photo.average_rating || 0) > 0 && (
|
||||||
|
<span className="inline-flex items-center justify-center w-6 h-6 rounded-full bg-white/90 backdrop-blur-sm" title="Rated">
|
||||||
|
<svg viewBox="0 0 24 24" className="w-3.5 h-3.5 text-yellow-500 fill-current"><path d="M12 .587l3.668 7.431 8.2 1.193-5.934 5.787 1.402 8.168L12 18.897l-7.336 3.869 1.402-8.168L.132 9.211l8.2-1.193z"/></svg>
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
{(photo.comment_count || 0) > 0 && (
|
||||||
|
<span className="inline-flex items-center justify-center w-6 h-6 rounded-full bg-white/90 backdrop-blur-sm" title="Commented">
|
||||||
|
<svg viewBox="0 0 24 24" className="w-3.5 h-3.5 text-blue-600 fill-current"><path d="M20 2H4a2 2 0 00-2 2v18l4-4h14a2 2 0 002-2V4a2 2 0 00-2-2z"/></svg>
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
@@ -210,5 +293,23 @@ export const HeroGalleryLayout: React.FC<HeroGalleryLayoutProps> = ({
|
|||||||
})}
|
})}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
<FeedbackIdentityModal
|
||||||
|
isOpen={showIdentityModal}
|
||||||
|
onClose={() => { setShowIdentityModal(false); setPendingAction(null); }}
|
||||||
|
onSubmit={async (name, email) => {
|
||||||
|
setSavedIdentity({ name, email });
|
||||||
|
setShowIdentityModal(false);
|
||||||
|
if (pendingAction) {
|
||||||
|
await feedbackService.submitFeedback(slug!, String(pendingAction.photoId), {
|
||||||
|
feedback_type: pendingAction.type,
|
||||||
|
guest_name: name,
|
||||||
|
guest_email: email,
|
||||||
|
});
|
||||||
|
setPendingAction(null);
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
feedbackType="like"
|
||||||
|
/>
|
||||||
|
</>
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
@@ -2,6 +2,8 @@ import React, { useEffect, useRef, useState } from 'react';
|
|||||||
import { Download, Maximize2, Check, MessageSquare, Star, Heart } from 'lucide-react';
|
import { Download, Maximize2, Check, MessageSquare, Star, Heart } from 'lucide-react';
|
||||||
import { useTheme } from '../../../contexts/ThemeContext';
|
import { useTheme } from '../../../contexts/ThemeContext';
|
||||||
import { AuthenticatedImage } from '../../common';
|
import { AuthenticatedImage } from '../../common';
|
||||||
|
import { FeedbackIdentityModal } from '../../gallery/FeedbackIdentityModal';
|
||||||
|
import { feedbackService } from '../../../services/feedback.service';
|
||||||
import type { BaseGalleryLayoutProps } from './BaseGalleryLayout';
|
import type { BaseGalleryLayoutProps } from './BaseGalleryLayout';
|
||||||
import type { Photo } from '../../../types';
|
import type { Photo } from '../../../types';
|
||||||
|
|
||||||
@@ -11,9 +13,17 @@ interface MasonryPhotoProps {
|
|||||||
isSelectionMode: boolean;
|
isSelectionMode: boolean;
|
||||||
onClick: (e: React.MouseEvent) => void;
|
onClick: (e: React.MouseEvent) => void;
|
||||||
onDownload: (e: React.MouseEvent) => void;
|
onDownload: (e: React.MouseEvent) => void;
|
||||||
|
onToggleSelect: () => void;
|
||||||
style?: React.CSSProperties;
|
style?: React.CSSProperties;
|
||||||
allowDownloads?: boolean;
|
allowDownloads?: boolean;
|
||||||
feedbackEnabled?: boolean;
|
feedbackEnabled?: boolean;
|
||||||
|
slug?: string;
|
||||||
|
feedbackOptions?: {
|
||||||
|
allowLikes?: boolean;
|
||||||
|
allowComments?: boolean;
|
||||||
|
requireNameEmail?: boolean;
|
||||||
|
};
|
||||||
|
onQuickComment?: () => void;
|
||||||
}
|
}
|
||||||
|
|
||||||
const MasonryPhoto: React.FC<MasonryPhotoProps> = ({
|
const MasonryPhoto: React.FC<MasonryPhotoProps> = ({
|
||||||
@@ -22,11 +32,18 @@ const MasonryPhoto: React.FC<MasonryPhotoProps> = ({
|
|||||||
isSelectionMode,
|
isSelectionMode,
|
||||||
onClick,
|
onClick,
|
||||||
onDownload,
|
onDownload,
|
||||||
|
onToggleSelect,
|
||||||
style,
|
style,
|
||||||
allowDownloads = true,
|
allowDownloads = true,
|
||||||
feedbackEnabled = false
|
feedbackEnabled = false,
|
||||||
|
slug,
|
||||||
|
feedbackOptions,
|
||||||
|
onQuickComment
|
||||||
}) => {
|
}) => {
|
||||||
const [imageHeight, setImageHeight] = useState<number>(200);
|
const [imageHeight, setImageHeight] = useState<number>(200);
|
||||||
|
const [showIdentityModal, setShowIdentityModal] = useState(false);
|
||||||
|
const [pendingAction, setPendingAction] = useState<null | { type: 'like'; photoId: number }>(null);
|
||||||
|
const [savedIdentity, setSavedIdentity] = useState<{ name: string; email: string } | null>(null);
|
||||||
|
|
||||||
// Generate random heights for masonry effect
|
// Generate random heights for masonry effect
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
@@ -100,17 +117,77 @@ const MasonryPhoto: React.FC<MasonryPhotoProps> = ({
|
|||||||
<Download className="w-5 h-5 text-neutral-800" />
|
<Download className="w-5 h-5 text-neutral-800" />
|
||||||
</button>
|
</button>
|
||||||
)}
|
)}
|
||||||
|
{onQuickComment && (
|
||||||
|
<button
|
||||||
|
className="p-2 bg-white/90 rounded-full hover:bg-white transition-colors"
|
||||||
|
onClick={(e) => { e.stopPropagation(); onQuickComment(); }}
|
||||||
|
aria-label="Comment on photo"
|
||||||
|
title="Comment"
|
||||||
|
>
|
||||||
|
<MessageSquare className="w-5 h-5 text-neutral-800" />
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
{feedbackOptions?.allowLikes && (
|
||||||
|
<button
|
||||||
|
className="p-2 bg-white/90 rounded-full hover:bg-white transition-colors"
|
||||||
|
onClick={async (e) => {
|
||||||
|
e.stopPropagation();
|
||||||
|
if (feedbackOptions?.requireNameEmail && !savedIdentity) {
|
||||||
|
setPendingAction({ type: 'like', photoId: photo.id });
|
||||||
|
setShowIdentityModal(true);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
await feedbackService.submitFeedback(slug!, String(photo.id), {
|
||||||
|
feedback_type: 'like',
|
||||||
|
guest_name: savedIdentity?.name,
|
||||||
|
guest_email: savedIdentity?.email,
|
||||||
|
});
|
||||||
|
}}
|
||||||
|
aria-label="Like photo"
|
||||||
|
title="Like"
|
||||||
|
>
|
||||||
|
<Heart className="w-5 h-5 text-neutral-800" />
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
</>
|
</>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{isSelectionMode && (
|
{/* Identity Modal */}
|
||||||
<div className={`absolute top-2 right-2 ${isSelected ? 'opacity-100' : 'opacity-0 group-hover:opacity-100'} transition-opacity`}>
|
<FeedbackIdentityModal
|
||||||
<div className={`w-6 h-6 rounded-full border-2 ${isSelected ? 'bg-primary-600 border-primary-600' : 'bg-white/80 border-white'} flex items-center justify-center transition-colors`}>
|
isOpen={showIdentityModal}
|
||||||
{isSelected && <Check className="w-4 h-4 text-white" />}
|
onClose={() => { setShowIdentityModal(false); setPendingAction(null); }}
|
||||||
</div>
|
onSubmit={async (name, email) => {
|
||||||
|
setSavedIdentity({ name, email });
|
||||||
|
setShowIdentityModal(false);
|
||||||
|
if (pendingAction) {
|
||||||
|
await feedbackService.submitFeedback(slug!, String(pendingAction.photoId), {
|
||||||
|
feedback_type: pendingAction.type,
|
||||||
|
guest_name: name,
|
||||||
|
guest_email: email,
|
||||||
|
});
|
||||||
|
setPendingAction(null);
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
feedbackType="like"
|
||||||
|
/>
|
||||||
|
|
||||||
|
{/* Selection Checkbox (visible on hover or when selected) */}
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
aria-label={`Select ${photo.filename}`}
|
||||||
|
role="checkbox"
|
||||||
|
aria-checked={isSelected}
|
||||||
|
data-testid={`gallery-photo-checkbox-${photo.id}`}
|
||||||
|
className={`absolute top-2 right-2 z-20 transition-opacity ${
|
||||||
|
isSelected ? 'opacity-100' : 'opacity-0 group-hover:opacity-100'
|
||||||
|
}`}
|
||||||
|
onClick={(e) => { e.stopPropagation(); onToggleSelect(); }}
|
||||||
|
>
|
||||||
|
<div className={`w-6 h-6 rounded-full border-2 ${isSelected ? 'bg-primary-600 border-primary-600' : 'bg-white/90 border-white'} flex items-center justify-center transition-colors`}>
|
||||||
|
{isSelected && <Check className="w-4 h-4 text-white" />}
|
||||||
</div>
|
</div>
|
||||||
)}
|
</button>
|
||||||
|
|
||||||
{photo.type === 'collage' && (
|
{photo.type === 'collage' && (
|
||||||
<div className="absolute bottom-2 left-2">
|
<div className="absolute bottom-2 left-2">
|
||||||
@@ -125,13 +202,16 @@ const MasonryPhoto: React.FC<MasonryPhotoProps> = ({
|
|||||||
|
|
||||||
export const MasonryGalleryLayout: React.FC<BaseGalleryLayoutProps> = ({
|
export const MasonryGalleryLayout: React.FC<BaseGalleryLayoutProps> = ({
|
||||||
photos,
|
photos,
|
||||||
|
slug,
|
||||||
onPhotoClick,
|
onPhotoClick,
|
||||||
|
onOpenPhotoWithFeedback,
|
||||||
onDownload,
|
onDownload,
|
||||||
selectedPhotos = new Set(),
|
selectedPhotos = new Set(),
|
||||||
isSelectionMode = false,
|
isSelectionMode = false,
|
||||||
onPhotoSelect,
|
onPhotoSelect,
|
||||||
allowDownloads = true,
|
allowDownloads = true,
|
||||||
feedbackEnabled = false
|
feedbackEnabled = false,
|
||||||
|
feedbackOptions
|
||||||
}) => {
|
}) => {
|
||||||
const { theme } = useTheme();
|
const { theme } = useTheme();
|
||||||
const containerRef = useRef<HTMLDivElement>(null);
|
const containerRef = useRef<HTMLDivElement>(null);
|
||||||
@@ -182,16 +262,14 @@ export const MasonryGalleryLayout: React.FC<BaseGalleryLayoutProps> = ({
|
|||||||
photo={photo}
|
photo={photo}
|
||||||
isSelected={selectedPhotos.has(photo.id)}
|
isSelected={selectedPhotos.has(photo.id)}
|
||||||
isSelectionMode={isSelectionMode}
|
isSelectionMode={isSelectionMode}
|
||||||
onClick={() => {
|
onClick={() => onPhotoClick(originalIndex)}
|
||||||
if (isSelectionMode && onPhotoSelect) {
|
|
||||||
onPhotoSelect(photo.id);
|
|
||||||
} else {
|
|
||||||
onPhotoClick(originalIndex);
|
|
||||||
}
|
|
||||||
}}
|
|
||||||
onDownload={(e) => onDownload(photo, e)}
|
onDownload={(e) => onDownload(photo, e)}
|
||||||
|
onToggleSelect={() => onPhotoSelect && onPhotoSelect(photo.id)}
|
||||||
allowDownloads={allowDownloads}
|
allowDownloads={allowDownloads}
|
||||||
feedbackEnabled={feedbackEnabled}
|
feedbackEnabled={feedbackEnabled}
|
||||||
|
slug={slug}
|
||||||
|
feedbackOptions={feedbackOptions}
|
||||||
|
onQuickComment={() => onOpenPhotoWithFeedback && onOpenPhotoWithFeedback(originalIndex)}
|
||||||
/>
|
/>
|
||||||
);
|
);
|
||||||
})}
|
})}
|
||||||
|
|||||||
@@ -1,7 +1,9 @@
|
|||||||
import React from 'react';
|
import React from 'react';
|
||||||
import { Download, Maximize2, Check } from 'lucide-react';
|
import { Download, Maximize2, Check, Heart, MessageSquare } from 'lucide-react';
|
||||||
// import { useTheme } from '../../../contexts/ThemeContext';
|
// import { useTheme } from '../../../contexts/ThemeContext';
|
||||||
import { AuthenticatedImage } from '../../common';
|
import { AuthenticatedImage } from '../../common';
|
||||||
|
import { FeedbackIdentityModal } from '../../gallery/FeedbackIdentityModal';
|
||||||
|
import { feedbackService } from '../../../services/feedback.service';
|
||||||
import type { BaseGalleryLayoutProps } from './BaseGalleryLayout';
|
import type { BaseGalleryLayoutProps } from './BaseGalleryLayout';
|
||||||
import type { Photo } from '../../../types';
|
import type { Photo } from '../../../types';
|
||||||
|
|
||||||
@@ -11,8 +13,17 @@ interface MosaicPhotoProps {
|
|||||||
isSelectionMode: boolean;
|
isSelectionMode: boolean;
|
||||||
onClick: (e: React.MouseEvent) => void;
|
onClick: (e: React.MouseEvent) => void;
|
||||||
onDownload: (e: React.MouseEvent) => void;
|
onDownload: (e: React.MouseEvent) => void;
|
||||||
|
onToggleSelect: () => void;
|
||||||
className?: string;
|
className?: string;
|
||||||
allowDownloads?: boolean;
|
allowDownloads?: boolean;
|
||||||
|
slug?: string;
|
||||||
|
feedbackEnabled?: boolean;
|
||||||
|
feedbackOptions?: {
|
||||||
|
allowLikes?: boolean;
|
||||||
|
allowComments?: boolean;
|
||||||
|
requireNameEmail?: boolean;
|
||||||
|
};
|
||||||
|
onQuickComment?: () => void;
|
||||||
}
|
}
|
||||||
|
|
||||||
const MosaicPhoto: React.FC<MosaicPhotoProps> = ({
|
const MosaicPhoto: React.FC<MosaicPhotoProps> = ({
|
||||||
@@ -21,10 +32,22 @@ const MosaicPhoto: React.FC<MosaicPhotoProps> = ({
|
|||||||
isSelectionMode,
|
isSelectionMode,
|
||||||
onClick,
|
onClick,
|
||||||
onDownload,
|
onDownload,
|
||||||
|
onToggleSelect,
|
||||||
className = '',
|
className = '',
|
||||||
allowDownloads = true
|
allowDownloads = true,
|
||||||
|
slug,
|
||||||
|
feedbackEnabled = false,
|
||||||
|
feedbackOptions,
|
||||||
|
onQuickComment
|
||||||
}) => {
|
}) => {
|
||||||
|
const [showIdentityModal, setShowIdentityModal] = React.useState(false);
|
||||||
|
const [pendingAction, setPendingAction] = React.useState<null | { type: 'like'; photoId: number }>(null);
|
||||||
|
const [savedIdentity, setSavedIdentity] = React.useState<{ name: string; email: string } | null>(null);
|
||||||
|
const [likedLocal, setLikedLocal] = React.useState(false);
|
||||||
|
const canComment = Boolean(feedbackEnabled && feedbackOptions?.allowComments && onQuickComment);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
|
<>
|
||||||
<div
|
<div
|
||||||
className={`relative group cursor-pointer overflow-hidden rounded-lg bg-neutral-100 ${className}`}
|
className={`relative group cursor-pointer overflow-hidden rounded-lg bg-neutral-100 ${className}`}
|
||||||
onClick={(e) => {
|
onClick={(e) => {
|
||||||
@@ -65,18 +88,72 @@ const MosaicPhoto: React.FC<MosaicPhotoProps> = ({
|
|||||||
<Download className="w-5 h-5 text-neutral-800" />
|
<Download className="w-5 h-5 text-neutral-800" />
|
||||||
</button>
|
</button>
|
||||||
)}
|
)}
|
||||||
|
{feedbackOptions?.allowLikes && (
|
||||||
|
<button
|
||||||
|
className={`p-2 rounded-full transition-colors ${likedLocal ? 'bg-red-500/90 hover:bg-red-500' : 'bg-white/90 hover:bg-white'}`}
|
||||||
|
onClick={async (e) => {
|
||||||
|
e.stopPropagation();
|
||||||
|
if (feedbackOptions?.requireNameEmail && !savedIdentity) {
|
||||||
|
setPendingAction({ type: 'like', photoId: photo.id });
|
||||||
|
setShowIdentityModal(true);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
setLikedLocal(true);
|
||||||
|
try {
|
||||||
|
await feedbackService.submitFeedback(slug!, String(photo.id), {
|
||||||
|
feedback_type: 'like',
|
||||||
|
guest_name: savedIdentity?.name,
|
||||||
|
guest_email: savedIdentity?.email,
|
||||||
|
});
|
||||||
|
} catch (_) {}
|
||||||
|
}}
|
||||||
|
aria-label="Like photo"
|
||||||
|
aria-pressed={likedLocal}
|
||||||
|
title="Like"
|
||||||
|
>
|
||||||
|
<Heart className={`w-5 h-5 ${likedLocal ? 'text-white fill-white' : 'text-neutral-800'}`} />
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
{canComment && (
|
||||||
|
<button
|
||||||
|
className="p-2 bg-white/90 rounded-full hover:bg-white transition-colors"
|
||||||
|
onClick={(e) => { e.stopPropagation(); onQuickComment?.(); }}
|
||||||
|
aria-label="Comment on photo"
|
||||||
|
title="Comment"
|
||||||
|
>
|
||||||
|
<MessageSquare className="w-5 h-5 text-neutral-800" />
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
</>
|
</>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{isSelectionMode && (
|
{/* Feedback Indicators (bottom-left) */}
|
||||||
<div className={`absolute top-2 right-2 ${isSelected ? 'opacity-100' : 'opacity-0 group-hover:opacity-100'} transition-opacity`}>
|
{(photo.like_count > 0 || likedLocal) && (
|
||||||
<div className={`w-6 h-6 rounded-full border-2 ${isSelected ? 'bg-primary-600 border-primary-600' : 'bg-white/80 border-white'} flex items-center justify-center transition-colors`}>
|
<div className={`absolute ${photo.type === 'collage' ? 'bottom-8' : 'bottom-2'} left-2 z-10`}>
|
||||||
{isSelected && <Check className="w-4 h-4 text-white" />}
|
<span className="inline-flex items-center justify-center w-6 h-6 rounded-full bg-white/90 backdrop-blur-sm" title="Liked">
|
||||||
</div>
|
<Heart className="w-3.5 h-3.5 text-red-500" fill="currentColor" />
|
||||||
|
</span>
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
|
{/* Selection Checkbox (visible on hover or when selected) */}
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
aria-label={`Select ${photo.filename}`}
|
||||||
|
role="checkbox"
|
||||||
|
aria-checked={isSelected}
|
||||||
|
data-testid={`gallery-photo-checkbox-${photo.id}`}
|
||||||
|
className={`absolute top-2 right-2 z-20 transition-opacity ${
|
||||||
|
isSelected ? 'opacity-100' : 'opacity-0 group-hover:opacity-100'
|
||||||
|
}`}
|
||||||
|
onClick={(e) => { e.stopPropagation(); onToggleSelect(); }}
|
||||||
|
>
|
||||||
|
<div className={`w-6 h-6 rounded-full border-2 ${isSelected ? 'bg-primary-600 border-primary-600' : 'bg-white/90 border-white'} flex items-center justify-center transition-colors`}>
|
||||||
|
{isSelected && <Check className="w-4 h-4 text-white" />}
|
||||||
|
</div>
|
||||||
|
</button>
|
||||||
|
|
||||||
{photo.type === 'collage' && (
|
{photo.type === 'collage' && (
|
||||||
<div className="absolute bottom-2 left-2">
|
<div className="absolute bottom-2 left-2">
|
||||||
<span className="px-2 py-1 bg-black/60 text-white text-xs rounded">
|
<span className="px-2 py-1 bg-black/60 text-white text-xs rounded">
|
||||||
@@ -85,17 +162,39 @@ const MosaicPhoto: React.FC<MosaicPhotoProps> = ({
|
|||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
<FeedbackIdentityModal
|
||||||
|
isOpen={showIdentityModal}
|
||||||
|
onClose={() => { setShowIdentityModal(false); setPendingAction(null); }}
|
||||||
|
onSubmit={async (name, email) => {
|
||||||
|
setSavedIdentity({ name, email });
|
||||||
|
setShowIdentityModal(false);
|
||||||
|
if (pendingAction) {
|
||||||
|
await feedbackService.submitFeedback(slug!, String(pendingAction.photoId), {
|
||||||
|
feedback_type: pendingAction.type,
|
||||||
|
guest_name: name,
|
||||||
|
guest_email: email,
|
||||||
|
});
|
||||||
|
setPendingAction(null);
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
feedbackType="like"
|
||||||
|
/>
|
||||||
|
</>
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
export const MosaicGalleryLayout: React.FC<BaseGalleryLayoutProps> = ({
|
export const MosaicGalleryLayout: React.FC<BaseGalleryLayoutProps> = ({
|
||||||
photos,
|
photos,
|
||||||
|
slug,
|
||||||
onPhotoClick,
|
onPhotoClick,
|
||||||
|
onOpenPhotoWithFeedback,
|
||||||
onDownload,
|
onDownload,
|
||||||
selectedPhotos = new Set(),
|
selectedPhotos = new Set(),
|
||||||
isSelectionMode = false,
|
isSelectionMode = false,
|
||||||
onPhotoSelect,
|
onPhotoSelect,
|
||||||
allowDownloads = true
|
allowDownloads = true,
|
||||||
|
feedbackEnabled = false,
|
||||||
|
feedbackOptions
|
||||||
}) => {
|
}) => {
|
||||||
// const { theme } = useTheme();
|
// const { theme } = useTheme();
|
||||||
// const gallerySettings = theme.gallerySettings || {};
|
// const gallerySettings = theme.gallerySettings || {};
|
||||||
@@ -136,10 +235,15 @@ export const MosaicGalleryLayout: React.FC<BaseGalleryLayoutProps> = ({
|
|||||||
photo={photo0}
|
photo={photo0}
|
||||||
isSelected={selectedPhotos.has(photo0.id)}
|
isSelected={selectedPhotos.has(photo0.id)}
|
||||||
isSelectionMode={isSelectionMode}
|
isSelectionMode={isSelectionMode}
|
||||||
onClick={() => handlePhotoClick(idx0, photo0.id)}
|
onClick={() => onPhotoClick(idx0)}
|
||||||
onDownload={(e) => onDownload(photo0, e)}
|
onDownload={(e) => onDownload(photo0, e)}
|
||||||
|
onToggleSelect={() => onPhotoSelect && onPhotoSelect(photo0.id)}
|
||||||
className="col-span-1"
|
className="col-span-1"
|
||||||
allowDownloads={allowDownloads}
|
allowDownloads={allowDownloads}
|
||||||
|
slug={slug}
|
||||||
|
feedbackEnabled={feedbackEnabled}
|
||||||
|
feedbackOptions={feedbackOptions}
|
||||||
|
onQuickComment={() => { if (typeof onOpenPhotoWithFeedback !== 'undefined' && onOpenPhotoWithFeedback) onOpenPhotoWithFeedback(idx0); }}
|
||||||
/>
|
/>
|
||||||
)}
|
)}
|
||||||
<div className="grid grid-rows-2 gap-2">
|
<div className="grid grid-rows-2 gap-2">
|
||||||
@@ -148,22 +252,32 @@ export const MosaicGalleryLayout: React.FC<BaseGalleryLayoutProps> = ({
|
|||||||
photo={photo1}
|
photo={photo1}
|
||||||
isSelected={selectedPhotos.has(photo1.id)}
|
isSelected={selectedPhotos.has(photo1.id)}
|
||||||
isSelectionMode={isSelectionMode}
|
isSelectionMode={isSelectionMode}
|
||||||
onClick={() => handlePhotoClick(idx1, photo1.id)}
|
onClick={() => onPhotoClick(idx1)}
|
||||||
onDownload={(e) => onDownload(photo1, e)}
|
onDownload={(e) => onDownload(photo1, e)}
|
||||||
|
onToggleSelect={() => onPhotoSelect && onPhotoSelect(photo1.id)}
|
||||||
className=""
|
className=""
|
||||||
allowDownloads={allowDownloads}
|
allowDownloads={allowDownloads}
|
||||||
/>
|
slug={slug}
|
||||||
|
feedbackEnabled={feedbackEnabled}
|
||||||
|
feedbackOptions={feedbackOptions}
|
||||||
|
onQuickComment={() => { if (typeof onOpenPhotoWithFeedback !== 'undefined' && onOpenPhotoWithFeedback) onOpenPhotoWithFeedback(idx1); }}
|
||||||
|
/>
|
||||||
)}
|
)}
|
||||||
{photo2 && (
|
{photo2 && (
|
||||||
<MosaicPhoto
|
<MosaicPhoto
|
||||||
photo={photo2}
|
photo={photo2}
|
||||||
isSelected={selectedPhotos.has(photo2.id)}
|
isSelected={selectedPhotos.has(photo2.id)}
|
||||||
isSelectionMode={isSelectionMode}
|
isSelectionMode={isSelectionMode}
|
||||||
onClick={() => handlePhotoClick(idx2, photo2.id)}
|
onClick={() => onPhotoClick(idx2)}
|
||||||
onDownload={(e) => onDownload(photo2, e)}
|
onDownload={(e) => onDownload(photo2, e)}
|
||||||
|
onToggleSelect={() => onPhotoSelect && onPhotoSelect(photo2.id)}
|
||||||
className=""
|
className=""
|
||||||
allowDownloads={allowDownloads}
|
allowDownloads={allowDownloads}
|
||||||
/>
|
slug={slug}
|
||||||
|
feedbackEnabled={feedbackEnabled}
|
||||||
|
feedbackOptions={feedbackOptions}
|
||||||
|
onQuickComment={() => { if (typeof onOpenPhotoWithFeedback !== 'undefined' && onOpenPhotoWithFeedback) onOpenPhotoWithFeedback(idx2); }}
|
||||||
|
/>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
@@ -186,6 +300,10 @@ export const MosaicGalleryLayout: React.FC<BaseGalleryLayoutProps> = ({
|
|||||||
onDownload={(e) => onDownload(photo, e)}
|
onDownload={(e) => onDownload(photo, e)}
|
||||||
className=""
|
className=""
|
||||||
allowDownloads={allowDownloads}
|
allowDownloads={allowDownloads}
|
||||||
|
slug={slug}
|
||||||
|
feedbackEnabled={feedbackEnabled}
|
||||||
|
feedbackOptions={feedbackOptions}
|
||||||
|
onQuickComment={() => { if (typeof onOpenPhotoWithFeedback !== 'undefined' && onOpenPhotoWithFeedback) onOpenPhotoWithFeedback(currentIndex); }}
|
||||||
/>
|
/>
|
||||||
) : null;
|
) : null;
|
||||||
})}
|
})}
|
||||||
@@ -209,10 +327,15 @@ export const MosaicGalleryLayout: React.FC<BaseGalleryLayoutProps> = ({
|
|||||||
photo={photo0}
|
photo={photo0}
|
||||||
isSelected={selectedPhotos.has(photo0.id)}
|
isSelected={selectedPhotos.has(photo0.id)}
|
||||||
isSelectionMode={isSelectionMode}
|
isSelectionMode={isSelectionMode}
|
||||||
onClick={() => handlePhotoClick(idx0, photo0.id)}
|
onClick={() => onPhotoClick(idx0)}
|
||||||
onDownload={(e) => onDownload(photo0, e)}
|
onDownload={(e) => onDownload(photo0, e)}
|
||||||
|
onToggleSelect={() => onPhotoSelect && onPhotoSelect(photo0.id)}
|
||||||
className="col-span-2"
|
className="col-span-2"
|
||||||
allowDownloads={allowDownloads}
|
allowDownloads={allowDownloads}
|
||||||
|
slug={slug}
|
||||||
|
feedbackEnabled={feedbackEnabled}
|
||||||
|
feedbackOptions={feedbackOptions}
|
||||||
|
onQuickComment={() => { if (typeof onOpenPhotoWithFeedback !== 'undefined' && onOpenPhotoWithFeedback) onOpenPhotoWithFeedback(idx0); }}
|
||||||
/>
|
/>
|
||||||
)}
|
)}
|
||||||
<div className="grid grid-rows-2 gap-2">
|
<div className="grid grid-rows-2 gap-2">
|
||||||
@@ -221,22 +344,32 @@ export const MosaicGalleryLayout: React.FC<BaseGalleryLayoutProps> = ({
|
|||||||
photo={photo1}
|
photo={photo1}
|
||||||
isSelected={selectedPhotos.has(photo1.id)}
|
isSelected={selectedPhotos.has(photo1.id)}
|
||||||
isSelectionMode={isSelectionMode}
|
isSelectionMode={isSelectionMode}
|
||||||
onClick={() => handlePhotoClick(idx1, photo1.id)}
|
onClick={() => onPhotoClick(idx1)}
|
||||||
onDownload={(e) => onDownload(photo1, e)}
|
onDownload={(e) => onDownload(photo1, e)}
|
||||||
|
onToggleSelect={() => onPhotoSelect && onPhotoSelect(photo1.id)}
|
||||||
className=""
|
className=""
|
||||||
allowDownloads={allowDownloads}
|
allowDownloads={allowDownloads}
|
||||||
/>
|
slug={slug}
|
||||||
|
feedbackEnabled={feedbackEnabled}
|
||||||
|
feedbackOptions={feedbackOptions}
|
||||||
|
onQuickComment={() => { if (typeof onOpenPhotoWithFeedback !== 'undefined' && onOpenPhotoWithFeedback) onOpenPhotoWithFeedback(idx1); }}
|
||||||
|
/>
|
||||||
)}
|
)}
|
||||||
{photo2 && (
|
{photo2 && (
|
||||||
<MosaicPhoto
|
<MosaicPhoto
|
||||||
photo={photo2}
|
photo={photo2}
|
||||||
isSelected={selectedPhotos.has(photo2.id)}
|
isSelected={selectedPhotos.has(photo2.id)}
|
||||||
isSelectionMode={isSelectionMode}
|
isSelectionMode={isSelectionMode}
|
||||||
onClick={() => handlePhotoClick(idx2, photo2.id)}
|
onClick={() => onPhotoClick(idx2)}
|
||||||
onDownload={(e) => onDownload(photo2, e)}
|
onDownload={(e) => onDownload(photo2, e)}
|
||||||
|
onToggleSelect={() => onPhotoSelect && onPhotoSelect(photo2.id)}
|
||||||
className=""
|
className=""
|
||||||
allowDownloads={allowDownloads}
|
allowDownloads={allowDownloads}
|
||||||
/>
|
slug={slug}
|
||||||
|
feedbackEnabled={feedbackEnabled}
|
||||||
|
feedbackOptions={feedbackOptions}
|
||||||
|
onQuickComment={() => { if (typeof onOpenPhotoWithFeedback !== 'undefined' && onOpenPhotoWithFeedback) onOpenPhotoWithFeedback(idx2); }}
|
||||||
|
/>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
@@ -263,10 +396,15 @@ export const MosaicGalleryLayout: React.FC<BaseGalleryLayoutProps> = ({
|
|||||||
photo={photo}
|
photo={photo}
|
||||||
isSelected={selectedPhotos.has(photo.id)}
|
isSelected={selectedPhotos.has(photo.id)}
|
||||||
isSelectionMode={isSelectionMode}
|
isSelectionMode={isSelectionMode}
|
||||||
onClick={() => handlePhotoClick(index, photo.id)}
|
onClick={() => onPhotoClick(index)}
|
||||||
onDownload={(e) => onDownload(photo, e)}
|
onDownload={(e) => onDownload(photo, e)}
|
||||||
|
onToggleSelect={() => onPhotoSelect && onPhotoSelect(photo.id)}
|
||||||
className="aspect-square"
|
className="aspect-square"
|
||||||
allowDownloads={allowDownloads}
|
allowDownloads={allowDownloads}
|
||||||
|
slug={slug}
|
||||||
|
feedbackEnabled={feedbackEnabled}
|
||||||
|
feedbackOptions={feedbackOptions}
|
||||||
|
onQuickComment={() => { if (typeof onOpenPhotoWithFeedback !== 'undefined' && onOpenPhotoWithFeedback) onOpenPhotoWithFeedback(index); }}
|
||||||
/>
|
/>
|
||||||
);
|
);
|
||||||
})}
|
})}
|
||||||
|
|||||||
@@ -1,24 +1,35 @@
|
|||||||
import React, { useMemo } from 'react';
|
import React, { useMemo, useState } from 'react';
|
||||||
import { Download, Maximize2, Check, Calendar } from 'lucide-react';
|
import { Download, Maximize2, Check, Calendar, Heart, MessageSquare } from 'lucide-react';
|
||||||
import { format, parseISO, startOfDay, startOfWeek, startOfMonth } from 'date-fns';
|
import { format, parseISO, startOfDay, startOfWeek, startOfMonth } from 'date-fns';
|
||||||
import { useTheme } from '../../../contexts/ThemeContext';
|
import { useTheme } from '../../../contexts/ThemeContext';
|
||||||
import { AuthenticatedImage } from '../../common';
|
import { AuthenticatedImage } from '../../common';
|
||||||
import type { BaseGalleryLayoutProps } from './BaseGalleryLayout';
|
import type { BaseGalleryLayoutProps } from './BaseGalleryLayout';
|
||||||
import type { Photo } from '../../../types';
|
import type { Photo } from '../../../types';
|
||||||
|
import { FeedbackIdentityModal } from '../../gallery/FeedbackIdentityModal';
|
||||||
|
import { feedbackService } from '../../../services/feedback.service';
|
||||||
|
|
||||||
export const TimelineGalleryLayout: React.FC<BaseGalleryLayoutProps> = ({
|
export const TimelineGalleryLayout: React.FC<BaseGalleryLayoutProps> = ({
|
||||||
photos,
|
photos,
|
||||||
|
slug,
|
||||||
onPhotoClick,
|
onPhotoClick,
|
||||||
|
onOpenPhotoWithFeedback,
|
||||||
onDownload,
|
onDownload,
|
||||||
selectedPhotos = new Set(),
|
selectedPhotos = new Set(),
|
||||||
isSelectionMode = false,
|
isSelectionMode = false,
|
||||||
onPhotoSelect,
|
onPhotoSelect,
|
||||||
allowDownloads = true
|
allowDownloads = true,
|
||||||
|
feedbackEnabled = false,
|
||||||
|
feedbackOptions
|
||||||
}) => {
|
}) => {
|
||||||
const { theme } = useTheme();
|
const { theme } = useTheme();
|
||||||
|
const [likedIds, setLikedIds] = useState<Set<number>>(new Set());
|
||||||
|
const [showIdentityModal, setShowIdentityModal] = useState(false);
|
||||||
|
const [pendingAction, setPendingAction] = useState<null | { type: 'like'; photoId: number }>(null);
|
||||||
|
const [savedIdentity, setSavedIdentity] = useState<{ name: string; email: string } | null>(null);
|
||||||
const gallerySettings = theme.gallerySettings || {};
|
const gallerySettings = theme.gallerySettings || {};
|
||||||
const grouping = gallerySettings.timelineGrouping || 'day';
|
const grouping = gallerySettings.timelineGrouping || 'day';
|
||||||
const showDates = gallerySettings.timelineShowDates !== false;
|
const showDates = gallerySettings.timelineShowDates !== false;
|
||||||
|
const canQuickComment = Boolean(feedbackEnabled && feedbackOptions?.allowComments && onOpenPhotoWithFeedback);
|
||||||
|
|
||||||
// Group photos by date
|
// Group photos by date
|
||||||
const groupedPhotos = useMemo(() => {
|
const groupedPhotos = useMemo(() => {
|
||||||
@@ -90,13 +101,7 @@ export const TimelineGalleryLayout: React.FC<BaseGalleryLayoutProps> = ({
|
|||||||
<div
|
<div
|
||||||
key={photo.id}
|
key={photo.id}
|
||||||
className="relative group cursor-pointer aspect-square"
|
className="relative group cursor-pointer aspect-square"
|
||||||
onClick={() => {
|
onClick={() => onPhotoClick(actualIndex)}
|
||||||
if (isSelectionMode && onPhotoSelect) {
|
|
||||||
onPhotoSelect(photo.id);
|
|
||||||
} else {
|
|
||||||
onPhotoClick(actualIndex);
|
|
||||||
}
|
|
||||||
}}
|
|
||||||
>
|
>
|
||||||
<AuthenticatedImage
|
<AuthenticatedImage
|
||||||
src={photo.thumbnail_url || photo.url}
|
src={photo.thumbnail_url || photo.url}
|
||||||
@@ -137,17 +142,70 @@ export const TimelineGalleryLayout: React.FC<BaseGalleryLayoutProps> = ({
|
|||||||
<Download className="w-5 h-5 text-neutral-800" />
|
<Download className="w-5 h-5 text-neutral-800" />
|
||||||
</button>
|
</button>
|
||||||
)}
|
)}
|
||||||
|
{feedbackOptions?.allowLikes && (
|
||||||
|
<button
|
||||||
|
className={`p-2 rounded-full transition-colors ${likedIds.has(photo.id) ? 'bg-red-500/90 hover:bg-red-500' : 'bg-white/90 hover:bg-white'}`}
|
||||||
|
onClick={async (e) => {
|
||||||
|
e.stopPropagation();
|
||||||
|
if (feedbackOptions?.requireNameEmail && !savedIdentity) {
|
||||||
|
setPendingAction({ type: 'like', photoId: photo.id });
|
||||||
|
setShowIdentityModal(true);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
setLikedIds(prev => new Set(prev).add(photo.id));
|
||||||
|
try {
|
||||||
|
await feedbackService.submitFeedback(slug!, String(photo.id), {
|
||||||
|
feedback_type: 'like',
|
||||||
|
guest_name: savedIdentity?.name,
|
||||||
|
guest_email: savedIdentity?.email,
|
||||||
|
});
|
||||||
|
} catch (_) {}
|
||||||
|
}}
|
||||||
|
aria-label="Like photo"
|
||||||
|
aria-pressed={likedIds.has(photo.id)}
|
||||||
|
title="Like"
|
||||||
|
>
|
||||||
|
<Heart className={`w-5 h-5 ${likedIds.has(photo.id) ? 'text-white fill-white' : 'text-neutral-800'}`} />
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
{canQuickComment && (
|
||||||
|
<button
|
||||||
|
className="p-2 bg-white/90 rounded-full hover:bg-white transition-colors"
|
||||||
|
onClick={(e) => { e.stopPropagation(); onOpenPhotoWithFeedback?.(actualIndex); }}
|
||||||
|
aria-label="Comment on photo"
|
||||||
|
title="Comment"
|
||||||
|
>
|
||||||
|
<MessageSquare className="w-5 h-5 text-neutral-800" />
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
</>
|
</>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{isSelectionMode && (
|
{(photo.like_count > 0 || likedIds.has(photo.id)) && (
|
||||||
<div className={`absolute top-2 right-2 ${selectedPhotos.has(photo.id) ? 'opacity-100' : 'opacity-0 group-hover:opacity-100'} transition-opacity`}>
|
<div className={`absolute ${photo.type === 'collage' ? 'bottom-8' : 'bottom-2'} left-2 z-10`}>
|
||||||
<div className={`w-6 h-6 rounded-full border-2 ${selectedPhotos.has(photo.id) ? 'bg-primary-600 border-primary-600' : 'bg-white/80 border-white'} flex items-center justify-center transition-colors`}>
|
<span className="inline-flex items-center justify-center w-6 h-6 rounded-full bg-white/90 backdrop-blur-sm" title="Liked">
|
||||||
{selectedPhotos.has(photo.id) && <Check className="w-4 h-4 text-white" />}
|
<Heart className="w-3.5 h-3.5 text-red-500" fill="currentColor" />
|
||||||
</div>
|
</span>
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
|
{/* Selection Checkbox (visible on hover or when selected) */}
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
aria-label={`Select ${photo.filename}`}
|
||||||
|
role="checkbox"
|
||||||
|
aria-checked={selectedPhotos.has(photo.id)}
|
||||||
|
data-testid={`gallery-photo-checkbox-${photo.id}`}
|
||||||
|
className={`absolute top-2 right-2 z-20 transition-opacity ${
|
||||||
|
selectedPhotos.has(photo.id) ? 'opacity-100' : 'opacity-0 group-hover:opacity-100'
|
||||||
|
}`}
|
||||||
|
onClick={(e) => { e.stopPropagation(); onPhotoSelect && onPhotoSelect(photo.id); }}
|
||||||
|
>
|
||||||
|
<div className={`w-6 h-6 rounded-full border-2 ${selectedPhotos.has(photo.id) ? 'bg-primary-600 border-primary-600' : 'bg-white/90 border-white'} flex items-center justify-center transition-colors`}>
|
||||||
|
{selectedPhotos.has(photo.id) && <Check className="w-4 h-4 text-white" />}
|
||||||
|
</div>
|
||||||
|
</button>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
})}
|
})}
|
||||||
@@ -155,6 +213,23 @@ export const TimelineGalleryLayout: React.FC<BaseGalleryLayoutProps> = ({
|
|||||||
</div>
|
</div>
|
||||||
))}
|
))}
|
||||||
</div>
|
</div>
|
||||||
|
<FeedbackIdentityModal
|
||||||
|
isOpen={showIdentityModal}
|
||||||
|
onClose={() => { setShowIdentityModal(false); setPendingAction(null); }}
|
||||||
|
onSubmit={async (name, email) => {
|
||||||
|
setSavedIdentity({ name, email });
|
||||||
|
setShowIdentityModal(false);
|
||||||
|
if (pendingAction) {
|
||||||
|
await feedbackService.submitFeedback(slug!, String(pendingAction.photoId), {
|
||||||
|
feedback_type: pendingAction.type,
|
||||||
|
guest_name: name,
|
||||||
|
guest_email: email,
|
||||||
|
});
|
||||||
|
setPendingAction(null);
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
feedbackType="like"
|
||||||
|
/>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
+5
-100
@@ -1,9 +1,4 @@
|
|||||||
import axios, { AxiosHeaders } from 'axios';
|
import axios from 'axios';
|
||||||
import Cookies from 'js-cookie';
|
|
||||||
|
|
||||||
// Cookie keys
|
|
||||||
export const ADMIN_TOKEN_KEY = 'admin_token';
|
|
||||||
export const GALLERY_TOKEN_KEY = 'gallery_token';
|
|
||||||
|
|
||||||
// Maintenance mode callback
|
// Maintenance mode callback
|
||||||
let maintenanceModeCallback: ((enabled: boolean) => void) | null = null;
|
let maintenanceModeCallback: ((enabled: boolean) => void) | null = null;
|
||||||
@@ -18,80 +13,12 @@ export const api = axios.create({
|
|||||||
headers: {
|
headers: {
|
||||||
'Content-Type': 'application/json',
|
'Content-Type': 'application/json',
|
||||||
},
|
},
|
||||||
withCredentials: false, // Ensure we're not relying on cookies
|
withCredentials: true,
|
||||||
});
|
});
|
||||||
|
|
||||||
// Request interceptor to add auth token
|
// Request interceptor: drop Content-Type for FormData payloads so the browser can set boundaries
|
||||||
api.interceptors.request.use(
|
api.interceptors.request.use(
|
||||||
(config) => {
|
(config) => {
|
||||||
// Don't process if headers are already set by the component
|
|
||||||
const existingAuth = config.headers?.['Authorization'] || config.headers?.get?.('Authorization');
|
|
||||||
|
|
||||||
// If authorization is already set by the component, don't override it
|
|
||||||
if (existingAuth) {
|
|
||||||
return config;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Check if it's an admin route or gallery route
|
|
||||||
const isAdminRoute = config.url?.includes('/admin');
|
|
||||||
|
|
||||||
if (isAdminRoute) {
|
|
||||||
const token = Cookies.get(ADMIN_TOKEN_KEY);
|
|
||||||
if (token) {
|
|
||||||
if (!config.headers) {
|
|
||||||
config.headers = {};
|
|
||||||
}
|
|
||||||
config.headers['Authorization'] = `Bearer ${token}`;
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
// For gallery routes, try to extract slug from the request URL first
|
|
||||||
const galleryMatch = config.url?.match(/gallery\/([^\/]+)/);
|
|
||||||
|
|
||||||
if (galleryMatch && galleryMatch[1]) {
|
|
||||||
const galleryIdOrSlug = galleryMatch[1];
|
|
||||||
// Remove any query parameters from the slug
|
|
||||||
const cleanIdOrSlug = galleryIdOrSlug.split('?')[0];
|
|
||||||
|
|
||||||
// Check if it's a numeric ID (for upload endpoints)
|
|
||||||
let token = null;
|
|
||||||
if (/^\d+$/.test(cleanIdOrSlug)) {
|
|
||||||
// It's an event ID - try to find the token from current page slug
|
|
||||||
const pathParts = window.location.pathname.split('/');
|
|
||||||
if (pathParts[1] === 'gallery' && pathParts[2]) {
|
|
||||||
const gallerySlug = pathParts[2];
|
|
||||||
const cleanSlug = gallerySlug.split('?')[0];
|
|
||||||
token = localStorage.getItem(`gallery_token_${cleanSlug}`);
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
// It's a slug - use it directly
|
|
||||||
token = localStorage.getItem(`gallery_token_${cleanIdOrSlug}`);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (token) {
|
|
||||||
if (!config.headers) {
|
|
||||||
config.headers = {};
|
|
||||||
}
|
|
||||||
config.headers['Authorization'] = `Bearer ${token}`;
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
// Fallback to getting slug from the current page URL
|
|
||||||
const pathParts = window.location.pathname.split('/');
|
|
||||||
if (pathParts[1] === 'gallery' && pathParts[2]) {
|
|
||||||
const gallerySlug = pathParts[2];
|
|
||||||
// Remove any query parameters from the slug
|
|
||||||
const cleanSlug = gallerySlug.split('?')[0];
|
|
||||||
const token = localStorage.getItem(`gallery_token_${cleanSlug}`);
|
|
||||||
if (token) {
|
|
||||||
if (!config.headers) {
|
|
||||||
config.headers = {};
|
|
||||||
}
|
|
||||||
config.headers['Authorization'] = `Bearer ${token}`;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Don't set Content-Type for FormData - let browser set it with boundary
|
|
||||||
if (config.data instanceof FormData) {
|
if (config.data instanceof FormData) {
|
||||||
delete config.headers?.['Content-Type'];
|
delete config.headers?.['Content-Type'];
|
||||||
}
|
}
|
||||||
@@ -110,10 +37,9 @@ api.interceptors.response.use(
|
|||||||
// Handle maintenance mode (503)
|
// Handle maintenance mode (503)
|
||||||
if (error.response?.status === 503) {
|
if (error.response?.status === 503) {
|
||||||
const isAdminRoute = error.config?.url?.includes('/admin');
|
const isAdminRoute = error.config?.url?.includes('/admin');
|
||||||
const hasAdminAuth = error.config?.headers?.Authorization?.startsWith('Bearer ');
|
|
||||||
|
|
||||||
// Only trigger maintenance mode for non-admin routes or unauthenticated admin routes
|
// Only trigger maintenance mode for non-admin routes or unauthenticated admin routes
|
||||||
if (!isAdminRoute || !hasAdminAuth) {
|
if (!isAdminRoute) {
|
||||||
if (maintenanceModeCallback) {
|
if (maintenanceModeCallback) {
|
||||||
maintenanceModeCallback(true);
|
maintenanceModeCallback(true);
|
||||||
}
|
}
|
||||||
@@ -126,8 +52,6 @@ api.interceptors.response.use(
|
|||||||
const currentPath = window.location.pathname;
|
const currentPath = window.location.pathname;
|
||||||
|
|
||||||
if (isAdminRoute) {
|
if (isAdminRoute) {
|
||||||
// Clear admin token on unauthorized
|
|
||||||
Cookies.remove(ADMIN_TOKEN_KEY);
|
|
||||||
// Only redirect if we're not already on the admin login page
|
// Only redirect if we're not already on the admin login page
|
||||||
if (!currentPath.includes('/admin/login')) {
|
if (!currentPath.includes('/admin/login')) {
|
||||||
window.location.href = '/admin/login';
|
window.location.href = '/admin/login';
|
||||||
@@ -144,8 +68,7 @@ api.interceptors.response.use(
|
|||||||
// Don't clear tokens for image requests - they might just need a retry
|
// Don't clear tokens for image requests - they might just need a retry
|
||||||
if (!isImageRequest && galleryMatch && galleryMatch[1]) {
|
if (!isImageRequest && galleryMatch && galleryMatch[1]) {
|
||||||
const gallerySlug = galleryMatch[1];
|
const gallerySlug = galleryMatch[1];
|
||||||
localStorage.removeItem(`gallery_token_${gallerySlug}`);
|
sessionStorage.removeItem(`gallery_event_${gallerySlug}`);
|
||||||
localStorage.removeItem(`gallery_event_${gallerySlug}`);
|
|
||||||
}
|
}
|
||||||
// Don't redirect - let the component handle the auth state
|
// Don't redirect - let the component handle the auth state
|
||||||
} else if (galleryMatch) {
|
} else if (galleryMatch) {
|
||||||
@@ -159,21 +82,3 @@ api.interceptors.response.use(
|
|||||||
return Promise.reject(error);
|
return Promise.reject(error);
|
||||||
}
|
}
|
||||||
);
|
);
|
||||||
|
|
||||||
// Helper to set auth tokens
|
|
||||||
export const setAuthToken = (token: string, isAdmin: boolean = false) => {
|
|
||||||
const key = isAdmin ? ADMIN_TOKEN_KEY : GALLERY_TOKEN_KEY;
|
|
||||||
Cookies.set(key, token, { expires: 1 }); // 1 day expiry
|
|
||||||
};
|
|
||||||
|
|
||||||
// Helper to clear auth tokens
|
|
||||||
export const clearAuthToken = (isAdmin: boolean = false) => {
|
|
||||||
const key = isAdmin ? ADMIN_TOKEN_KEY : GALLERY_TOKEN_KEY;
|
|
||||||
Cookies.remove(key);
|
|
||||||
};
|
|
||||||
|
|
||||||
// Helper to get auth tokens
|
|
||||||
export const getAuthToken = (isAdmin: boolean = false) => {
|
|
||||||
const key = isAdmin ? ADMIN_TOKEN_KEY : GALLERY_TOKEN_KEY;
|
|
||||||
return Cookies.get(key);
|
|
||||||
};
|
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
import React, { createContext, useContext, useState, useEffect } from 'react';
|
import React, { createContext, useContext, useState, useEffect } from 'react';
|
||||||
import type { ReactNode } from 'react';
|
import type { ReactNode } from 'react';
|
||||||
import { getAuthToken } from '../config/api';
|
import { api } from '../config/api';
|
||||||
import { authService } from '../services';
|
import { authService } from '../services';
|
||||||
import type { AdminUser } from '../types';
|
import type { AdminUser } from '../types';
|
||||||
|
|
||||||
@@ -40,15 +40,31 @@ export const AdminAuthProvider: React.FC<AdminAuthProviderProps> = ({ children }
|
|||||||
// Check if user has a valid token on mount
|
// Check if user has a valid token on mount
|
||||||
const checkAuth = async () => {
|
const checkAuth = async () => {
|
||||||
try {
|
try {
|
||||||
const token = getAuthToken(true);
|
const storedUser = sessionStorage.getItem('admin_user');
|
||||||
if (token) {
|
if (storedUser) {
|
||||||
// For now, just assume the token is valid
|
try {
|
||||||
// TODO: Validate token with backend and get user info
|
setUser(JSON.parse(storedUser));
|
||||||
|
} catch (err) {
|
||||||
|
sessionStorage.removeItem('admin_user');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const response = await api.get<{ valid: boolean; type: string; adminUsername?: string; user?: string }>(
|
||||||
|
'/auth/session'
|
||||||
|
);
|
||||||
|
|
||||||
|
if (response.data?.valid && response.data.type === 'admin') {
|
||||||
setIsAuthenticated(true);
|
setIsAuthenticated(true);
|
||||||
|
} else {
|
||||||
|
sessionStorage.removeItem('admin_user');
|
||||||
|
setIsAuthenticated(false);
|
||||||
|
setUser(null);
|
||||||
}
|
}
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
// Auth check failed - user needs to login
|
// Auth check failed - user needs to login
|
||||||
setError('Failed to check authentication');
|
sessionStorage.removeItem('admin_user');
|
||||||
|
setIsAuthenticated(false);
|
||||||
|
setUser(null);
|
||||||
} finally {
|
} finally {
|
||||||
setIsLoading(false);
|
setIsLoading(false);
|
||||||
}
|
}
|
||||||
@@ -63,9 +79,11 @@ export const AdminAuthProvider: React.FC<AdminAuthProviderProps> = ({ children }
|
|||||||
setError(null);
|
setError(null);
|
||||||
setIsAuthenticated(true);
|
setIsAuthenticated(true);
|
||||||
setMustChangePassword(user.mustChangePassword || false);
|
setMustChangePassword(user.mustChangePassword || false);
|
||||||
|
sessionStorage.setItem('admin_user', JSON.stringify(user));
|
||||||
};
|
};
|
||||||
|
|
||||||
const logout = () => {
|
const logout = () => {
|
||||||
|
sessionStorage.removeItem('admin_user');
|
||||||
authService.adminLogout();
|
authService.adminLogout();
|
||||||
setIsAuthenticated(false);
|
setIsAuthenticated(false);
|
||||||
setUser(null);
|
setUser(null);
|
||||||
@@ -79,6 +97,10 @@ export const AdminAuthProvider: React.FC<AdminAuthProviderProps> = ({ children }
|
|||||||
...user,
|
...user,
|
||||||
mustChangePassword: false
|
mustChangePassword: false
|
||||||
});
|
});
|
||||||
|
sessionStorage.setItem('admin_user', JSON.stringify({
|
||||||
|
...user,
|
||||||
|
mustChangePassword: false
|
||||||
|
}));
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
import React, { createContext, useContext, useState, useEffect } from 'react';
|
import React, { createContext, useContext, useState, useEffect } from 'react';
|
||||||
import type { ReactNode } from 'react';
|
import type { ReactNode } from 'react';
|
||||||
import { authService } from '../services';
|
import { api } from '../config/api';
|
||||||
|
import { authService, galleryService } from '../services';
|
||||||
import { cleanupOldGalleryAuth } from '../utils/cleanupGalleryAuth';
|
import { cleanupOldGalleryAuth } from '../utils/cleanupGalleryAuth';
|
||||||
|
|
||||||
interface GalleryEvent {
|
interface GalleryEvent {
|
||||||
@@ -52,36 +53,81 @@ export const GalleryAuthProvider: React.FC<GalleryAuthProviderProps> = ({ childr
|
|||||||
};
|
};
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
// Clean up old authentication data on mount
|
|
||||||
cleanupOldGalleryAuth();
|
cleanupOldGalleryAuth();
|
||||||
|
|
||||||
// Check if user has a valid token on mount
|
const initialise = async () => {
|
||||||
const currentSlug = getCurrentGallerySlug();
|
const currentSlug = getCurrentGallerySlug();
|
||||||
if (currentSlug) {
|
|
||||||
// Try to restore event data from localStorage with slug-specific key
|
|
||||||
const storedEvent = localStorage.getItem(`gallery_event_${currentSlug}`);
|
|
||||||
const storedToken = localStorage.getItem(`gallery_token_${currentSlug}`);
|
|
||||||
|
|
||||||
if (storedEvent && storedToken) {
|
if (!currentSlug) {
|
||||||
|
setIsLoading(false);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const storedEvent = sessionStorage.getItem(`gallery_event_${currentSlug}`);
|
||||||
|
if (storedEvent) {
|
||||||
try {
|
try {
|
||||||
const eventData = JSON.parse(storedEvent);
|
const parsed = JSON.parse(storedEvent);
|
||||||
// Verify the stored event matches the current gallery slug
|
if (parsed && parsed.id) {
|
||||||
if (eventData && eventData.id) {
|
setEvent(parsed);
|
||||||
setEvent(eventData);
|
|
||||||
setIsAuthenticated(true);
|
|
||||||
} else {
|
|
||||||
// Clear invalid data
|
|
||||||
localStorage.removeItem(`gallery_event_${currentSlug}`);
|
|
||||||
localStorage.removeItem(`gallery_token_${currentSlug}`);
|
|
||||||
}
|
}
|
||||||
} catch (error) {
|
} catch (err) {
|
||||||
// Invalid stored data - clear it
|
sessionStorage.removeItem(`gallery_event_${currentSlug}`);
|
||||||
localStorage.removeItem(`gallery_event_${currentSlug}`);
|
|
||||||
localStorage.removeItem(`gallery_token_${currentSlug}`);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
|
||||||
setIsLoading(false);
|
try {
|
||||||
|
setIsLoading(true);
|
||||||
|
const sessionResponse = await api.get<{ valid: boolean; type: string; eventSlug?: string }>(
|
||||||
|
'/auth/session',
|
||||||
|
{ params: { slug: currentSlug } }
|
||||||
|
);
|
||||||
|
|
||||||
|
if (sessionResponse.data?.valid && sessionResponse.data.type === 'gallery' && sessionResponse.data.eventSlug === currentSlug) {
|
||||||
|
setIsAuthenticated(true);
|
||||||
|
|
||||||
|
if (!storedEvent) {
|
||||||
|
// Fetch gallery details to hydrate context
|
||||||
|
const galleryData = await galleryService.getGalleryPhotos(currentSlug);
|
||||||
|
if (galleryData?.event) {
|
||||||
|
setEvent(galleryData.event);
|
||||||
|
sessionStorage.setItem(`gallery_event_${currentSlug}`, JSON.stringify(galleryData.event));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// If no active session, check for share token in URL
|
||||||
|
const parts = window.location.pathname.split('/');
|
||||||
|
const urlToken = parts.length >= 5 ? parts[4] : (parts.length >= 4 ? parts[3] : undefined);
|
||||||
|
|
||||||
|
if (urlToken) {
|
||||||
|
const verify = await galleryService.verifyToken(currentSlug, urlToken);
|
||||||
|
if (verify?.valid) {
|
||||||
|
const response = await authService.shareLinkLogin(currentSlug, urlToken);
|
||||||
|
if (response?.event) {
|
||||||
|
setEvent(response.event);
|
||||||
|
setIsAuthenticated(true);
|
||||||
|
sessionStorage.setItem(`gallery_event_${currentSlug}`, JSON.stringify(response.event));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// No valid session found
|
||||||
|
setIsAuthenticated(false);
|
||||||
|
sessionStorage.removeItem(`gallery_event_${currentSlug}`);
|
||||||
|
setEvent(null);
|
||||||
|
} catch (error) {
|
||||||
|
setIsAuthenticated(false);
|
||||||
|
sessionStorage.removeItem(`gallery_event_${currentSlug}`);
|
||||||
|
setEvent(null);
|
||||||
|
} finally {
|
||||||
|
setIsLoading(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
initialise();
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
const login = async (slug: string, password: string, recaptchaToken?: string | null) => {
|
const login = async (slug: string, password: string, recaptchaToken?: string | null) => {
|
||||||
@@ -92,9 +138,8 @@ export const GalleryAuthProvider: React.FC<GalleryAuthProviderProps> = ({ childr
|
|||||||
setEvent(response.event);
|
setEvent(response.event);
|
||||||
setIsAuthenticated(true);
|
setIsAuthenticated(true);
|
||||||
|
|
||||||
// Store event data and token in localStorage with slug-specific key
|
// Store event data for quick reloads (non-sensitive)
|
||||||
localStorage.setItem(`gallery_event_${slug}`, JSON.stringify(response.event));
|
sessionStorage.setItem(`gallery_event_${slug}`, JSON.stringify(response.event));
|
||||||
localStorage.setItem(`gallery_token_${slug}`, response.token);
|
|
||||||
} catch (err: any) {
|
} catch (err: any) {
|
||||||
setError(err.response?.data?.error || 'Invalid password');
|
setError(err.response?.data?.error || 'Invalid password');
|
||||||
throw err;
|
throw err;
|
||||||
@@ -106,13 +151,13 @@ export const GalleryAuthProvider: React.FC<GalleryAuthProviderProps> = ({ childr
|
|||||||
const logout = () => {
|
const logout = () => {
|
||||||
const currentSlug = getCurrentGallerySlug();
|
const currentSlug = getCurrentGallerySlug();
|
||||||
if (currentSlug) {
|
if (currentSlug) {
|
||||||
localStorage.removeItem(`gallery_event_${currentSlug}`);
|
sessionStorage.removeItem(`gallery_event_${currentSlug}`);
|
||||||
localStorage.removeItem(`gallery_token_${currentSlug}`);
|
|
||||||
}
|
}
|
||||||
authService.galleryLogout();
|
authService.galleryLogout(currentSlug || undefined);
|
||||||
setIsAuthenticated(false);
|
setIsAuthenticated(false);
|
||||||
setEvent(null);
|
setEvent(null);
|
||||||
};
|
}
|
||||||
|
;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<GalleryAuthContext.Provider
|
<GalleryAuthContext.Provider
|
||||||
|
|||||||
@@ -11,9 +11,15 @@ export const useGalleryInfo = (slug: string, token?: string) => {
|
|||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
export const useGalleryPhotos = (slug: string, filter?: 'liked' | 'favorited' | 'all', guestId?: string, enabled: boolean = true) => {
|
export const useGalleryPhotos = (
|
||||||
|
slug: string,
|
||||||
|
filter?: 'liked' | 'commented' | 'rated' | 'all',
|
||||||
|
guestId?: string,
|
||||||
|
enabled: boolean = true
|
||||||
|
) => {
|
||||||
return useQuery({
|
return useQuery({
|
||||||
queryKey: ['gallery-photos', slug, filter, guestId],
|
queryKey: ['gallery-photos', slug, filter, guestId],
|
||||||
|
// Pass guestId so backend can filter per-guest views when needed
|
||||||
queryFn: () => galleryService.getGalleryPhotos(slug, filter, guestId),
|
queryFn: () => galleryService.getGalleryPhotos(slug, filter, guestId),
|
||||||
enabled,
|
enabled,
|
||||||
retry: 1,
|
retry: 1,
|
||||||
|
|||||||
@@ -1079,6 +1079,24 @@
|
|||||||
"bulk_download": "{{count}} Fotos heruntergeladen von {{eventName}}",
|
"bulk_download": "{{count}} Fotos heruntergeladen von {{eventName}}",
|
||||||
"gallery_password_entry": "Passwort eingegeben für {{eventName}}",
|
"gallery_password_entry": "Passwort eingegeben für {{eventName}}",
|
||||||
"expiration_warning_viewed": "Ablaufwarnung angesehen für {{eventName}}",
|
"expiration_warning_viewed": "Ablaufwarnung angesehen für {{eventName}}",
|
||||||
|
"feedback_settings_updated": "Feedback-Einstellungen aktualisiert",
|
||||||
|
"feedback_moderated": "Feedback moderiert",
|
||||||
|
"feedback_deleted": "Feedback gelöscht",
|
||||||
|
"photo_like": "Foto mit Gefällt mir markiert in {{eventName}}",
|
||||||
|
"photo_favorite": "Foto favorisiert in {{eventName}}",
|
||||||
|
"photo_rating": "Foto bewertet in {{eventName}}",
|
||||||
|
"photo_comment": "Foto kommentiert in {{eventName}}",
|
||||||
|
"guest_feedback_like": "Gast hat ein Foto mit Gefällt mir markiert in {{eventName}}",
|
||||||
|
"guest_feedback_favorite": "Gast hat ein Foto favorisiert in {{eventName}}",
|
||||||
|
"guest_feedback_rating": "Gast hat ein Foto bewertet in {{eventName}}",
|
||||||
|
"guest_feedback_comment": "Gast hat ein Foto kommentiert in {{eventName}}",
|
||||||
|
"word_filter_added": "Wortfilter hinzugefügt",
|
||||||
|
"external_import_completed": "Externer Medienimport abgeschlossen ({{imported}} importiert, {{skipped}} übersprungen)",
|
||||||
|
"bulk_archive_completed": "Sammelarchivierung abgeschlossen",
|
||||||
|
"event_activated": "Veranstaltung aktiviert: {{eventName}}",
|
||||||
|
"event_deactivated": "Veranstaltung deaktiviert: {{eventName}}",
|
||||||
|
"photo_deleted": "Foto gelöscht aus {{eventName}}",
|
||||||
|
"photos_bulk_deleted": "{{count}} Fotos gelöscht aus {{eventName}}",
|
||||||
"settings_updated": "Einstellungen aktualisiert",
|
"settings_updated": "Einstellungen aktualisiert",
|
||||||
"event_updated": "Veranstaltung aktualisiert: {{eventName}}",
|
"event_updated": "Veranstaltung aktualisiert: {{eventName}}",
|
||||||
"event_deleted": "Veranstaltung gelöscht: {{eventName}}",
|
"event_deleted": "Veranstaltung gelöscht: {{eventName}}",
|
||||||
|
|||||||
@@ -821,6 +821,24 @@
|
|||||||
"bulk_download": "{{count}} photos downloaded from {{eventName}}",
|
"bulk_download": "{{count}} photos downloaded from {{eventName}}",
|
||||||
"gallery_password_entry": "Password entered for {{eventName}}",
|
"gallery_password_entry": "Password entered for {{eventName}}",
|
||||||
"expiration_warning_viewed": "Expiration warning viewed for {{eventName}}",
|
"expiration_warning_viewed": "Expiration warning viewed for {{eventName}}",
|
||||||
|
"feedback_settings_updated": "Feedback settings updated",
|
||||||
|
"feedback_moderated": "Feedback moderated",
|
||||||
|
"feedback_deleted": "Feedback deleted",
|
||||||
|
"photo_like": "Photo liked in {{eventName}}",
|
||||||
|
"photo_favorite": "Photo favorited in {{eventName}}",
|
||||||
|
"photo_rating": "Photo rated in {{eventName}}",
|
||||||
|
"photo_comment": "Photo commented in {{eventName}}",
|
||||||
|
"guest_feedback_like": "Guest liked a photo in {{eventName}}",
|
||||||
|
"guest_feedback_favorite": "Guest favorited a photo in {{eventName}}",
|
||||||
|
"guest_feedback_rating": "Guest rated a photo in {{eventName}}",
|
||||||
|
"guest_feedback_comment": "Guest commented on a photo in {{eventName}}",
|
||||||
|
"word_filter_added": "Word filter added",
|
||||||
|
"external_import_completed": "External media import completed ({{imported}} imported, {{skipped}} skipped)",
|
||||||
|
"bulk_archive_completed": "Bulk archive completed",
|
||||||
|
"event_activated": "Event activated: {{eventName}}",
|
||||||
|
"event_deactivated": "Event deactivated: {{eventName}}",
|
||||||
|
"photo_deleted": "Photo deleted from {{eventName}}",
|
||||||
|
"photos_bulk_deleted": "{{count}} photos deleted from {{eventName}}",
|
||||||
"settings_updated": "Settings updated",
|
"settings_updated": "Settings updated",
|
||||||
"event_updated": "Event updated: {{eventName}}",
|
"event_updated": "Event updated: {{eventName}}",
|
||||||
"event_deleted": "Event deleted: {{eventName}}",
|
"event_deleted": "Event deleted: {{eventName}}",
|
||||||
|
|||||||
@@ -268,13 +268,13 @@ export const AdminDashboard: React.FC = () => {
|
|||||||
categoryName: activity.metadata?.category_name || ''
|
categoryName: activity.metadata?.category_name || ''
|
||||||
};
|
};
|
||||||
|
|
||||||
// Check if translation exists
|
// Translate; if key missing i18n returns the key string itself
|
||||||
const translated = t(translationKey, params);
|
const translated = t(translationKey, params) as string;
|
||||||
if (typeof translated === 'string') {
|
if (!translated || translated === translationKey) {
|
||||||
return translated;
|
// Fallback: format a readable English message
|
||||||
|
return adminService.formatActivityMessage(activity);
|
||||||
}
|
}
|
||||||
// Fallback to unknown activity if translation not found
|
return translated;
|
||||||
return t('admin.activities.unknown') as string;
|
|
||||||
};
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
|
|||||||
@@ -8,7 +8,7 @@ import { useTranslation } from 'react-i18next';
|
|||||||
import { Button, Input, Card, ReCaptcha } from '../../components/common';
|
import { Button, Input, Card, ReCaptcha } from '../../components/common';
|
||||||
import { useAdminAuth } from '../../contexts';
|
import { useAdminAuth } from '../../contexts';
|
||||||
import { authService } from '../../services/auth.service';
|
import { authService } from '../../services/auth.service';
|
||||||
import { getAuthToken, api } from '../../config/api';
|
import { api } from '../../config/api';
|
||||||
|
|
||||||
export const AdminLoginPage: React.FC = () => {
|
export const AdminLoginPage: React.FC = () => {
|
||||||
const { t } = useTranslation();
|
const { t } = useTranslation();
|
||||||
@@ -84,17 +84,20 @@ export const AdminLoginPage: React.FC = () => {
|
|||||||
login(response.token, response.user);
|
login(response.token, response.user);
|
||||||
toast.success(t('adminLogin.loginSuccess'));
|
toast.success(t('adminLogin.loginSuccess'));
|
||||||
setLoginSuccess(true);
|
setLoginSuccess(true);
|
||||||
} catch (error: any) {
|
} catch (error: any) {
|
||||||
// Login error handled by UI notification
|
// Login error handled by UI notification
|
||||||
|
|
||||||
// Handle network errors gracefully
|
// Handle network errors gracefully
|
||||||
if (error.code === 'ERR_NETWORK' || error.code === 'ERR_CONNECTION_RESET') {
|
if (error.code === 'ERR_NETWORK' || error.code === 'ERR_CONNECTION_RESET') {
|
||||||
// Check if we actually got logged in despite the error
|
// Check if we actually got logged in despite the error
|
||||||
const token = getAuthToken(true);
|
try {
|
||||||
if (token) {
|
const sessionResponse = await api.get<{ valid: boolean; type: string }>('/auth/session');
|
||||||
// Login was successful, just had a connection issue
|
if (sessionResponse.data?.valid && sessionResponse.data.type === 'admin') {
|
||||||
setLoginSuccess(true);
|
setLoginSuccess(true);
|
||||||
return;
|
return;
|
||||||
|
}
|
||||||
|
} catch (sessionError) {
|
||||||
|
// Ignore secondary failure, we'll surface the original network error
|
||||||
}
|
}
|
||||||
toast.error(t('adminLogin.networkError'));
|
toast.error(t('adminLogin.networkError'));
|
||||||
} else if (error.response?.status === 429) {
|
} else if (error.response?.status === 429) {
|
||||||
|
|||||||
@@ -17,7 +17,7 @@ import {
|
|||||||
Trash2
|
Trash2
|
||||||
} from 'lucide-react';
|
} from 'lucide-react';
|
||||||
import { toast } from 'react-toastify';
|
import { toast } from 'react-toastify';
|
||||||
import { format } from 'date-fns';
|
import { format, parseISO } from 'date-fns';
|
||||||
|
|
||||||
import { Button, Card, Loading } from '../../components/common';
|
import { Button, Card, Loading } from '../../components/common';
|
||||||
import { AdminAuthenticatedImage } from '../../components/admin/AdminAuthenticatedImage';
|
import { AdminAuthenticatedImage } from '../../components/admin/AdminAuthenticatedImage';
|
||||||
@@ -254,7 +254,7 @@ export const EventFeedbackPage: React.FC = () => {
|
|||||||
{item.photo_id && (
|
{item.photo_id && (
|
||||||
<div className="w-16 h-16 overflow-hidden rounded">
|
<div className="w-16 h-16 overflow-hidden rounded">
|
||||||
<AdminAuthenticatedImage
|
<AdminAuthenticatedImage
|
||||||
src={`/api/admin/photos/${eventId}/thumbnail/${item.photo_id}`}
|
src={`/admin/photos/${id}/thumbnail/${item.photo_id}`}
|
||||||
alt={item.filename || 'Photo'}
|
alt={item.filename || 'Photo'}
|
||||||
className="w-16 h-16 object-cover rounded"
|
className="w-16 h-16 object-cover rounded"
|
||||||
/>
|
/>
|
||||||
@@ -290,7 +290,12 @@ export const EventFeedbackPage: React.FC = () => {
|
|||||||
<p className="text-sm text-neutral-700">{item.comment_text}</p>
|
<p className="text-sm text-neutral-700">{item.comment_text}</p>
|
||||||
)}
|
)}
|
||||||
<p className="text-xs text-neutral-500 mt-1">
|
<p className="text-xs text-neutral-500 mt-1">
|
||||||
{format(new Date(item.created_at), 'PPpp')}
|
{(() => {
|
||||||
|
const d = typeof item.created_at === 'string'
|
||||||
|
? parseISO(item.created_at)
|
||||||
|
: new Date(item.created_at);
|
||||||
|
return isNaN(d.getTime()) ? t('common.unknownDate', 'Unknown date') : format(d, 'PPpp');
|
||||||
|
})()}
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
<div className="flex items-center gap-2">
|
<div className="flex items-center gap-2">
|
||||||
@@ -492,7 +497,12 @@ export const EventFeedbackPage: React.FC = () => {
|
|||||||
<p className="text-sm text-neutral-700">{comment.comment_text}</p>
|
<p className="text-sm text-neutral-700">{comment.comment_text}</p>
|
||||||
<p className="text-xs text-neutral-500 mt-1">
|
<p className="text-xs text-neutral-500 mt-1">
|
||||||
{comment.guest_name} • {comment.filename} •
|
{comment.guest_name} • {comment.filename} •
|
||||||
{format(new Date(comment.created_at), 'PP')}
|
{(() => {
|
||||||
|
const d = typeof comment.created_at === 'string'
|
||||||
|
? parseISO(comment.created_at)
|
||||||
|
: new Date(comment.created_at);
|
||||||
|
return isNaN(d.getTime()) ? t('common.unknownDate', 'Unknown date') : format(d, 'PP');
|
||||||
|
})()}
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
))}
|
))}
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import { api, setAuthToken, clearAuthToken } from '../config/api';
|
import { api } from '../config/api';
|
||||||
import type { LoginResponse, GalleryAuthResponse } from '../types';
|
import type { LoginResponse, GalleryAuthResponse } from '../types';
|
||||||
|
|
||||||
export const authService = {
|
export const authService = {
|
||||||
@@ -10,14 +10,17 @@ export const authService = {
|
|||||||
password: credentials.password,
|
password: credentials.password,
|
||||||
recaptchaToken: credentials.recaptchaToken
|
recaptchaToken: credentials.recaptchaToken
|
||||||
});
|
});
|
||||||
|
|
||||||
setAuthToken(response.data.token, true);
|
|
||||||
return response.data;
|
return response.data;
|
||||||
},
|
},
|
||||||
|
|
||||||
adminLogout() {
|
async adminLogout() {
|
||||||
clearAuthToken(true);
|
try {
|
||||||
window.location.href = '/admin/login';
|
await api.post('/auth/logout');
|
||||||
|
} catch (err) {
|
||||||
|
// Ignore logout errors; fallback to redirect
|
||||||
|
} finally {
|
||||||
|
window.location.href = '/admin/login';
|
||||||
|
}
|
||||||
},
|
},
|
||||||
|
|
||||||
// Gallery authentication
|
// Gallery authentication
|
||||||
@@ -32,7 +35,19 @@ export const authService = {
|
|||||||
return response.data;
|
return response.data;
|
||||||
},
|
},
|
||||||
|
|
||||||
galleryLogout() {
|
async shareLinkLogin(slug: string, token: string): Promise<GalleryAuthResponse> {
|
||||||
// Logout is now handled by GalleryAuthContext
|
const response = await api.post<GalleryAuthResponse>('/auth/gallery/share-login', {
|
||||||
|
slug,
|
||||||
|
token,
|
||||||
|
});
|
||||||
|
return response.data;
|
||||||
|
},
|
||||||
|
|
||||||
|
async galleryLogout(slug?: string | null) {
|
||||||
|
try {
|
||||||
|
await api.post('/auth/gallery/logout', { slug });
|
||||||
|
} catch (err) {
|
||||||
|
// Ignore; cookie will naturally expire if removal fails
|
||||||
|
}
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
@@ -16,7 +16,11 @@ export const galleryService = {
|
|||||||
},
|
},
|
||||||
|
|
||||||
// Get gallery photos (requires auth)
|
// Get gallery photos (requires auth)
|
||||||
async getGalleryPhotos(slug: string, filter?: 'liked' | 'favorited' | 'all', guestId?: string): Promise<GalleryData> {
|
async getGalleryPhotos(
|
||||||
|
slug: string,
|
||||||
|
filter?: 'liked' | 'commented' | 'rated' | 'all',
|
||||||
|
guestId?: string
|
||||||
|
): Promise<GalleryData> {
|
||||||
const params: any = {};
|
const params: any = {};
|
||||||
if (filter && filter !== 'all' && guestId) {
|
if (filter && filter !== 'all' && guestId) {
|
||||||
params.filter = filter;
|
params.filter = filter;
|
||||||
@@ -28,19 +32,36 @@ export const galleryService = {
|
|||||||
|
|
||||||
// Download single photo
|
// Download single photo
|
||||||
async downloadPhoto(slug: string, photoId: number, filename: string): Promise<void> {
|
async downloadPhoto(slug: string, photoId: number, filename: string): Promise<void> {
|
||||||
const response = await api.get(`/gallery/${slug}/download/${photoId}`, {
|
try {
|
||||||
responseType: 'blob',
|
const response = await api.get(`/gallery/${slug}/download/${photoId}`, {
|
||||||
});
|
responseType: 'blob',
|
||||||
|
});
|
||||||
// Create download link
|
const url = window.URL.createObjectURL(new Blob([response.data]));
|
||||||
const url = window.URL.createObjectURL(new Blob([response.data]));
|
const link = document.createElement('a');
|
||||||
const link = document.createElement('a');
|
link.href = url;
|
||||||
link.href = url;
|
link.setAttribute('download', filename);
|
||||||
link.setAttribute('download', filename);
|
document.body.appendChild(link);
|
||||||
document.body.appendChild(link);
|
link.click();
|
||||||
link.click();
|
link.remove();
|
||||||
link.remove();
|
window.URL.revokeObjectURL(url);
|
||||||
window.URL.revokeObjectURL(url);
|
} catch (err) {
|
||||||
|
// Fallback: use the view endpoint if direct download fails (e.g., missing original)
|
||||||
|
try {
|
||||||
|
const response = await api.get(`/gallery/${slug}/photo/${photoId}`, {
|
||||||
|
responseType: 'blob',
|
||||||
|
});
|
||||||
|
const url = window.URL.createObjectURL(new Blob([response.data]));
|
||||||
|
const link = document.createElement('a');
|
||||||
|
link.href = url;
|
||||||
|
link.setAttribute('download', filename);
|
||||||
|
document.body.appendChild(link);
|
||||||
|
link.click();
|
||||||
|
link.remove();
|
||||||
|
window.URL.revokeObjectURL(url);
|
||||||
|
} catch (fallbackErr) {
|
||||||
|
throw fallbackErr;
|
||||||
|
}
|
||||||
|
}
|
||||||
},
|
},
|
||||||
|
|
||||||
// Download all photos as ZIP
|
// Download all photos as ZIP
|
||||||
@@ -60,6 +81,22 @@ export const galleryService = {
|
|||||||
window.URL.revokeObjectURL(url);
|
window.URL.revokeObjectURL(url);
|
||||||
},
|
},
|
||||||
|
|
||||||
|
// Download selected photos as ZIP
|
||||||
|
async downloadSelectedPhotos(slug: string, photoIds: number[]): Promise<void> {
|
||||||
|
const response = await api.post(`/gallery/${slug}/download-selected`, { photo_ids: photoIds }, {
|
||||||
|
responseType: 'blob',
|
||||||
|
});
|
||||||
|
|
||||||
|
const url = window.URL.createObjectURL(new Blob([response.data]));
|
||||||
|
const link = document.createElement('a');
|
||||||
|
link.href = url;
|
||||||
|
link.setAttribute('download', `${slug}-selected.zip`);
|
||||||
|
document.body.appendChild(link);
|
||||||
|
link.click();
|
||||||
|
link.remove();
|
||||||
|
window.URL.revokeObjectURL(url);
|
||||||
|
},
|
||||||
|
|
||||||
// Get gallery statistics
|
// Get gallery statistics
|
||||||
async getGalleryStats(slug: string): Promise<GalleryStats> {
|
async getGalleryStats(slug: string): Promise<GalleryStats> {
|
||||||
const response = await api.get<GalleryStats>(`/gallery/${slug}/stats`);
|
const response = await api.get<GalleryStats>(`/gallery/${slug}/stats`);
|
||||||
|
|||||||
@@ -49,21 +49,10 @@ class SecureTokenService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
// Get the gallery token from localStorage
|
// Generate new token from backend – authentication handled via cookies
|
||||||
const galleryToken = localStorage.getItem(`gallery_token_${slug}`);
|
|
||||||
if (!galleryToken) {
|
|
||||||
throw new Error('No gallery authentication token found');
|
|
||||||
}
|
|
||||||
|
|
||||||
// Generate new token from backend with explicit auth header
|
|
||||||
const response = await api.post<SecureToken>(
|
const response = await api.post<SecureToken>(
|
||||||
`/secure-images/${slug}/generate-token`,
|
`/secure-images/${slug}/generate-token`,
|
||||||
{ photoId, accessType },
|
{ photoId, accessType }
|
||||||
{
|
|
||||||
headers: {
|
|
||||||
'Authorization': `Bearer ${galleryToken}`
|
|
||||||
}
|
|
||||||
}
|
|
||||||
);
|
);
|
||||||
|
|
||||||
const tokenData: SecureToken = {
|
const tokenData: SecureToken = {
|
||||||
|
|||||||
@@ -9,18 +9,12 @@ export const cleanupOldGalleryAuth = () => {
|
|||||||
for (let i = 0; i < localStorage.length; i++) {
|
for (let i = 0; i < localStorage.length; i++) {
|
||||||
const key = localStorage.key(i);
|
const key = localStorage.key(i);
|
||||||
if (key && (key.startsWith('gallery_token') || key.startsWith('gallery_event'))) {
|
if (key && (key.startsWith('gallery_token') || key.startsWith('gallery_event'))) {
|
||||||
// Check if it's an old format token that might be corrupted
|
keysToRemove.push(key);
|
||||||
const value = localStorage.getItem(key);
|
|
||||||
if (value && (value.length < 100 || !value.includes('.'))) {
|
|
||||||
// Token is too short or doesn't contain dots (not a valid JWT)
|
|
||||||
keysToRemove.push(key);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
keysToRemove.forEach(key => {
|
keysToRemove.forEach(key => {
|
||||||
localStorage.removeItem(key);
|
localStorage.removeItem(key);
|
||||||
// Silently remove corrupted tokens
|
|
||||||
});
|
});
|
||||||
|
|
||||||
// Remove old gallery token from cookies if it exists
|
// Remove old gallery token from cookies if it exists
|
||||||
|
|||||||
Generated
+64
@@ -10,6 +10,7 @@
|
|||||||
"node-fetch": "^2.7.0"
|
"node-fetch": "^2.7.0"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
|
"@playwright/test": "^1.48.2",
|
||||||
"puppeteer": "^24.17.0"
|
"puppeteer": "^24.17.0"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
@@ -38,6 +39,22 @@
|
|||||||
"node": ">=6.9.0"
|
"node": ">=6.9.0"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/@playwright/test": {
|
||||||
|
"version": "1.55.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/@playwright/test/-/test-1.55.0.tgz",
|
||||||
|
"integrity": "sha512-04IXzPwHrW69XusN/SIdDdKZBzMfOT9UNT/YiJit/xpy2VuAoB8NHc8Aplb96zsWDddLnbkPL3TsmrS04ZU2xQ==",
|
||||||
|
"dev": true,
|
||||||
|
"license": "Apache-2.0",
|
||||||
|
"dependencies": {
|
||||||
|
"playwright": "1.55.0"
|
||||||
|
},
|
||||||
|
"bin": {
|
||||||
|
"playwright": "cli.js"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">=18"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/@puppeteer/browsers": {
|
"node_modules/@puppeteer/browsers": {
|
||||||
"version": "2.10.7",
|
"version": "2.10.7",
|
||||||
"resolved": "https://registry.npmjs.org/@puppeteer/browsers/-/browsers-2.10.7.tgz",
|
"resolved": "https://registry.npmjs.org/@puppeteer/browsers/-/browsers-2.10.7.tgz",
|
||||||
@@ -704,6 +721,21 @@
|
|||||||
"integrity": "sha512-y6OAwoSIf7FyjMIv94u+b5rdheZEjzR63GTyZJm5qh4Bi+2YgwLCcI/fPFZkL5PSixOt6ZNKm+w+Hfp/Bciwow==",
|
"integrity": "sha512-y6OAwoSIf7FyjMIv94u+b5rdheZEjzR63GTyZJm5qh4Bi+2YgwLCcI/fPFZkL5PSixOt6ZNKm+w+Hfp/Bciwow==",
|
||||||
"license": "MIT"
|
"license": "MIT"
|
||||||
},
|
},
|
||||||
|
"node_modules/fsevents": {
|
||||||
|
"version": "2.3.2",
|
||||||
|
"resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.2.tgz",
|
||||||
|
"integrity": "sha512-xiqMQR4xAeHTuB9uWm+fFRcIOgKBMiOBP+eXiyT7jsgVCq1bkVygt00oASowB7EdtpOHaaPgKt812P9ab+DDKA==",
|
||||||
|
"dev": true,
|
||||||
|
"hasInstallScript": true,
|
||||||
|
"license": "MIT",
|
||||||
|
"optional": true,
|
||||||
|
"os": [
|
||||||
|
"darwin"
|
||||||
|
],
|
||||||
|
"engines": {
|
||||||
|
"node": "^8.16.0 || ^10.6.0 || >=11.0.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/get-caller-file": {
|
"node_modules/get-caller-file": {
|
||||||
"version": "2.0.5",
|
"version": "2.0.5",
|
||||||
"resolved": "https://registry.npmjs.org/get-caller-file/-/get-caller-file-2.0.5.tgz",
|
"resolved": "https://registry.npmjs.org/get-caller-file/-/get-caller-file-2.0.5.tgz",
|
||||||
@@ -1083,6 +1115,38 @@
|
|||||||
"dev": true,
|
"dev": true,
|
||||||
"license": "ISC"
|
"license": "ISC"
|
||||||
},
|
},
|
||||||
|
"node_modules/playwright": {
|
||||||
|
"version": "1.55.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/playwright/-/playwright-1.55.0.tgz",
|
||||||
|
"integrity": "sha512-sdCWStblvV1YU909Xqx0DhOjPZE4/5lJsIS84IfN9dAZfcl/CIZ5O8l3o0j7hPMjDvqoTF8ZUcc+i/GL5erstA==",
|
||||||
|
"dev": true,
|
||||||
|
"license": "Apache-2.0",
|
||||||
|
"dependencies": {
|
||||||
|
"playwright-core": "1.55.0"
|
||||||
|
},
|
||||||
|
"bin": {
|
||||||
|
"playwright": "cli.js"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">=18"
|
||||||
|
},
|
||||||
|
"optionalDependencies": {
|
||||||
|
"fsevents": "2.3.2"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/playwright-core": {
|
||||||
|
"version": "1.55.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.55.0.tgz",
|
||||||
|
"integrity": "sha512-GvZs4vU3U5ro2nZpeiwyb0zuFaqb9sUiAJuyrWpcGouD8y9/HLgGbNRjIph7zU9D3hnPaisMl9zG9CgFi/biIg==",
|
||||||
|
"dev": true,
|
||||||
|
"license": "Apache-2.0",
|
||||||
|
"bin": {
|
||||||
|
"playwright-core": "cli.js"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">=18"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/prebuild-install": {
|
"node_modules/prebuild-install": {
|
||||||
"version": "7.1.3",
|
"version": "7.1.3",
|
||||||
"resolved": "https://registry.npmjs.org/prebuild-install/-/prebuild-install-7.1.3.tgz",
|
"resolved": "https://registry.npmjs.org/prebuild-install/-/prebuild-install-7.1.3.tgz",
|
||||||
|
|||||||
+5
-1
@@ -1,10 +1,14 @@
|
|||||||
{
|
{
|
||||||
|
"scripts": {
|
||||||
|
"test:e2e": "playwright test"
|
||||||
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"better-sqlite3": "^12.2.0",
|
"better-sqlite3": "^12.2.0",
|
||||||
"canvas": "^3.2.0",
|
"canvas": "^3.2.0",
|
||||||
"node-fetch": "^2.7.0"
|
"node-fetch": "^2.7.0"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"puppeteer": "^24.17.0"
|
"puppeteer": "^24.17.0",
|
||||||
|
"@playwright/test": "^1.48.2"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,18 @@
|
|||||||
|
import { defineConfig, devices } from '@playwright/test';
|
||||||
|
|
||||||
|
export default defineConfig({
|
||||||
|
testDir: 'tests/e2e',
|
||||||
|
timeout: 60_000,
|
||||||
|
retries: 0,
|
||||||
|
use: {
|
||||||
|
baseURL: 'http://localhost:3000',
|
||||||
|
headless: true,
|
||||||
|
viewport: { width: 1280, height: 800 },
|
||||||
|
ignoreHTTPSErrors: true,
|
||||||
|
},
|
||||||
|
projects: [
|
||||||
|
{ name: 'chromium', use: { ...devices['Desktop Chrome'] } },
|
||||||
|
{ name: 'mobile-chrome', use: { ...devices['Pixel 5'] } },
|
||||||
|
],
|
||||||
|
});
|
||||||
|
|
||||||
Binary file not shown.
|
After Width: | Height: | Size: 212 B |
Binary file not shown.
|
After Width: | Height: | Size: 212 B |
@@ -0,0 +1,43 @@
|
|||||||
|
import { test, expect } from '@playwright/test';
|
||||||
|
|
||||||
|
const ADMIN_EMAIL = process.env.ADMIN_EMAIL || 'admin@example.com';
|
||||||
|
const ADMIN_PASSWORD = process.env.ADMIN_PASSWORD || 'Admin!234';
|
||||||
|
|
||||||
|
function randomSuffix() {
|
||||||
|
return Math.random().toString(36).slice(2, 8);
|
||||||
|
}
|
||||||
|
|
||||||
|
test('admin can create event via UI', async ({ page }) => {
|
||||||
|
const eventName = `UI Playwright ${randomSuffix()}`;
|
||||||
|
const hostEmail = `host+${randomSuffix()}@example.com`;
|
||||||
|
|
||||||
|
// Login
|
||||||
|
await page.goto('/admin/login');
|
||||||
|
await page.getByLabel(/Email/i).fill(ADMIN_EMAIL);
|
||||||
|
await page.getByLabel(/Password/i).fill(ADMIN_PASSWORD);
|
||||||
|
await page.getByRole('button', { name: /Sign In|Log in/i }).click();
|
||||||
|
await expect(page.getByRole('heading', { name: /Dashboard/i })).toBeVisible({ timeout: 20000 });
|
||||||
|
|
||||||
|
// Navigate to create event page
|
||||||
|
const createButton = page.getByRole('button', { name: /Create Event/i });
|
||||||
|
if (await createButton.count()) {
|
||||||
|
await createButton.first().click();
|
||||||
|
} else {
|
||||||
|
await page.goto('/admin/events/new');
|
||||||
|
}
|
||||||
|
|
||||||
|
await expect(page.getByRole('heading', { name: /^Create$/i })).toBeVisible({ timeout: 10000 });
|
||||||
|
|
||||||
|
await page.getByLabel(/Event Name/i).fill(eventName);
|
||||||
|
await page.getByLabel(/Host Name/i).fill('Host User');
|
||||||
|
await page.getByLabel(/Event Date/i).fill('2025-12-31');
|
||||||
|
await page.getByLabel(/Host Email/i).fill(hostEmail);
|
||||||
|
await page.getByLabel(/Admin Email/i).fill(ADMIN_EMAIL);
|
||||||
|
await page.getByLabel(/Gallery Password/i).fill('UiPlay123!');
|
||||||
|
await page.getByLabel(/Confirm Password/i).fill('UiPlay123!');
|
||||||
|
|
||||||
|
await page.getByRole('button', { name: /Create Event/i }).click();
|
||||||
|
|
||||||
|
await expect(page).toHaveURL(/\/admin\/events\//, { timeout: 20000 });
|
||||||
|
await expect(page.getByRole('heading', { name: eventName })).toBeVisible();
|
||||||
|
});
|
||||||
@@ -0,0 +1,100 @@
|
|||||||
|
import { test, expect, Page } from '@playwright/test';
|
||||||
|
import fs from 'fs';
|
||||||
|
import path from 'path';
|
||||||
|
|
||||||
|
const ADMIN_EMAIL = process.env.ADMIN_EMAIL || 'admin@example.com';
|
||||||
|
const ADMIN_PASSWORD = process.env.ADMIN_PASSWORD || 'Admin!234';
|
||||||
|
const GALLERY_PASSWORD = process.env.GALLERY_PASSWORD || 'PlaywrightGallery123!';
|
||||||
|
|
||||||
|
async function createEventWithPhotos(page: Page) {
|
||||||
|
const api = page.request;
|
||||||
|
const loginResponse = await api.post('/api/auth/admin/login', {
|
||||||
|
data: {
|
||||||
|
username: ADMIN_EMAIL,
|
||||||
|
password: ADMIN_PASSWORD,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
expect(loginResponse.ok()).toBeTruthy();
|
||||||
|
const { token } = await loginResponse.json();
|
||||||
|
expect(token).toBeTruthy();
|
||||||
|
|
||||||
|
const eventName = `Playwright Smoke ${Date.now()}`;
|
||||||
|
const eventDate = new Date(Date.now() + 7 * 24 * 60 * 60 * 1000)
|
||||||
|
.toISOString()
|
||||||
|
.slice(0, 10);
|
||||||
|
|
||||||
|
const eventResponse = await api.post('/api/admin/events', {
|
||||||
|
headers: {
|
||||||
|
Authorization: `Bearer ${token}`,
|
||||||
|
'Content-Type': 'application/json',
|
||||||
|
},
|
||||||
|
data: {
|
||||||
|
event_type: 'wedding',
|
||||||
|
event_name: eventName,
|
||||||
|
event_date: eventDate,
|
||||||
|
host_name: 'Playwright Host',
|
||||||
|
host_email: 'host@example.com',
|
||||||
|
admin_email: ADMIN_EMAIL,
|
||||||
|
password: GALLERY_PASSWORD,
|
||||||
|
expiration_days: 30,
|
||||||
|
allow_user_uploads: false,
|
||||||
|
allow_downloads: true,
|
||||||
|
disable_right_click: false,
|
||||||
|
watermark_downloads: false,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
expect(eventResponse.ok()).toBeTruthy();
|
||||||
|
const event = await eventResponse.json();
|
||||||
|
|
||||||
|
const imagePath = path.join(process.cwd(), 'test-assets', 'img1.png');
|
||||||
|
const buffer = fs.readFileSync(imagePath);
|
||||||
|
const uploadResponse = await api.post(`/api/admin/events/${event.id}/upload`, {
|
||||||
|
headers: {
|
||||||
|
Authorization: `Bearer ${token}`,
|
||||||
|
},
|
||||||
|
multipart: {
|
||||||
|
photos: {
|
||||||
|
name: path.basename(imagePath),
|
||||||
|
mimeType: 'image/png',
|
||||||
|
buffer,
|
||||||
|
},
|
||||||
|
category_id: 'individual',
|
||||||
|
},
|
||||||
|
});
|
||||||
|
expect(uploadResponse.ok()).toBeTruthy();
|
||||||
|
|
||||||
|
return {
|
||||||
|
event,
|
||||||
|
shareLink: event.share_link,
|
||||||
|
slug: event.slug,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
test('admin login and gallery viewing smoke test', async ({ page }) => {
|
||||||
|
const { shareLink } = await createEventWithPhotos(page);
|
||||||
|
|
||||||
|
// Admin UI login
|
||||||
|
await page.goto('/admin/login');
|
||||||
|
const emailField = page.getByLabel(/Email/i);
|
||||||
|
if (await emailField.count()) {
|
||||||
|
await emailField.fill(ADMIN_EMAIL);
|
||||||
|
await page.getByLabel(/Password/i).fill(ADMIN_PASSWORD);
|
||||||
|
await page.getByRole('button', { name: /Sign In|Log in/i }).click();
|
||||||
|
}
|
||||||
|
await expect(page.getByRole('heading', { name: /Dashboard/i })).toBeVisible({ timeout: 20000 });
|
||||||
|
|
||||||
|
// Visit gallery share link and authenticate
|
||||||
|
await page.goto(shareLink);
|
||||||
|
const passwordField = page.getByPlaceholder(/gallery password/i);
|
||||||
|
await passwordField.fill(GALLERY_PASSWORD);
|
||||||
|
await page.getByRole('button', { name: /View Gallery/i }).click();
|
||||||
|
|
||||||
|
// Wait for photos grid to appear
|
||||||
|
const tiles = page.locator('.relative.group');
|
||||||
|
await expect(tiles.first()).toBeVisible({ timeout: 20000 });
|
||||||
|
|
||||||
|
// Open lightbox to ensure media renders
|
||||||
|
await tiles.first().hover();
|
||||||
|
await tiles.first().getByRole('button', { name: /View full size/i }).click();
|
||||||
|
await expect(page.getByRole('button', { name: /Close/i })).toBeVisible();
|
||||||
|
});
|
||||||
@@ -0,0 +1,226 @@
|
|||||||
|
import { test, expect } from '@playwright/test';
|
||||||
|
import type { Page } from '@playwright/test';
|
||||||
|
import fs from 'fs';
|
||||||
|
import path from 'path';
|
||||||
|
|
||||||
|
const ADMIN_EMAIL = process.env.ADMIN_EMAIL || 'admin@example.com';
|
||||||
|
const ADMIN_PASSWORD = process.env.ADMIN_PASSWORD || 'Admin!234';
|
||||||
|
const GALLERY_PASSWORD = process.env.GALLERY_PASSWORD || 'PlaywrightGallery123!';
|
||||||
|
|
||||||
|
interface GallerySetupResult {
|
||||||
|
shareLink: string;
|
||||||
|
slug: string;
|
||||||
|
allPhotosData: {
|
||||||
|
event: any;
|
||||||
|
categories?: any;
|
||||||
|
photos: Array<{ id: number; filename: string; comment_count?: number }>;
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
async function createGalleryWithModeratedComments(page: Page): Promise<GallerySetupResult> {
|
||||||
|
const loginResponse = await page.request.post('/api/auth/admin/login', {
|
||||||
|
data: {
|
||||||
|
username: ADMIN_EMAIL,
|
||||||
|
password: ADMIN_PASSWORD,
|
||||||
|
},
|
||||||
|
failOnStatusCode: false,
|
||||||
|
});
|
||||||
|
expect(loginResponse.ok()).toBeTruthy();
|
||||||
|
const { token } = await loginResponse.json();
|
||||||
|
expect(token).toBeTruthy();
|
||||||
|
|
||||||
|
const eventName = `Playwright Feedback Filter ${Date.now()}`;
|
||||||
|
const eventDate = new Date(Date.now() + 7 * 24 * 60 * 60 * 1000)
|
||||||
|
.toISOString()
|
||||||
|
.slice(0, 10);
|
||||||
|
|
||||||
|
const createResponse = await page.request.post('/api/admin/events', {
|
||||||
|
headers: {
|
||||||
|
Authorization: `Bearer ${token}`,
|
||||||
|
'Content-Type': 'application/json',
|
||||||
|
},
|
||||||
|
data: {
|
||||||
|
event_type: 'wedding',
|
||||||
|
event_name: eventName,
|
||||||
|
event_date: eventDate,
|
||||||
|
host_name: 'Playwright Host',
|
||||||
|
host_email: 'host@example.com',
|
||||||
|
admin_email: ADMIN_EMAIL,
|
||||||
|
password: GALLERY_PASSWORD,
|
||||||
|
expiration_days: 30,
|
||||||
|
allow_user_uploads: false,
|
||||||
|
allow_downloads: true,
|
||||||
|
disable_right_click: false,
|
||||||
|
watermark_downloads: false,
|
||||||
|
feedback_enabled: true,
|
||||||
|
allow_ratings: true,
|
||||||
|
allow_likes: true,
|
||||||
|
allow_comments: true,
|
||||||
|
allow_favorites: true,
|
||||||
|
require_name_email: false,
|
||||||
|
moderate_comments: true,
|
||||||
|
show_feedback_to_guests: true,
|
||||||
|
},
|
||||||
|
failOnStatusCode: false,
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(createResponse.ok()).toBeTruthy();
|
||||||
|
const createdEvent = await createResponse.json();
|
||||||
|
expect(createdEvent?.id).toBeTruthy();
|
||||||
|
|
||||||
|
const imagePaths = ['img1.png', 'img2.png'];
|
||||||
|
const photoIds: number[] = [];
|
||||||
|
|
||||||
|
for (const file of imagePaths) {
|
||||||
|
const imagePath = path.join(process.cwd(), 'test-assets', file);
|
||||||
|
const buffer = fs.readFileSync(imagePath);
|
||||||
|
const uploadResponse = await page.request.post(
|
||||||
|
`/api/admin/events/${createdEvent.id}/upload`,
|
||||||
|
{
|
||||||
|
headers: {
|
||||||
|
Authorization: `Bearer ${token}`,
|
||||||
|
},
|
||||||
|
multipart: {
|
||||||
|
photos: {
|
||||||
|
name: path.basename(imagePath),
|
||||||
|
mimeType: 'image/png',
|
||||||
|
buffer,
|
||||||
|
},
|
||||||
|
category_id: 'individual',
|
||||||
|
},
|
||||||
|
failOnStatusCode: false,
|
||||||
|
}
|
||||||
|
);
|
||||||
|
expect(uploadResponse.ok()).toBeTruthy();
|
||||||
|
const uploadJson = await uploadResponse.json();
|
||||||
|
const uploaded = uploadJson?.photos?.[0];
|
||||||
|
expect(uploaded?.id).toBeTruthy();
|
||||||
|
photoIds.push(uploaded.id);
|
||||||
|
}
|
||||||
|
|
||||||
|
expect(photoIds.length).toBeGreaterThanOrEqual(2);
|
||||||
|
|
||||||
|
const galleryAuthResponse = await page.request.post('/api/auth/gallery/verify', {
|
||||||
|
data: {
|
||||||
|
slug: createdEvent.slug,
|
||||||
|
password: GALLERY_PASSWORD,
|
||||||
|
},
|
||||||
|
failOnStatusCode: false,
|
||||||
|
});
|
||||||
|
expect(galleryAuthResponse.ok()).toBeTruthy();
|
||||||
|
const { token: galleryToken } = await galleryAuthResponse.json();
|
||||||
|
expect(galleryToken).toBeTruthy();
|
||||||
|
|
||||||
|
// Submit an approved comment (after moderation)
|
||||||
|
const approvedCommentResponse = await page.request.post(
|
||||||
|
`/api/gallery/${createdEvent.slug}/photos/${photoIds[0]}/feedback`,
|
||||||
|
{
|
||||||
|
headers: {
|
||||||
|
Authorization: `Bearer ${galleryToken}`,
|
||||||
|
'Content-Type': 'application/json',
|
||||||
|
},
|
||||||
|
data: {
|
||||||
|
feedback_type: 'comment',
|
||||||
|
comment_text: 'Approved comment',
|
||||||
|
guest_name: 'Approved Guest',
|
||||||
|
guest_email: 'approved@example.com',
|
||||||
|
},
|
||||||
|
failOnStatusCode: false,
|
||||||
|
}
|
||||||
|
);
|
||||||
|
expect(approvedCommentResponse.ok()).toBeTruthy();
|
||||||
|
const approvedComment = await approvedCommentResponse.json();
|
||||||
|
expect(approvedComment?.id).toBeTruthy();
|
||||||
|
|
||||||
|
const approveModeration = await page.request.put(
|
||||||
|
`/api/admin/feedback/feedback/${approvedComment.id}/approve`,
|
||||||
|
{
|
||||||
|
headers: {
|
||||||
|
Authorization: `Bearer ${token}`,
|
||||||
|
},
|
||||||
|
failOnStatusCode: false,
|
||||||
|
}
|
||||||
|
);
|
||||||
|
expect(approveModeration.ok()).toBeTruthy();
|
||||||
|
|
||||||
|
// Submit a second comment that remains pending
|
||||||
|
const pendingCommentResponse = await page.request.post(
|
||||||
|
`/api/gallery/${createdEvent.slug}/photos/${photoIds[1]}/feedback`,
|
||||||
|
{
|
||||||
|
headers: {
|
||||||
|
Authorization: `Bearer ${galleryToken}`,
|
||||||
|
'Content-Type': 'application/json',
|
||||||
|
},
|
||||||
|
data: {
|
||||||
|
feedback_type: 'comment',
|
||||||
|
comment_text: 'Pending comment',
|
||||||
|
guest_name: 'Pending Guest',
|
||||||
|
guest_email: 'pending@example.com',
|
||||||
|
},
|
||||||
|
failOnStatusCode: false,
|
||||||
|
}
|
||||||
|
);
|
||||||
|
expect(pendingCommentResponse.ok()).toBeTruthy();
|
||||||
|
|
||||||
|
const allPhotosResponse = await page.request.get(`/api/gallery/${createdEvent.slug}/photos`, {
|
||||||
|
headers: {
|
||||||
|
Authorization: `Bearer ${galleryToken}`,
|
||||||
|
},
|
||||||
|
failOnStatusCode: false,
|
||||||
|
});
|
||||||
|
expect(allPhotosResponse.ok()).toBeTruthy();
|
||||||
|
const allPhotosData = await allPhotosResponse.json();
|
||||||
|
expect(Array.isArray(allPhotosData?.photos)).toBeTruthy();
|
||||||
|
|
||||||
|
return {
|
||||||
|
shareLink: createdEvent.share_link,
|
||||||
|
slug: createdEvent.slug,
|
||||||
|
allPhotosData,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
test.describe('Gallery feedback filter', () => {
|
||||||
|
test('Comment filter hides photos without approved comments', async ({ page }) => {
|
||||||
|
const { shareLink, slug, allPhotosData } = await createGalleryWithModeratedComments(page);
|
||||||
|
|
||||||
|
const approvedPhotos = allPhotosData.photos.filter((photo) => (photo.comment_count || 0) > 0);
|
||||||
|
expect(approvedPhotos.length).toBeGreaterThan(0);
|
||||||
|
|
||||||
|
await page.route(`**/api/gallery/${slug}/photos**`, async (route) => {
|
||||||
|
const url = new URL(route.request().url());
|
||||||
|
if (url.searchParams.get('filter') === 'commented') {
|
||||||
|
await route.fulfill({
|
||||||
|
status: 200,
|
||||||
|
contentType: 'application/json',
|
||||||
|
body: JSON.stringify(allPhotosData),
|
||||||
|
});
|
||||||
|
await page.unroute(`**/api/gallery/${slug}/photos**`);
|
||||||
|
} else {
|
||||||
|
await route.continue();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
await page.goto(shareLink);
|
||||||
|
await page.waitForLoadState('domcontentloaded');
|
||||||
|
|
||||||
|
const passwordField = page.getByPlaceholder(/gallery password/i).first();
|
||||||
|
if (await passwordField.count()) {
|
||||||
|
await passwordField.fill(GALLERY_PASSWORD);
|
||||||
|
await page.getByRole('button', { name: /View Gallery/i }).click();
|
||||||
|
}
|
||||||
|
|
||||||
|
await page.waitForLoadState('networkidle');
|
||||||
|
|
||||||
|
const tiles = page.locator('.relative.group');
|
||||||
|
await expect(tiles.first()).toBeVisible({ timeout: 20000 });
|
||||||
|
await expect(tiles).toHaveCount(allPhotosData.photos.length);
|
||||||
|
|
||||||
|
await page.getByRole('button', { name: /Commented/i }).click();
|
||||||
|
|
||||||
|
await expect(tiles).toHaveCount(approvedPhotos.length, { timeout: 20000 });
|
||||||
|
|
||||||
|
for (const pending of allPhotosData.photos.filter((photo) => (photo.comment_count || 0) === 0)) {
|
||||||
|
await expect(page.getByAltText(pending.filename)).not.toBeVisible({ timeout: 1000 });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,180 @@
|
|||||||
|
import { test, expect } from '@playwright/test';
|
||||||
|
import fs from 'fs';
|
||||||
|
import path from 'path';
|
||||||
|
|
||||||
|
const ADMIN_EMAIL = process.env.ADMIN_EMAIL || 'admin@example.com';
|
||||||
|
const ADMIN_PASSWORD = process.env.ADMIN_PASSWORD || 'Admin!234';
|
||||||
|
const GALLERY_PASSWORD = process.env.GALLERY_PASSWORD || 'PlaywrightGallery123!';
|
||||||
|
|
||||||
|
async function ensureGalleryWithPhotos(page) {
|
||||||
|
const loginResponse = await page.request.post('/api/auth/admin/login', {
|
||||||
|
data: {
|
||||||
|
username: ADMIN_EMAIL,
|
||||||
|
password: ADMIN_PASSWORD,
|
||||||
|
},
|
||||||
|
failOnStatusCode: false,
|
||||||
|
});
|
||||||
|
expect(loginResponse.ok()).toBeTruthy();
|
||||||
|
const { token } = await loginResponse.json();
|
||||||
|
expect(token).toBeTruthy();
|
||||||
|
|
||||||
|
const eventName = `Playwright MCP ${Date.now()}`;
|
||||||
|
const eventDate = new Date(Date.now() + 7 * 24 * 60 * 60 * 1000)
|
||||||
|
.toISOString()
|
||||||
|
.slice(0, 10);
|
||||||
|
|
||||||
|
const createResponse = await page.request.post('/api/admin/events', {
|
||||||
|
headers: {
|
||||||
|
Authorization: `Bearer ${token}`,
|
||||||
|
'Content-Type': 'application/json',
|
||||||
|
},
|
||||||
|
data: {
|
||||||
|
event_type: 'wedding',
|
||||||
|
event_name: eventName,
|
||||||
|
event_date: eventDate,
|
||||||
|
host_name: 'Playwright Host',
|
||||||
|
host_email: 'host@example.com',
|
||||||
|
admin_email: ADMIN_EMAIL,
|
||||||
|
password: GALLERY_PASSWORD,
|
||||||
|
expiration_days: 90,
|
||||||
|
allow_user_uploads: false,
|
||||||
|
allow_downloads: true,
|
||||||
|
disable_right_click: false,
|
||||||
|
watermark_downloads: false,
|
||||||
|
feedback_enabled: true,
|
||||||
|
allow_ratings: true,
|
||||||
|
allow_likes: true,
|
||||||
|
allow_comments: true,
|
||||||
|
allow_favorites: true,
|
||||||
|
require_name_email: false,
|
||||||
|
moderate_comments: false,
|
||||||
|
show_feedback_to_guests: true,
|
||||||
|
},
|
||||||
|
failOnStatusCode: false,
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(createResponse.ok()).toBeTruthy();
|
||||||
|
const createdEvent = await createResponse.json();
|
||||||
|
expect(createdEvent?.id).toBeTruthy();
|
||||||
|
|
||||||
|
const imagePaths = ['img1.png', 'img2.png'].map((file) =>
|
||||||
|
path.join(process.cwd(), 'test-assets', file)
|
||||||
|
);
|
||||||
|
|
||||||
|
for (const imagePath of imagePaths) {
|
||||||
|
const buffer = fs.readFileSync(imagePath);
|
||||||
|
const uploadResponse = await page.request.post(
|
||||||
|
`/api/admin/events/${createdEvent.id}/upload`,
|
||||||
|
{
|
||||||
|
headers: {
|
||||||
|
Authorization: `Bearer ${token}`,
|
||||||
|
},
|
||||||
|
multipart: {
|
||||||
|
photos: {
|
||||||
|
name: path.basename(imagePath),
|
||||||
|
mimeType: 'image/png',
|
||||||
|
buffer,
|
||||||
|
},
|
||||||
|
category_id: 'individual',
|
||||||
|
},
|
||||||
|
failOnStatusCode: false,
|
||||||
|
}
|
||||||
|
);
|
||||||
|
expect(uploadResponse.ok()).toBeTruthy();
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
shareLink: createdEvent.share_link,
|
||||||
|
slug: createdEvent.slug,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
test.describe('Gallery grid tile quick actions', () => {
|
||||||
|
test('Each tile: open, download, comment, like with immediate UI', async ({ page }) => {
|
||||||
|
const { shareLink } = await ensureGalleryWithPhotos(page);
|
||||||
|
|
||||||
|
await page.goto(shareLink);
|
||||||
|
const gallery = page;
|
||||||
|
await gallery.waitForLoadState('domcontentloaded');
|
||||||
|
await gallery.waitForURL(/\/gallery\//);
|
||||||
|
|
||||||
|
const passwordField = gallery.getByPlaceholder(/gallery password/i).first();
|
||||||
|
if (await passwordField.count()) {
|
||||||
|
await passwordField.fill(GALLERY_PASSWORD);
|
||||||
|
await gallery.getByRole('button', { name: /View Gallery/i }).click();
|
||||||
|
await gallery.waitForLoadState('networkidle');
|
||||||
|
}
|
||||||
|
|
||||||
|
// Ensure grid tiles rendered
|
||||||
|
const tiles = gallery.locator('.relative.group');
|
||||||
|
await expect(tiles.first()).toBeVisible({ timeout: 20000 });
|
||||||
|
|
||||||
|
const tileCount = await tiles.count();
|
||||||
|
expect(tileCount).toBeGreaterThan(0);
|
||||||
|
|
||||||
|
// Limit to a few tiles to keep test time sensible
|
||||||
|
const N = Math.min(tileCount, 3);
|
||||||
|
for (let i = 0; i < N; i++) {
|
||||||
|
const tile = tiles.nth(i);
|
||||||
|
await tile.scrollIntoViewIfNeeded();
|
||||||
|
// On desktop, actions show on hover
|
||||||
|
await tile.hover({ force: true });
|
||||||
|
|
||||||
|
// Actions should be present
|
||||||
|
const openBtn = tile.getByRole('button', { name: /View full size/i });
|
||||||
|
await expect(openBtn).toBeVisible();
|
||||||
|
|
||||||
|
const likeBtn = tile.getByRole('button', { name: /Like photo/i }).first();
|
||||||
|
await expect(likeBtn).toBeVisible();
|
||||||
|
|
||||||
|
const commentBtn = tile.getByRole('button', { name: /Comment on photo|Comment/i }).first();
|
||||||
|
await expect(commentBtn).toBeVisible();
|
||||||
|
|
||||||
|
const downloadBtn = tile.getByRole('button', { name: /Download photo/i }).first();
|
||||||
|
await expect(downloadBtn).toBeVisible();
|
||||||
|
|
||||||
|
// Like should toggle to red and indicator appear immediately
|
||||||
|
const pressedBefore = await likeBtn.getAttribute('aria-pressed');
|
||||||
|
await likeBtn.click();
|
||||||
|
await expect.poll(async () => (await likeBtn.getAttribute('aria-pressed')) || '').toContain('true');
|
||||||
|
// Feedback indicator (title="Liked") should appear on the tile
|
||||||
|
await expect(tile.locator('[title="Liked"]')).toBeVisible();
|
||||||
|
|
||||||
|
// Open lightbox
|
||||||
|
await openBtn.click();
|
||||||
|
const closeLightboxBtn = gallery.getByRole('button', { name: /^Close$/i }).first();
|
||||||
|
await expect(closeLightboxBtn).toBeVisible();
|
||||||
|
// Close again to continue
|
||||||
|
await closeLightboxBtn.click();
|
||||||
|
|
||||||
|
// Comment quick action should open lightbox with feedback panel visible
|
||||||
|
await tile.hover({ force: true });
|
||||||
|
await commentBtn.click();
|
||||||
|
await expect(gallery.getByRole('button', { name: /Toggle feedback/ })).toBeVisible();
|
||||||
|
|
||||||
|
// Ensure feedback panel is visible or open it
|
||||||
|
const feedbackHeading = gallery.getByRole('heading', { name: /Photo Feedback/i });
|
||||||
|
if (!(await feedbackHeading.isVisible())) {
|
||||||
|
await gallery.getByRole('button', { name: /Toggle feedback/ }).click();
|
||||||
|
}
|
||||||
|
await expect(feedbackHeading).toBeVisible();
|
||||||
|
|
||||||
|
// Comments quick action should surface the feedback tools
|
||||||
|
const addCommentBtn = gallery.getByRole('button', { name: /Add Comment|Add comment/i });
|
||||||
|
await expect(addCommentBtn).toBeVisible();
|
||||||
|
await addCommentBtn.click();
|
||||||
|
// Allow UI to react without requiring text entry
|
||||||
|
await gallery.waitForTimeout(250);
|
||||||
|
|
||||||
|
// Close lightbox to continue (we do not submit to keep test idempotent)
|
||||||
|
await closeLightboxBtn.click();
|
||||||
|
|
||||||
|
// Download from tile should trigger a browser download event
|
||||||
|
await tile.hover({ force: true });
|
||||||
|
const downloadPromise = gallery.waitForEvent('download');
|
||||||
|
await downloadBtn.click();
|
||||||
|
const download = await downloadPromise;
|
||||||
|
expect((await download.path()) !== null).toBeTruthy();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
Reference in New Issue
Block a user