Compare commits
84 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 | |||
| 0d77a3a0a8 | |||
| 0618b78725 | |||
| 0178e71c67 | |||
| aa9b3a0227 | |||
| 410a33fecf | |||
| 05ebaaeedb | |||
| 84d0f63d36 | |||
| 6a4b549d9f | |||
| f3604b438b | |||
| 531831e84b | |||
| 90bb21e38b | |||
| 2f1a137342 | |||
| adf576fbe1 | |||
| 4264026bbe | |||
| 24b4a314a9 | |||
| ba825823a0 | |||
| fb16b7bbb8 | |||
| 8404125ff0 | |||
| 61ad2d61c1 | |||
| 9fd6b44487 | |||
| 9fe10bcce2 | |||
| f2abb40987 | |||
| 3697344cd0 | |||
| 4aa0ff705f | |||
| dc482e614a | |||
| 448882cfef | |||
| 7f9cb33a40 | |||
| 798f6211e0 | |||
| b992b151d3 | |||
| 87b8414e44 | |||
| ee13556c5c | |||
| afeb35a446 | |||
| ab324f1928 | |||
| 78ab0ad2e9 | |||
| 49c77785e7 | |||
| 1d826accdc | |||
| ceefe4f5a7 | |||
| e9171c7115 | |||
| 758c085467 | |||
| ecbc48815d | |||
| e91b138154 | |||
| dad1787aad | |||
| 909e760447 | |||
| 41857ec499 | |||
| f7a8765f58 | |||
| 214f120f7a | |||
| f26becad1d | |||
| 67ff415840 | |||
| 88659f1fa6 | |||
| c1e10f14a3 | |||
| 0881a0fa71 | |||
| e91209f7cb | |||
| 828d6bc456 | |||
| f945573f09 | |||
| 296430e4d7 | |||
| 7b517fa290 | |||
| 2c9a56f217 | |||
| 986b101040 | |||
| 0c283717cb | |||
| 4029559954 |
@@ -34,9 +34,15 @@ SMTP_PASS=your-app-specific-password
|
||||
EMAIL_FROM=noreply@yourdomain.com
|
||||
|
||||
# Application URLs
|
||||
# Use full origin with scheme, no trailing slash.
|
||||
# Admin UI is served by the frontend at /admin.
|
||||
FRONTEND_URL=https://yourdomain.com
|
||||
ADMIN_URL=https://yourdomain.com:3001
|
||||
VITE_API_URL=https://yourdomain.com:3001/api
|
||||
ADMIN_URL=https://yourdomain.com
|
||||
|
||||
# Frontend API base
|
||||
# For pre-built images and production behind a reverse proxy, keep '/api'.
|
||||
# If you rebuild the frontend yourself, you may set a full URL at build time.
|
||||
VITE_API_URL=/api
|
||||
|
||||
# Port Configuration (optional)
|
||||
# BACKEND_PORT=3001
|
||||
@@ -47,7 +53,25 @@ VITE_API_URL=https://yourdomain.com:3001/api
|
||||
# Timezone
|
||||
TZ=UTC
|
||||
|
||||
# Runtime user mapping for Docker (optional)
|
||||
# Set these to your host user's UID/GID to avoid permission issues on bind mounts.
|
||||
# Run `id -u` and `id -g` on host to get values. Defaults to 1001.
|
||||
PUID=1001
|
||||
PGID=1001
|
||||
|
||||
# Analytics (Optional - Umami)
|
||||
VITE_UMAMI_URL=
|
||||
VITE_UMAMI_WEBSITE_ID=
|
||||
VITE_UMAMI_SHARE_URL=
|
||||
VITE_UMAMI_SHARE_URL=
|
||||
|
||||
# Storage variables (host paths)
|
||||
# These control where data is stored on the host. Defaults are local folders.
|
||||
APP_STORAGE=./storage
|
||||
APP_DATA=./data
|
||||
LOGS=./logs
|
||||
|
||||
# Note on FRONTEND_API_URL (documentation only):
|
||||
# When using pre-built frontend images, runtime env vars cannot override the built JS.
|
||||
# Do NOT rely on FRONTEND_API_URL in Compose. Instead, keep VITE_API_URL=/api and
|
||||
# let the frontend Nginx proxy /api to the backend. Only if you rebuild the frontend
|
||||
# should you change VITE_API_URL at build time.
|
||||
|
||||
@@ -33,7 +33,7 @@ jobs:
|
||||
# Remove sensitive files/directories if they exist
|
||||
echo "Removing sensitive files..."
|
||||
rm -rf .gitea/ || true
|
||||
rm -rf scripts/ || true
|
||||
rm -rf scripts/install-gitea-runner.sh || true
|
||||
rm -rf .drone* || true
|
||||
rm -rf photo-sharing-prd.md || true
|
||||
rm -rf CLAUDE.md || true
|
||||
|
||||
@@ -0,0 +1,213 @@
|
||||
# Docker Build and Push Workflow
|
||||
|
||||
This GitHub Actions workflow automatically builds and pushes Docker images for both the backend and frontend to GitHub Container Registry (ghcr.io).
|
||||
|
||||
## Features
|
||||
|
||||
- 🔧 **Automatic builds** on push to main/develop branches, PRs, and releases
|
||||
- 🏗️ **Multi-architecture support** (linux/amd64 and linux/arm64)
|
||||
- 🏷️ **Smart tagging** based on branches, versions, and commits
|
||||
- 🔒 **Security scanning** with Trivy vulnerability scanner
|
||||
- 💾 **Build caching** for faster subsequent builds
|
||||
- 📊 **Build summaries** in GitHub Actions UI
|
||||
|
||||
## Authentication
|
||||
|
||||
The workflow uses the built-in `GITHUB_TOKEN` for authentication with GitHub Container Registry. No additional setup or personal access tokens are required.
|
||||
|
||||
### Required Permissions
|
||||
|
||||
The workflow automatically sets the necessary permissions:
|
||||
- `contents: read` - To checkout the repository
|
||||
- `packages: write` - To push images to ghcr.io
|
||||
- `security-events: write` - To upload security scan results
|
||||
|
||||
## Image Tags
|
||||
|
||||
Images are automatically tagged based on the trigger event:
|
||||
|
||||
| Event | Tags Generated |
|
||||
|-------|---------------|
|
||||
| Push to main | `latest`, `main`, `main-<short-sha>` |
|
||||
| Push to develop | `develop`, `develop-<short-sha>` |
|
||||
| Pull Request | `pr-<number>` |
|
||||
| Release (v1.2.3) | `1.2.3`, `1.2`, `1`, `latest` |
|
||||
| Manual trigger | Based on branch + optional push |
|
||||
|
||||
## Usage
|
||||
|
||||
### Pull Images
|
||||
|
||||
Once published, images can be pulled using:
|
||||
|
||||
```bash
|
||||
# Pull backend image
|
||||
docker pull ghcr.io/the-luap/picpeak/backend:latest
|
||||
|
||||
# Pull frontend image
|
||||
docker pull ghcr.io/the-luap/picpeak/frontend:latest
|
||||
|
||||
# Pull specific version
|
||||
docker pull ghcr.io/the-luap/picpeak/backend:v1.0.0
|
||||
|
||||
# Pull for specific architecture
|
||||
docker pull --platform linux/arm64 ghcr.io/the-luap/picpeak/backend:latest
|
||||
```
|
||||
|
||||
### Using in Docker Compose
|
||||
|
||||
```yaml
|
||||
version: '3.8'
|
||||
|
||||
services:
|
||||
backend:
|
||||
image: ghcr.io/the-luap/picpeak/backend:latest
|
||||
environment:
|
||||
- NODE_ENV=production
|
||||
ports:
|
||||
- "3001:3000"
|
||||
|
||||
frontend:
|
||||
image: ghcr.io/the-luap/picpeak/frontend:latest
|
||||
ports:
|
||||
- "80:80"
|
||||
```
|
||||
|
||||
### Using in Kubernetes
|
||||
|
||||
```yaml
|
||||
apiVersion: apps/v1
|
||||
kind: Deployment
|
||||
metadata:
|
||||
name: picpeak-backend
|
||||
spec:
|
||||
replicas: 3
|
||||
template:
|
||||
spec:
|
||||
containers:
|
||||
- name: backend
|
||||
image: ghcr.io/the-luap/picpeak/backend:latest
|
||||
imagePullPolicy: Always
|
||||
```
|
||||
|
||||
## Manual Workflow Trigger
|
||||
|
||||
You can manually trigger the workflow from the Actions tab:
|
||||
|
||||
1. Go to Actions → "Build and Push Docker Images"
|
||||
2. Click "Run workflow"
|
||||
3. Select branch and whether to push images
|
||||
4. Click "Run workflow"
|
||||
|
||||
## Security Scanning
|
||||
|
||||
The workflow includes Trivy vulnerability scanning that:
|
||||
- Scans for CRITICAL and HIGH severity vulnerabilities
|
||||
- Uploads results to GitHub Security tab
|
||||
- Available under Security → Code scanning alerts
|
||||
|
||||
## Build Optimization
|
||||
|
||||
The workflow uses several optimization techniques:
|
||||
|
||||
1. **GitHub Actions Cache**: Speeds up builds by caching layers
|
||||
2. **Multi-stage builds**: Reduces final image size
|
||||
3. **Parallel builds**: Backend and frontend build simultaneously
|
||||
4. **Smart rebuilds**: Only rebuilds changed components
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
### Permission Denied Errors
|
||||
|
||||
If you encounter permission errors when pushing images:
|
||||
|
||||
1. **First-time setup**: The first push creates a private package. You may need to:
|
||||
- Go to your package settings at `https://github.com/users/YOUR_USERNAME/packages`
|
||||
- Link the package to your repository
|
||||
- Set package visibility (public/private)
|
||||
|
||||
2. **Organization repositories**: Ensure the organization allows GitHub Actions to create packages
|
||||
|
||||
### Build Failures
|
||||
|
||||
Check the workflow logs in the Actions tab for detailed error messages. Common issues:
|
||||
- Missing dependencies in package.json
|
||||
- Dockerfile syntax errors
|
||||
- Network issues during package installation
|
||||
|
||||
### Image Not Found
|
||||
|
||||
If images aren't visible after successful push:
|
||||
- Check package visibility settings
|
||||
- Ensure you're authenticated to pull private images:
|
||||
```bash
|
||||
echo $GITHUB_TOKEN | docker login ghcr.io -u YOUR_USERNAME --password-stdin
|
||||
```
|
||||
|
||||
## Package Management
|
||||
|
||||
### View Packages
|
||||
|
||||
Your Docker images are available at:
|
||||
- Backend: `https://github.com/users/the-luap/packages/container/package/picpeak%2Fbackend`
|
||||
- Frontend: `https://github.com/users/the-luap/packages/container/package/picpeak%2Ffrontend`
|
||||
|
||||
### Delete Old Versions
|
||||
|
||||
To save storage, you can delete old versions:
|
||||
1. Go to package settings
|
||||
2. Click on "Manage versions"
|
||||
3. Select versions to delete
|
||||
4. Click "Delete selected versions"
|
||||
|
||||
### Set Retention Policy
|
||||
|
||||
Configure automatic cleanup in package settings:
|
||||
1. Go to package settings
|
||||
2. Click on "Manage Actions access"
|
||||
3. Set retention days for untagged versions
|
||||
|
||||
## Best Practices
|
||||
|
||||
1. **Use semantic versioning** for releases (e.g., v1.2.3)
|
||||
2. **Test images locally** before pushing to production
|
||||
3. **Monitor security alerts** from Trivy scans
|
||||
4. **Clean up old images** regularly to save storage
|
||||
5. **Use specific tags** in production (avoid `latest`)
|
||||
|
||||
## Advanced Configuration
|
||||
|
||||
### Custom Registry
|
||||
|
||||
To use a different registry, update the workflow:
|
||||
|
||||
```yaml
|
||||
env:
|
||||
REGISTRY: docker.io # or your custom registry
|
||||
BACKEND_IMAGE_NAME: yourusername/picpeak-backend
|
||||
```
|
||||
|
||||
### Additional Platforms
|
||||
|
||||
To build for more platforms:
|
||||
|
||||
```yaml
|
||||
platforms: linux/amd64,linux/arm64,linux/arm/v7
|
||||
```
|
||||
|
||||
### Custom Build Arguments
|
||||
|
||||
Add build arguments in the workflow:
|
||||
|
||||
```yaml
|
||||
build-args: |
|
||||
NODE_VERSION=20
|
||||
API_URL=${{ secrets.API_URL }}
|
||||
```
|
||||
|
||||
## Related Documentation
|
||||
|
||||
- [GitHub Container Registry Docs](https://docs.github.com/en/packages/working-with-a-github-packages-registry/working-with-the-container-registry)
|
||||
- [Docker Build Action](https://github.com/docker/build-push-action)
|
||||
- [Trivy Security Scanner](https://github.com/aquasecurity/trivy)
|
||||
- [Multi-platform Builds](https://docs.docker.com/build/building/multi-platform/)
|
||||
@@ -0,0 +1,229 @@
|
||||
name: Build and Push Docker Images
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [ main, develop ]
|
||||
tags: [ 'v*.*.*' ]
|
||||
pull_request:
|
||||
branches: [ main ]
|
||||
release:
|
||||
types: [ published ]
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
push:
|
||||
description: 'Push images to registry'
|
||||
required: false
|
||||
default: 'false'
|
||||
type: choice
|
||||
options:
|
||||
- 'true'
|
||||
- 'false'
|
||||
|
||||
env:
|
||||
REGISTRY: ghcr.io
|
||||
BACKEND_IMAGE_NAME: ${{ github.repository }}/backend
|
||||
FRONTEND_IMAGE_NAME: ${{ github.repository }}/frontend
|
||||
|
||||
jobs:
|
||||
build-backend:
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: read
|
||||
packages: write
|
||||
security-events: write
|
||||
|
||||
steps:
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Set up Docker Buildx
|
||||
uses: docker/setup-buildx-action@v3
|
||||
with:
|
||||
platforms: linux/amd64,linux/arm64
|
||||
|
||||
- name: Log in to Container Registry
|
||||
if: github.event_name != 'pull_request' || github.event.inputs.push == 'true'
|
||||
id: login-ghcr
|
||||
continue-on-error: true
|
||||
uses: docker/login-action@v3
|
||||
with:
|
||||
registry: ${{ env.REGISTRY }}
|
||||
username: ${{ github.actor }}
|
||||
password: ${{ secrets.GITHUB_TOKEN }}
|
||||
|
||||
- name: Extract metadata for Backend
|
||||
id: meta-backend
|
||||
uses: docker/metadata-action@v5
|
||||
with:
|
||||
images: ${{ env.REGISTRY }}/${{ env.BACKEND_IMAGE_NAME }}
|
||||
labels: |
|
||||
org.opencontainers.image.title=PicPeak Backend
|
||||
org.opencontainers.image.description=PicPeak photo sharing platform backend service
|
||||
org.opencontainers.image.vendor=PicPeak
|
||||
maintainer=${{ github.repository_owner }}
|
||||
tags: |
|
||||
type=ref,event=branch
|
||||
type=ref,event=pr
|
||||
type=semver,pattern={{version}}
|
||||
type=semver,pattern={{major}}.{{minor}}
|
||||
type=semver,pattern={{major}}
|
||||
type=sha,prefix={{branch}}-,format=short
|
||||
type=raw,value=latest,enable={{is_default_branch}}
|
||||
|
||||
- name: Build and push Backend Docker image
|
||||
uses: docker/build-push-action@v5
|
||||
with:
|
||||
context: ./backend
|
||||
file: ./backend/Dockerfile
|
||||
# Always build; only push when registry login succeeded
|
||||
push: ${{ (github.event_name != 'pull_request' || github.event.inputs.push == 'true') && steps.login-ghcr.outcome == 'success' }}
|
||||
tags: ${{ steps.meta-backend.outputs.tags }}
|
||||
labels: ${{ steps.meta-backend.outputs.labels }}
|
||||
platforms: linux/amd64,linux/arm64
|
||||
cache-from: type=gha,scope=backend
|
||||
cache-to: type=gha,mode=max,scope=backend
|
||||
build-args: |
|
||||
CACHEBUST=${{ github.run_number }}
|
||||
BUILD_DATE=${{ github.event.head_commit.timestamp }}
|
||||
VCS_REF=${{ github.sha }}
|
||||
VERSION=${{ steps.meta-backend.outputs.version }}
|
||||
|
||||
- name: Run Trivy vulnerability scanner
|
||||
if: github.event_name != 'pull_request' && steps.login-ghcr.outcome == 'success'
|
||||
uses: aquasecurity/trivy-action@master
|
||||
with:
|
||||
image-ref: ${{ env.REGISTRY }}/${{ env.BACKEND_IMAGE_NAME }}:${{ steps.meta-backend.outputs.version }}
|
||||
format: 'sarif'
|
||||
output: 'trivy-backend.sarif'
|
||||
severity: 'CRITICAL,HIGH'
|
||||
timeout: '10m'
|
||||
|
||||
- name: Upload Trivy scan results to GitHub Security tab
|
||||
if: github.event_name != 'pull_request' && steps.login-ghcr.outcome == 'success'
|
||||
uses: github/codeql-action/upload-sarif@v3
|
||||
with:
|
||||
sarif_file: 'trivy-backend.sarif'
|
||||
category: 'backend-vulnerabilities'
|
||||
|
||||
build-frontend:
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: read
|
||||
packages: write
|
||||
security-events: write
|
||||
|
||||
steps:
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Set up Docker Buildx
|
||||
uses: docker/setup-buildx-action@v3
|
||||
with:
|
||||
platforms: linux/amd64,linux/arm64
|
||||
|
||||
- name: Log in to Container Registry
|
||||
if: github.event_name != 'pull_request' || github.event.inputs.push == 'true'
|
||||
id: login-ghcr
|
||||
continue-on-error: true
|
||||
uses: docker/login-action@v3
|
||||
with:
|
||||
registry: ${{ env.REGISTRY }}
|
||||
username: ${{ github.actor }}
|
||||
password: ${{ secrets.GITHUB_TOKEN }}
|
||||
|
||||
- name: Extract metadata for Frontend
|
||||
id: meta-frontend
|
||||
uses: docker/metadata-action@v5
|
||||
with:
|
||||
images: ${{ env.REGISTRY }}/${{ env.FRONTEND_IMAGE_NAME }}
|
||||
labels: |
|
||||
org.opencontainers.image.title=PicPeak Frontend
|
||||
org.opencontainers.image.description=PicPeak photo sharing platform frontend application
|
||||
org.opencontainers.image.vendor=PicPeak
|
||||
maintainer=${{ github.repository_owner }}
|
||||
tags: |
|
||||
type=ref,event=branch
|
||||
type=ref,event=pr
|
||||
type=semver,pattern={{version}}
|
||||
type=semver,pattern={{major}}.{{minor}}
|
||||
type=semver,pattern={{major}}
|
||||
type=sha,prefix={{branch}}-,format=short
|
||||
type=raw,value=latest,enable={{is_default_branch}}
|
||||
|
||||
- name: Build and push Frontend Docker image
|
||||
uses: docker/build-push-action@v5
|
||||
with:
|
||||
context: ./frontend
|
||||
file: ./frontend/Dockerfile
|
||||
# Always build; only push when registry login succeeded
|
||||
push: ${{ (github.event_name != 'pull_request' || github.event.inputs.push == 'true') && steps.login-ghcr.outcome == 'success' }}
|
||||
tags: ${{ steps.meta-frontend.outputs.tags }}
|
||||
labels: ${{ steps.meta-frontend.outputs.labels }}
|
||||
platforms: linux/amd64,linux/arm64
|
||||
cache-from: type=gha,scope=frontend
|
||||
cache-to: type=gha,mode=max,scope=frontend
|
||||
build-args: |
|
||||
CACHEBUST=${{ github.run_number }}
|
||||
BUILD_DATE=${{ github.event.head_commit.timestamp }}
|
||||
VCS_REF=${{ github.sha }}
|
||||
VERSION=${{ steps.meta-frontend.outputs.version }}
|
||||
|
||||
- name: Run Trivy vulnerability scanner
|
||||
if: github.event_name != 'pull_request' && steps.login-ghcr.outcome == 'success'
|
||||
uses: aquasecurity/trivy-action@master
|
||||
with:
|
||||
image-ref: ${{ env.REGISTRY }}/${{ env.FRONTEND_IMAGE_NAME }}:${{ steps.meta-frontend.outputs.version }}
|
||||
format: 'sarif'
|
||||
output: 'trivy-frontend.sarif'
|
||||
severity: 'CRITICAL,HIGH'
|
||||
timeout: '10m'
|
||||
|
||||
- name: Upload Trivy scan results to GitHub Security tab
|
||||
if: github.event_name != 'pull_request' && steps.login-ghcr.outcome == 'success'
|
||||
uses: github/codeql-action/upload-sarif@v3
|
||||
with:
|
||||
sarif_file: 'trivy-frontend.sarif'
|
||||
category: 'frontend-vulnerabilities'
|
||||
|
||||
# Note: The publish-manifest job is not needed since docker/build-push-action@v5
|
||||
# automatically creates multi-arch manifests when building for multiple platforms.
|
||||
# The images are already properly tagged and include all architectures.
|
||||
|
||||
summary:
|
||||
needs: [build-backend, build-frontend]
|
||||
if: always()
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
steps:
|
||||
- name: Build Summary
|
||||
run: |
|
||||
echo "## 🐳 Docker Build Summary" >> $GITHUB_STEP_SUMMARY
|
||||
echo "" >> $GITHUB_STEP_SUMMARY
|
||||
|
||||
if [[ "${{ needs.build-backend.result }}" == "success" ]]; then
|
||||
echo "✅ **Backend**: Successfully built" >> $GITHUB_STEP_SUMMARY
|
||||
else
|
||||
echo "❌ **Backend**: Build failed" >> $GITHUB_STEP_SUMMARY
|
||||
fi
|
||||
|
||||
if [[ "${{ needs.build-frontend.result }}" == "success" ]]; then
|
||||
echo "✅ **Frontend**: Successfully built" >> $GITHUB_STEP_SUMMARY
|
||||
else
|
||||
echo "❌ **Frontend**: Build failed" >> $GITHUB_STEP_SUMMARY
|
||||
fi
|
||||
|
||||
echo "" >> $GITHUB_STEP_SUMMARY
|
||||
echo "### 📦 Images" >> $GITHUB_STEP_SUMMARY
|
||||
echo "- Backend: \`${{ env.REGISTRY }}/${{ env.BACKEND_IMAGE_NAME }}\`" >> $GITHUB_STEP_SUMMARY
|
||||
echo "- Frontend: \`${{ env.REGISTRY }}/${{ env.FRONTEND_IMAGE_NAME }}\`" >> $GITHUB_STEP_SUMMARY
|
||||
|
||||
echo "" >> $GITHUB_STEP_SUMMARY
|
||||
echo "### 🏷️ Tags" >> $GITHUB_STEP_SUMMARY
|
||||
echo "Images are tagged based on:" >> $GITHUB_STEP_SUMMARY
|
||||
echo "- Branch name (for branch pushes)" >> $GITHUB_STEP_SUMMARY
|
||||
echo "- PR number (for pull requests)" >> $GITHUB_STEP_SUMMARY
|
||||
echo "- Version tags (for releases)" >> $GITHUB_STEP_SUMMARY
|
||||
echo "- Short SHA with branch prefix" >> $GITHUB_STEP_SUMMARY
|
||||
echo "- \`latest\` (for main branch)" >> $GITHUB_STEP_SUMMARY
|
||||
@@ -72,3 +72,12 @@ logs/
|
||||
storage/
|
||||
data/
|
||||
certbot/
|
||||
|
||||
# Ignore local contributor guide copy
|
||||
AGENTS.md
|
||||
|
||||
# Local artifacts from browser tooling
|
||||
.playwright-mcp/
|
||||
|
||||
# Local SQLite files in backend
|
||||
backend/*.sqlite*
|
||||
|
||||
|
Before Width: | Height: | Size: 211 KiB |
|
Before Width: | Height: | Size: 211 KiB |
|
Before Width: | Height: | Size: 8.4 KiB |
|
Before Width: | Height: | Size: 20 KiB |
|
Before Width: | Height: | Size: 196 KiB |
|
Before Width: | Height: | Size: 47 KiB |
|
Before Width: | Height: | Size: 100 KiB |
|
Before Width: | Height: | Size: 102 KiB |
|
Before Width: | Height: | Size: 209 KiB |
|
Before Width: | Height: | Size: 106 KiB |
|
Before Width: | Height: | Size: 163 KiB |
|
Before Width: | Height: | Size: 93 KiB |
|
Before Width: | Height: | Size: 174 KiB |
|
Before Width: | Height: | Size: 181 KiB |
@@ -4,27 +4,62 @@ This guide covers multiple deployment options for PicPeak, from simple local set
|
||||
|
||||
## 🎯 Quick Start - Simple Setup (Recommended for Beginners)
|
||||
|
||||
For the easiest installation without Docker or complex configurations, use our **simple setup script**:
|
||||
For the easiest installation without Docker or complex configurations, use our **unified setup script**:
|
||||
|
||||
```bash
|
||||
curl -fsSL https://raw.githubusercontent.com/yourusername/wedding-photo-sharing/main/scripts/simple-setup.sh -o setup.sh && \
|
||||
curl -fsSL https://raw.githubusercontent.com/the-luap/picpeak/main/scripts/setup.sh -o setup.sh && \
|
||||
chmod +x setup.sh && \
|
||||
sudo ./setup.sh
|
||||
```
|
||||
|
||||
This automated script handles everything including OS detection, dependencies, database setup, and service configuration. Perfect for:
|
||||
This automated script handles everything including:
|
||||
- Choice between Docker or Native installation
|
||||
- OS detection and dependency installation
|
||||
- Database setup and service configuration
|
||||
- SSL/HTTPS setup (optional)
|
||||
|
||||
Perfect for:
|
||||
- Small to medium deployments
|
||||
- Local or VPS installations
|
||||
- Users who prefer avoiding Docker complexity
|
||||
- Users new to server management
|
||||
- Quick testing and evaluation
|
||||
|
||||
👉 **See [SIMPLE_SETUP_GUIDE.md](./SIMPLE_SETUP_GUIDE.md) for detailed instructions.**
|
||||
👉 **See [SIMPLE_SETUP.md](./SIMPLE_SETUP.md) for detailed instructions.**
|
||||
|
||||
---
|
||||
|
||||
## 🐳 Docker Compose Deployment
|
||||
|
||||
This section covers deploying PicPeak using Docker Compose with direct port exposure. For internet-facing deployments, you'll need to add a reverse proxy (nginx, Traefik, Caddy, etc.) for SSL/HTTPS.
|
||||
### Option 1: Using Pre-built Images (Recommended)
|
||||
|
||||
PicPeak provides official Docker images via GitHub Container Registry for quick deployment without building:
|
||||
|
||||
```bash
|
||||
# Clone repository for configuration files
|
||||
git clone https://github.com/the-luap/picpeak.git
|
||||
cd picpeak
|
||||
|
||||
# Copy and configure environment
|
||||
cp .env.example .env
|
||||
nano .env # Edit with your values
|
||||
|
||||
# Use pre-built images deployment
|
||||
docker compose -f docker-compose.production.yml up -d
|
||||
```
|
||||
|
||||
The production compose file uses:
|
||||
- **Backend**: `ghcr.io/the-luap/picpeak/backend:latest`
|
||||
- **Frontend**: `ghcr.io/the-luap/picpeak/frontend:latest`
|
||||
|
||||
Available tags:
|
||||
- `latest` - Latest stable release
|
||||
- `main` - Latest main branch build
|
||||
- `develop` - Development branch (may be unstable)
|
||||
- `v1.0.0` - Specific version tags
|
||||
|
||||
### Option 2: Building from Source
|
||||
|
||||
If you need to customize the application or the pre-built images aren't available, you can build locally:
|
||||
|
||||
## 📋 Table of Contents
|
||||
|
||||
@@ -36,6 +71,7 @@ This section covers deploying PicPeak using Docker Compose with direct port expo
|
||||
- [Reverse Proxy Setup](#reverse-proxy-setup)
|
||||
- [Maintenance](#maintenance)
|
||||
- [Troubleshooting](#troubleshooting)
|
||||
- [External Media Library](#external-media-library)
|
||||
|
||||
## Prerequisites
|
||||
|
||||
@@ -46,6 +82,75 @@ This section covers deploying PicPeak using Docker Compose with direct port expo
|
||||
|
||||
## 🚀 Quick Start
|
||||
|
||||
### Method 1: Using Pre-built Images (Fastest)
|
||||
|
||||
1. **Clone the repository for configs**
|
||||
```bash
|
||||
git clone https://github.com/the-luap/picpeak.git
|
||||
cd picpeak
|
||||
```
|
||||
|
||||
2. **Set up environment**
|
||||
```bash
|
||||
cp .env.example .env
|
||||
nano .env # Edit with your values
|
||||
```
|
||||
|
||||
3. **Create required directories**
|
||||
```bash
|
||||
mkdir -p events/active events/archived data logs backup storage
|
||||
chmod -R 755 events data logs backup storage
|
||||
```
|
||||
|
||||
4. **Deploy using pre-built images**
|
||||
```bash
|
||||
docker compose -f docker-compose.production.yml up -d
|
||||
```
|
||||
|
||||
5. **Check logs**
|
||||
```bash
|
||||
docker compose -f docker-compose.production.yml logs -f
|
||||
```
|
||||
|
||||
## External Media Library
|
||||
|
||||
PicPeak can reference an existing, read‑only media library mounted into the backend container. This avoids copying originals into PicPeak storage.
|
||||
|
||||
- Map your host library path to the container as read‑only in `docker-compose.production.yml`:
|
||||
- Add volume under `backend`: `- ${EXTERNAL_MEDIA}:/external-media:ro`
|
||||
- Add backend env: `EXTERNAL_MEDIA_ROOT=/external-media`
|
||||
- In `.env`, set:
|
||||
- `EXTERNAL_MEDIA=/mnt/photos` (example host path)
|
||||
- `EXTERNAL_MEDIA_ROOT=/external-media`
|
||||
|
||||
Usage:
|
||||
- In Admin → Events, set “Source Mode” to “Reference (external folder)”, select a folder under `/external-media`, then import to index and generate thumbnails. Originals stay in your library.
|
||||
|
||||
Backups and Archives:
|
||||
- Backups only include data under `STORAGE_PATH` and exclude external originals. The backup manifest includes `metadata.external_references = { excluded: true, events: N, photos: M }` and the Admin UI surfaces a warning.
|
||||
- Archiving reference events creates a manifest‑only ZIP and deletes thumbnails for that event. External originals are never moved or deleted.
|
||||
|
||||
Local (npm) setup (no Docker):
|
||||
|
||||
1. Create or choose a folder that contains your external originals, e.g. `/Users/you/Pictures/picpeak-external` (macOS/Linux) or `C:\\Pictures\\picpeak-external` (Windows).
|
||||
2. In `backend/.env` (or your shell), set:
|
||||
- `EXTERNAL_MEDIA_ROOT=/absolute/path/to/picpeak-external`
|
||||
- Ensure `STORAGE_PATH` points to your PicPeak storage (defaults to `./storage`).
|
||||
3. Start services from source:
|
||||
- Backend: `cd backend && npm install && npm run migrate && JWT_SECRET=... npm start`
|
||||
- Frontend: `cd frontend && npm install && npm run dev` (or build + serve)
|
||||
4. In Admin → Events:
|
||||
- Create an event, set “Source Mode” to “Reference (external folder)”.
|
||||
- Use the folder picker to browse under your `EXTERNAL_MEDIA_ROOT` and select the subfolder to reference.
|
||||
- Click “Import from selected folder” to index files and generate thumbnails on demand.
|
||||
|
||||
Notes:
|
||||
- PicPeak only reads from `EXTERNAL_MEDIA_ROOT`; it never modifies or deletes your originals there.
|
||||
- Thumbnails are generated under `STORAGE_PATH/thumbnails` and are included in backups; originals in `EXTERNAL_MEDIA_ROOT` are excluded.
|
||||
- On Windows, use absolute paths (e.g., `C:\\Photos\\Library`) for `EXTERNAL_MEDIA_ROOT`.
|
||||
|
||||
### Method 2: Building from Source
|
||||
|
||||
1. **Clone the repository**
|
||||
```bash
|
||||
git clone https://github.com/the-luap/picpeak.git
|
||||
@@ -64,8 +169,9 @@ This section covers deploying PicPeak using Docker Compose with direct port expo
|
||||
chmod -R 755 events data logs backup storage
|
||||
```
|
||||
|
||||
4. **Deploy**
|
||||
4. **Build and deploy**
|
||||
```bash
|
||||
docker compose build
|
||||
docker compose up -d
|
||||
```
|
||||
|
||||
@@ -102,8 +208,28 @@ Update `.env` with:
|
||||
- `REDIS_PASSWORD` - Redis password
|
||||
- `SMTP_*` - Email configuration
|
||||
- **URL Configuration** (for backend CORS):
|
||||
- `FRONTEND_URL` - Frontend URL (e.g., `http://localhost:3000` for Docker)
|
||||
- `ADMIN_URL` - Admin URL (e.g., `http://localhost:3000` for Docker)
|
||||
- `FRONTEND_URL` - Frontend origin (use full URL with scheme, no trailing slash)
|
||||
- Example (Docker): `http://localhost:3000`
|
||||
- `ADMIN_URL` - Admin origin (same as `FRONTEND_URL` for Docker; full URL, no trailing slash)
|
||||
- Example (Docker): `http://localhost:3000`
|
||||
|
||||
Notes:
|
||||
- Do not include trailing `/` (e.g., use `http://host:3000`, not `http://host:3000/`).
|
||||
- Always include the scheme (`http://` or `https://`).
|
||||
- The backend compares origins strictly for CORS; malformed values will cause login requests to fail with 500.
|
||||
|
||||
#### External Database Example
|
||||
To use an external PostgreSQL instead of the bundled container, set the following in `.env` and ensure the `postgres` service is disabled or removed:
|
||||
|
||||
```env
|
||||
DB_HOST=db.example.com
|
||||
DB_PORT=5432
|
||||
DB_USER=picpeak
|
||||
DB_PASSWORD=change_me
|
||||
DB_NAME=picpeak_prod
|
||||
```
|
||||
|
||||
Compose uses these values via `env_file: .env`. The backend service also defaults `DB_HOST=${DB_HOST:-postgres}` so if you don’t set `DB_HOST` it will use the bundled `postgres` container.
|
||||
|
||||
### Frontend Configuration (frontend/.env)
|
||||
Create `frontend/.env` from `frontend/.env.example`:
|
||||
@@ -113,9 +239,10 @@ cp frontend/.env.example frontend/.env
|
||||
|
||||
Update `frontend/.env` with:
|
||||
- `VITE_API_URL` - Backend API URL
|
||||
- For Docker deployment: `http://localhost:3001/api`
|
||||
- For non-Docker local dev: `http://localhost:3001`
|
||||
- For production with reverse proxy: `/api`
|
||||
- Docker (pre-built images) and production behind reverse proxy: `/api` (recommended; avoids CORS and matches the frontend Nginx proxy in the image)
|
||||
- Local dev (Vite): `http://localhost:3001` or `/api` if proxying through a dev proxy
|
||||
|
||||
Note: When using pre-built frontend images, runtime container env does not change the already-built JS. Prefer the default `/api` and let the frontend Nginx proxy forward to the backend.
|
||||
|
||||
⚠️ **IMPORTANT PORT CONFIGURATION**:
|
||||
- The frontend runs on port **3000** in Docker (exposed via nginx)
|
||||
@@ -145,12 +272,29 @@ SMTP_PASS=your-sendgrid-api-key
|
||||
|
||||
## 📦 Deployment
|
||||
|
||||
### Build and Start Services
|
||||
### Using Pre-built Images (Fastest)
|
||||
|
||||
```bash
|
||||
# Build images
|
||||
# Pull latest images from GitHub Container Registry
|
||||
docker pull ghcr.io/the-luap/picpeak/backend:latest
|
||||
docker pull ghcr.io/the-luap/picpeak/frontend:latest
|
||||
|
||||
# Start services using production compose file
|
||||
docker compose -f docker-compose.production.yml up -d
|
||||
|
||||
# View running containers
|
||||
docker compose ps
|
||||
```
|
||||
|
||||
### Building from Source (For Customization)
|
||||
|
||||
```bash
|
||||
# Build images locally
|
||||
docker compose build
|
||||
|
||||
# Or build with no cache for clean build
|
||||
docker compose build --no-cache
|
||||
|
||||
# Start all services
|
||||
docker compose up -d
|
||||
|
||||
@@ -161,8 +305,8 @@ docker compose ps
|
||||
### Access Points
|
||||
|
||||
By default, services are exposed on:
|
||||
- Frontend: http://localhost:3000
|
||||
- Backend/API: http://localhost:3001
|
||||
- Frontend (UI + Admin): http://localhost:3000 (admin at `/admin`)
|
||||
- Backend/API: http://localhost:3001 (API only; no UI routes)
|
||||
- PostgreSQL: localhost:5432 (if needed)
|
||||
- Redis: localhost:6379 (if needed)
|
||||
|
||||
@@ -233,7 +377,11 @@ After deployment, you must complete the first login process which includes manda
|
||||
|
||||
### Step 2: Access Admin Panel
|
||||
|
||||
1. Navigate to your admin panel URL (e.g., `http://your-domain.com:3001/admin` or `https://your-domain.com/admin`)
|
||||
1. Navigate to your frontend domain and open the admin section:
|
||||
- `http://your-domain.com/admin` (behind reverse proxy)
|
||||
- `http://localhost:3000/admin` (Docker local)
|
||||
|
||||
The backend at `:3001` serves API only and does not serve the admin UI.
|
||||
2. Login using:
|
||||
- **Email**: `admin@example.com` (or your custom admin email)
|
||||
- **Password**: The auto-generated password from the logs
|
||||
@@ -307,7 +455,16 @@ server {
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
}
|
||||
|
||||
# Backend API
|
||||
# Frontend (serves UI and /admin/*)
|
||||
location / {
|
||||
proxy_pass http://localhost:3000;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
}
|
||||
|
||||
# Backend API and protected resources
|
||||
location /api {
|
||||
proxy_pass http://localhost:3001;
|
||||
proxy_set_header Host $host;
|
||||
@@ -315,21 +472,11 @@ server {
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
}
|
||||
|
||||
# Protected photos and uploads
|
||||
location ~ ^/(photos|thumbnails|uploads) {
|
||||
proxy_pass http://localhost:3001;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
}
|
||||
|
||||
# Admin routes
|
||||
location /admin {
|
||||
proxy_pass http://localhost:3001;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
}
|
||||
}
|
||||
@@ -446,14 +593,50 @@ The application includes a built-in backup service. Configure it in the admin pa
|
||||
|
||||
### Updates
|
||||
|
||||
#### Method 1: Using Pre-built Images (Recommended)
|
||||
|
||||
```bash
|
||||
# Pull latest changes (for configuration updates)
|
||||
git pull
|
||||
|
||||
# Pull latest images from GitHub Container Registry
|
||||
docker compose -f docker-compose.production.yml pull
|
||||
|
||||
# Restart with new images
|
||||
docker compose -f docker-compose.production.yml down
|
||||
docker compose -f docker-compose.production.yml up -d
|
||||
|
||||
# Verify services are healthy
|
||||
docker compose -f docker-compose.production.yml ps
|
||||
```
|
||||
|
||||
#### Method 2: Building from Source
|
||||
|
||||
```bash
|
||||
# Pull latest changes
|
||||
git pull
|
||||
|
||||
# Rebuild and restart
|
||||
docker compose down
|
||||
docker compose build
|
||||
docker compose build --no-cache
|
||||
docker compose up -d
|
||||
|
||||
# Verify services are healthy
|
||||
docker compose ps
|
||||
```
|
||||
|
||||
#### Specific Version Updates
|
||||
|
||||
To use a specific version of the images:
|
||||
|
||||
```bash
|
||||
# Edit docker-compose.production.yml to specify version tags
|
||||
# Change: ghcr.io/the-luap/picpeak/backend:latest
|
||||
# To: ghcr.io/the-luap/picpeak/backend:v1.0.0
|
||||
|
||||
# Then pull and restart
|
||||
docker compose -f docker-compose.production.yml pull
|
||||
docker compose -f docker-compose.production.yml up -d
|
||||
```
|
||||
|
||||
### Database Migrations
|
||||
@@ -614,4 +797,4 @@ For issues and questions:
|
||||
- Error messages
|
||||
- Log output
|
||||
- Environment details (without secrets)
|
||||
- Steps to reproduce
|
||||
- Steps to reproduce
|
||||
|
||||
@@ -28,6 +28,7 @@ Unlike expensive SaaS solutions, PicPeak gives you:
|
||||
|
||||
### For Photographers
|
||||
- 📁 **Drag & Drop Upload** - Simply drop photos into folders
|
||||
- 🔗 **External Media (Reference Mode)** - Browse and import from a read‑only external folder library without copying originals
|
||||
- ⏰ **Auto-Expiring Galleries** - Set expiration dates (default: 30 days)
|
||||
- 🔐 **Password Protection** - Secure client galleries
|
||||
- 📧 **Automated Emails** - Creation confirmations and expiration warnings
|
||||
@@ -45,6 +46,7 @@ Unlike expensive SaaS solutions, PicPeak gives you:
|
||||
### Technical Excellence
|
||||
- 🐳 **Docker Ready** - Deploy in minutes
|
||||
- 🔄 **Auto-Processing** - Automatic thumbnail generation
|
||||
- 🗂️ **Reference Library Support** - Point PicPeak at `EXTERNAL_MEDIA_ROOT` to reference existing originals, index quickly, and generate thumbnails on demand
|
||||
- 💾 **Smart Storage** - Automatic archiving of expired galleries
|
||||
- 🛡️ **Security First** - JWT auth, rate limiting, CORS protection
|
||||
- 📈 **Scalable** - From small studios to large agencies
|
||||
@@ -70,9 +72,18 @@ docker-compose up -d
|
||||
# Access at http://localhost:3005
|
||||
```
|
||||
|
||||
Note on Docker file permissions (PUID/PGID)
|
||||
- When using bind mounts (e.g., `./storage`, `./data`, `./logs`, `./events`), ensure the container user can write to these host folders. The backend runs as a non‑root user by default.
|
||||
- Set `PUID` and `PGID` in your `.env` to match your host user’s UID/GID (run `id -u` and `id -g` on the host). Compose maps the container user to these values.
|
||||
- Example in `.env`:
|
||||
- `PUID=1000`
|
||||
- `PGID=1000`
|
||||
- Without this, creating events, uploads, thumbnails, or logs can fail with “Permission denied”.
|
||||
|
||||
## 📖 Documentation
|
||||
|
||||
- 📘 [**Deployment Guide**](DEPLOYMENT_GUIDE.md) - Detailed installation instructions
|
||||
- Includes the new [External Media Library](DEPLOYMENT_GUIDE.md#external-media-library) reference mode
|
||||
- 🤝 [**Contributing**](CONTRIBUTING.md) - How to contribute
|
||||
- 📜 [**License**](LICENSE) - MIT License
|
||||
- 🔒 [**Security**](SECURITY.md) - Security policies
|
||||
@@ -192,11 +203,13 @@ These features are currently in beta testing and may have limited functionality
|
||||
| Feature | Description | Priority | Status |
|
||||
|---------|-------------|----------|---------|
|
||||
| **Backup & Restore** | Comprehensive backup system with S3/MinIO support, automated scheduling, and safe restore functionality | High | ✅ Implemented |
|
||||
| **External Media Library (Reference Mode)** | Use an external folder library as a read‑only source with import and on‑demand thumbnail generation | High | ✅ Implemented |
|
||||
| **Gallery Templates** | Additional gallery layouts and themes (masonry, slideshow, story-style) for different event types | Medium | 🔄 Open |
|
||||
| **Face Recognition** | AI-powered face detection to help guests find their photos and create automatic person-based albums | Low | 🔄 Open |
|
||||
| **Gallery Feedback** | Allow guests to like, rate, and comment on photos with admin notifications and moderation | Medium | ✅ Implemented (not tested) |
|
||||
| **Gallery Feedback** | Allow guests to like, rate, and comment on photos with admin notifications and moderation | Medium | ✅ Implemented |
|
||||
| **Video Support** | Upload and display videos alongside photos in galleries with streaming support | Low | 🔄 Open |
|
||||
| **Multiple Administrators** | Support for multiple admin accounts with role-based permissions and activity tracking | Low | 📋 Planned |
|
||||
| **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
|
||||
|
||||
@@ -233,4 +246,4 @@ PicPeak is released under the [MIT License](LICENSE). Use it freely for personal
|
||||
<a href="https://github.com/the-luap/picpeak">GitHub</a> •
|
||||
<a href="DEPLOYMENT_GUIDE.md">Documentation</a> •
|
||||
<a href="https://github.com/the-luap/picpeak/issues">Support</a>
|
||||
</p>
|
||||
</p>
|
||||
|
||||
@@ -8,7 +8,7 @@ This guide provides easy installation instructions for PicPeak on Linux servers
|
||||
|
||||
```bash
|
||||
# Download and run the unified setup script
|
||||
curl -fsSL https://raw.githubusercontent.com/yourusername/wedding-photo-sharing/main/scripts/setup.sh -o setup.sh && \
|
||||
curl -fsSL https://raw.githubusercontent.com/the-luap/picpeak/main/scripts/setup.sh -o setup.sh && \
|
||||
chmod +x setup.sh && \
|
||||
sudo ./setup.sh
|
||||
```
|
||||
@@ -166,8 +166,10 @@ sudo ./setup.sh --native --unattended \
|
||||
## 🌐 Access Methods
|
||||
|
||||
### Direct Access (Simplest)
|
||||
- **Docker**: `http://your-server:3000` (frontend), `http://your-server:3001/admin` (admin)
|
||||
- **Native**: `http://your-server:3001/admin` (admin panel)
|
||||
- Docker: `http://your-server:3000` (frontend and admin at `/admin`)
|
||||
- Backend/API: `http://your-server:3001` (API only; no UI routes)
|
||||
|
||||
For native installs, serve the built frontend (e.g., with nginx or Caddy) and access the admin at `/admin` on the frontend domain.
|
||||
|
||||
### With Domain & HTTPS
|
||||
If configured during setup:
|
||||
@@ -175,9 +177,23 @@ If configured during setup:
|
||||
- `https://your-domain.com/admin` - Admin panel
|
||||
|
||||
### Behind Existing Proxy
|
||||
Add to your Nginx/Apache configuration:
|
||||
Add to your Nginx/Apache configuration (split frontend vs backend):
|
||||
```nginx
|
||||
# Frontend (UI + /admin/*)
|
||||
location / {
|
||||
proxy_pass http://localhost:3000;
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Upgrade $http_upgrade;
|
||||
proxy_set_header Connection 'upgrade';
|
||||
proxy_set_header Host $host;
|
||||
proxy_cache_bypass $http_upgrade;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
}
|
||||
|
||||
# Backend API and protected resources
|
||||
location /api {
|
||||
proxy_pass http://localhost:3001;
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Upgrade $http_upgrade;
|
||||
@@ -189,6 +205,14 @@ location / {
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
client_max_body_size 100M;
|
||||
}
|
||||
location ~ ^/(photos|thumbnails|uploads) {
|
||||
proxy_pass http://localhost:3001;
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
}
|
||||
```
|
||||
|
||||
## 📁 Managing Galleries
|
||||
@@ -268,6 +292,7 @@ sudo systemctl stop picpeak-backend picpeak-workers
|
||||
sudo systemctl restart picpeak-backend picpeak-workers
|
||||
|
||||
# Update PicPeak
|
||||
# (reruns migrations to pick up schema fixes for native installs)
|
||||
sudo ./setup.sh --update
|
||||
```
|
||||
|
||||
@@ -281,9 +306,9 @@ docker compose restart
|
||||
```
|
||||
|
||||
### Native Configuration
|
||||
Edit `/opt/picpeak/backend/.env`:
|
||||
Edit `/opt/picpeak/app/backend/.env`:
|
||||
```bash
|
||||
sudo nano /opt/picpeak/backend/.env
|
||||
sudo nano /opt/picpeak/app/backend/.env
|
||||
sudo systemctl restart picpeak-backend
|
||||
```
|
||||
|
||||
@@ -345,7 +370,7 @@ tar -czf photos-backup.tar.gz storage/events/
|
||||
#### Native:
|
||||
```bash
|
||||
# Database backup
|
||||
sudo cp /opt/picpeak/backend/database.sqlite /backup/database-$(date +%Y%m%d).sqlite
|
||||
sudo cp /opt/picpeak/app/backend/data/photo_sharing.db /backup/database-$(date +%Y%m%d).sqlite
|
||||
|
||||
# Photos backup
|
||||
sudo tar -czf /backup/photos-$(date +%Y%m%d).tar.gz /opt/picpeak/events/
|
||||
@@ -422,7 +447,7 @@ ls -la ~/picpeak/storage/events/
|
||||
docker exec picpeak-backend node scripts/reset-admin-password.js
|
||||
|
||||
# Native
|
||||
cd /opt/picpeak/backend
|
||||
cd /opt/picpeak/app/backend
|
||||
sudo -u picpeak node scripts/reset-admin-password.js
|
||||
```
|
||||
|
||||
@@ -434,11 +459,11 @@ sudo -u picpeak node scripts/reset-admin-password.js
|
||||
- Installation: `/tmp/picpeak-setup-*.log`
|
||||
|
||||
2. **Documentation:**
|
||||
- [Full Documentation](https://github.com/yourusername/wedding-photo-sharing)
|
||||
- [Full Documentation](https://github.com/the-luap/picpeak)
|
||||
- [Deployment Guide](./DEPLOYMENT_GUIDE.md)
|
||||
|
||||
3. **Support:**
|
||||
- [GitHub Issues](https://github.com/yourusername/wedding-photo-sharing/issues)
|
||||
- [GitHub Issues](https://github.com/the-luap/picpeak/issues)
|
||||
- Include: Error messages, system info (`uname -a`), installation method
|
||||
|
||||
## 🔒 Security Best Practices
|
||||
@@ -474,7 +499,7 @@ services:
|
||||
### Native Optimization
|
||||
```bash
|
||||
# Increase Node.js memory
|
||||
echo "NODE_OPTIONS=--max-old-space-size=2048" >> /opt/picpeak/backend/.env
|
||||
echo "NODE_OPTIONS=--max-old-space-size=2048" >> /opt/picpeak/app/backend/.env
|
||||
sudo systemctl restart picpeak-backend
|
||||
```
|
||||
|
||||
@@ -516,4 +541,4 @@ sudo ./setup.sh --native \
|
||||
|
||||
---
|
||||
|
||||
**PicPeak Setup v1.0** | [Documentation](https://github.com/yourusername/wedding-photo-sharing) | [Support](https://github.com/yourusername/wedding-photo-sharing/issues)
|
||||
**PicPeak Setup v1.0** | [Documentation](https://github.com/the-luap/picpeak) | [Support](https://github.com/the-luap/picpeak/issues)
|
||||
|
||||
@@ -1,7 +1,15 @@
|
||||
FROM node:18-alpine AS builder
|
||||
|
||||
# Add build argument for cache busting
|
||||
# Add build arguments
|
||||
ARG CACHEBUST=1
|
||||
ARG BUILD_DATE
|
||||
ARG VCS_REF
|
||||
ARG VERSION
|
||||
|
||||
# Add labels for GitHub Container Registry
|
||||
LABEL org.opencontainers.image.source="https://github.com/the-luap/picpeak"
|
||||
LABEL org.opencontainers.image.description="PicPeak Backend Service"
|
||||
LABEL org.opencontainers.image.licenses="MIT"
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
|
||||
@@ -26,29 +26,37 @@ const config = {
|
||||
|
||||
production: {
|
||||
client: process.env.DATABASE_CLIENT || 'pg',
|
||||
connection: {
|
||||
host: process.env.DB_HOST || 'db',
|
||||
port: process.env.DB_PORT || 5432,
|
||||
user: process.env.DB_USER || 'picpeak',
|
||||
password: process.env.DB_PASSWORD,
|
||||
database: process.env.DB_NAME || 'picpeak',
|
||||
ssl: process.env.DB_SSL === 'true' ? { rejectUnauthorized: false } : false,
|
||||
// Connection stability settings
|
||||
connectionTimeoutMillis: 30000,
|
||||
idleTimeoutMillis: 30000,
|
||||
keepAlive: true,
|
||||
keepAliveInitialDelayMillis: 0
|
||||
},
|
||||
pool: {
|
||||
min: 5,
|
||||
max: 25,
|
||||
acquireTimeoutMillis: 60000,
|
||||
createTimeoutMillis: 60000,
|
||||
idleTimeoutMillis: 30000,
|
||||
reapIntervalMillis: 1000,
|
||||
createRetryIntervalMillis: 200,
|
||||
propagateCreateError: false
|
||||
},
|
||||
// Support both Postgres and SQLite in production based on DATABASE_CLIENT
|
||||
connection: (process.env.DATABASE_CLIENT || 'pg') === 'pg'
|
||||
? {
|
||||
host: process.env.DB_HOST || 'db',
|
||||
port: process.env.DB_PORT || 5432,
|
||||
user: process.env.DB_USER || 'picpeak',
|
||||
password: process.env.DB_PASSWORD,
|
||||
database: process.env.DB_NAME || 'picpeak',
|
||||
ssl: process.env.DB_SSL === 'true' ? { rejectUnauthorized: false } : false,
|
||||
// Connection stability settings
|
||||
connectionTimeoutMillis: 30000,
|
||||
idleTimeoutMillis: 30000,
|
||||
keepAlive: true,
|
||||
keepAliveInitialDelayMillis: 0
|
||||
}
|
||||
: {
|
||||
filename: path.join(__dirname, process.env.DATABASE_PATH || './data/photo_sharing.db')
|
||||
},
|
||||
useNullAsDefault: (process.env.DATABASE_CLIENT || 'pg') !== 'pg',
|
||||
pool: (process.env.DATABASE_CLIENT || 'pg') === 'pg'
|
||||
? {
|
||||
min: 5,
|
||||
max: 25,
|
||||
acquireTimeoutMillis: 60000,
|
||||
createTimeoutMillis: 60000,
|
||||
idleTimeoutMillis: 30000,
|
||||
reapIntervalMillis: 1000,
|
||||
createRetryIntervalMillis: 200,
|
||||
propagateCreateError: false
|
||||
}
|
||||
: undefined,
|
||||
migrations: {
|
||||
directory: './migrations'
|
||||
},
|
||||
@@ -56,4 +64,4 @@ const config = {
|
||||
}
|
||||
};
|
||||
|
||||
module.exports = config[process.env.NODE_ENV || 'development'];
|
||||
module.exports = config[process.env.NODE_ENV || 'development'];
|
||||
|
||||
@@ -0,0 +1,89 @@
|
||||
exports.up = async function(knex) {
|
||||
console.log('Running migration: 041_add_logo_customization_settings');
|
||||
|
||||
// Add default logo customization settings
|
||||
const logoSettings = [
|
||||
{
|
||||
setting_key: 'branding_logo_size',
|
||||
setting_value: JSON.stringify('medium'),
|
||||
setting_type: 'branding',
|
||||
description: 'Logo size: small, medium, large, xlarge, or custom',
|
||||
created_at: new Date(),
|
||||
updated_at: new Date()
|
||||
},
|
||||
{
|
||||
setting_key: 'branding_logo_max_height',
|
||||
setting_value: JSON.stringify(48),
|
||||
setting_type: 'branding',
|
||||
description: 'Maximum logo height in pixels (used when size is custom)',
|
||||
created_at: new Date(),
|
||||
updated_at: new Date()
|
||||
},
|
||||
{
|
||||
setting_key: 'branding_logo_position',
|
||||
setting_value: JSON.stringify('left'),
|
||||
setting_type: 'branding',
|
||||
description: 'Logo position in header: left, center, right',
|
||||
created_at: new Date(),
|
||||
updated_at: new Date()
|
||||
},
|
||||
{
|
||||
setting_key: 'branding_logo_display_header',
|
||||
setting_value: JSON.stringify(true),
|
||||
setting_type: 'branding',
|
||||
description: 'Show logo in gallery header',
|
||||
created_at: new Date(),
|
||||
updated_at: new Date()
|
||||
},
|
||||
{
|
||||
setting_key: 'branding_logo_display_hero',
|
||||
setting_value: JSON.stringify(true),
|
||||
setting_type: 'branding',
|
||||
description: 'Show logo in hero section (for non-grid layouts)',
|
||||
created_at: new Date(),
|
||||
updated_at: new Date()
|
||||
},
|
||||
{
|
||||
setting_key: 'branding_logo_display_mode',
|
||||
setting_value: JSON.stringify('logo_and_text'),
|
||||
setting_type: 'branding',
|
||||
description: 'Display mode: logo_only, text_only, logo_and_text',
|
||||
created_at: new Date(),
|
||||
updated_at: new Date()
|
||||
}
|
||||
];
|
||||
|
||||
// Insert settings that don't already exist
|
||||
for (const setting of logoSettings) {
|
||||
const exists = await knex('app_settings')
|
||||
.where('setting_key', setting.setting_key)
|
||||
.first();
|
||||
|
||||
if (!exists) {
|
||||
await knex('app_settings').insert(setting);
|
||||
console.log(`Added setting: ${setting.setting_key}`);
|
||||
} else {
|
||||
console.log(`Setting already exists: ${setting.setting_key}`);
|
||||
}
|
||||
}
|
||||
|
||||
console.log('Migration 041_add_logo_customization_settings completed');
|
||||
};
|
||||
|
||||
exports.down = async function(knex) {
|
||||
console.log('Rolling back migration: 041_add_logo_customization_settings');
|
||||
|
||||
// Remove the logo customization settings
|
||||
await knex('app_settings')
|
||||
.whereIn('setting_key', [
|
||||
'branding_logo_size',
|
||||
'branding_logo_max_height',
|
||||
'branding_logo_position',
|
||||
'branding_logo_display_header',
|
||||
'branding_logo_display_hero',
|
||||
'branding_logo_display_mode'
|
||||
])
|
||||
.del();
|
||||
|
||||
console.log('Rollback of 041_add_logo_customization_settings completed');
|
||||
};
|
||||
@@ -0,0 +1,54 @@
|
||||
/**
|
||||
* Migration 041: Add external media reference support
|
||||
* - events.source_mode: 'managed' | 'reference'
|
||||
* - events.external_path: relative path under external media root
|
||||
* - photos.source_origin: 'managed' | 'external'
|
||||
* - photos.external_relpath: relative path within event.external_path
|
||||
*/
|
||||
|
||||
const { addColumnIfNotExists } = require('../helpers');
|
||||
|
||||
exports.up = async function(knex) {
|
||||
console.log('Running migration: 041_add_external_media');
|
||||
|
||||
// events.source_mode (default 'managed')
|
||||
await addColumnIfNotExists(knex, 'events', 'source_mode', (table) => {
|
||||
table.string('source_mode').notNullable().defaultTo('managed');
|
||||
});
|
||||
|
||||
// events.external_path (nullable)
|
||||
await addColumnIfNotExists(knex, 'events', 'external_path', (table) => {
|
||||
table.text('external_path');
|
||||
});
|
||||
|
||||
// photos.source_origin (default 'managed')
|
||||
await addColumnIfNotExists(knex, 'photos', 'source_origin', (table) => {
|
||||
table.string('source_origin').notNullable().defaultTo('managed');
|
||||
});
|
||||
|
||||
// photos.external_relpath (nullable)
|
||||
await addColumnIfNotExists(knex, 'photos', 'external_relpath', (table) => {
|
||||
table.text('external_relpath');
|
||||
});
|
||||
|
||||
// Helpful index for queries
|
||||
try {
|
||||
if (knex.client.config.client === 'pg') {
|
||||
await knex.raw("CREATE INDEX IF NOT EXISTS photos_event_source_idx ON photos (event_id, source_origin)");
|
||||
} else {
|
||||
await knex.schema.alterTable('photos', (table) => {
|
||||
table.index(['event_id', 'source_origin'], 'photos_event_source_idx');
|
||||
});
|
||||
}
|
||||
} catch (e) {
|
||||
console.log('Index creation skipped or failed (may already exist):', e.message);
|
||||
}
|
||||
|
||||
console.log('Migration 041_add_external_media completed');
|
||||
};
|
||||
|
||||
exports.down = async function(knex) {
|
||||
console.log('Rollback: 041_add_external_media');
|
||||
// Keep columns (safe rollback not removing data). Intentionally no-op.
|
||||
};
|
||||
|
||||
@@ -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
|
||||
};
|
||||
@@ -1,21 +1,22 @@
|
||||
{
|
||||
"name": "picpeak-backend",
|
||||
"version": "1.0.103",
|
||||
"version": "1.0.129",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "picpeak-backend",
|
||||
"version": "1.0.103",
|
||||
"version": "1.0.129",
|
||||
"dependencies": {
|
||||
"@aws-sdk/client-s3": "^3.850.0",
|
||||
"@aws-sdk/lib-storage": "^3.850.0",
|
||||
"@aws-sdk/s3-request-presigner": "^3.850.0",
|
||||
"adm-zip": "^0.5.16",
|
||||
"archiver": "^5.3.1",
|
||||
"axios": "^1.10.0",
|
||||
"axios": "^1.12.2",
|
||||
"bcrypt": "6.0.0",
|
||||
"chokidar": "4.0.3",
|
||||
"cookie-parser": "^1.4.7",
|
||||
"cors": "^2.8.5",
|
||||
"dotenv": "^16.0.3",
|
||||
"express": "^4.18.2",
|
||||
@@ -3889,13 +3890,13 @@
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/axios": {
|
||||
"version": "1.10.0",
|
||||
"resolved": "https://registry.npmjs.org/axios/-/axios-1.10.0.tgz",
|
||||
"integrity": "sha512-/1xYAC4MP/HEG+3duIhFr4ZQXR4sQXOIe+o6sdqzeykGLx6Upp/1p8MHqhINOvGeP7xyNHe7tsiJByc4SSVUxw==",
|
||||
"version": "1.12.2",
|
||||
"resolved": "https://registry.npmjs.org/axios/-/axios-1.12.2.tgz",
|
||||
"integrity": "sha512-vMJzPewAlRyOgxV2dU0Cuz2O8zzzx9VYtbJOaBgXFeLc4IV/Eg50n4LowmehOOR61S8ZMpc2K5Sa7g6A4jfkUw==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"follow-redirects": "^1.15.6",
|
||||
"form-data": "^4.0.0",
|
||||
"form-data": "^4.0.4",
|
||||
"proxy-from-env": "^1.1.0"
|
||||
}
|
||||
},
|
||||
@@ -4727,6 +4728,28 @@
|
||||
"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": {
|
||||
"version": "1.0.6",
|
||||
"resolved": "https://registry.npmjs.org/cookie-signature/-/cookie-signature-1.0.6.tgz",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "picpeak-backend",
|
||||
"version": "1.0.103",
|
||||
"version": "1.0.129",
|
||||
"description": "Backend for PicPeak event photo sharing platform",
|
||||
"main": "server.js",
|
||||
"scripts": {
|
||||
@@ -17,9 +17,10 @@
|
||||
"@aws-sdk/s3-request-presigner": "^3.850.0",
|
||||
"adm-zip": "^0.5.16",
|
||||
"archiver": "^5.3.1",
|
||||
"axios": "^1.10.0",
|
||||
"axios": "^1.12.2",
|
||||
"bcrypt": "6.0.0",
|
||||
"chokidar": "4.0.3",
|
||||
"cookie-parser": "^1.4.7",
|
||||
"cors": "^2.8.5",
|
||||
"dotenv": "^16.0.3",
|
||||
"express": "^4.18.2",
|
||||
|
||||
@@ -36,4 +36,4 @@ async function setAdminPassword() {
|
||||
}
|
||||
}
|
||||
|
||||
setAdminPassword();
|
||||
setAdminPassword();
|
||||
|
||||
@@ -12,6 +12,7 @@ logger.info('Server starting up', {
|
||||
timestamp: new Date().toISOString()
|
||||
});
|
||||
|
||||
const fs = require('fs');
|
||||
const express = require('express');
|
||||
const helmet = require('helmet');
|
||||
const cors = require('cors');
|
||||
@@ -25,6 +26,11 @@ const { startScheduledBackups } = require('./src/services/databaseBackup');
|
||||
const { maintenanceMiddleware } = require('./src/middleware/maintenance');
|
||||
const { sessionTimeoutMiddleware } = require('./src/middleware/sessionTimeout');
|
||||
const { createRateLimiter, createAuthRateLimiter } = require('./src/services/rateLimitService');
|
||||
const cookieParser = require('cookie-parser');
|
||||
const {
|
||||
getAdminTokenFromRequest,
|
||||
getGalleryTokenFromRequest,
|
||||
} = require('./src/utils/tokenUtils');
|
||||
|
||||
// Import routes
|
||||
const authRoutes = require('./src/routes/auth-enhanced');
|
||||
@@ -42,25 +48,59 @@ const PORT = process.env.PORT || 3000;
|
||||
app.set('trust proxy', 'loopback, linklocal, uniquelocal');
|
||||
|
||||
// Security middleware with custom CSP
|
||||
// In native HTTP installs, do NOT force HTTPS for subresources.
|
||||
const enableHsts = process.env.ENABLE_HSTS === 'true';
|
||||
const cspDirectives = {
|
||||
defaultSrc: ["'self'"],
|
||||
scriptSrc: [
|
||||
"'self'",
|
||||
'https://www.google.com',
|
||||
'https://www.gstatic.com'
|
||||
],
|
||||
styleSrc: ["'self'", "'unsafe-inline'", "https:"], // Required for styled components
|
||||
imgSrc: ["'self'", "data:", "https:", "blob:"], // Allow data URLs and external images
|
||||
connectSrc: ["'self'", 'https://www.google.com', 'https://www.gstatic.com'], // API connections
|
||||
fontSrc: ["'self'", "https:", "data:"], // Web fonts
|
||||
objectSrc: ["'none'"], // Disable plugins
|
||||
mediaSrc: ["'self'"], // Audio/video
|
||||
frameSrc: ["'self'", 'https://www.google.com'],
|
||||
};
|
||||
// Only upgrade insecure requests when HSTS explicitly enabled (HTTPS deployment)
|
||||
if (enableHsts) {
|
||||
// In helmet, an empty array enables the directive
|
||||
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({
|
||||
contentSecurityPolicy: {
|
||||
directives: {
|
||||
defaultSrc: ["'self'"],
|
||||
scriptSrc: ["'self'", "'unsafe-inline'"], // Required for React
|
||||
styleSrc: ["'self'", "'unsafe-inline'", "https:"], // Required for styled components
|
||||
imgSrc: ["'self'", "data:", "https:", "blob:"], // Allow data URLs and external images
|
||||
connectSrc: ["'self'"], // API connections
|
||||
fontSrc: ["'self'", "https:", "data:"], // Web fonts
|
||||
objectSrc: ["'none'"], // Disable plugins
|
||||
mediaSrc: ["'self'"], // Audio/video
|
||||
frameSrc: ["'none'"], // Disable iframes
|
||||
},
|
||||
// Avoid helmet adding defaults like upgrade-insecure-requests when not desired
|
||||
useDefaults: false,
|
||||
directives: cspDirectives,
|
||||
},
|
||||
hsts: {
|
||||
hsts: enableHsts ? {
|
||||
maxAge: 31536000, // 1 year
|
||||
includeSubDomains: true,
|
||||
preload: true
|
||||
},
|
||||
} : false,
|
||||
permittedCrossDomainPolicies: false,
|
||||
referrerPolicy: { policy: "strict-origin-when-cross-origin" }
|
||||
}));
|
||||
@@ -72,14 +112,14 @@ app.use((req, res, next) => {
|
||||
next();
|
||||
});
|
||||
|
||||
// CORS configuration
|
||||
// CORS configuration (apply only to API routes)
|
||||
const corsOptions = {
|
||||
origin: function (origin, callback) {
|
||||
const allowedOrigins = [
|
||||
process.env.FRONTEND_URL || 'http://localhost:3005',
|
||||
process.env.ADMIN_URL || 'http://localhost:3005'
|
||||
];
|
||||
|
||||
|
||||
// In development, also allow localhost origins
|
||||
if (process.env.NODE_ENV === 'development') {
|
||||
allowedOrigins.push(
|
||||
@@ -89,18 +129,22 @@ const corsOptions = {
|
||||
'http://localhost:3000' // Direct backend access
|
||||
);
|
||||
}
|
||||
|
||||
// Allow requests with no origin (like mobile apps or curl)
|
||||
|
||||
// Allow requests with no origin (like curl) and allow-listed origins
|
||||
if (!origin || allowedOrigins.indexOf(origin) !== -1) {
|
||||
callback(null, true);
|
||||
} else {
|
||||
callback(new Error('Not allowed by CORS'));
|
||||
// Do not error globally; just omit CORS headers on disallowed origins
|
||||
callback(null, false);
|
||||
}
|
||||
},
|
||||
credentials: true
|
||||
};
|
||||
|
||||
app.use(cors(corsOptions));
|
||||
// Only attach CORS to API endpoints, not static assets
|
||||
app.use('/api', cors(corsOptions));
|
||||
// Handle preflight explicitly for API paths
|
||||
app.options('/api/*', cors(corsOptions));
|
||||
|
||||
// Initialize rate limiters (they will be created dynamically)
|
||||
let generalRateLimiter;
|
||||
@@ -124,6 +168,22 @@ async function initializeRateLimiters() {
|
||||
app.use(express.json({ limit: '100mb' }));
|
||||
app.use(express.urlencoded({ extended: true, limit: '100mb' }));
|
||||
|
||||
// Request logging for API routes (with timestamps)
|
||||
const apiRequestLogger = (req, res, next) => {
|
||||
try {
|
||||
const started = Date.now();
|
||||
const ts = new Date().toISOString();
|
||||
logger.info(`[${ts}] ${req.method} ${req.originalUrl}`);
|
||||
res.on('finish', () => {
|
||||
const ms = Date.now() - started;
|
||||
const tsDone = new Date().toISOString();
|
||||
logger.info(`[${tsDone}] ${req.method} ${req.originalUrl} -> ${res.statusCode} (${ms}ms)`);
|
||||
});
|
||||
} catch (_) {}
|
||||
next();
|
||||
};
|
||||
app.use('/api', apiRequestLogger);
|
||||
|
||||
// Maintenance mode middleware - add after body parsing but before routes
|
||||
app.use(maintenanceMiddleware);
|
||||
|
||||
@@ -143,6 +203,7 @@ const secureStatic = require('./src/middleware/secureStatic');
|
||||
|
||||
// Get storage path from environment or use default
|
||||
const storagePath = process.env.STORAGE_PATH || path.join(__dirname, '../storage');
|
||||
process.env.EXTERNAL_MEDIA_ROOT = process.env.EXTERNAL_MEDIA_ROOT || '/external-media';
|
||||
|
||||
// Static file serving for photos (protected)
|
||||
app.use('/photos', require('./src/middleware/photoAuth'), setCorsHeaders, secureStatic(path.join(storagePath, 'events/active')));
|
||||
@@ -199,7 +260,8 @@ app.get('/health', async (req, res) => {
|
||||
|
||||
// Routes
|
||||
app.use('/api/auth', authRoutes);
|
||||
app.use('/api/events', eventRoutes);
|
||||
app.use('/api/events', eventRoutes);
|
||||
app.use('/api/admin/external-media', require('./src/routes/adminExternalMedia'));
|
||||
// Gallery routes - main routes first, then feedback routes
|
||||
app.use('/api/gallery', galleryRoutes);
|
||||
app.use('/api/gallery', require('./src/routes/galleryFeedback'));
|
||||
@@ -217,6 +279,27 @@ app.use('/api/public', require('./src/routes/publicCMS'));
|
||||
app.use('/api/images', require('./src/routes/protectedImages'));
|
||||
app.use('/api/secure-images', secureImagesRoutes);
|
||||
|
||||
// Optional: Serve built frontend (native installs)
|
||||
try {
|
||||
const serveFrontendEnv = process.env.SERVE_FRONTEND; // 'true' | 'false' | undefined
|
||||
const frontendDir = process.env.FRONTEND_DIR || path.join(__dirname, '../frontend/dist');
|
||||
const indexPath = path.join(frontendDir, 'index.html');
|
||||
// Auto-serve when dist exists unless explicitly disabled
|
||||
const shouldServe = (serveFrontendEnv === 'true') || ((serveFrontendEnv === undefined || serveFrontendEnv === 'auto') && fs.existsSync(indexPath));
|
||||
if (shouldServe) {
|
||||
logger.info(`Serving frontend from ${frontendDir}`);
|
||||
app.use(express.static(frontendDir));
|
||||
// SPA fallback for non-API routes
|
||||
app.get([ '/', '/admin', '/admin/*', '/gallery/*' ], (req, res) => {
|
||||
res.sendFile(indexPath);
|
||||
});
|
||||
} else {
|
||||
logger.info('Frontend static serving disabled or dist not found', { serveFrontendEnv, frontendDir });
|
||||
}
|
||||
} catch (e) {
|
||||
logger.warn('Failed to enable frontend static serving', { error: e.message });
|
||||
}
|
||||
|
||||
// Error handling middleware
|
||||
app.use((err, req, res, next) => {
|
||||
console.error('EXPRESS ERROR HANDLER:', err);
|
||||
|
||||
@@ -1,7 +1,28 @@
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
const knex = require('knex');
|
||||
const knexConfig = require('../../knexfile');
|
||||
const logger = require('../utils/logger');
|
||||
|
||||
// Ensure SQLite directory exists when using file-based DB (native installs)
|
||||
try {
|
||||
const isPostgres = knexConfig && knexConfig.client === 'pg';
|
||||
if (!isPostgres && knexConfig && knexConfig.connection) {
|
||||
const filename = typeof knexConfig.connection === 'object'
|
||||
? knexConfig.connection.filename
|
||||
: (typeof knexConfig.connection === 'string' ? knexConfig.connection : null);
|
||||
if (filename && typeof filename === 'string') {
|
||||
const dir = path.dirname(filename);
|
||||
if (dir && dir !== '.') {
|
||||
fs.mkdirSync(dir, { recursive: true });
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
// Non-fatal: log and continue; SQLite will fail later if still missing
|
||||
try { logger.warn('SQLite directory ensure failed', { error: e.message }); } catch (_) {}
|
||||
}
|
||||
|
||||
// Create database connection with built-in retry logic
|
||||
const db = knex(knexConfig);
|
||||
|
||||
@@ -54,6 +75,13 @@ async function initializeDatabase() {
|
||||
table.boolean('is_archived').defaultTo(false);
|
||||
table.string('archive_path');
|
||||
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 {
|
||||
// Check if color_theme needs to be updated to TEXT type
|
||||
@@ -83,11 +111,39 @@ async function initializeDatabase() {
|
||||
archive_path TEXT,
|
||||
archived_at DATETIME,
|
||||
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('ALTER TABLE events_new RENAME TO events');
|
||||
} catch (error) {
|
||||
@@ -108,6 +164,7 @@ async function initializeDatabase() {
|
||||
table.string('thumbnail_path');
|
||||
table.string('type').notNullable(); // 'collage' or 'individual'
|
||||
table.integer('size_bytes');
|
||||
table.string('uploaded_by').defaultTo('admin');
|
||||
table.datetime('uploaded_at').defaultTo(db.fn.now());
|
||||
table.integer('view_count').defaultTo(0);
|
||||
table.integer('download_count').defaultTo(0);
|
||||
@@ -138,11 +195,24 @@ async function initializeDatabase() {
|
||||
table.string('email_type').notNullable(); // 'creation', 'warning', 'expiration', 'archive_complete'
|
||||
table.json('email_data');
|
||||
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('sent_at');
|
||||
table.text('error_message');
|
||||
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
|
||||
@@ -160,6 +230,7 @@ async function initializeDatabase() {
|
||||
table.datetime('updated_at').defaultTo(db.fn.now());
|
||||
table.datetime('last_login');
|
||||
table.string('last_login_ip');
|
||||
table.string('language', 2).defaultTo('en');
|
||||
});
|
||||
} else {
|
||||
// Check if updated_at column exists
|
||||
@@ -195,6 +266,13 @@ async function initializeDatabase() {
|
||||
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
|
||||
@@ -270,6 +348,18 @@ async function initializeDatabase() {
|
||||
table.datetime('updated_at').defaultTo(db.fn.now());
|
||||
});
|
||||
}
|
||||
|
||||
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
|
||||
const hasActivityLogsTable = await db.schema.hasTable('activity_logs');
|
||||
@@ -294,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
|
||||
@@ -312,4 +482,4 @@ async function logActivity(activityType, metadata = {}, eventId = null, actor =
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = { db, initializeDatabase, logActivity, withRetry };
|
||||
module.exports = { db, initializeDatabase, logActivity, withRetry };
|
||||
|
||||
@@ -3,13 +3,14 @@ const { db } = require('../database/db');
|
||||
const { formatBoolean } = require('../utils/dbCompat');
|
||||
const { isTokenRevoked } = require('../utils/tokenRevocation');
|
||||
const logger = require('../utils/logger');
|
||||
const { getAdminTokenFromRequest, getGalleryTokenFromRequest } = require('../utils/tokenUtils');
|
||||
|
||||
/**
|
||||
* Enhanced admin authentication middleware with revocation checking
|
||||
*/
|
||||
async function adminAuth(req, res, next) {
|
||||
try {
|
||||
const token = req.headers.authorization?.split(' ')[1];
|
||||
const token = getAdminTokenFromRequest(req);
|
||||
if (!token) {
|
||||
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) {
|
||||
try {
|
||||
const token = req.headers.authorization?.split(' ')[1];
|
||||
const slug = req.params?.slug || req.requestedSlug;
|
||||
const token = getGalleryTokenFromRequest(req, slug);
|
||||
if (!token) {
|
||||
return res.status(401).json({ error: 'No token provided' });
|
||||
}
|
||||
@@ -164,4 +166,4 @@ module.exports = {
|
||||
adminAuth,
|
||||
galleryAuth,
|
||||
// ... other exports
|
||||
};
|
||||
};
|
||||
|
||||
@@ -2,6 +2,7 @@ const jwt = require('jsonwebtoken');
|
||||
const { db } = require('../database/db');
|
||||
const { formatBoolean } = require('../utils/dbCompat');
|
||||
const logger = require('../utils/logger');
|
||||
const { getAdminTokenFromRequest, getGalleryTokenFromRequest } = require('../utils/tokenUtils');
|
||||
|
||||
/**
|
||||
* Enhanced admin authentication middleware
|
||||
@@ -9,7 +10,7 @@ const logger = require('../utils/logger');
|
||||
*/
|
||||
async function adminAuth(req, res, next) {
|
||||
try {
|
||||
const token = req.headers.authorization?.split(' ')[1];
|
||||
const token = getAdminTokenFromRequest(req);
|
||||
if (!token) {
|
||||
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) {
|
||||
try {
|
||||
const token = req.headers.authorization?.split(' ')[1];
|
||||
const slug = req.params?.slug || req.requestedSlug;
|
||||
const token = getGalleryTokenFromRequest(req, slug);
|
||||
if (!token) {
|
||||
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) {
|
||||
try {
|
||||
const token = req.headers.authorization?.split(' ')[1];
|
||||
const slug = req.params?.slug || req.requestedSlug;
|
||||
const token = getAdminTokenFromRequest(req) || getGalleryTokenFromRequest(req, slug);
|
||||
if (!token) {
|
||||
return res.status(401).json({ error: 'Authentication required' });
|
||||
}
|
||||
@@ -235,4 +238,4 @@ module.exports = {
|
||||
galleryAuth,
|
||||
photoAuth,
|
||||
verifyGalleryAccess
|
||||
};
|
||||
};
|
||||
|
||||
@@ -2,10 +2,11 @@ const jwt = require('jsonwebtoken');
|
||||
const { db } = require('../database/db');
|
||||
const { formatBoolean } = require('../utils/dbCompat');
|
||||
const logger = require('../utils/logger');
|
||||
const { getAdminTokenFromRequest } = require('../utils/tokenUtils');
|
||||
|
||||
async function adminAuth(req, res, next) {
|
||||
try {
|
||||
const token = req.headers.authorization?.split(' ')[1];
|
||||
const token = getAdminTokenFromRequest(req);
|
||||
if (!token) {
|
||||
const clientIp = req.headers['x-forwarded-for']?.split(',')[0]?.trim() ||
|
||||
req.headers['x-real-ip'] ||
|
||||
|
||||
@@ -1,17 +1,17 @@
|
||||
const jwt = require('jsonwebtoken');
|
||||
const { db, withRetry } = require('../database/db');
|
||||
const { formatBoolean } = require('../utils/dbCompat');
|
||||
const { getGalleryTokenFromRequest } = require('../utils/tokenUtils');
|
||||
|
||||
// Middleware to verify gallery access
|
||||
async function verifyGalleryAccess(req, res, next) {
|
||||
try {
|
||||
const authHeader = req.headers.authorization;
|
||||
const token = authHeader?.split(' ')[1];
|
||||
const requestedSlug = req.params.slug || req.requestedSlug;
|
||||
const token = getGalleryTokenFromRequest(req, requestedSlug);
|
||||
if (!token) {
|
||||
return res.status(401).json({ error: 'No token provided' });
|
||||
}
|
||||
|
||||
|
||||
// Try to verify with issuer first, fallback to no issuer for backward compatibility
|
||||
let decoded;
|
||||
try {
|
||||
@@ -29,8 +29,6 @@ async function verifyGalleryAccess(req, res, next) {
|
||||
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
|
||||
const requestedSlug = req.params.slug || req.requestedSlug;
|
||||
|
||||
let event;
|
||||
if (requestedSlug) {
|
||||
// Verify by slug and ensure it matches the token's event
|
||||
@@ -84,10 +82,10 @@ async function verifyGalleryAccess(req, res, next) {
|
||||
next();
|
||||
} catch (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' });
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
verifyGalleryAccess
|
||||
};
|
||||
};
|
||||
|
||||
@@ -2,6 +2,7 @@ const bcrypt = require('bcrypt');
|
||||
const jwt = require('jsonwebtoken');
|
||||
const { db } = require('../database/db');
|
||||
const { formatBoolean } = require('../utils/dbCompat');
|
||||
const { getGalleryTokenFromRequest } = require('../utils/tokenUtils');
|
||||
|
||||
async function photoAuth(req, res, next) {
|
||||
try {
|
||||
@@ -20,9 +21,9 @@ async function photoAuth(req, res, next) {
|
||||
}
|
||||
|
||||
// First check for JWT token (from gallery access)
|
||||
const authHeader = req.headers.authorization;
|
||||
if (authHeader && authHeader.startsWith('Bearer ')) {
|
||||
const token = authHeader.replace('Bearer ', '');
|
||||
const tokenFromRequest = getGalleryTokenFromRequest(req, eventSlug);
|
||||
if (tokenFromRequest) {
|
||||
const token = tokenFromRequest;
|
||||
try {
|
||||
// Try to verify with issuer first, fallback to no issuer for backward compatibility
|
||||
let decoded;
|
||||
@@ -88,7 +89,7 @@ async function photoAuth(req, res, next) {
|
||||
// Check for password header (legacy support)
|
||||
const password = req.headers['x-gallery-password'];
|
||||
|
||||
if (!password && !authHeader) {
|
||||
if (!password && !tokenFromRequest) {
|
||||
return res.status(401).json({ error: 'Authentication required' });
|
||||
}
|
||||
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
const jwt = require('jsonwebtoken');
|
||||
const { db } = require('../database/db');
|
||||
const { getAdminTokenFromRequest } = require('../utils/tokenUtils');
|
||||
|
||||
// In-memory session tracking (in production, use Redis)
|
||||
const sessions = new Map();
|
||||
@@ -67,11 +68,7 @@ async function getSessionTimeout() {
|
||||
|
||||
async function sessionTimeoutMiddleware(req, res, next) {
|
||||
// Skip for non-authenticated routes
|
||||
if (!req.headers.authorization) {
|
||||
return next();
|
||||
}
|
||||
|
||||
const token = req.headers.authorization.split(' ')[1];
|
||||
const token = getAdminTokenFromRequest(req);
|
||||
if (!token) {
|
||||
return next();
|
||||
}
|
||||
@@ -150,4 +147,4 @@ module.exports = {
|
||||
sessionTimeoutMiddleware,
|
||||
endSession,
|
||||
getActiveSessions
|
||||
};
|
||||
};
|
||||
|
||||
@@ -221,7 +221,11 @@ router.post('/test-connection', adminAuth, async (req, res) => {
|
||||
await fs.access(config.path, fs.constants.W_OK);
|
||||
res.json({ success: true, message: 'Local path is writable' });
|
||||
} 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;
|
||||
|
||||
@@ -243,7 +247,11 @@ router.post('/test-connection', adminAuth, async (req, res) => {
|
||||
const { stdout } = await execAsync(testCommand);
|
||||
res.json({ success: true, message: 'Rsync connection successful' });
|
||||
} 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;
|
||||
|
||||
@@ -274,7 +282,7 @@ router.get('/manifest/:backupRunId', adminAuth, async (req, res) => {
|
||||
});
|
||||
} catch (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) {
|
||||
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) {
|
||||
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) {
|
||||
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) {
|
||||
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) {
|
||||
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) {
|
||||
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) {
|
||||
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) {
|
||||
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) {
|
||||
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) {
|
||||
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,12 +953,13 @@ async function validateManifestData(manifestData) {
|
||||
}
|
||||
};
|
||||
} catch (error) {
|
||||
logger.error('Manifest validation error', { error: error.message });
|
||||
return {
|
||||
valid: false,
|
||||
error: `Validation error: ${error.message}`,
|
||||
details: { error: error.message }
|
||||
error: 'Validation error encountered while processing manifest',
|
||||
details: { hint: 'See server logs for diagnostic details.' }
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = router;
|
||||
module.exports = router;
|
||||
|
||||
@@ -515,13 +515,11 @@ router.delete('/:id', adminAuth, async (req, res) => {
|
||||
// Provide more specific error messages
|
||||
if (error.message && error.message.includes('foreign key constraint')) {
|
||||
res.status(500).json({
|
||||
error: 'Cannot delete event due to existing references. Please contact support.',
|
||||
details: error.message
|
||||
error: 'Cannot delete event due to existing references. Please contact support.'
|
||||
});
|
||||
} else {
|
||||
res.status(500).json({
|
||||
error: 'Failed to delete event',
|
||||
details: process.env.NODE_ENV === 'development' ? error.message : undefined
|
||||
error: 'Failed to delete event'
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -780,7 +778,7 @@ router.post('/bulk-archive', adminAuth, [
|
||||
results.failed.push({
|
||||
id: event.id,
|
||||
name: event.event_name,
|
||||
error: error.message
|
||||
error: 'Failed to archive event. Check server logs for details.'
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -806,4 +804,4 @@ router.post('/bulk-archive', adminAuth, [
|
||||
}
|
||||
});
|
||||
|
||||
module.exports = router;
|
||||
module.exports = router;
|
||||
|
||||
@@ -0,0 +1,121 @@
|
||||
const express = require('express');
|
||||
const path = require('path');
|
||||
const fs = require('fs').promises;
|
||||
const { adminAuth } = require('../middleware/auth');
|
||||
const { list, resolveExternalPath, getExternalMediaRoot } = require('../services/externalMediaService');
|
||||
const { db, logActivity } = require('../database/db');
|
||||
const logger = require('../utils/logger');
|
||||
|
||||
const router = express.Router();
|
||||
|
||||
// GET /api/admin/external-media/list?path=relative/dir
|
||||
router.get('/list', adminAuth, async (req, res) => {
|
||||
try {
|
||||
const relPath = (req.query.path || '').replace(/^\/+/, '');
|
||||
const result = await list(relPath);
|
||||
res.json(result);
|
||||
} catch (error) {
|
||||
logger.warn('Invalid external media path requested', {
|
||||
path: req.query.path,
|
||||
error: error.message
|
||||
});
|
||||
res.status(400).json({ error: 'Invalid external media path' });
|
||||
}
|
||||
});
|
||||
|
||||
// Helper to recursively collect files under a directory, filtered by image extensions
|
||||
async function walkDir(dir, baseDir) {
|
||||
const results = [];
|
||||
const entries = await fs.readdir(dir, { withFileTypes: true });
|
||||
for (const e of entries) {
|
||||
if (e.name.startsWith('.')) continue;
|
||||
const full = path.join(dir, e.name);
|
||||
if (e.isDirectory()) {
|
||||
results.push(...await walkDir(full, baseDir));
|
||||
} else if (e.isFile()) {
|
||||
const ext = path.extname(e.name).toLowerCase();
|
||||
if (['.jpg', '.jpeg', '.png', '.webp'].includes(ext)) {
|
||||
const rel = path.relative(baseDir, full);
|
||||
results.push({ full, rel, name: e.name });
|
||||
}
|
||||
}
|
||||
}
|
||||
return results;
|
||||
}
|
||||
|
||||
// POST /api/admin/events/:id/import-external
|
||||
// Body: { external_path: string, recursive?: boolean, map?: { individual?: string, collages?: string } }
|
||||
router.post('/events/:id/import-external', adminAuth, async (req, res) => {
|
||||
try {
|
||||
const eventId = parseInt(req.params.id);
|
||||
const { external_path, recursive = true, map = { individual: 'individual', collages: 'collages' } } = req.body || {};
|
||||
if (!external_path) return res.status(400).json({ error: 'external_path is required' });
|
||||
|
||||
// Load event
|
||||
const event = await db('events').where('id', eventId).first();
|
||||
if (!event) return res.status(404).json({ error: 'Event not found' });
|
||||
|
||||
const baseAbs = resolveExternalPath({ external_path }, '');
|
||||
// Collect files
|
||||
const files = recursive ? await walkDir(baseAbs, baseAbs) : (await fs.readdir(baseAbs, { withFileTypes: true }))
|
||||
.filter(e => e.isFile())
|
||||
.map(e => ({ full: path.join(baseAbs, e.name), rel: e.name, name: e.name }))
|
||||
.filter(f => ['.jpg', '.jpeg', '.png', '.webp'].includes(path.extname(f.name).toLowerCase()));
|
||||
|
||||
let imported = 0;
|
||||
let skipped = 0;
|
||||
|
||||
// Insert photos
|
||||
for (const f of files) {
|
||||
// Infer type by subfolder names
|
||||
const segs = f.rel.split(path.sep);
|
||||
let type = 'individual';
|
||||
if (segs[0] === map.collages) type = 'collage';
|
||||
if (segs[0] === map.individual) type = 'individual';
|
||||
|
||||
try {
|
||||
// Check if already exists (by external_relpath)
|
||||
const exists = await db('photos')
|
||||
.where({ event_id: eventId, external_relpath: f.rel })
|
||||
.first();
|
||||
if (exists) { skipped++; continue; }
|
||||
|
||||
const stats = await fs.stat(f.full);
|
||||
const inserted = await db('photos')
|
||||
.insert({
|
||||
event_id: eventId,
|
||||
filename: f.name,
|
||||
// Keep path as a hint for legacy code but not used for resolution in external mode
|
||||
path: path.join(event.slug, f.name),
|
||||
thumbnail_path: null,
|
||||
type,
|
||||
size_bytes: stats.size,
|
||||
source_origin: 'external',
|
||||
external_relpath: f.rel
|
||||
})
|
||||
.returning('id');
|
||||
|
||||
imported += (inserted?.length ? 1 : 0);
|
||||
} catch (e) {
|
||||
skipped++;
|
||||
}
|
||||
}
|
||||
|
||||
// Update event fields
|
||||
await db('events').where('id', eventId).update({ source_mode: 'reference', external_path });
|
||||
|
||||
// Queue thumbnail generation lazily by reading thumbnails via ensure endpoint as needed
|
||||
await logActivity('external_import_completed', { event_id: eventId, imported, skipped, external_path }, eventId, { type: 'admin' });
|
||||
|
||||
res.json({ imported, skipped, thumbnailsQueued: 0 });
|
||||
} catch (error) {
|
||||
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;
|
||||
@@ -60,8 +60,8 @@ router.put('/events/:eventId/feedback-settings',
|
||||
settings: updatedSettings
|
||||
}, eventId, {
|
||||
type: 'admin',
|
||||
id: req.user.id,
|
||||
name: req.user.username
|
||||
id: req.admin.id,
|
||||
name: req.admin.username
|
||||
});
|
||||
|
||||
res.json(updatedSettings);
|
||||
@@ -167,7 +167,7 @@ router.put('/feedback/:feedbackId/:action',
|
||||
return res.status(400).json({ error: 'Invalid action' });
|
||||
}
|
||||
|
||||
await feedbackService.moderateFeedback(feedbackId, action, req.user.id);
|
||||
await feedbackService.moderateFeedback(feedbackId, action, req.admin.id);
|
||||
|
||||
res.json({ success: true });
|
||||
} catch (error) {
|
||||
@@ -184,7 +184,7 @@ router.delete('/feedback/:feedbackId',
|
||||
try {
|
||||
const { feedbackId } = req.params;
|
||||
|
||||
await feedbackService.deleteFeedback(feedbackId, req.user.id);
|
||||
await feedbackService.deleteFeedback(feedbackId, req.admin.id);
|
||||
|
||||
res.json({ success: true });
|
||||
} catch (error) {
|
||||
@@ -368,7 +368,7 @@ router.post('/word-filters',
|
||||
res.json({ success: true });
|
||||
} catch (error) {
|
||||
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);
|
||||
res.status(500).json({ error: 'Failed to add word filter' });
|
||||
@@ -430,4 +430,4 @@ function convertToCSV(data) {
|
||||
return [csvHeaders, ...csvRows].join('\n');
|
||||
}
|
||||
|
||||
module.exports = router;
|
||||
module.exports = router;
|
||||
|
||||
@@ -606,8 +606,9 @@ router.get('/:eventId/photos/:photoId/download', adminAuth, async (req, res) =>
|
||||
return res.status(404).json({ error: 'Photo not found' });
|
||||
}
|
||||
|
||||
const storagePath = getStoragePath();
|
||||
const filePath = path.join(storagePath, 'events/active', photo.path);
|
||||
const { resolvePhotoFilePath } = require('../services/photoResolver');
|
||||
const event = await db('events').where('id', eventId).first();
|
||||
const filePath = resolvePhotoFilePath(event, photo);
|
||||
|
||||
// Check if file exists
|
||||
try {
|
||||
@@ -684,8 +685,10 @@ router.get('/:eventId/photos', adminAuth, async (req, res) => {
|
||||
photos: photos.map(photo => ({
|
||||
id: photo.id,
|
||||
filename: photo.filename,
|
||||
url: `/admin/events/${eventId}/photo/${photo.id}`,
|
||||
thumbnail_url: photo.thumbnail_path ? `/admin/events/${eventId}/thumbnail/${photo.id}` : null,
|
||||
// Use the correct admin photos router base for serving images
|
||||
url: `/admin/photos/${eventId}/photo/${photo.id}`,
|
||||
// Always expose a thumbnail URL; backend will generate on demand if missing
|
||||
thumbnail_url: `/admin/photos/${eventId}/thumbnail/${photo.id}`,
|
||||
type: photo.type,
|
||||
category_id: photo.type,
|
||||
category_name: photo.type === 'individual' ? 'Individual Photos' : 'Collages',
|
||||
@@ -719,8 +722,9 @@ router.get('/:eventId/photo/:photoId', adminAuth, async (req, res) => {
|
||||
return res.status(404).json({ error: 'Photo not found' });
|
||||
}
|
||||
|
||||
const storagePath = getStoragePath();
|
||||
const filePath = path.join(storagePath, 'events/active', photo.path);
|
||||
const { resolvePhotoFilePath } = require('../services/photoResolver');
|
||||
const event = await db('events').where('id', eventId).first();
|
||||
const filePath = resolvePhotoFilePath(event, photo);
|
||||
|
||||
// Check if file exists
|
||||
try {
|
||||
@@ -798,8 +802,9 @@ router.get('/:eventId/debug', adminAuth, async (req, res) => {
|
||||
storagePath: getStoragePath()
|
||||
});
|
||||
} 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' });
|
||||
}
|
||||
});
|
||||
|
||||
module.exports = router;
|
||||
module.exports = router;
|
||||
|
||||
@@ -82,7 +82,7 @@ router.post('/validate', [
|
||||
logger.error('Restore validation failed:', error);
|
||||
res.status(400).json({
|
||||
success: false,
|
||||
error: error.message,
|
||||
error: 'Restore validation failed',
|
||||
logs: restoreService.restoreLog
|
||||
});
|
||||
}
|
||||
@@ -162,7 +162,7 @@ router.post('/start', [
|
||||
logger.error('Failed to start restore:', error);
|
||||
res.status(500).json({
|
||||
success: false,
|
||||
error: error.message
|
||||
error: 'Failed to start restore operation'
|
||||
});
|
||||
}
|
||||
});
|
||||
@@ -458,4 +458,4 @@ async function getBackupConfig() {
|
||||
return config;
|
||||
}
|
||||
|
||||
module.exports = router;
|
||||
module.exports = router;
|
||||
|
||||
@@ -170,7 +170,13 @@ router.put('/branding', adminAuth, async (req, res) => {
|
||||
watermark_size,
|
||||
favicon_url,
|
||||
logo_url,
|
||||
watermark_logo_url
|
||||
watermark_logo_url,
|
||||
logo_size,
|
||||
logo_max_height,
|
||||
logo_position,
|
||||
logo_display_header,
|
||||
logo_display_hero,
|
||||
logo_display_mode
|
||||
} = req.body;
|
||||
|
||||
const brandingSettings = {
|
||||
@@ -184,7 +190,13 @@ router.put('/branding', adminAuth, async (req, res) => {
|
||||
watermark_size,
|
||||
favicon_url,
|
||||
logo_url,
|
||||
watermark_logo_url
|
||||
watermark_logo_url,
|
||||
logo_size,
|
||||
logo_max_height,
|
||||
logo_position,
|
||||
logo_display_header,
|
||||
logo_display_hero,
|
||||
logo_display_mode
|
||||
};
|
||||
|
||||
// Handle favicon deletion if empty string or null is provided
|
||||
|
||||
@@ -5,6 +5,7 @@ const fs = require('fs').promises;
|
||||
const path = require('path');
|
||||
const os = require('os');
|
||||
const { formatBoolean } = require('../utils/dbCompat');
|
||||
const logger = require('../utils/logger');
|
||||
const router = express.Router();
|
||||
|
||||
// Get system version
|
||||
@@ -208,10 +209,14 @@ router.get('/database', adminAuth, async (req, res) => {
|
||||
});
|
||||
} catch (error) {
|
||||
// Table might not exist
|
||||
logger.warn('Failed to retrieve table info', {
|
||||
table,
|
||||
error: error.message
|
||||
});
|
||||
tableInfo.push({
|
||||
name: table,
|
||||
rows: 0,
|
||||
error: error.message
|
||||
error: 'Unable to retrieve table details'
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -226,4 +231,4 @@ router.get('/database', adminAuth, async (req, res) => {
|
||||
}
|
||||
});
|
||||
|
||||
module.exports = router;
|
||||
module.exports = router;
|
||||
|
||||
@@ -14,6 +14,14 @@ const {
|
||||
} = require('../utils/authSecurity');
|
||||
const { endSession } = require('../middleware/sessionTimeout');
|
||||
const logger = require('../utils/logger');
|
||||
const {
|
||||
setAdminAuthCookie,
|
||||
clearAdminAuthCookie,
|
||||
setGalleryAuthCookies,
|
||||
clearGalleryAuthCookies,
|
||||
getAdminTokenFromRequest,
|
||||
getGalleryTokenFromRequest,
|
||||
} = require('../utils/tokenUtils');
|
||||
const router = express.Router();
|
||||
|
||||
// Admin login with enhanced security
|
||||
@@ -91,6 +99,8 @@ router.post('/admin/login', [
|
||||
expiresIn: '24h',
|
||||
issuer: 'picpeak-auth'
|
||||
});
|
||||
|
||||
setAdminAuthCookie(res, token);
|
||||
|
||||
res.json({
|
||||
token,
|
||||
@@ -110,13 +120,14 @@ router.post('/admin/login', [
|
||||
// Logout endpoint
|
||||
router.post('/logout', async (req, res) => {
|
||||
try {
|
||||
const token = req.headers.authorization?.split(' ')[1];
|
||||
|
||||
const adminToken = getAdminTokenFromRequest(req);
|
||||
const galleryToken = getGalleryTokenFromRequest(req);
|
||||
const token = adminToken || galleryToken;
|
||||
|
||||
if (token) {
|
||||
// End the session
|
||||
endSession(token);
|
||||
|
||||
// Log the logout
|
||||
|
||||
try {
|
||||
const decoded = jwt.verify(token, process.env.JWT_SECRET);
|
||||
logger.info('User logged out', {
|
||||
@@ -124,11 +135,23 @@ router.post('/logout', async (req, res) => {
|
||||
username: decoded.username,
|
||||
type: decoded.type
|
||||
});
|
||||
|
||||
if (decoded.type === 'admin') {
|
||||
clearAdminAuthCookie(res);
|
||||
} else if (decoded.type === 'gallery') {
|
||||
clearGalleryAuthCookies(res, decoded.eventSlug);
|
||||
}
|
||||
} 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' });
|
||||
} catch (error) {
|
||||
logger.error('Logout error:', error);
|
||||
@@ -209,6 +232,8 @@ router.post('/gallery/verify', [
|
||||
expiresIn: '24h',
|
||||
issuer: 'picpeak-auth'
|
||||
});
|
||||
|
||||
setGalleryAuthCookies(res, token, event.slug);
|
||||
|
||||
res.json({
|
||||
token,
|
||||
@@ -230,15 +255,94 @@ 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
|
||||
router.get('/session', async (req, res) => {
|
||||
try {
|
||||
const token = req.headers.authorization?.split(' ')[1];
|
||||
const { slug } = req.query;
|
||||
const token = getAdminTokenFromRequest(req) || getGalleryTokenFromRequest(req, slug);
|
||||
|
||||
if (!token) {
|
||||
return res.status(401).json({ error: 'No token provided' });
|
||||
}
|
||||
|
||||
|
||||
try {
|
||||
const decoded = jwt.verify(token, process.env.JWT_SECRET);
|
||||
|
||||
@@ -250,7 +354,9 @@ router.get('/session', async (req, res) => {
|
||||
valid: true,
|
||||
type: decoded.type,
|
||||
expiresIn: Math.floor(remainingTime),
|
||||
user: decoded.username || decoded.eventSlug
|
||||
user: decoded.username || decoded.eventSlug,
|
||||
eventSlug: decoded.eventSlug,
|
||||
adminUsername: decoded.username
|
||||
});
|
||||
} catch (err) {
|
||||
res.json({
|
||||
@@ -263,4 +369,4 @@ router.get('/session', async (req, res) => {
|
||||
}
|
||||
});
|
||||
|
||||
module.exports = router;
|
||||
module.exports = router;
|
||||
|
||||
@@ -37,7 +37,7 @@ router.get('/:slug/verify-token/:token', async (req, res) => {
|
||||
res.json({ valid: true });
|
||||
} catch (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,19 +90,58 @@ router.get('/:slug/info', async (req, res) => {
|
||||
});
|
||||
} catch (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' });
|
||||
}
|
||||
});
|
||||
|
||||
// Get all photos
|
||||
router.get('/:slug/photos', verifyGalleryAccess, async (req, res) => {
|
||||
try {
|
||||
// Get filter parameters from query
|
||||
const { filter, guest_id } = req.query;
|
||||
const feedbackService = require('../services/feedbackService');
|
||||
|
||||
// First get all photos
|
||||
const photos = await db('photos')
|
||||
let photos = await db('photos')
|
||||
.where('photos.event_id', req.event.id)
|
||||
.select('photos.*')
|
||||
.orderBy('photos.uploaded_at', 'desc');
|
||||
|
||||
// Apply filtering if requested (global, based on aggregate counts)
|
||||
if (filter) {
|
||||
const f = String(filter).toLowerCase();
|
||||
const parts = f.split(',').map(s => s.trim());
|
||||
const include = new Set();
|
||||
|
||||
// Helper to include IDs for a predicate
|
||||
const includeBy = (predicate) => {
|
||||
photos.forEach(p => { if (predicate(p)) include.add(p.id); });
|
||||
};
|
||||
|
||||
if (parts.includes('liked')) {
|
||||
includeBy(p => (p.like_count || 0) > 0);
|
||||
}
|
||||
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));
|
||||
}
|
||||
|
||||
if (include.size > 0) {
|
||||
photos = photos.filter(p => include.has(p.id));
|
||||
}
|
||||
}
|
||||
|
||||
// Then get comment counts separately
|
||||
const commentCounts = await db('photo_feedback')
|
||||
.whereIn('photo_id', photos.map(p => p.id))
|
||||
@@ -150,13 +189,6 @@ router.get('/:slug/photos', verifyGalleryAccess, async (req, res) => {
|
||||
overlay_protection: req.event.overlay_protection !== false
|
||||
};
|
||||
|
||||
console.log('[Gallery Photos] Event data:', {
|
||||
id: req.event.id,
|
||||
slug: req.params.slug,
|
||||
protection_level: req.event.protection_level,
|
||||
calculated_protection: protectionSettings.protection_level,
|
||||
is_basic_or_standard: (protectionSettings.protection_level === 'basic' || protectionSettings.protection_level === 'standard')
|
||||
});
|
||||
|
||||
res.json({
|
||||
event: {
|
||||
@@ -181,8 +213,6 @@ router.get('/:slug/photos', verifyGalleryAccess, async (req, res) => {
|
||||
`/api/gallery/${req.params.slug}/photo/${photo.id}` :
|
||||
`/api/secure-images/${req.params.slug}/secure/${photo.id}/{{token}}`;
|
||||
|
||||
console.log(`[Photo ${photo.id}] Protection: ${protectionSettings.protection_level}, Use JWT: ${useJwtUrl}, URL: ${photoUrl}`);
|
||||
|
||||
return {
|
||||
id: photo.id,
|
||||
filename: photo.filename,
|
||||
@@ -209,7 +239,7 @@ router.get('/:slug/photos', verifyGalleryAccess, async (req, res) => {
|
||||
});
|
||||
} catch (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' });
|
||||
}
|
||||
});
|
||||
|
||||
@@ -363,14 +393,87 @@ router.get('/:slug/download-all', verifyGalleryAccess, async (req, res) => {
|
||||
}
|
||||
});
|
||||
|
||||
// Test route
|
||||
router.get('/:slug/photo-test/:photoId',
|
||||
verifyGalleryAccess,
|
||||
(req, res) => {
|
||||
console.log('TEST ROUTE EXECUTED!');
|
||||
res.json({ message: 'Test route works!', photoId: req.params.photoId });
|
||||
// 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)
|
||||
router.get('/:slug/photo/:photoId',
|
||||
@@ -400,18 +503,9 @@ router.get('/:slug/photo/:photoId',
|
||||
});
|
||||
}
|
||||
|
||||
// Photo path should be in storage/events/active directory
|
||||
// Handle both legacy paths (just slug/filename) and new paths (events/active/slug/filename)
|
||||
const storagePath = getStoragePath();
|
||||
|
||||
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);
|
||||
}
|
||||
// Resolve the absolute file path for this photo, supporting both managed and external reference modes
|
||||
const { resolvePhotoFilePath } = require('../services/photoResolver');
|
||||
const filePath = resolvePhotoFilePath(req.event, photo);
|
||||
|
||||
|
||||
// Log access - temporarily disabled for debugging
|
||||
@@ -453,7 +547,7 @@ router.get('/:slug/photo/:photoId',
|
||||
photoId: req.params.photoId,
|
||||
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' });
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
@@ -24,14 +24,15 @@ router.get('/:slug/feedback-settings',
|
||||
const settings = await feedbackService.getEventFeedbackSettings(event.id);
|
||||
|
||||
// Only send relevant settings to guests
|
||||
// Convert SQLite boolean values (0/1) to proper booleans
|
||||
const guestSettings = {
|
||||
feedback_enabled: settings.feedback_enabled,
|
||||
allow_ratings: settings.allow_ratings,
|
||||
allow_likes: settings.allow_likes,
|
||||
allow_comments: settings.allow_comments,
|
||||
allow_favorites: settings.allow_favorites,
|
||||
require_name_email: settings.require_name_email,
|
||||
show_feedback_to_guests: settings.show_feedback_to_guests
|
||||
feedback_enabled: Boolean(settings.feedback_enabled),
|
||||
allow_ratings: Boolean(settings.allow_ratings),
|
||||
allow_likes: Boolean(settings.allow_likes),
|
||||
allow_comments: Boolean(settings.allow_comments),
|
||||
allow_favorites: Boolean(settings.allow_favorites),
|
||||
require_name_email: Boolean(settings.require_name_email),
|
||||
show_feedback_to_guests: Boolean(settings.show_feedback_to_guests)
|
||||
};
|
||||
|
||||
res.json(guestSettings);
|
||||
|
||||
@@ -42,6 +42,12 @@ router.get('/', async (req, res) => {
|
||||
branding_watermark_size: settingsObject.branding_watermark_size || 15,
|
||||
branding_favicon_url: settingsObject.branding_favicon_url || '',
|
||||
branding_logo_url: settingsObject.branding_logo_url || '',
|
||||
branding_logo_size: settingsObject.branding_logo_size || 'medium',
|
||||
branding_logo_max_height: settingsObject.branding_logo_max_height || 48,
|
||||
branding_logo_position: settingsObject.branding_logo_position || 'left',
|
||||
branding_logo_display_header: settingsObject.branding_logo_display_header !== false,
|
||||
branding_logo_display_hero: settingsObject.branding_logo_display_hero !== false,
|
||||
branding_logo_display_mode: settingsObject.branding_logo_display_mode || 'logo_and_text',
|
||||
theme_config: settingsObject.theme_config || null,
|
||||
default_language: settingsObject.general_default_language || 'en',
|
||||
enable_analytics: settingsObject.general_enable_analytics !== false,
|
||||
|
||||
@@ -0,0 +1,67 @@
|
||||
const fs = require('fs').promises;
|
||||
const path = require('path');
|
||||
const { safePathJoin } = require('../utils/fileSecurityUtils');
|
||||
|
||||
function getExternalMediaRoot() {
|
||||
return process.env.EXTERNAL_MEDIA_ROOT || '/external-media';
|
||||
}
|
||||
|
||||
function isUnderRoot(p) {
|
||||
const root = path.resolve(getExternalMediaRoot());
|
||||
const resolved = path.resolve(p);
|
||||
return resolved === root || resolved.startsWith(root + path.sep);
|
||||
}
|
||||
|
||||
async function list(relativePath = '') {
|
||||
const root = getExternalMediaRoot();
|
||||
// Normalize and ensure safe join under root
|
||||
const targetDir = safePathJoin(root, relativePath || '.');
|
||||
|
||||
const entries = [];
|
||||
try {
|
||||
const dirents = await fs.readdir(targetDir, { withFileTypes: true });
|
||||
for (const d of dirents) {
|
||||
// Skip hidden files and directories
|
||||
if (d.name.startsWith('.')) continue;
|
||||
const full = path.join(targetDir, d.name);
|
||||
const stat = await fs.stat(full).catch(() => null);
|
||||
if (!stat) continue;
|
||||
|
||||
if (d.isDirectory()) {
|
||||
entries.push({ name: d.name, type: 'dir' });
|
||||
} else if (d.isFile()) {
|
||||
const ext = path.extname(d.name).toLowerCase();
|
||||
if (['.jpg', '.jpeg', '.png', '.webp'].includes(ext)) {
|
||||
entries.push({ name: d.name, type: 'file', size: stat.size, mtime: stat.mtime });
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
// Propagate errors for caller to handle (e.g., invalid path)
|
||||
throw e;
|
||||
}
|
||||
|
||||
const rootResolved = path.resolve(root);
|
||||
const currentResolved = path.resolve(targetDir);
|
||||
const canNavigateUp = currentResolved !== rootResolved;
|
||||
|
||||
// Return normalized relative path from root
|
||||
const relFromRoot = path.relative(rootResolved, currentResolved);
|
||||
|
||||
return { path: relFromRoot, entries, canNavigateUp };
|
||||
}
|
||||
|
||||
function resolveExternalPath(event, relpath) {
|
||||
const root = getExternalMediaRoot();
|
||||
const base = event?.external_path ? path.join(event.external_path) : '';
|
||||
const combined = base ? path.join(base, relpath || '') : (relpath || '');
|
||||
return safePathJoin(root, combined);
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
getExternalMediaRoot,
|
||||
isUnderRoot,
|
||||
list,
|
||||
resolveExternalPath,
|
||||
};
|
||||
|
||||
@@ -390,6 +390,76 @@ class FeedbackService {
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get filtered photos based on feedback criteria
|
||||
* @param {number} eventId - Event ID
|
||||
* @param {string} guestIdentifier - Guest identifier
|
||||
* @param {object} filters - Filter criteria
|
||||
* @param {boolean} filters.liked - Include liked photos
|
||||
* @param {boolean} filters.favorited - Include favorited photos
|
||||
* @param {string} filters.operator - 'AND' or 'OR' for multiple filters
|
||||
* @returns {Promise<number[]>} Array of photo IDs that match criteria
|
||||
*/
|
||||
async getFilteredPhotos(eventId, guestIdentifier, filters = {}) {
|
||||
try {
|
||||
const { liked, favorited, operator = 'OR' } = filters;
|
||||
|
||||
// If no filters specified, return all photos
|
||||
if (!liked && !favorited) {
|
||||
const allPhotos = await db('photos')
|
||||
.where('event_id', eventId)
|
||||
.select('id');
|
||||
return allPhotos.map(p => p.id);
|
||||
}
|
||||
|
||||
// Build query based on filters
|
||||
let query = db('photo_feedback')
|
||||
.where('event_id', eventId)
|
||||
.where('guest_identifier', guestIdentifier)
|
||||
.where('is_hidden', false);
|
||||
|
||||
// Apply filter logic
|
||||
if (operator === 'AND' && liked && favorited) {
|
||||
// For AND operation, we need photos that have both types of feedback
|
||||
const likedPhotos = await db('photo_feedback')
|
||||
.where('event_id', eventId)
|
||||
.where('guest_identifier', guestIdentifier)
|
||||
.where('feedback_type', 'like')
|
||||
.where('is_hidden', false)
|
||||
.select('photo_id');
|
||||
|
||||
const favoritedPhotos = await db('photo_feedback')
|
||||
.where('event_id', eventId)
|
||||
.where('guest_identifier', guestIdentifier)
|
||||
.where('feedback_type', 'favorite')
|
||||
.where('is_hidden', false)
|
||||
.select('photo_id');
|
||||
|
||||
const likedIds = new Set(likedPhotos.map(p => p.photo_id));
|
||||
const favoritedIds = new Set(favoritedPhotos.map(p => p.photo_id));
|
||||
|
||||
// Return intersection of both sets
|
||||
return Array.from(likedIds).filter(id => favoritedIds.has(id));
|
||||
} else {
|
||||
// OR operation or single filter
|
||||
const feedbackTypes = [];
|
||||
if (liked) feedbackTypes.push('like');
|
||||
if (favorited) feedbackTypes.push('favorite');
|
||||
|
||||
query.whereIn('feedback_type', feedbackTypes);
|
||||
}
|
||||
|
||||
const filteredPhotos = await query
|
||||
.distinct('photo_id')
|
||||
.select('photo_id');
|
||||
|
||||
return filteredPhotos.map(p => p.photo_id);
|
||||
} catch (error) {
|
||||
logger.error('Error getting filtered photos:', error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = new FeedbackService();
|
||||
@@ -132,7 +132,8 @@ async function generateThumbnail(imagePath, options = {}) {
|
||||
|
||||
return path.relative(getStoragePath(), thumbnailPath);
|
||||
} catch (error) {
|
||||
logger.error(`Failed to generate thumbnail for ${filename}:`, error.message);
|
||||
const msg = (error && error.message) ? error.message : String(error);
|
||||
logger.error(`Failed to generate thumbnail for ${filename}: ${msg}`);
|
||||
|
||||
// Clean up any partially created file
|
||||
try {
|
||||
@@ -171,8 +172,18 @@ async function isThumbnailValid(thumbnailPath) {
|
||||
* Regenerate thumbnail if it's broken or missing
|
||||
*/
|
||||
async function ensureThumbnail(photo) {
|
||||
const storagePath = getStoragePath();
|
||||
const originalPath = path.join(storagePath, 'events/active', photo.path);
|
||||
const { db } = require('../database/db');
|
||||
const { resolvePhotoFilePath } = require('./photoResolver');
|
||||
let originalPath;
|
||||
try {
|
||||
const event = await db('events').where('id', photo.event_id).first();
|
||||
originalPath = resolvePhotoFilePath(event, photo);
|
||||
logger.info(`Ensuring thumbnail for photo ${photo.id} from source: ${originalPath}`);
|
||||
} catch (e) {
|
||||
const msg = (e && e.message) ? e.message : String(e);
|
||||
logger.error(`Failed to resolve original path for thumbnail (photo ${photo.id}): ${msg}`);
|
||||
return null;
|
||||
}
|
||||
|
||||
// Check if thumbnail exists and is valid
|
||||
if (photo.thumbnail_path) {
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
const path = require('path');
|
||||
const { resolveExternalPath } = require('./externalMediaService');
|
||||
|
||||
const getStoragePath = () => process.env.STORAGE_PATH || path.join(__dirname, '../../../storage');
|
||||
|
||||
/**
|
||||
* Resolve absolute photo file path based on event + photo origin
|
||||
* Managed: storage/events/active + photo.path (legacy variants supported)
|
||||
* External reference: EXTERNAL_MEDIA_ROOT + event.external_path + photo.external_relpath
|
||||
*/
|
||||
function resolvePhotoFilePath(event, photo) {
|
||||
if (!event || !photo) throw new Error('resolvePhotoFilePath requires event and photo');
|
||||
|
||||
const mode = (event.source_mode || photo.source_origin || 'managed');
|
||||
if (mode === 'reference' || photo.source_origin === 'external') {
|
||||
if (!photo.external_relpath) {
|
||||
throw new Error('Missing external_relpath for external photo');
|
||||
}
|
||||
// Normalize duplicate leaf segments (e.g., event.external_path ends with 'individual'
|
||||
// and external_relpath starts with 'individual/') to avoid double segment like
|
||||
// '/external-media/.../individual/individual/file.jpg'
|
||||
let rel = photo.external_relpath;
|
||||
try {
|
||||
const lastSeg = path.basename(event.external_path || '');
|
||||
const firstSeg = rel.split(path.sep)[0];
|
||||
if (lastSeg && firstSeg && lastSeg === firstSeg) {
|
||||
rel = rel.split(path.sep).slice(1).join(path.sep) || '';
|
||||
}
|
||||
} catch (_) {
|
||||
// ignore normalization errors
|
||||
}
|
||||
return resolveExternalPath(event, rel);
|
||||
}
|
||||
|
||||
const storagePath = getStoragePath();
|
||||
if (photo.path && photo.path.startsWith('events/active/')) {
|
||||
return path.join(storagePath, photo.path);
|
||||
}
|
||||
return path.join(storagePath, 'events/active', photo.path || '');
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
resolvePhotoFilePath,
|
||||
};
|
||||
@@ -2,6 +2,7 @@ const rateLimit = require('express-rate-limit');
|
||||
const jwt = require('jsonwebtoken');
|
||||
const { db } = require('../database/db');
|
||||
const logger = require('../utils/logger');
|
||||
const { getAdminTokenFromRequest, getGalleryTokenFromRequest } = require('../utils/tokenUtils');
|
||||
|
||||
// Cache for rate limit settings
|
||||
let settingsCache = null;
|
||||
@@ -95,12 +96,9 @@ function clearSettingsCache() {
|
||||
*/
|
||||
function isAuthenticated(req) {
|
||||
try {
|
||||
const authHeader = req.headers.authorization;
|
||||
if (!authHeader || !authHeader.startsWith('Bearer ')) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const token = authHeader.substring(7);
|
||||
const slugMatch = req.path.match(/\/api\/(?:gallery|secure-images)\/([^\/]+)/);
|
||||
const slug = slugMatch ? slugMatch[1] : req.requestedSlug;
|
||||
const token = getAdminTokenFromRequest(req) || getGalleryTokenFromRequest(req, slug);
|
||||
const decoded = jwt.verify(token, process.env.JWT_SECRET);
|
||||
|
||||
// Check if token is valid
|
||||
@@ -280,4 +278,4 @@ module.exports = {
|
||||
createAuthRateLimiter,
|
||||
isAuthenticated,
|
||||
shouldSkipRateLimit
|
||||
};
|
||||
};
|
||||
|
||||
@@ -227,11 +227,17 @@ async function validateGuestRequirements(settings, guestData) {
|
||||
|
||||
const errors = [];
|
||||
|
||||
if (!guestData.guest_name || guestData.guest_name.trim().length === 0) {
|
||||
// Check for name - handle both undefined and empty strings
|
||||
const name = guestData.guest_name;
|
||||
if (!name || (typeof name === 'string' && name.trim().length === 0)) {
|
||||
errors.push('Name is required');
|
||||
}
|
||||
|
||||
if (!guestData.guest_email || !validator.isEmail(guestData.guest_email)) {
|
||||
// Check for email - handle both undefined and empty strings
|
||||
const email = guestData.guest_email;
|
||||
if (!email || (typeof email === 'string' && email.trim().length === 0)) {
|
||||
errors.push('Email is required');
|
||||
} else if (email && typeof email === 'string' && !validator.isEmail(email.trim())) {
|
||||
errors.push('Valid email is required');
|
||||
}
|
||||
|
||||
|
||||
@@ -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,
|
||||
};
|
||||
@@ -0,0 +1,63 @@
|
||||
// Test script for filter functionality
|
||||
const axios = require('axios');
|
||||
|
||||
const API_URL = 'http://localhost:3001/api';
|
||||
const TEST_SLUG = 'wedding-test-feedback-event-2025-09-02';
|
||||
const TEST_PASSWORD = 'StrongTiger3610%';
|
||||
|
||||
async function testFilterFunctionality() {
|
||||
try {
|
||||
console.log('Testing filter functionality...\n');
|
||||
|
||||
// 1. Authenticate to get JWT token
|
||||
console.log('1. Authenticating with gallery...');
|
||||
const authResponse = await axios.post(`${API_URL}/auth/gallery-login`, {
|
||||
slug: TEST_SLUG,
|
||||
password: TEST_PASSWORD
|
||||
});
|
||||
|
||||
const token = authResponse.data.token;
|
||||
console.log('✅ Authentication successful\n');
|
||||
|
||||
// 2. Test fetching all photos (no filter)
|
||||
console.log('2. Fetching all photos (no filter)...');
|
||||
const allPhotosResponse = await axios.get(`${API_URL}/gallery/${TEST_SLUG}/photos`, {
|
||||
headers: { Authorization: `Bearer ${token}` }
|
||||
});
|
||||
console.log(`✅ Found ${allPhotosResponse.data.photos.length} total photos\n`);
|
||||
|
||||
// 3. Test fetching with liked filter
|
||||
console.log('3. Testing filter for liked photos...');
|
||||
const guestId = 'test_guest_123';
|
||||
const likedPhotosResponse = await axios.get(`${API_URL}/gallery/${TEST_SLUG}/photos`, {
|
||||
params: { filter: 'liked', guest_id: guestId },
|
||||
headers: { Authorization: `Bearer ${token}` }
|
||||
});
|
||||
console.log(`✅ Found ${likedPhotosResponse.data.photos.length} liked photos for guest ${guestId}\n`);
|
||||
|
||||
// 4. Test fetching with favorited filter
|
||||
console.log('4. Testing filter for favorited photos...');
|
||||
const favoritedPhotosResponse = await axios.get(`${API_URL}/gallery/${TEST_SLUG}/photos`, {
|
||||
params: { filter: 'favorited', guest_id: guestId },
|
||||
headers: { Authorization: `Bearer ${token}` }
|
||||
});
|
||||
console.log(`✅ Found ${favoritedPhotosResponse.data.photos.length} favorited photos for guest ${guestId}\n`);
|
||||
|
||||
// 5. Test combined filter
|
||||
console.log('5. Testing combined filter (liked OR favorited)...');
|
||||
const combinedPhotosResponse = await axios.get(`${API_URL}/gallery/${TEST_SLUG}/photos`, {
|
||||
params: { filter: 'liked,favorited', guest_id: guestId },
|
||||
headers: { Authorization: `Bearer ${token}` }
|
||||
});
|
||||
console.log(`✅ Found ${combinedPhotosResponse.data.photos.length} photos that are liked OR favorited\n`);
|
||||
|
||||
console.log('🎉 All filter tests passed successfully!');
|
||||
|
||||
} catch (error) {
|
||||
console.error('❌ Test failed:', error.response?.data || error.message);
|
||||
process.exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
// Run the test
|
||||
testFilterFunctionality();
|
||||
@@ -0,0 +1,114 @@
|
||||
version: '3.8'
|
||||
|
||||
services:
|
||||
postgres:
|
||||
image: postgres:15-alpine
|
||||
container_name: picpeak-postgres
|
||||
environment:
|
||||
POSTGRES_USER: ${DB_USER:-picpeak}
|
||||
POSTGRES_PASSWORD: ${DB_PASSWORD}
|
||||
POSTGRES_DB: ${DB_NAME:-picpeak}
|
||||
volumes:
|
||||
- postgres-data:/var/lib/postgresql/data
|
||||
networks:
|
||||
- picpeak-network
|
||||
restart: unless-stopped
|
||||
healthcheck:
|
||||
test: ["CMD-SHELL", "pg_isready -U ${DB_USER:-picpeak}"]
|
||||
interval: 10s
|
||||
timeout: 5s
|
||||
retries: 5
|
||||
|
||||
redis:
|
||||
image: redis:7-alpine
|
||||
container_name: picpeak-redis
|
||||
command: redis-server --requirepass ${REDIS_PASSWORD}
|
||||
volumes:
|
||||
- redis-data:/data
|
||||
networks:
|
||||
- picpeak-network
|
||||
restart: unless-stopped
|
||||
healthcheck:
|
||||
test: ["CMD", "redis-cli", "--raw", "incr", "ping"]
|
||||
interval: 10s
|
||||
timeout: 5s
|
||||
retries: 5
|
||||
|
||||
backend:
|
||||
# Use pre-built image from GitHub Container Registry
|
||||
image: ghcr.io/the-luap/picpeak/backend:latest
|
||||
container_name: picpeak-backend
|
||||
env_file: .env
|
||||
environment:
|
||||
- NODE_ENV=production
|
||||
- DB_HOST=${DB_HOST:-postgres}
|
||||
- REDIS_HOST=redis
|
||||
- PHOTOS_DIR=/app/storage/events
|
||||
volumes:
|
||||
- ${APP_STORAGE}:/app/storage
|
||||
- ${LOGS}:/app/logs
|
||||
- ${APP_DATA}:/app/data
|
||||
ports:
|
||||
- "${BACKEND_PORT:-3001}:3000"
|
||||
networks:
|
||||
- picpeak-network
|
||||
depends_on:
|
||||
postgres:
|
||||
condition: service_healthy
|
||||
redis:
|
||||
condition: service_healthy
|
||||
restart: unless-stopped
|
||||
healthcheck:
|
||||
# Backend exposes /health on internal port 3000
|
||||
test: ["CMD", "curl", "-f", "http://localhost:3000/health"]
|
||||
interval: 30s
|
||||
timeout: 10s
|
||||
retries: 3
|
||||
|
||||
frontend:
|
||||
# Use pre-built image from GitHub Container Registry
|
||||
image: ghcr.io/the-luap/picpeak/frontend:latest
|
||||
container_name: picpeak-frontend
|
||||
# Note: Pre-built frontend uses Nginx to proxy /api to backend:3001.
|
||||
# Prefer keeping API base as '/api' in builds to avoid CORS.
|
||||
ports:
|
||||
- "${FRONTEND_PORT:-3000}:80"
|
||||
networks:
|
||||
- picpeak-network
|
||||
depends_on:
|
||||
- backend
|
||||
restart: unless-stopped
|
||||
healthcheck:
|
||||
test: ["CMD", "curl", "-f", "http://localhost/health"]
|
||||
interval: 30s
|
||||
timeout: 10s
|
||||
retries: 3
|
||||
|
||||
# Optional: Nginx reverse proxy for production with SSL
|
||||
# Uncomment and configure if you want built-in HTTPS support
|
||||
# nginx:
|
||||
# image: nginx:alpine
|
||||
# container_name: picpeak-nginx
|
||||
# ports:
|
||||
# - "80:80"
|
||||
# - "443:443"
|
||||
# volumes:
|
||||
# - ./nginx/nginx.conf:/etc/nginx/nginx.conf:ro
|
||||
# - ./nginx/ssl:/etc/nginx/ssl:ro
|
||||
# - ./nginx/conf.d:/etc/nginx/conf.d:ro
|
||||
# networks:
|
||||
# - picpeak-network
|
||||
# depends_on:
|
||||
# - frontend
|
||||
# - backend
|
||||
# restart: unless-stopped
|
||||
|
||||
volumes:
|
||||
postgres-data:
|
||||
driver: local
|
||||
redis-data:
|
||||
driver: local
|
||||
|
||||
networks:
|
||||
picpeak-network:
|
||||
driver: bridge
|
||||
@@ -11,6 +11,7 @@ services:
|
||||
- JWT_SECRET=${JWT_SECRET}
|
||||
- ADMIN_USERNAME=${ADMIN_USERNAME:-admin}
|
||||
- ADMIN_EMAIL=${ADMIN_EMAIL:-admin@example.com}
|
||||
- ADMIN_PASSWORD=${ADMIN_PASSWORD}
|
||||
- DATABASE_CLIENT=pg
|
||||
- DATABASE_URL=postgresql://${DB_USER}:${DB_PASSWORD}@postgres:5432/${DB_NAME}
|
||||
- DB_TYPE=postgresql
|
||||
@@ -19,6 +20,7 @@ services:
|
||||
- DB_USER=${DB_USER}
|
||||
- DB_PASSWORD=${DB_PASSWORD}
|
||||
- DB_NAME=${DB_NAME}
|
||||
- EXTERNAL_MEDIA_ROOT=${EXTERNAL_MEDIA_ROOT:-/app/storage/external-media}
|
||||
- SMTP_HOST=${SMTP_HOST}
|
||||
- SMTP_PORT=${SMTP_PORT}
|
||||
- SMTP_SECURE=${SMTP_SECURE:-false}
|
||||
@@ -29,6 +31,11 @@ services:
|
||||
- ADMIN_URL=${ADMIN_URL:-http://localhost:3001}
|
||||
- TZ=${TZ:-UTC}
|
||||
- STORAGE_PATH=/app/storage
|
||||
# Optional: run container as matching host user to avoid bind mount permission issues
|
||||
- PUID=${PUID:-1001}
|
||||
- PGID=${PGID:-1001}
|
||||
# Use host-matching user ID/GID so bind-mounted folders are writable
|
||||
user: "${PUID:-1001}:${PGID:-1001}"
|
||||
volumes:
|
||||
- ./events:/app/events
|
||||
- ./data:/app/data
|
||||
@@ -122,4 +129,4 @@ volumes:
|
||||
|
||||
networks:
|
||||
picpeak-network:
|
||||
driver: bridge
|
||||
driver: bridge
|
||||
|
||||
@@ -1,6 +1,17 @@
|
||||
# Build stage
|
||||
FROM node:20-alpine AS builder
|
||||
|
||||
# Add build arguments
|
||||
ARG CACHEBUST=1
|
||||
ARG BUILD_DATE
|
||||
ARG VCS_REF
|
||||
ARG VERSION
|
||||
|
||||
# Add labels for GitHub Container Registry
|
||||
LABEL org.opencontainers.image.source="https://github.com/the-luap/picpeak"
|
||||
LABEL org.opencontainers.image.description="PicPeak Frontend Application"
|
||||
LABEL org.opencontainers.image.licenses="MIT"
|
||||
|
||||
# Set working directory
|
||||
WORKDIR /app
|
||||
|
||||
|
||||
@@ -4,6 +4,10 @@ server {
|
||||
root /usr/share/nginx/html;
|
||||
index index.html;
|
||||
|
||||
# Allow larger file uploads (up to 100MB)
|
||||
client_max_body_size 100M;
|
||||
client_body_timeout 300s;
|
||||
|
||||
# Gzip compression
|
||||
gzip on;
|
||||
gzip_vary on;
|
||||
@@ -49,6 +53,10 @@ server {
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
proxy_cache_bypass $http_upgrade;
|
||||
proxy_read_timeout 86400;
|
||||
|
||||
# Allow larger uploads for API endpoints
|
||||
client_max_body_size 100M;
|
||||
client_body_timeout 300s;
|
||||
}
|
||||
|
||||
# Photo serving proxy
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
{
|
||||
"name": "picpeak-frontend",
|
||||
"version": "1.0.103",
|
||||
"version": "1.0.128",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "picpeak-frontend",
|
||||
"version": "1.0.103",
|
||||
"version": "1.0.128",
|
||||
"dependencies": {
|
||||
"@tanstack/react-query": "^5.0.0",
|
||||
"@tiptap/extension-character-count": "^2.26.1",
|
||||
@@ -20,14 +20,14 @@
|
||||
"@types/dompurify": "^3.0.5",
|
||||
"@types/lodash": "^4.17.20",
|
||||
"@types/react-google-recaptcha": "^2.1.9",
|
||||
"axios": "^1.3.2",
|
||||
"axios": "^1.12.2",
|
||||
"clsx": "^2.0.0",
|
||||
"date-fns": "4.1.0",
|
||||
"dompurify": "^3.2.6",
|
||||
"i18next": "^25.3.1",
|
||||
"i18next-browser-languagedetector": "^8.2.0",
|
||||
"i18next-http-backend": "^3.0.2",
|
||||
"js-cookie": "^3.0.5",
|
||||
"linkifyjs": "^4.3.2",
|
||||
"lodash": "^4.17.21",
|
||||
"lowlight": "^2.9.0",
|
||||
"lucide-react": "0.525.0",
|
||||
@@ -44,7 +44,6 @@
|
||||
},
|
||||
"devDependencies": {
|
||||
"@eslint/js": "^9.29.0",
|
||||
"@types/js-cookie": "^3.0.6",
|
||||
"@types/react": "^18.3.12",
|
||||
"@types/react-dom": "^18.3.1",
|
||||
"@vitejs/plugin-react": "^4.5.2",
|
||||
@@ -57,7 +56,7 @@
|
||||
"tailwindcss": "^3.3.0",
|
||||
"typescript": "~5.8.3",
|
||||
"typescript-eslint": "^8.34.1",
|
||||
"vite": "^7.0.0"
|
||||
"vite": "^7.1.6"
|
||||
}
|
||||
},
|
||||
"node_modules/@alloc/quick-lru": {
|
||||
@@ -2014,13 +2013,6 @@
|
||||
"@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": {
|
||||
"version": "7.0.15",
|
||||
"resolved": "https://registry.npmjs.org/@types/json-schema/-/json-schema-7.0.15.tgz",
|
||||
@@ -2549,13 +2541,13 @@
|
||||
}
|
||||
},
|
||||
"node_modules/axios": {
|
||||
"version": "1.10.0",
|
||||
"resolved": "https://registry.npmjs.org/axios/-/axios-1.10.0.tgz",
|
||||
"integrity": "sha512-/1xYAC4MP/HEG+3duIhFr4ZQXR4sQXOIe+o6sdqzeykGLx6Upp/1p8MHqhINOvGeP7xyNHe7tsiJByc4SSVUxw==",
|
||||
"version": "1.12.2",
|
||||
"resolved": "https://registry.npmjs.org/axios/-/axios-1.12.2.tgz",
|
||||
"integrity": "sha512-vMJzPewAlRyOgxV2dU0Cuz2O8zzzx9VYtbJOaBgXFeLc4IV/Eg50n4LowmehOOR61S8ZMpc2K5Sa7g6A4jfkUw==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"follow-redirects": "^1.15.6",
|
||||
"form-data": "^4.0.0",
|
||||
"form-data": "^4.0.4",
|
||||
"proxy-from-env": "^1.1.0"
|
||||
}
|
||||
},
|
||||
@@ -3903,15 +3895,6 @@
|
||||
"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": {
|
||||
"version": "4.0.0",
|
||||
"resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz",
|
||||
@@ -4032,9 +4015,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/linkifyjs": {
|
||||
"version": "4.3.1",
|
||||
"resolved": "https://registry.npmjs.org/linkifyjs/-/linkifyjs-4.3.1.tgz",
|
||||
"integrity": "sha512-DRSlB9DKVW04c4SUdGvKK5FR6be45lTU9M76JnngqPeeGDqPwYc0zdUErtsNVMtxPXgUWV4HbXbnC4sNyBxkYg==",
|
||||
"version": "4.3.2",
|
||||
"resolved": "https://registry.npmjs.org/linkifyjs/-/linkifyjs-4.3.2.tgz",
|
||||
"integrity": "sha512-NT1CJtq3hHIreOianA8aSXn6Cw0JzYOuDQbOrSPe7gqFnCpKP++MQe3ODgO3oh2GJFORkAAdqredOa60z63GbA==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/locate-path": {
|
||||
@@ -5524,14 +5507,14 @@
|
||||
}
|
||||
},
|
||||
"node_modules/tinyglobby": {
|
||||
"version": "0.2.14",
|
||||
"resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.14.tgz",
|
||||
"integrity": "sha512-tX5e7OM1HnYr2+a2C/4V0htOcSQcoSTH9KgJnVvNm5zm/cyEWKJ7j7YutsH9CxMdtOkkLFy2AHrMci9IM8IPZQ==",
|
||||
"version": "0.2.15",
|
||||
"resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.15.tgz",
|
||||
"integrity": "sha512-j2Zq4NyQYG5XMST4cbs02Ak8iJUdxRM0XI5QyxXuZOzKOINmWurp3smXu3y5wDcJrptwpSjgXHzIQxR0omXljQ==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"fdir": "^6.4.4",
|
||||
"picomatch": "^4.0.2"
|
||||
"fdir": "^6.5.0",
|
||||
"picomatch": "^4.0.3"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=12.0.0"
|
||||
@@ -5541,11 +5524,14 @@
|
||||
}
|
||||
},
|
||||
"node_modules/tinyglobby/node_modules/fdir": {
|
||||
"version": "6.4.6",
|
||||
"resolved": "https://registry.npmjs.org/fdir/-/fdir-6.4.6.tgz",
|
||||
"integrity": "sha512-hiFoqpyZcfNm1yc4u8oWCf9A2c4D3QjCrks3zmoVKVxpQRzmPNar1hUJcBG2RQHvEVGDN+Jm81ZheVLAQMK6+w==",
|
||||
"version": "6.5.0",
|
||||
"resolved": "https://registry.npmjs.org/fdir/-/fdir-6.5.0.tgz",
|
||||
"integrity": "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=12.0.0"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"picomatch": "^3 || ^4"
|
||||
},
|
||||
@@ -5731,18 +5717,18 @@
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/vite": {
|
||||
"version": "7.0.5",
|
||||
"resolved": "https://registry.npmjs.org/vite/-/vite-7.0.5.tgz",
|
||||
"integrity": "sha512-1mncVwJxy2C9ThLwz0+2GKZyEXuC3MyWtAAlNftlZZXZDP3AJt5FmwcMit/IGGaNZ8ZOB2BNO/HFUB+CpN0NQw==",
|
||||
"version": "7.1.6",
|
||||
"resolved": "https://registry.npmjs.org/vite/-/vite-7.1.6.tgz",
|
||||
"integrity": "sha512-SRYIB8t/isTwNn8vMB3MR6E+EQZM/WG1aKmmIUCfDXfVvKfc20ZpamngWHKzAmmu9ppsgxsg4b2I7c90JZudIQ==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"esbuild": "^0.25.0",
|
||||
"fdir": "^6.4.6",
|
||||
"picomatch": "^4.0.2",
|
||||
"fdir": "^6.5.0",
|
||||
"picomatch": "^4.0.3",
|
||||
"postcss": "^8.5.6",
|
||||
"rollup": "^4.40.0",
|
||||
"tinyglobby": "^0.2.14"
|
||||
"rollup": "^4.43.0",
|
||||
"tinyglobby": "^0.2.15"
|
||||
},
|
||||
"bin": {
|
||||
"vite": "bin/vite.js"
|
||||
@@ -5806,11 +5792,14 @@
|
||||
}
|
||||
},
|
||||
"node_modules/vite/node_modules/fdir": {
|
||||
"version": "6.4.6",
|
||||
"resolved": "https://registry.npmjs.org/fdir/-/fdir-6.4.6.tgz",
|
||||
"integrity": "sha512-hiFoqpyZcfNm1yc4u8oWCf9A2c4D3QjCrks3zmoVKVxpQRzmPNar1hUJcBG2RQHvEVGDN+Jm81ZheVLAQMK6+w==",
|
||||
"version": "6.5.0",
|
||||
"resolved": "https://registry.npmjs.org/fdir/-/fdir-6.5.0.tgz",
|
||||
"integrity": "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=12.0.0"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"picomatch": "^3 || ^4"
|
||||
},
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "picpeak-frontend",
|
||||
"private": true,
|
||||
"version": "1.0.103",
|
||||
"version": "1.0.128",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
@@ -23,14 +23,14 @@
|
||||
"@types/dompurify": "^3.0.5",
|
||||
"@types/lodash": "^4.17.20",
|
||||
"@types/react-google-recaptcha": "^2.1.9",
|
||||
"axios": "^1.3.2",
|
||||
"axios": "^1.12.2",
|
||||
"clsx": "^2.0.0",
|
||||
"date-fns": "4.1.0",
|
||||
"dompurify": "^3.2.6",
|
||||
"i18next": "^25.3.1",
|
||||
"i18next-browser-languagedetector": "^8.2.0",
|
||||
"i18next-http-backend": "^3.0.2",
|
||||
"js-cookie": "^3.0.5",
|
||||
"linkifyjs": "^4.3.2",
|
||||
"lodash": "^4.17.21",
|
||||
"lowlight": "^2.9.0",
|
||||
"lucide-react": "0.525.0",
|
||||
@@ -47,7 +47,6 @@
|
||||
},
|
||||
"devDependencies": {
|
||||
"@eslint/js": "^9.29.0",
|
||||
"@types/js-cookie": "^3.0.6",
|
||||
"@types/react": "^18.3.12",
|
||||
"@types/react-dom": "^18.3.1",
|
||||
"@vitejs/plugin-react": "^4.5.2",
|
||||
@@ -60,6 +59,6 @@
|
||||
"tailwindcss": "^3.3.0",
|
||||
"typescript": "~5.8.3",
|
||||
"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 { useQuery } from '@tanstack/react-query';
|
||||
import { MaintenanceMode } from './MaintenanceMode';
|
||||
import { useMaintenanceMode } from '../contexts/MaintenanceContext';
|
||||
import { setMaintenanceModeCallback, api, getAuthToken } from '../config/api';
|
||||
import { setMaintenanceModeCallback, api } from '../config/api';
|
||||
|
||||
interface MaintenanceWrapperProps {
|
||||
children: React.ReactNode;
|
||||
@@ -12,10 +12,38 @@ interface MaintenanceWrapperProps {
|
||||
export const MaintenanceWrapper: React.FC<MaintenanceWrapperProps> = ({ children }) => {
|
||||
const location = useLocation();
|
||||
const { isMaintenanceMode, setMaintenanceMode } = useMaintenanceMode();
|
||||
const [hasAdminSession, setHasAdminSession] = useState(false);
|
||||
|
||||
// Check if current route is admin route
|
||||
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
|
||||
useEffect(() => {
|
||||
@@ -37,7 +65,7 @@ export const MaintenanceWrapper: React.FC<MaintenanceWrapperProps> = ({ children
|
||||
} catch (error: any) {
|
||||
if (error.response?.status === 503) {
|
||||
// Only set maintenance mode for non-admin routes or unauthenticated admin routes
|
||||
if (!isAdminRoute || !hasAdminAuth) {
|
||||
if (!isAdminRoute || !hasAdminSession) {
|
||||
setMaintenanceMode(true);
|
||||
return { maintenance: true };
|
||||
}
|
||||
@@ -47,13 +75,13 @@ export const MaintenanceWrapper: React.FC<MaintenanceWrapperProps> = ({ children
|
||||
},
|
||||
staleTime: 30000, // Check every 30 seconds
|
||||
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
|
||||
if (isMaintenanceMode && (!isAdminRoute || !hasAdminAuth)) {
|
||||
if (isMaintenanceMode && (!isAdminRoute || !hasAdminSession)) {
|
||||
return <MaintenanceMode />;
|
||||
}
|
||||
|
||||
return <>{children}</>;
|
||||
};
|
||||
};
|
||||
|
||||
@@ -71,35 +71,29 @@ export const AdminHeader: React.FC<AdminHeaderProps> = ({ onMenuClick }) => {
|
||||
<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="flex items-center justify-between h-16">
|
||||
{/* Left side - Menu button and Date */}
|
||||
<div className="flex items-center gap-3">
|
||||
{/* Left side - Menu button, Logo, and Date */}
|
||||
<div className="flex items-center gap-3 min-w-0">
|
||||
<button
|
||||
onClick={onMenuClick}
|
||||
className="lg:hidden text-neutral-500 hover:text-neutral-700"
|
||||
>
|
||||
<Menu className="w-6 h-6" />
|
||||
</button>
|
||||
|
||||
{/* Date display - hidden on small screens */}
|
||||
<div className="hidden xl:block">
|
||||
|
||||
{/* PicPeak logo - sticky to the left on all sizes */}
|
||||
<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">
|
||||
{format(new Date(), 'PPPP')}
|
||||
</p>
|
||||
</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 */}
|
||||
<div className="flex items-center gap-3">
|
||||
{/* Language Selector */}
|
||||
@@ -253,4 +247,4 @@ export const AdminHeader: React.FC<AdminHeaderProps> = ({ onMenuClick }) => {
|
||||
/>
|
||||
</header>
|
||||
);
|
||||
};
|
||||
};
|
||||
|
||||
@@ -29,7 +29,10 @@ export const AdminPhotoGrid: React.FC<AdminPhotoGridProps> = ({
|
||||
if (e) {
|
||||
e.stopPropagation();
|
||||
}
|
||||
|
||||
// Auto-enable selection mode when selecting via checkbox
|
||||
if (!isSelectionMode) {
|
||||
setIsSelectionMode(true);
|
||||
}
|
||||
const newSelected = new Set(selectedPhotos);
|
||||
if (newSelected.has(photoId)) {
|
||||
newSelected.delete(photoId);
|
||||
@@ -126,7 +129,7 @@ export const AdminPhotoGrid: React.FC<AdminPhotoGridProps> = ({
|
||||
{isSelectionMode ? 'Cancel Selection' : 'Select Photos'}
|
||||
</Button>
|
||||
|
||||
{isSelectionMode && (
|
||||
{(isSelectionMode || selectedPhotos.size > 0) && (
|
||||
<>
|
||||
<Button
|
||||
variant="ghost"
|
||||
@@ -167,25 +170,32 @@ export const AdminPhotoGrid: React.FC<AdminPhotoGridProps> = ({
|
||||
return (
|
||||
<div
|
||||
key={photo.id}
|
||||
data-testid={`admin-photo-tile-${photo.id}`}
|
||||
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') : ''
|
||||
} ${isDeleting ? 'opacity-50' : ''}`}
|
||||
onClick={() => !isDeleting && (isSelectionMode ? handlePhotoSelect(photo.id) : onPhotoClick(photo, index))}
|
||||
onClick={() => !isDeleting && onPhotoClick(photo, index)}
|
||||
>
|
||||
{/* Selection Checkbox */}
|
||||
{isSelectionMode && (
|
||||
<div className="absolute top-2 left-2 z-10">
|
||||
<div className={`w-6 h-6 rounded border-2 flex items-center justify-center ${
|
||||
selectedPhotos.has(photo.id)
|
||||
? 'bg-primary-500 border-primary-500'
|
||||
: 'bg-white/80 border-neutral-300'
|
||||
}`}>
|
||||
{selectedPhotos.has(photo.id) && (
|
||||
<Check className="w-4 h-4 text-white" />
|
||||
)}
|
||||
</div>
|
||||
{/* Selection Checkbox (top-right) */}
|
||||
<button
|
||||
type="button"
|
||||
aria-label={`Select ${photo.filename}`}
|
||||
role="checkbox"
|
||||
aria-checked={selectedPhotos.has(photo.id)}
|
||||
data-testid={`admin-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) => handlePhotoSelect(photo.id, e)}
|
||||
>
|
||||
<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>
|
||||
)}
|
||||
</button>
|
||||
|
||||
{/* Thumbnail */}
|
||||
<div className="aspect-square">
|
||||
@@ -238,30 +248,30 @@ export const AdminPhotoGrid: React.FC<AdminPhotoGridProps> = ({
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Category Badge */}
|
||||
{/* Category Badge - move to top-left and prevent overlap with select checkbox */}
|
||||
{photo.category_name && (
|
||||
<div className="absolute top-2 right-2">
|
||||
<span className="px-2 py-1 text-xs font-medium bg-white/90 text-neutral-700 rounded">
|
||||
<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 max-w-[70%] whitespace-nowrap overflow-hidden text-ellipsis">
|
||||
{photo.category_name}
|
||||
</span>
|
||||
</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) && (
|
||||
<div className="absolute top-2 left-2 flex gap-1 z-10" style={{ left: isSelectionMode ? '40px' : '8px' }}>
|
||||
{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 className="absolute bottom-2 right-2 flex items-center gap-1 z-10">
|
||||
{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)}`}>
|
||||
<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>
|
||||
</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>
|
||||
@@ -276,4 +286,4 @@ export const AdminPhotoGrid: React.FC<AdminPhotoGridProps> = ({
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
};
|
||||
|
||||
@@ -15,6 +15,7 @@ import { parseISO } from 'date-fns';
|
||||
import { toast } from 'react-toastify';
|
||||
|
||||
import { Card, Loading, Button } from '../common';
|
||||
import { AdminAuthenticatedImage } from './AdminAuthenticatedImage';
|
||||
import { feedbackService } from '../../services/feedback.service';
|
||||
import { useLocalizedDate } from '../../hooks/useLocalizedDate';
|
||||
|
||||
@@ -118,14 +119,28 @@ export const FeedbackModerationPanel: React.FC<FeedbackModerationPanelProps> = (
|
||||
</span>
|
||||
<span className="text-neutral-500">•</span>
|
||||
<span className="text-neutral-500">
|
||||
{format(parseISO(item.created_at), 'MMM d, h:mm a')}
|
||||
{format(
|
||||
typeof item.created_at === 'string'
|
||||
? parseISO(item.created_at)
|
||||
: new Date(item.created_at),
|
||||
'MMM d, h:mm a'
|
||||
)}
|
||||
</span>
|
||||
</div>
|
||||
<p className="mt-1 text-sm text-neutral-700">{item.comment}</p>
|
||||
{item.photo_filename && (
|
||||
<p className="mt-1 text-xs text-neutral-500">
|
||||
{t('feedback.onPhoto', 'On photo')}: {item.photo_filename}
|
||||
</p>
|
||||
<p className="mt-1 text-sm text-neutral-700">{item.comment_text || item.comment}</p>
|
||||
{item.photo_id && (
|
||||
<div className="mt-2 flex items-center gap-2">
|
||||
<div className="w-16 h-16 overflow-hidden rounded">
|
||||
<AdminAuthenticatedImage
|
||||
src={`/admin/photos/${eventId}/thumbnail/${item.photo_id}`}
|
||||
alt={item.filename || 'Photo'}
|
||||
className="w-16 h-16 object-cover rounded"
|
||||
/>
|
||||
</div>
|
||||
<p className="text-xs text-neutral-500">
|
||||
{t('feedback.onPhoto', 'On photo')}: {item.filename || item.photo_filename || `#${item.photo_id}`}
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
@@ -202,4 +217,4 @@ export const FeedbackModerationPanel: React.FC<FeedbackModerationPanelProps> = (
|
||||
);
|
||||
};
|
||||
|
||||
FeedbackModerationPanel.displayName = 'FeedbackModerationPanel';
|
||||
FeedbackModerationPanel.displayName = 'FeedbackModerationPanel';
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
import React, { useState, useEffect } from 'react';
|
||||
import { getAuthToken } from '../../config/api';
|
||||
import { buildResourceUrl } from '../../utils/url';
|
||||
|
||||
interface AuthenticatedImageProps extends React.ImgHTMLAttributes<HTMLImageElement> {
|
||||
@@ -25,33 +24,12 @@ export const AuthenticatedImage: React.FC<AuthenticatedImageProps> = ({
|
||||
let objectUrl: string | null = null;
|
||||
|
||||
// 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) {
|
||||
setImageSrc(fallbackSrc || '');
|
||||
setIsLoading(false);
|
||||
return;
|
||||
}
|
||||
|
||||
if (!token) {
|
||||
// No auth token - use fallback
|
||||
setImageSrc(fallbackSrc || '');
|
||||
setIsLoading(false);
|
||||
return;
|
||||
}
|
||||
|
||||
setIsLoading(true);
|
||||
setError(false);
|
||||
|
||||
@@ -71,9 +49,7 @@ export const AuthenticatedImage: React.FC<AuthenticatedImageProps> = ({
|
||||
|
||||
// Fetch authenticated image
|
||||
const response = await fetch(fullImageUrl, {
|
||||
headers: {
|
||||
'Authorization': `Bearer ${token}`
|
||||
}
|
||||
credentials: 'include'
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
@@ -119,4 +95,4 @@ export const AuthenticatedImage: React.FC<AuthenticatedImageProps> = ({
|
||||
}
|
||||
|
||||
return <img src={imageSrc} alt={alt} {...props} />;
|
||||
};
|
||||
};
|
||||
|
||||
@@ -0,0 +1,104 @@
|
||||
import React, { useState } from 'react';
|
||||
import { X } from 'lucide-react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Button, Input } from '../common';
|
||||
|
||||
interface FeedbackIdentityModalProps {
|
||||
isOpen: boolean;
|
||||
onClose: () => void;
|
||||
onSubmit: (name: string, email: string) => void;
|
||||
feedbackType: string;
|
||||
}
|
||||
|
||||
export const FeedbackIdentityModal: React.FC<FeedbackIdentityModalProps> = ({
|
||||
isOpen,
|
||||
onClose,
|
||||
onSubmit,
|
||||
feedbackType
|
||||
}) => {
|
||||
const { t } = useTranslation();
|
||||
const [name, setName] = useState('');
|
||||
const [email, setEmail] = useState('');
|
||||
const [errors, setErrors] = useState<Record<string, string>>({});
|
||||
|
||||
if (!isOpen) return null;
|
||||
|
||||
const handleSubmit = (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
const newErrors: Record<string, string> = {};
|
||||
|
||||
if (!name.trim()) {
|
||||
newErrors.name = t('feedback.nameRequired', 'Name is required');
|
||||
}
|
||||
if (!email.trim()) {
|
||||
newErrors.email = t('feedback.emailRequired', 'Email is required');
|
||||
} else if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) {
|
||||
newErrors.email = t('feedback.invalidEmail', 'Invalid email address');
|
||||
}
|
||||
|
||||
if (Object.keys(newErrors).length > 0) {
|
||||
setErrors(newErrors);
|
||||
return;
|
||||
}
|
||||
|
||||
onSubmit(name.trim(), email.trim());
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="fixed inset-0 z-50 flex items-center justify-center p-4">
|
||||
<div className="fixed inset-0 bg-black bg-opacity-50" onClick={onClose} />
|
||||
<div className="relative bg-white rounded-lg shadow-xl max-w-md w-full p-6">
|
||||
<button
|
||||
onClick={onClose}
|
||||
className="absolute top-4 right-4 p-1 hover:bg-neutral-100 rounded-lg transition-colors"
|
||||
>
|
||||
<X className="w-5 h-5 text-neutral-600" />
|
||||
</button>
|
||||
|
||||
<h2 className="text-lg font-semibold text-neutral-900 mb-2">
|
||||
{t('feedback.identityRequired', 'Your Information Required')}
|
||||
</h2>
|
||||
<p className="text-sm text-neutral-600 mb-4">
|
||||
{t('feedback.identityReason', 'Please provide your name and email to submit {{type}}.', { type: feedbackType })}
|
||||
</p>
|
||||
|
||||
<form onSubmit={handleSubmit} className="space-y-4">
|
||||
<Input
|
||||
label={t('feedback.yourName', 'Your Name')}
|
||||
value={name}
|
||||
onChange={(e) => setName(e.target.value)}
|
||||
error={errors.name}
|
||||
placeholder={t('feedback.namePlaceholder', 'Enter your name')}
|
||||
required
|
||||
/>
|
||||
<Input
|
||||
type="email"
|
||||
label={t('feedback.yourEmail', 'Your Email')}
|
||||
value={email}
|
||||
onChange={(e) => setEmail(e.target.value)}
|
||||
error={errors.email}
|
||||
placeholder={t('feedback.emailPlaceholder', 'Enter your email')}
|
||||
required
|
||||
/>
|
||||
<div className="flex gap-2 pt-2">
|
||||
<Button
|
||||
type="submit"
|
||||
variant="primary"
|
||||
className="flex-1"
|
||||
>
|
||||
{t('feedback.submitFeedback', 'Submit Feedback')}
|
||||
</Button>
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
onClick={onClose}
|
||||
className="flex-1"
|
||||
>
|
||||
{t('common.cancel', 'Cancel')}
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,185 @@
|
||||
import React from 'react';
|
||||
import { Heart, Star, MessageSquare } from 'lucide-react';
|
||||
import { Button } from '../common';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
|
||||
export type FilterType = 'all' | 'liked' | 'rated' | 'commented';
|
||||
|
||||
interface GalleryFilterProps {
|
||||
currentFilter: FilterType;
|
||||
onFilterChange: (filter: FilterType) => void;
|
||||
feedbackEnabled: boolean;
|
||||
likeCount?: number;
|
||||
ratedCount?: number;
|
||||
className?: string;
|
||||
isMobile?: boolean;
|
||||
variant?: 'default' | 'compact';
|
||||
}
|
||||
|
||||
export const GalleryFilter: React.FC<GalleryFilterProps> = ({
|
||||
currentFilter,
|
||||
onFilterChange,
|
||||
feedbackEnabled,
|
||||
likeCount = 0,
|
||||
ratedCount = 0,
|
||||
className = '',
|
||||
isMobile = false,
|
||||
variant = 'default'
|
||||
}) => {
|
||||
const { t } = useTranslation();
|
||||
|
||||
if (!feedbackEnabled) {
|
||||
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 (
|
||||
<div className={`${className}`}>
|
||||
{/* Mobile-optimized vertical layout */}
|
||||
{isMobile ? (
|
||||
<div className="space-y-2">
|
||||
<div className="text-xs text-neutral-600 font-medium">
|
||||
{t('gallery.feedbackFilter', 'Feedback Filter')}
|
||||
</div>
|
||||
<div className="flex flex-wrap gap-2">
|
||||
<Button
|
||||
variant={currentFilter === 'all' ? 'primary' : 'outline'}
|
||||
size="sm"
|
||||
onClick={() => onFilterChange('all')}
|
||||
className="text-xs flex-1 min-w-[80px]"
|
||||
>
|
||||
{t('gallery.all', 'All')}
|
||||
</Button>
|
||||
|
||||
<Button
|
||||
variant={currentFilter === 'liked' ? 'primary' : 'outline'}
|
||||
size="sm"
|
||||
onClick={() => onFilterChange('liked')}
|
||||
className="text-xs flex-1 min-w-[80px] flex items-center justify-center gap-1"
|
||||
>
|
||||
<Heart className="w-3 h-3" />
|
||||
<span>{likeCount > 0 ? likeCount : t('gallery.liked', 'Liked')}</span>
|
||||
</Button>
|
||||
|
||||
<Button
|
||||
variant={currentFilter === 'rated' ? 'primary' : 'outline'}
|
||||
size="sm"
|
||||
onClick={() => onFilterChange('rated')}
|
||||
className="text-xs flex-1 min-w-[80px] flex items-center justify-center gap-1"
|
||||
>
|
||||
<Star className="w-3 h-3" />
|
||||
<span>{ratedCount > 0 ? ratedCount : t('gallery.rated', 'Rated')}</span>
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
/* Desktop layout - inline with categories */
|
||||
<div className="flex items-center gap-3">
|
||||
<span className="text-sm text-neutral-600 font-medium whitespace-nowrap">
|
||||
{t('gallery.feedbackFilter', 'Feedback Filter')}:
|
||||
</span>
|
||||
<div className="flex gap-2">
|
||||
<Button
|
||||
variant={currentFilter === 'all' ? 'primary' : 'outline'}
|
||||
size="sm"
|
||||
onClick={() => onFilterChange('all')}
|
||||
className="text-xs sm:text-sm"
|
||||
>
|
||||
{t('gallery.all', '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 sm:w-4 sm:h-4" />
|
||||
<span className="hidden sm:inline">{t('gallery.liked', 'Liked')}</span>
|
||||
{likeCount > 0 && (
|
||||
<span className="bg-primary-100 text-primary-700 px-1.5 rounded">
|
||||
{likeCount}
|
||||
</span>
|
||||
)}
|
||||
</Button>
|
||||
|
||||
<Button
|
||||
variant={currentFilter === 'rated' ? 'primary' : 'outline'}
|
||||
size="sm"
|
||||
onClick={() => onFilterChange('rated')}
|
||||
className="text-xs sm:text-sm flex items-center gap-1"
|
||||
>
|
||||
<Star className="w-3 h-3 sm:w-4 sm:h-4" />
|
||||
<span className="hidden sm:inline">{t('gallery.rated', 'Rated')}</span>
|
||||
{ratedCount > 0 && (
|
||||
<span className="bg-primary-100 text-primary-700 px-1.5 rounded">
|
||||
{ratedCount}
|
||||
</span>
|
||||
)}
|
||||
</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>
|
||||
);
|
||||
};
|
||||
@@ -23,6 +23,12 @@ interface GalleryLayoutProps {
|
||||
footer_text?: string;
|
||||
favicon_url?: string;
|
||||
logo_url?: string;
|
||||
logo_size?: 'small' | 'medium' | 'large' | 'xlarge' | 'custom';
|
||||
logo_max_height?: number;
|
||||
logo_position?: 'left' | 'center' | 'right';
|
||||
logo_display_header?: boolean;
|
||||
logo_display_hero?: boolean;
|
||||
logo_display_mode?: 'logo_only' | 'text_only' | 'logo_and_text';
|
||||
};
|
||||
showLogout?: boolean;
|
||||
onLogout?: () => void;
|
||||
@@ -56,6 +62,53 @@ export const GalleryLayout: React.FC<GalleryLayoutProps> = ({
|
||||
const fontFamily = theme.fontFamily || 'Inter, sans-serif';
|
||||
const headingFontFamily = theme.headingFontFamily || fontFamily;
|
||||
|
||||
// Calculate logo size classes based on settings
|
||||
const getLogoSizeClass = (context: 'header' | 'hero') => {
|
||||
const size = brandingSettings?.logo_size || 'medium';
|
||||
const maxHeight = brandingSettings?.logo_max_height || 48;
|
||||
|
||||
if (size === 'custom') {
|
||||
return { maxHeight: `${maxHeight}px`, height: 'auto' };
|
||||
}
|
||||
|
||||
const sizeMap = {
|
||||
small: context === 'header' ? 'h-6 sm:h-8' : 'h-12 sm:h-14 lg:h-16',
|
||||
medium: context === 'header' ? 'h-8 sm:h-10 lg:h-12' : 'h-16 sm:h-20 lg:h-24',
|
||||
large: context === 'header' ? 'h-10 sm:h-12 lg:h-16' : 'h-20 sm:h-24 lg:h-32',
|
||||
xlarge: context === 'header' ? 'h-12 sm:h-16 lg:h-20' : 'h-24 sm:h-32 lg:h-40'
|
||||
};
|
||||
|
||||
return sizeMap[size] || sizeMap.medium;
|
||||
};
|
||||
|
||||
// Determine logo position classes
|
||||
const getLogoPositionClass = () => {
|
||||
const position = brandingSettings?.logo_position || 'left';
|
||||
return {
|
||||
left: 'justify-start',
|
||||
center: 'justify-center',
|
||||
right: 'justify-end'
|
||||
}[position];
|
||||
};
|
||||
|
||||
// Check if logo should be displayed
|
||||
const shouldShowLogo = (context: 'header' | 'hero') => {
|
||||
const displayMode = brandingSettings?.logo_display_mode || 'logo_and_text';
|
||||
if (displayMode === 'text_only') return false;
|
||||
|
||||
if (context === 'header') {
|
||||
return brandingSettings?.logo_display_header !== false;
|
||||
} else {
|
||||
return brandingSettings?.logo_display_hero !== false;
|
||||
}
|
||||
};
|
||||
|
||||
// Check if company name should be displayed
|
||||
const shouldShowCompanyName = () => {
|
||||
const displayMode = brandingSettings?.logo_display_mode || 'logo_and_text';
|
||||
return displayMode !== 'logo_only';
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="min-h-screen bg-neutral-50">
|
||||
{/* Dynamic Favicon */}
|
||||
@@ -122,16 +175,31 @@ export const GalleryLayout: React.FC<GalleryLayoutProps> = ({
|
||||
)}
|
||||
|
||||
{/* Logo - Show custom logo or fallback to PicPeak logo */}
|
||||
<div className="flex-shrink-0">
|
||||
<img
|
||||
src={brandingSettings?.logo_url ?
|
||||
buildResourceUrl(brandingSettings.logo_url) :
|
||||
'/picpeak-logo-transparent.png'
|
||||
}
|
||||
alt={brandingSettings?.company_name || 'PicPeak'}
|
||||
className="h-8 sm:h-10 lg:h-12 w-auto object-contain"
|
||||
/>
|
||||
</div>
|
||||
{shouldShowLogo('header') && (
|
||||
<div className={`flex-shrink-0 flex items-center gap-2 ${brandingSettings?.logo_position === 'center' ? 'flex-1' : ''} ${getLogoPositionClass()}`}>
|
||||
<img
|
||||
src={brandingSettings?.logo_url ?
|
||||
buildResourceUrl(brandingSettings.logo_url) :
|
||||
'/picpeak-logo-transparent.png'
|
||||
}
|
||||
alt={brandingSettings?.company_name || 'PicPeak'}
|
||||
className={`${typeof getLogoSizeClass('header') === 'string' ? getLogoSizeClass('header') : ''} w-auto object-contain`}
|
||||
style={typeof getLogoSizeClass('header') === 'object' ? getLogoSizeClass('header') : undefined}
|
||||
/>
|
||||
{shouldShowCompanyName() && brandingSettings?.company_name && (
|
||||
<span className="hidden sm:inline text-lg font-semibold text-neutral-900">
|
||||
{brandingSettings.company_name}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
{!shouldShowLogo('header') && shouldShowCompanyName() && brandingSettings?.company_name && (
|
||||
<div className={`flex-shrink-0 ${brandingSettings?.logo_position === 'center' ? 'flex-1' : ''} ${getLogoPositionClass()}`}>
|
||||
<span className="text-lg font-semibold text-neutral-900">
|
||||
{brandingSettings.company_name || 'PicPeak'}
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Center - Event info */}
|
||||
@@ -277,19 +345,32 @@ export const GalleryLayout: React.FC<GalleryLayoutProps> = ({
|
||||
<div className="container py-12 sm:py-16 lg:py-20 relative z-10">
|
||||
<div className="text-center max-w-4xl mx-auto">
|
||||
{/* Logo - Show custom logo or fallback to PicPeak logo */}
|
||||
<div className="mb-6">
|
||||
<img
|
||||
src={brandingSettings?.logo_url ?
|
||||
buildResourceUrl(brandingSettings.logo_url) :
|
||||
'/picpeak-logo-transparent.png'
|
||||
}
|
||||
alt={brandingSettings?.company_name || 'PicPeak'}
|
||||
className="h-16 sm:h-20 lg:h-24 w-auto object-contain mx-auto"
|
||||
style={{
|
||||
filter: 'brightness(0) invert(1) drop-shadow(0 2px 4px rgba(0, 0, 0, 0.3))'
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
{shouldShowLogo('hero') && (
|
||||
<div className="mb-6">
|
||||
<img
|
||||
src={brandingSettings?.logo_url ?
|
||||
buildResourceUrl(brandingSettings.logo_url) :
|
||||
'/picpeak-logo-transparent.png'
|
||||
}
|
||||
alt={brandingSettings?.company_name || 'PicPeak'}
|
||||
className={`${typeof getLogoSizeClass('hero') === 'string' ? getLogoSizeClass('hero') : ''} w-auto object-contain mx-auto`}
|
||||
style={typeof getLogoSizeClass('hero') === 'object' ?
|
||||
{ ...getLogoSizeClass('hero'), filter: 'brightness(0) invert(1) drop-shadow(0 2px 4px rgba(0, 0, 0, 0.3))' } :
|
||||
{ filter: 'brightness(0) invert(1) drop-shadow(0 2px 4px rgba(0, 0, 0, 0.3))' }
|
||||
}
|
||||
/>
|
||||
{shouldShowCompanyName() && brandingSettings?.company_name && (
|
||||
<div className="mt-3 text-xl sm:text-2xl font-semibold text-white/90" style={{ textShadow: '0 2px 4px rgba(0, 0, 0, 0.3)' }}>
|
||||
{brandingSettings.company_name}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
{!shouldShowLogo('hero') && shouldShowCompanyName() && brandingSettings?.company_name && (
|
||||
<div className="mb-6 text-2xl sm:text-3xl font-bold text-white" style={{ textShadow: '0 2px 4px rgba(0, 0, 0, 0.3)' }}>
|
||||
{brandingSettings.company_name || 'PicPeak'}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Event Name */}
|
||||
<h1
|
||||
|
||||
@@ -3,6 +3,7 @@ import { X, Download, Filter, SortAsc, Search, Calendar, Type, HardDrive, Check,
|
||||
import { Button } from '../common';
|
||||
import { PhotoCategory } from '../../types';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { GalleryFilter, type FilterType } from './GalleryFilter';
|
||||
|
||||
interface GallerySidebarProps {
|
||||
isOpen: boolean;
|
||||
@@ -28,6 +29,11 @@ interface GallerySidebarProps {
|
||||
galleryLayout?: string;
|
||||
allowUploads?: boolean;
|
||||
onUploadClick?: () => void;
|
||||
feedbackEnabled?: boolean;
|
||||
filterType?: FilterType;
|
||||
onFilterChange?: (filter: FilterType) => void;
|
||||
likeCount?: number;
|
||||
ratedCount?: number;
|
||||
}
|
||||
|
||||
export const GallerySidebar: React.FC<GallerySidebarProps> = ({
|
||||
@@ -53,7 +59,12 @@ export const GallerySidebar: React.FC<GallerySidebarProps> = ({
|
||||
isMobile,
|
||||
galleryLayout,
|
||||
allowUploads,
|
||||
onUploadClick
|
||||
onUploadClick,
|
||||
feedbackEnabled = false,
|
||||
filterType = 'all',
|
||||
onFilterChange,
|
||||
likeCount = 0,
|
||||
ratedCount = 0
|
||||
}) => {
|
||||
const { t } = useTranslation();
|
||||
const sidebarRef = useRef<HTMLDivElement>(null);
|
||||
@@ -103,7 +114,7 @@ export const GallerySidebar: React.FC<GallerySidebarProps> = ({
|
||||
<div
|
||||
ref={sidebarRef}
|
||||
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'}
|
||||
${isOpen ? 'translate-x-0' : '-translate-x-full'}
|
||||
`}
|
||||
@@ -194,13 +205,31 @@ export const GallerySidebar: React.FC<GallerySidebarProps> = ({
|
||||
disabled={isDownloading}
|
||||
className="w-full"
|
||||
>
|
||||
{t('gallery.downloadSelected')} ({selectedCount})
|
||||
{t('gallery.downloadSelected', { count: selectedCount })} ({selectedCount})
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Feedback Filter Section */}
|
||||
{feedbackEnabled && onFilterChange && (
|
||||
<div className="p-4 border-b border-neutral-200">
|
||||
<GalleryFilter
|
||||
currentFilter={filterType}
|
||||
onFilterChange={(filter) => {
|
||||
onFilterChange(filter);
|
||||
if (isMobile) onClose();
|
||||
}}
|
||||
feedbackEnabled={feedbackEnabled}
|
||||
likeCount={likeCount}
|
||||
ratedCount={ratedCount}
|
||||
className="w-full"
|
||||
variant="compact"
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Categories Section - Hidden for carousel layout */}
|
||||
{galleryLayout !== 'carousel' && categories.length > 0 && (
|
||||
<div className="p-4 border-b border-neutral-200">
|
||||
@@ -300,4 +329,4 @@ export const GallerySidebar: React.FC<GallerySidebarProps> = ({
|
||||
|
||||
</>
|
||||
);
|
||||
};
|
||||
};
|
||||
|
||||
@@ -13,6 +13,7 @@ import { GalleryLayout } from './GalleryLayout';
|
||||
import { GallerySidebar } from './GallerySidebar';
|
||||
import { PhotoFilterBar } from './PhotoFilterBar';
|
||||
import { UserPhotoUpload } from './UserPhotoUpload';
|
||||
import type { FilterType } from './GalleryFilter';
|
||||
import { analyticsService } from '../../services/analytics.service';
|
||||
import { useDevToolsProtection } from '../../hooks/useDevToolsProtection';
|
||||
import { GALLERY_THEME_PRESETS } from '../../types/theme.types';
|
||||
@@ -21,6 +22,7 @@ import { Upload, Menu } from 'lucide-react';
|
||||
import { galleryService } from '../../services/gallery.service';
|
||||
import { feedbackService } from '../../services/feedback.service';
|
||||
import { useWatermarkSettings } from '../../hooks/useWatermarkSettings';
|
||||
import type { Photo } from '../../types';
|
||||
|
||||
interface GalleryViewProps {
|
||||
slug: string;
|
||||
@@ -55,9 +57,23 @@ export const GalleryView: React.FC<GalleryViewProps> = ({ slug, event }) => {
|
||||
const [isMobile, setIsMobile] = useState(window.innerWidth < 768);
|
||||
const { watermarkEnabled } = useWatermarkSettings();
|
||||
const [protectionLevel, setProtectionLevel] = useState<'basic' | 'standard' | 'enhanced' | 'maximum'>('standard');
|
||||
const [filterType, setFilterType] = useState<FilterType>('all');
|
||||
const [guestId, setGuestId] = useState<string>('');
|
||||
const [staticHeroPhoto, setStaticHeroPhoto] = useState<Photo | null>(null);
|
||||
|
||||
// Fetch photos
|
||||
const { data, isLoading, error, refetch } = useGalleryPhotos(slug);
|
||||
// Generate a unique guest ID for this session
|
||||
useEffect(() => {
|
||||
// Use existing guest ID from localStorage or generate new one
|
||||
let storedGuestId = localStorage.getItem('gallery_guest_id');
|
||||
if (!storedGuestId) {
|
||||
storedGuestId = `guest_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
|
||||
localStorage.setItem('gallery_guest_id', storedGuestId);
|
||||
}
|
||||
setGuestId(storedGuestId);
|
||||
}, []);
|
||||
|
||||
// Fetch photos with filter support
|
||||
const { data, isLoading, error, refetch } = useGalleryPhotos(slug, filterType, guestId);
|
||||
|
||||
// Set protection level when data is available
|
||||
useEffect(() => {
|
||||
@@ -122,7 +138,6 @@ export const GalleryView: React.FC<GalleryViewProps> = ({ slug, event }) => {
|
||||
try {
|
||||
// Use public endpoint to get feedback settings
|
||||
const response = await api.get(`/gallery/${slug}/feedback-settings`);
|
||||
console.log('Feedback settings response:', response.data);
|
||||
return response.data;
|
||||
} catch (error) {
|
||||
console.error('Error fetching feedback settings:', error);
|
||||
@@ -136,7 +151,6 @@ export const GalleryView: React.FC<GalleryViewProps> = ({ slug, event }) => {
|
||||
// Update feedbackEnabled when settings change
|
||||
useEffect(() => {
|
||||
if (feedbackSettings) {
|
||||
console.log('Setting feedbackEnabled to:', feedbackSettings.feedback_enabled);
|
||||
setFeedbackEnabled(feedbackSettings.feedback_enabled || false);
|
||||
}
|
||||
}, [feedbackSettings]);
|
||||
@@ -155,6 +169,23 @@ export const GalleryView: React.FC<GalleryViewProps> = ({ slug, event }) => {
|
||||
}
|
||||
}, [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
|
||||
useEffect(() => {
|
||||
if (settingsData && data?.event) {
|
||||
@@ -235,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
|
||||
photos.sort((a, b) => {
|
||||
switch (sortBy) {
|
||||
@@ -267,7 +313,7 @@ export const GalleryView: React.FC<GalleryViewProps> = ({ slug, event }) => {
|
||||
}
|
||||
|
||||
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)
|
||||
const allowDownloads = !isExpired && (data?.event?.allow_downloads === true);
|
||||
@@ -424,6 +470,11 @@ export const GalleryView: React.FC<GalleryViewProps> = ({ slug, event }) => {
|
||||
galleryLayout={theme.galleryLayout}
|
||||
allowUploads={data?.event?.allow_user_uploads || event?.allow_user_uploads || false}
|
||||
onUploadClick={() => setShowUploadModal(true)}
|
||||
feedbackEnabled={feedbackEnabled}
|
||||
filterType={filterType}
|
||||
onFilterChange={setFilterType}
|
||||
likeCount={data?.photos?.filter(p => p.like_count > 0).length || 0}
|
||||
ratedCount={data?.photos?.filter(p => (p.total_ratings || 0) > 0).length || 0}
|
||||
/>
|
||||
) : null}
|
||||
|
||||
@@ -510,6 +561,10 @@ export const GalleryView: React.FC<GalleryViewProps> = ({ slug, event }) => {
|
||||
sortBy={sortBy}
|
||||
onSortChange={setSortBy}
|
||||
photoCount={filteredPhotos.length}
|
||||
// Feedback filter props
|
||||
feedbackEnabled={feedbackEnabled}
|
||||
currentFilter={filterType}
|
||||
onFilterChange={setFilterType}
|
||||
/>
|
||||
</div>
|
||||
) : null}
|
||||
@@ -520,7 +575,16 @@ export const GalleryView: React.FC<GalleryViewProps> = ({ slug, event }) => {
|
||||
photos={filteredPhotos}
|
||||
slug={slug}
|
||||
categoryId={selectedCategoryId}
|
||||
onFeedbackChange={() => refetch()}
|
||||
heroPhotoOverride={staticHeroPhoto}
|
||||
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}
|
||||
selectedPhotos={selectedPhotos}
|
||||
onSelectionChange={setSelectedPhotos}
|
||||
@@ -552,4 +616,4 @@ export const GalleryView: React.FC<GalleryViewProps> = ({ slug, event }) => {
|
||||
</GalleryLayout>
|
||||
</>
|
||||
);
|
||||
};
|
||||
};
|
||||
|
||||
@@ -103,8 +103,8 @@ export const PhotoComments: React.FC<PhotoCommentsProps> = ({
|
||||
|
||||
submitCommentMutation.mutate({
|
||||
comment_text: commentText.trim(),
|
||||
guest_name: guestName.trim(),
|
||||
guest_email: guestEmail.trim()
|
||||
guest_name: guestName.trim() || undefined,
|
||||
guest_email: guestEmail.trim() || undefined
|
||||
});
|
||||
};
|
||||
|
||||
|
||||
@@ -4,6 +4,7 @@ import { useTranslation } from 'react-i18next';
|
||||
import { useMutation, useQueryClient } from '@tanstack/react-query';
|
||||
import { feedbackService } from '../../services/feedback.service';
|
||||
import { toast } from 'react-toastify';
|
||||
import { FeedbackIdentityModal } from './FeedbackIdentityModal';
|
||||
|
||||
interface PhotoFavoritesProps {
|
||||
photoId: string;
|
||||
@@ -11,6 +12,7 @@ interface PhotoFavoritesProps {
|
||||
isFavorited: boolean;
|
||||
favoriteCount: number;
|
||||
isEnabled: boolean;
|
||||
requireNameEmail?: boolean;
|
||||
onFavoriteChange?: (favorited: boolean) => void;
|
||||
}
|
||||
|
||||
@@ -20,17 +22,22 @@ export const PhotoFavorites: React.FC<PhotoFavoritesProps> = ({
|
||||
isFavorited,
|
||||
favoriteCount,
|
||||
isEnabled,
|
||||
requireNameEmail = false,
|
||||
onFavoriteChange
|
||||
}) => {
|
||||
const { t } = useTranslation();
|
||||
const queryClient = useQueryClient();
|
||||
const [isSubmitting, setIsSubmitting] = useState(false);
|
||||
const [animating, setAnimating] = useState(false);
|
||||
const [showIdentityModal, setShowIdentityModal] = useState(false);
|
||||
const [savedIdentity, setSavedIdentity] = useState<{ name: string; email: string } | null>(null);
|
||||
|
||||
const submitFavoriteMutation = useMutation({
|
||||
mutationFn: () =>
|
||||
mutationFn: (data: { guest_name?: string; guest_email?: string } = {}) =>
|
||||
feedbackService.submitFeedback(gallerySlug, photoId, {
|
||||
feedback_type: 'favorite'
|
||||
feedback_type: 'favorite',
|
||||
guest_name: data.guest_name || undefined,
|
||||
guest_email: data.guest_email || undefined
|
||||
}),
|
||||
onMutate: async () => {
|
||||
setIsSubmitting(true);
|
||||
@@ -62,13 +69,25 @@ export const PhotoFavorites: React.FC<PhotoFavoritesProps> = ({
|
||||
|
||||
const handleFavoriteClick = () => {
|
||||
if (!isEnabled || isSubmitting) return;
|
||||
submitFavoriteMutation.mutate();
|
||||
|
||||
if (requireNameEmail && !savedIdentity) {
|
||||
setShowIdentityModal(true);
|
||||
} else {
|
||||
submitFavoriteMutation.mutate(savedIdentity || {});
|
||||
}
|
||||
};
|
||||
|
||||
const handleIdentitySubmit = (name: string, email: string) => {
|
||||
setSavedIdentity({ name, email });
|
||||
setShowIdentityModal(false);
|
||||
submitFavoriteMutation.mutate({ guest_name: name, guest_email: email });
|
||||
};
|
||||
|
||||
if (!isEnabled) return null;
|
||||
|
||||
return (
|
||||
<button
|
||||
<>
|
||||
<button
|
||||
onClick={handleFavoriteClick}
|
||||
disabled={isSubmitting}
|
||||
className={`group flex items-center gap-2 px-3 py-2 rounded-lg transition-all ${
|
||||
@@ -88,6 +107,13 @@ export const PhotoFavorites: React.FC<PhotoFavoritesProps> = ({
|
||||
<span className="text-sm font-medium">
|
||||
{favoriteCount > 0 ? favoriteCount : ''}
|
||||
</span>
|
||||
</button>
|
||||
</button>
|
||||
<FeedbackIdentityModal
|
||||
isOpen={showIdentityModal}
|
||||
onClose={() => setShowIdentityModal(false)}
|
||||
onSubmit={handleIdentitySubmit}
|
||||
feedbackType={t('feedback.favorite', 'favorite')}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
};
|
||||
@@ -4,7 +4,6 @@ import { feedbackService } from '../../services/feedback.service';
|
||||
import { PhotoRating } from './PhotoRating';
|
||||
import { PhotoLikes } from './PhotoLikes';
|
||||
import { PhotoComments } from './PhotoComments';
|
||||
import { PhotoFavorites } from './PhotoFavorites';
|
||||
import { Skeleton } from '../common';
|
||||
import type { FeedbackSettings } from '../../services/feedback.service';
|
||||
|
||||
@@ -26,7 +25,10 @@ export const PhotoFeedback: React.FC<PhotoFeedbackProps> = ({
|
||||
// Fetch feedback settings for the gallery
|
||||
const { data: settings, isLoading: settingsLoading } = useQuery({
|
||||
queryKey: ['gallery-feedback-settings', gallerySlug],
|
||||
queryFn: () => feedbackService.getGalleryFeedbackSettings(gallerySlug),
|
||||
queryFn: async () => {
|
||||
const data = await feedbackService.getGalleryFeedbackSettings(gallerySlug);
|
||||
return data;
|
||||
},
|
||||
staleTime: 5 * 60 * 1000, // Cache for 5 minutes
|
||||
});
|
||||
|
||||
@@ -40,18 +42,14 @@ export const PhotoFeedback: React.FC<PhotoFeedbackProps> = ({
|
||||
// Local state for optimistic updates
|
||||
const [currentRating, setCurrentRating] = useState(0);
|
||||
const [isLiked, setIsLiked] = useState(false);
|
||||
const [isFavorited, setIsFavorited] = useState(false);
|
||||
const [likeCount, setLikeCount] = useState(0);
|
||||
const [favoriteCount, setFavoriteCount] = useState(0);
|
||||
|
||||
// Update local state when data loads
|
||||
useEffect(() => {
|
||||
if (feedbackData) {
|
||||
setCurrentRating(feedbackData.my_feedback.rating || 0);
|
||||
setIsLiked(feedbackData.my_feedback.liked);
|
||||
setIsFavorited(feedbackData.my_feedback.favorited);
|
||||
setLikeCount(feedbackData.summary.like_count);
|
||||
setFavoriteCount(feedbackData.summary.favorite_count);
|
||||
}
|
||||
}, [feedbackData]);
|
||||
|
||||
@@ -67,12 +65,6 @@ export const PhotoFeedback: React.FC<PhotoFeedbackProps> = ({
|
||||
if (onFeedbackUpdate) onFeedbackUpdate();
|
||||
};
|
||||
|
||||
const handleFavoriteChange = (favorited: boolean) => {
|
||||
setIsFavorited(favorited);
|
||||
setFavoriteCount(prev => favorited ? prev + 1 : Math.max(0, prev - 1));
|
||||
if (onFeedbackUpdate) onFeedbackUpdate();
|
||||
};
|
||||
|
||||
if (settingsLoading) {
|
||||
return (
|
||||
<div className={`space-y-3 ${className}`}>
|
||||
@@ -87,7 +79,7 @@ export const PhotoFeedback: React.FC<PhotoFeedbackProps> = ({
|
||||
}
|
||||
|
||||
const hasAnyFeedbackType = settings.allow_ratings || settings.allow_likes ||
|
||||
settings.allow_comments || settings.allow_favorites;
|
||||
settings.allow_comments;
|
||||
|
||||
if (!hasAnyFeedbackType) {
|
||||
return null;
|
||||
@@ -104,12 +96,13 @@ export const PhotoFeedback: React.FC<PhotoFeedbackProps> = ({
|
||||
averageRating={Number(feedbackData?.summary?.average_rating) || 0}
|
||||
totalRatings={Number(feedbackData?.summary?.total_ratings) || 0}
|
||||
isEnabled={true}
|
||||
requireNameEmail={settings.require_name_email || false}
|
||||
onRatingChange={handleRatingChange}
|
||||
/>
|
||||
)}
|
||||
|
||||
{/* Action Buttons */}
|
||||
{(settings.allow_likes || settings.allow_favorites) && (
|
||||
{settings.allow_likes && (
|
||||
<div className="flex items-center gap-2">
|
||||
{settings.allow_likes && (
|
||||
<PhotoLikes
|
||||
@@ -118,19 +111,10 @@ export const PhotoFeedback: React.FC<PhotoFeedbackProps> = ({
|
||||
isLiked={isLiked}
|
||||
likeCount={likeCount}
|
||||
isEnabled={true}
|
||||
requireNameEmail={settings.require_name_email || false}
|
||||
onLikeChange={handleLikeChange}
|
||||
/>
|
||||
)}
|
||||
{settings.allow_favorites && (
|
||||
<PhotoFavorites
|
||||
photoId={photoId}
|
||||
gallerySlug={gallerySlug}
|
||||
isFavorited={isFavorited}
|
||||
favoriteCount={favoriteCount}
|
||||
isEnabled={true}
|
||||
onFavoriteChange={handleFavoriteChange}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
@@ -152,4 +136,4 @@ export const PhotoFeedback: React.FC<PhotoFeedbackProps> = ({
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
};
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
import React, { useState } from 'react';
|
||||
import { Search, SortAsc, Grid } from 'lucide-react';
|
||||
import { Search, SortAsc, Grid, Heart, Star, MessageSquare } from 'lucide-react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Button, Input } from '../common';
|
||||
import type { FilterType } from './GalleryFilter';
|
||||
|
||||
interface PhotoCategory {
|
||||
id: number;
|
||||
@@ -13,6 +14,8 @@ interface PhotoCategory {
|
||||
interface Photo {
|
||||
id: number;
|
||||
category_id?: number;
|
||||
like_count?: number;
|
||||
favorite_count?: number;
|
||||
}
|
||||
|
||||
interface PhotoFilterBarProps {
|
||||
@@ -25,6 +28,10 @@ interface PhotoFilterBarProps {
|
||||
sortBy: 'date' | 'name' | 'size' | 'rating';
|
||||
onSortChange: (sort: 'date' | 'name' | 'size' | 'rating') => void;
|
||||
photoCount: number;
|
||||
// Feedback filter props
|
||||
feedbackEnabled?: boolean;
|
||||
currentFilter?: FilterType;
|
||||
onFilterChange?: (filter: FilterType) => void;
|
||||
}
|
||||
|
||||
export const PhotoFilterBar: React.FC<PhotoFilterBarProps> = ({
|
||||
@@ -37,6 +44,9 @@ export const PhotoFilterBar: React.FC<PhotoFilterBarProps> = ({
|
||||
sortBy,
|
||||
onSortChange,
|
||||
photoCount,
|
||||
feedbackEnabled = false,
|
||||
currentFilter = 'all',
|
||||
onFilterChange,
|
||||
}) => {
|
||||
const { t } = useTranslation();
|
||||
const [showSortMenu, setShowSortMenu] = useState(false);
|
||||
@@ -44,7 +54,7 @@ export const PhotoFilterBar: React.FC<PhotoFilterBarProps> = ({
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
{/* Search and Sort */}
|
||||
<div className="flex flex-col sm:flex-row gap-3 sm:gap-4">
|
||||
<div className="flex flex-col md:flex-row gap-3 md:gap-4">
|
||||
{/* Search Bar */}
|
||||
<div className="flex-1">
|
||||
<Input
|
||||
@@ -53,7 +63,7 @@ export const PhotoFilterBar: React.FC<PhotoFilterBarProps> = ({
|
||||
leftIcon={<Search className="w-5 h-5 text-neutral-400" />}
|
||||
value={searchTerm}
|
||||
onChange={(e) => onSearchChange(e.target.value)}
|
||||
className="text-sm sm:text-base"
|
||||
className="text-sm md:text-base"
|
||||
/>
|
||||
</div>
|
||||
|
||||
@@ -64,9 +74,9 @@ export const PhotoFilterBar: React.FC<PhotoFilterBarProps> = ({
|
||||
size="md"
|
||||
leftIcon={<SortAsc className="w-4 h-4" />}
|
||||
onClick={() => setShowSortMenu(!showSortMenu)}
|
||||
className="w-full sm:w-auto text-sm sm:text-base"
|
||||
className="w-full md:w-auto text-sm md:text-base"
|
||||
>
|
||||
<span className="hidden sm:inline">{t('common.sortBy')} </span>
|
||||
<span className="hidden md:inline">{t('common.sortBy')} </span>
|
||||
{sortBy === 'date' ? t('gallery.sortByDate').replace('Sort by ', '') :
|
||||
sortBy === 'name' ? t('gallery.sortByName').replace('Sort by ', '') :
|
||||
sortBy === 'size' ? t('gallery.sortBySize').replace('Sort by ', '') :
|
||||
@@ -74,7 +84,7 @@ export const PhotoFilterBar: React.FC<PhotoFilterBarProps> = ({
|
||||
</Button>
|
||||
|
||||
{showSortMenu && (
|
||||
<div className="absolute right-0 sm:right-auto sm:left-0 mt-2 w-48 bg-white rounded-lg shadow-lg border border-neutral-200 py-1 z-10">
|
||||
<div className="absolute right-0 md:right-auto md:left-0 mt-2 w-48 bg-white rounded-lg shadow-lg border border-neutral-200 py-1 z-10">
|
||||
<button
|
||||
onClick={() => {
|
||||
onSortChange('date');
|
||||
@@ -124,18 +134,20 @@ export const PhotoFilterBar: React.FC<PhotoFilterBarProps> = ({
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Category Filter */}
|
||||
{categories && categories.length > 0 && (
|
||||
<div className="space-y-3">
|
||||
<div className="flex items-start sm:items-center justify-between flex-col sm:flex-row gap-3">
|
||||
<div className="w-full sm:w-auto overflow-x-auto pb-2 sm:pb-0">
|
||||
{/* Category and Feedback Filters */}
|
||||
<div className="space-y-3">
|
||||
{/* Categories Row */}
|
||||
{categories && categories.length > 0 && (
|
||||
<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="flex items-center gap-2 min-w-max">
|
||||
<Button
|
||||
variant={selectedCategoryId === null ? 'primary' : 'outline'}
|
||||
size="sm"
|
||||
onClick={() => onCategoryChange(null)}
|
||||
leftIcon={<Grid className="w-3 h-3 sm:w-4 sm:h-4" />}
|
||||
className="text-xs sm:text-sm whitespace-nowrap"
|
||||
leftIcon={<Grid className="w-3 h-3 md:w-4 md:h-4" />}
|
||||
className="text-xs md:text-sm whitespace-nowrap flex-shrink-0"
|
||||
>
|
||||
{t('gallery.allPhotos')} ({photos.length})
|
||||
</Button>
|
||||
@@ -149,7 +161,7 @@ export const PhotoFilterBar: React.FC<PhotoFilterBarProps> = ({
|
||||
variant={selectedCategoryId === category.id ? 'primary' : 'outline'}
|
||||
size="sm"
|
||||
onClick={() => onCategoryChange(category.id)}
|
||||
className="text-xs sm:text-sm whitespace-nowrap"
|
||||
className="text-xs md:text-sm whitespace-nowrap flex-shrink-0"
|
||||
>
|
||||
{category.name} ({categoryPhotoCount})
|
||||
</Button>
|
||||
@@ -158,14 +170,108 @@ export const PhotoFilterBar: React.FC<PhotoFilterBarProps> = ({
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<p className="text-xs sm:text-sm text-neutral-600 flex-shrink-0">
|
||||
{/* 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">
|
||||
{photoCount} {photoCount === 1 ? t('common.photo') : t('common.photos')}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
)}
|
||||
|
||||
{/* Mobile/Tablet: compact horizontal icons with headline below categories */}
|
||||
{feedbackEnabled && onFilterChange && (
|
||||
<div className="flex lg:hidden items-center gap-2">
|
||||
<span className="text-xs 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>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
PhotoFilterBar.displayName = 'PhotoFilterBar';
|
||||
PhotoFilterBar.displayName = 'PhotoFilterBar';
|
||||
|
||||
@@ -95,35 +95,17 @@ export const PhotoGrid: React.FC<PhotoGridProps> = ({
|
||||
|
||||
const handleDownloadSelected = async () => {
|
||||
if (selectedPhotos.size === 0) return;
|
||||
|
||||
const selectedPhotosList = photos.filter(p => selectedPhotos.has(p.id));
|
||||
|
||||
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;
|
||||
})
|
||||
);
|
||||
|
||||
const ids = Array.from(selectedPhotos);
|
||||
toastify.info(t('gallery.downloading', { count: ids.length }));
|
||||
|
||||
try {
|
||||
await Promise.all(downloadPromises);
|
||||
toastify.success(t('gallery.downloadedPhotos', { count: selectedPhotos.size }));
|
||||
|
||||
// Track bulk download
|
||||
analyticsService.trackGalleryEvent('bulk_download', {
|
||||
gallery: slug,
|
||||
photo_count: selectedPhotos.size
|
||||
});
|
||||
|
||||
// Clear selection after download
|
||||
setSelectedPhotos(new Set());
|
||||
setIsSelectionMode(false);
|
||||
await galleryService.downloadSelectedPhotos(slug, ids);
|
||||
analyticsService.trackGalleryEvent('bulk_download_selected', { gallery: slug, photo_count: ids.length });
|
||||
} catch (error) {
|
||||
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 */}
|
||||
<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 && (
|
||||
<>
|
||||
<button
|
||||
@@ -365,4 +347,4 @@ const PhotoThumbnail: React.FC<PhotoThumbnailProps> = ({
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
};
|
||||
|
||||
@@ -25,6 +25,9 @@ interface PhotoGridWithLayoutsProps {
|
||||
photos: Photo[];
|
||||
slug: string;
|
||||
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;
|
||||
selectedPhotos?: Set<number>;
|
||||
onSelectionChange?: (photos: Set<number>) => void;
|
||||
@@ -38,15 +41,26 @@ interface PhotoGridWithLayoutsProps {
|
||||
allowDownloads?: boolean;
|
||||
protectionLevel?: 'basic' | 'standard' | 'enhanced' | 'maximum';
|
||||
useEnhancedProtection?: boolean;
|
||||
feedbackOptions?: {
|
||||
allowLikes?: boolean;
|
||||
allowFavorites?: boolean;
|
||||
allowRatings?: boolean;
|
||||
allowComments?: boolean;
|
||||
requireNameEmail?: boolean;
|
||||
};
|
||||
onFeedbackChange?: () => void;
|
||||
}
|
||||
|
||||
export const PhotoGridWithLayouts: React.FC<PhotoGridWithLayoutsProps> = ({
|
||||
photos,
|
||||
slug,
|
||||
categoryId,
|
||||
heroPhotoOverride,
|
||||
isSelectionMode: parentSelectionMode,
|
||||
selectedPhotos: parentSelectedPhotos,
|
||||
feedbackEnabled,
|
||||
feedbackOptions,
|
||||
onFeedbackChange,
|
||||
allowDownloads = true,
|
||||
protectionLevel = 'standard',
|
||||
useEnhancedProtection = false,
|
||||
@@ -61,6 +75,7 @@ export const PhotoGridWithLayouts: React.FC<PhotoGridWithLayoutsProps> = ({
|
||||
const { t } = useTranslation();
|
||||
const { theme } = useTheme();
|
||||
const [selectedPhotoIndex, setSelectedPhotoIndex] = useState<number | null>(null);
|
||||
const [openFeedbackInitially, setOpenFeedbackInitially] = useState<boolean>(false);
|
||||
const [localSelectedPhotos, setLocalSelectedPhotos] = useState<Set<number>>(new Set());
|
||||
const [localSelectionMode, setLocalSelectionMode] = useState(false);
|
||||
const downloadPhotoMutation = useDownloadPhoto();
|
||||
@@ -77,10 +92,24 @@ export const PhotoGridWithLayouts: React.FC<PhotoGridWithLayoutsProps> = ({
|
||||
}, [categoryId]);
|
||||
|
||||
const handlePhotoClick = (index: number) => {
|
||||
setOpenFeedbackInitially(false);
|
||||
setSelectedPhotoIndex(index);
|
||||
};
|
||||
|
||||
const handleOpenWithFeedback = (index: number) => {
|
||||
setOpenFeedbackInitially(true);
|
||||
setSelectedPhotoIndex(index);
|
||||
};
|
||||
|
||||
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);
|
||||
if (newSelected.has(photoId)) {
|
||||
newSelected.delete(photoId);
|
||||
@@ -114,39 +143,21 @@ export const PhotoGridWithLayouts: React.FC<PhotoGridWithLayoutsProps> = ({
|
||||
|
||||
const handleDownloadSelected = async () => {
|
||||
if (selectedPhotos.size === 0) return;
|
||||
|
||||
const selectedPhotosList = photos.filter(p => selectedPhotos.has(p.id));
|
||||
|
||||
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;
|
||||
})
|
||||
);
|
||||
|
||||
const ids = Array.from(selectedPhotos);
|
||||
toastify.info(t('gallery.downloading', { count: ids.length }));
|
||||
|
||||
try {
|
||||
await Promise.all(downloadPromises);
|
||||
toastify.success(t('gallery.downloadedPhotos', { count: selectedPhotos.size }));
|
||||
|
||||
// Track bulk download
|
||||
analyticsService.trackGalleryEvent('bulk_download', {
|
||||
gallery: slug,
|
||||
photo_count: selectedPhotos.size
|
||||
});
|
||||
|
||||
// Clear selection after download
|
||||
await galleryService.downloadSelectedPhotos(slug, ids);
|
||||
analyticsService.trackGalleryEvent('bulk_download_selected', { gallery: slug, photo_count: ids.length });
|
||||
} catch (error) {
|
||||
toastify.error(t('gallery.downloadError'));
|
||||
} finally {
|
||||
setSelectedPhotos(new Set());
|
||||
if (parentToggleSelectionMode) {
|
||||
parentToggleSelectionMode();
|
||||
} else {
|
||||
setLocalSelectionMode(false);
|
||||
}
|
||||
} catch (error) {
|
||||
toastify.error(t('gallery.downloadError'));
|
||||
}
|
||||
};
|
||||
|
||||
@@ -166,7 +177,10 @@ export const PhotoGridWithLayouts: React.FC<PhotoGridWithLayoutsProps> = ({
|
||||
photos,
|
||||
slug,
|
||||
onPhotoClick: handlePhotoClick,
|
||||
onOpenPhotoWithFeedback: handleOpenWithFeedback,
|
||||
onFeedbackChange: onFeedbackChange,
|
||||
onDownload: handleDownload,
|
||||
heroPhotoOverride,
|
||||
selectedPhotos,
|
||||
allowDownloads,
|
||||
protectionLevel,
|
||||
@@ -178,6 +192,7 @@ export const PhotoGridWithLayouts: React.FC<PhotoGridWithLayoutsProps> = ({
|
||||
eventDate,
|
||||
expiresAt,
|
||||
feedbackEnabled,
|
||||
feedbackOptions,
|
||||
};
|
||||
|
||||
let LayoutComponent;
|
||||
@@ -275,8 +290,9 @@ export const PhotoGridWithLayouts: React.FC<PhotoGridWithLayoutsProps> = ({
|
||||
allowDownloads={allowDownloads}
|
||||
protectionLevel={protectionLevel}
|
||||
useEnhancedProtection={useEnhancedProtection}
|
||||
initialShowFeedback={openFeedbackInitially}
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
};
|
||||
};
|
||||
|
||||
@@ -1,10 +1,12 @@
|
||||
import React, { useState, useEffect } from 'react';
|
||||
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 { useDownloadPhoto } from '../../hooks/useGallery';
|
||||
import { AuthenticatedImage } from '../common';
|
||||
import { PhotoFeedback } from './PhotoFeedback';
|
||||
import { feedbackService } from '../../services/feedback.service';
|
||||
import { FeedbackIdentityModal } from './FeedbackIdentityModal';
|
||||
|
||||
interface PhotoLightboxProps {
|
||||
photos: Photo[];
|
||||
@@ -15,6 +17,7 @@ interface PhotoLightboxProps {
|
||||
allowDownloads?: boolean;
|
||||
protectionLevel?: 'basic' | 'standard' | 'enhanced' | 'maximum';
|
||||
useEnhancedProtection?: boolean;
|
||||
initialShowFeedback?: boolean;
|
||||
}
|
||||
|
||||
export const PhotoLightbox: React.FC<PhotoLightboxProps> = ({
|
||||
@@ -26,6 +29,7 @@ export const PhotoLightbox: React.FC<PhotoLightboxProps> = ({
|
||||
allowDownloads = true,
|
||||
protectionLevel = 'standard',
|
||||
useEnhancedProtection = false,
|
||||
initialShowFeedback = false,
|
||||
}) => {
|
||||
const [currentIndex, setCurrentIndex] = useState(initialIndex);
|
||||
const [zoom, setZoom] = useState(1);
|
||||
@@ -33,10 +37,28 @@ export const PhotoLightbox: React.FC<PhotoLightboxProps> = ({
|
||||
const [dragStart, setDragStart] = useState({ x: 0, y: 0 });
|
||||
const [dragOffset, setDragOffset] = useState({ x: 0, y: 0 });
|
||||
const [touchDistance, setTouchDistance] = useState<number | null>(null);
|
||||
const [showFeedback, setShowFeedback] = useState(false);
|
||||
|
||||
// Debug logging
|
||||
console.log('PhotoLightbox feedbackEnabled:', feedbackEnabled);
|
||||
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 currentPhoto = photos[currentIndex];
|
||||
@@ -114,6 +136,81 @@ export const PhotoLightbox: React.FC<PhotoLightboxProps> = ({
|
||||
};
|
||||
}, [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 = () => {
|
||||
setCurrentIndex((prev) => (prev > 0 ? prev - 1 : photos.length - 1));
|
||||
resetZoom();
|
||||
@@ -214,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';
|
||||
|
||||
const desktopFeedbackWidth = 416; // 26rem; keep in sync with panel width
|
||||
const isDesktopFeedback = showFeedback && !isSmallScreen;
|
||||
|
||||
return (
|
||||
<div className={lightboxClass}>
|
||||
{/* Close button */}
|
||||
<button
|
||||
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"
|
||||
style={{ right: isDesktopFeedback ? `${desktopFeedbackWidth + 16}px` : '1rem' }}
|
||||
>
|
||||
<X className="w-6 h-6 text-white" />
|
||||
</button>
|
||||
@@ -234,16 +335,22 @@ export const PhotoLightbox: React.FC<PhotoLightboxProps> = ({
|
||||
<ChevronLeft className="w-6 h-6 text-white" />
|
||||
</button>
|
||||
|
||||
<button
|
||||
onClick={goToNext}
|
||||
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"
|
||||
aria-label="Next photo"
|
||||
>
|
||||
<ChevronRight className="w-6 h-6 text-white" />
|
||||
</button>
|
||||
{!showFeedback || !isSmallScreen ? (
|
||||
<button
|
||||
onClick={goToNext}
|
||||
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"
|
||||
style={{ right: isDesktopFeedback ? `${desktopFeedbackWidth + 16}px` : '1rem' }}
|
||||
>
|
||||
<ChevronRight className="w-6 h-6 text-white" />
|
||||
</button>
|
||||
) : null}
|
||||
|
||||
{/* 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="text-white">
|
||||
<p className="text-sm opacity-75">
|
||||
@@ -283,12 +390,44 @@ export const PhotoLightbox: React.FC<PhotoLightboxProps> = ({
|
||||
<Download className="w-5 h-5 text-white" />
|
||||
</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 */}
|
||||
{feedbackEnabled && (
|
||||
<button
|
||||
onClick={() => {
|
||||
console.log('Feedback button clicked, current feedbackEnabled:', feedbackEnabled);
|
||||
setShowFeedback(!showFeedback);
|
||||
}}
|
||||
className="relative p-2 bg-white/10 hover:bg-white/20 rounded-full transition-colors"
|
||||
@@ -309,7 +448,7 @@ export const PhotoLightbox: React.FC<PhotoLightboxProps> = ({
|
||||
|
||||
{/* Image container */}
|
||||
<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}
|
||||
onMouseDown={handleMouseDown}
|
||||
onMouseMove={handleMouseMove}
|
||||
@@ -318,11 +457,15 @@ export const PhotoLightbox: React.FC<PhotoLightboxProps> = ({
|
||||
onTouchStart={handleTouchStart}
|
||||
onTouchMove={handleTouchMove}
|
||||
onTouchEnd={handleTouchEnd}
|
||||
style={{ cursor: zoom > 1 ? (isDragging ? 'grabbing' : 'grab') : 'default' }}
|
||||
style={{
|
||||
cursor: zoom > 1 ? (isDragging ? 'grabbing' : 'grab') : 'default',
|
||||
right: isDesktopFeedback ? `${desktopFeedbackWidth}px` : 0,
|
||||
}}
|
||||
>
|
||||
<AuthenticatedImage
|
||||
src={currentPhoto.url}
|
||||
alt={currentPhoto.filename}
|
||||
fallbackSrc={currentPhoto.thumbnail_url || undefined}
|
||||
className="max-w-full max-h-full object-contain select-none"
|
||||
style={{
|
||||
transform: `scale(${zoom}) translate(${dragOffset.x / zoom}px, ${dragOffset.y / zoom}px)`,
|
||||
@@ -373,7 +516,7 @@ export const PhotoLightbox: React.FC<PhotoLightboxProps> = ({
|
||||
|
||||
{/* Feedback Panel */}
|
||||
{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">
|
||||
<h3 className="font-semibold text-neutral-900">Photo Feedback</h3>
|
||||
<button
|
||||
@@ -384,7 +527,7 @@ export const PhotoLightbox: React.FC<PhotoLightboxProps> = ({
|
||||
<X className="w-5 h-5" />
|
||||
</button>
|
||||
</div>
|
||||
<div className="p-4">
|
||||
<div className="p-4 flex-1 overflow-y-auto">
|
||||
<PhotoFeedback
|
||||
photoId={currentPhoto.id}
|
||||
gallerySlug={slug}
|
||||
@@ -394,6 +537,34 @@ export const PhotoLightbox: React.FC<PhotoLightboxProps> = ({
|
||||
</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>
|
||||
);
|
||||
};
|
||||
};
|
||||
|
||||
@@ -4,6 +4,7 @@ import { useTranslation } from 'react-i18next';
|
||||
import { useMutation, useQueryClient } from '@tanstack/react-query';
|
||||
import { feedbackService } from '../../services/feedback.service';
|
||||
import { toast } from 'react-toastify';
|
||||
import { FeedbackIdentityModal } from './FeedbackIdentityModal';
|
||||
|
||||
interface PhotoLikesProps {
|
||||
photoId: string;
|
||||
@@ -11,6 +12,7 @@ interface PhotoLikesProps {
|
||||
isLiked: boolean;
|
||||
likeCount: number;
|
||||
isEnabled: boolean;
|
||||
requireNameEmail?: boolean;
|
||||
onLikeChange?: (liked: boolean) => void;
|
||||
}
|
||||
|
||||
@@ -20,17 +22,22 @@ export const PhotoLikes: React.FC<PhotoLikesProps> = ({
|
||||
isLiked,
|
||||
likeCount,
|
||||
isEnabled,
|
||||
requireNameEmail = false,
|
||||
onLikeChange
|
||||
}) => {
|
||||
const { t } = useTranslation();
|
||||
const queryClient = useQueryClient();
|
||||
const [isSubmitting, setIsSubmitting] = useState(false);
|
||||
const [animating, setAnimating] = useState(false);
|
||||
const [showIdentityModal, setShowIdentityModal] = useState(false);
|
||||
const [savedIdentity, setSavedIdentity] = useState<{ name: string; email: string } | null>(null);
|
||||
|
||||
const submitLikeMutation = useMutation({
|
||||
mutationFn: () =>
|
||||
mutationFn: (data: { guest_name?: string; guest_email?: string } = {}) =>
|
||||
feedbackService.submitFeedback(gallerySlug, photoId, {
|
||||
feedback_type: 'like'
|
||||
feedback_type: 'like',
|
||||
guest_name: data.guest_name || undefined,
|
||||
guest_email: data.guest_email || undefined
|
||||
}),
|
||||
onMutate: async () => {
|
||||
setIsSubmitting(true);
|
||||
@@ -62,13 +69,25 @@ export const PhotoLikes: React.FC<PhotoLikesProps> = ({
|
||||
|
||||
const handleLikeClick = () => {
|
||||
if (!isEnabled || isSubmitting) return;
|
||||
submitLikeMutation.mutate();
|
||||
|
||||
if (requireNameEmail && !savedIdentity) {
|
||||
setShowIdentityModal(true);
|
||||
} else {
|
||||
submitLikeMutation.mutate(savedIdentity || {});
|
||||
}
|
||||
};
|
||||
|
||||
const handleIdentitySubmit = (name: string, email: string) => {
|
||||
setSavedIdentity({ name, email });
|
||||
setShowIdentityModal(false);
|
||||
submitLikeMutation.mutate({ guest_name: name, guest_email: email });
|
||||
};
|
||||
|
||||
if (!isEnabled) return null;
|
||||
|
||||
return (
|
||||
<button
|
||||
<>
|
||||
<button
|
||||
onClick={handleLikeClick}
|
||||
disabled={isSubmitting}
|
||||
className={`group flex items-center gap-2 px-3 py-2 rounded-lg transition-all ${
|
||||
@@ -88,6 +107,13 @@ export const PhotoLikes: React.FC<PhotoLikesProps> = ({
|
||||
<span className="text-sm font-medium">
|
||||
{likeCount > 0 ? likeCount : ''}
|
||||
</span>
|
||||
</button>
|
||||
</button>
|
||||
<FeedbackIdentityModal
|
||||
isOpen={showIdentityModal}
|
||||
onClose={() => setShowIdentityModal(false)}
|
||||
onSubmit={handleIdentitySubmit}
|
||||
feedbackType={t('feedback.like', 'like')}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
};
|
||||
@@ -4,6 +4,7 @@ import { useTranslation } from 'react-i18next';
|
||||
import { useMutation, useQueryClient } from '@tanstack/react-query';
|
||||
import { feedbackService } from '../../services/feedback.service';
|
||||
import { toast } from 'react-toastify';
|
||||
import { FeedbackIdentityModal } from './FeedbackIdentityModal';
|
||||
|
||||
interface PhotoRatingProps {
|
||||
photoId: string;
|
||||
@@ -12,6 +13,7 @@ interface PhotoRatingProps {
|
||||
averageRating?: number;
|
||||
totalRatings?: number;
|
||||
isEnabled: boolean;
|
||||
requireNameEmail?: boolean;
|
||||
onRatingChange?: (rating: number) => void;
|
||||
}
|
||||
|
||||
@@ -22,6 +24,7 @@ export const PhotoRating: React.FC<PhotoRatingProps> = ({
|
||||
averageRating = 0,
|
||||
totalRatings = 0,
|
||||
isEnabled,
|
||||
requireNameEmail = false,
|
||||
onRatingChange
|
||||
}) => {
|
||||
// Ensure averageRating is a valid number
|
||||
@@ -30,18 +33,23 @@ export const PhotoRating: React.FC<PhotoRatingProps> = ({
|
||||
const queryClient = useQueryClient();
|
||||
const [hoveredRating, setHoveredRating] = useState(0);
|
||||
const [isSubmitting, setIsSubmitting] = useState(false);
|
||||
const [showIdentityModal, setShowIdentityModal] = useState(false);
|
||||
const [pendingRating, setPendingRating] = useState(0);
|
||||
const [savedIdentity, setSavedIdentity] = useState<{ name: string; email: string } | null>(null);
|
||||
|
||||
const submitRatingMutation = useMutation({
|
||||
mutationFn: (rating: number) =>
|
||||
mutationFn: (data: { rating: number; guest_name?: string; guest_email?: string }) =>
|
||||
feedbackService.submitFeedback(gallerySlug, photoId, {
|
||||
feedback_type: 'rating',
|
||||
rating
|
||||
rating: data.rating,
|
||||
guest_name: data.guest_name || undefined,
|
||||
guest_email: data.guest_email || undefined
|
||||
}),
|
||||
onMutate: async (rating) => {
|
||||
onMutate: async (data) => {
|
||||
setIsSubmitting(true);
|
||||
// Optimistic update
|
||||
if (onRatingChange) {
|
||||
onRatingChange(rating);
|
||||
onRatingChange(data.rating);
|
||||
}
|
||||
},
|
||||
onSuccess: () => {
|
||||
@@ -69,47 +77,75 @@ export const PhotoRating: React.FC<PhotoRatingProps> = ({
|
||||
|
||||
// If clicking the same rating, remove it
|
||||
const newRating = rating === currentRating ? 0 : rating;
|
||||
submitRatingMutation.mutate(newRating);
|
||||
|
||||
if (requireNameEmail && !savedIdentity) {
|
||||
setPendingRating(newRating);
|
||||
setShowIdentityModal(true);
|
||||
} else {
|
||||
submitRatingMutation.mutate({
|
||||
rating: newRating,
|
||||
guest_name: savedIdentity?.name,
|
||||
guest_email: savedIdentity?.email
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
const handleIdentitySubmit = (name: string, email: string) => {
|
||||
setSavedIdentity({ name, email });
|
||||
setShowIdentityModal(false);
|
||||
submitRatingMutation.mutate({
|
||||
rating: pendingRating,
|
||||
guest_name: name,
|
||||
guest_email: email
|
||||
});
|
||||
};
|
||||
|
||||
if (!isEnabled) return null;
|
||||
|
||||
return (
|
||||
<div className="flex flex-col items-center gap-2">
|
||||
{/* Star Rating Input */}
|
||||
<div className="flex items-center gap-1">
|
||||
{[1, 2, 3, 4, 5].map((star) => (
|
||||
<button
|
||||
key={star}
|
||||
onClick={() => handleRatingClick(star)}
|
||||
onMouseEnter={() => setHoveredRating(star)}
|
||||
onMouseLeave={() => setHoveredRating(0)}
|
||||
disabled={isSubmitting}
|
||||
className={`p-1 transition-all ${
|
||||
isSubmitting ? 'cursor-not-allowed opacity-50' : 'cursor-pointer hover:scale-110'
|
||||
}`}
|
||||
aria-label={t('feedback.rateStar', 'Rate {{count}} stars', { count: star })}
|
||||
>
|
||||
<Star
|
||||
className={`w-6 h-6 transition-colors ${
|
||||
star <= (hoveredRating || currentRating)
|
||||
? 'fill-yellow-500 text-yellow-500'
|
||||
: 'text-neutral-300 hover:text-yellow-400'
|
||||
<>
|
||||
<div className="flex flex-col items-center gap-2">
|
||||
{/* Star Rating Input */}
|
||||
<div className="flex items-center gap-1">
|
||||
{[1, 2, 3, 4, 5].map((star) => (
|
||||
<button
|
||||
key={star}
|
||||
onClick={() => handleRatingClick(star)}
|
||||
onMouseEnter={() => setHoveredRating(star)}
|
||||
onMouseLeave={() => setHoveredRating(0)}
|
||||
disabled={isSubmitting}
|
||||
className={`p-1 transition-all ${
|
||||
isSubmitting ? 'cursor-not-allowed opacity-50' : 'cursor-pointer hover:scale-110'
|
||||
}`}
|
||||
/>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{/* Average Rating Display */}
|
||||
{totalRatings > 0 && (
|
||||
<div className="text-sm text-neutral-600">
|
||||
<span className="font-medium">{safeAverageRating.toFixed(1)}</span>
|
||||
<span className="text-neutral-400 ml-1">
|
||||
({t('feedback.ratingsCount', '{{count}} ratings', { count: totalRatings })})
|
||||
</span>
|
||||
aria-label={t('feedback.rateStar', 'Rate {{count}} stars', { count: star })}
|
||||
>
|
||||
<Star
|
||||
className={`w-6 h-6 transition-colors ${
|
||||
star <= (hoveredRating || currentRating)
|
||||
? 'fill-yellow-500 text-yellow-500'
|
||||
: 'text-neutral-300 hover:text-yellow-400'
|
||||
}`}
|
||||
/>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Average Rating Display */}
|
||||
{totalRatings > 0 && (
|
||||
<div className="text-sm text-neutral-600">
|
||||
<span className="font-medium">{safeAverageRating.toFixed(1)}</span>
|
||||
<span className="text-neutral-400 ml-1">
|
||||
({t('feedback.ratingsCount', '{{count}} ratings', { count: totalRatings })})
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<FeedbackIdentityModal
|
||||
isOpen={showIdentityModal}
|
||||
onClose={() => setShowIdentityModal(false)}
|
||||
onSubmit={handleIdentitySubmit}
|
||||
feedbackType={t('feedback.rating', 'rating')}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
};
|
||||
@@ -10,4 +10,3 @@ export { PhotoFeedback } from './PhotoFeedback';
|
||||
export { PhotoRating } from './PhotoRating';
|
||||
export { PhotoLikes } from './PhotoLikes';
|
||||
export { PhotoComments } from './PhotoComments';
|
||||
export { PhotoFavorites } from './PhotoFavorites';
|
||||
@@ -5,6 +5,10 @@ export interface BaseGalleryLayoutProps {
|
||||
photos: Photo[];
|
||||
slug: string;
|
||||
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;
|
||||
selectedPhotos?: Set<number>;
|
||||
isSelectionMode?: boolean;
|
||||
@@ -17,8 +21,15 @@ export interface BaseGalleryLayoutProps {
|
||||
protectionLevel?: 'basic' | 'standard' | 'enhanced' | 'maximum';
|
||||
useEnhancedProtection?: 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> {
|
||||
abstract render(): React.ReactNode;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,16 +1,20 @@
|
||||
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 { AuthenticatedImage, Button } from '../../common';
|
||||
import type { BaseGalleryLayoutProps } from './BaseGalleryLayout';
|
||||
import { FeedbackIdentityModal } from '../../gallery/FeedbackIdentityModal';
|
||||
import { feedbackService } from '../../../services/feedback.service';
|
||||
|
||||
export const CarouselGalleryLayout: React.FC<BaseGalleryLayoutProps> = ({
|
||||
photos,
|
||||
slug,
|
||||
onPhotoClick,
|
||||
onOpenPhotoWithFeedback,
|
||||
onDownload,
|
||||
allowDownloads = true,
|
||||
// selectedPhotos = new Set(),
|
||||
// isSelectionMode = false
|
||||
feedbackEnabled = false,
|
||||
feedbackOptions
|
||||
}) => {
|
||||
const { theme } = useTheme();
|
||||
const [currentIndex, setCurrentIndex] = useState(0);
|
||||
@@ -59,6 +63,11 @@ export const CarouselGalleryLayout: React.FC<BaseGalleryLayoutProps> = ({
|
||||
if (photos.length === 0) return null;
|
||||
|
||||
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 (
|
||||
<div className="relative">
|
||||
@@ -136,6 +145,44 @@ export const CarouselGalleryLayout: React.FC<BaseGalleryLayoutProps> = ({
|
||||
<Download className="w-5 h-5" />
|
||||
</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>
|
||||
|
||||
@@ -181,6 +228,24 @@ export const CarouselGalleryLayout: React.FC<BaseGalleryLayoutProps> = ({
|
||||
</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>{`
|
||||
@keyframes progress {
|
||||
from { width: 0%; }
|
||||
@@ -189,4 +254,4 @@ export const CarouselGalleryLayout: React.FC<BaseGalleryLayoutProps> = ({
|
||||
`}</style>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
};
|
||||
|
||||
@@ -3,6 +3,8 @@ import { Download, Maximize2, Check, MessageSquare, Star, Heart } from 'lucide-r
|
||||
import { useInView } from 'react-intersection-observer';
|
||||
import { useTheme } from '../../../contexts/ThemeContext';
|
||||
import { AuthenticatedImage } from '../../common';
|
||||
import { FeedbackIdentityModal } from '../../gallery/FeedbackIdentityModal';
|
||||
import { feedbackService } from '../../../services/feedback.service';
|
||||
import type { BaseGalleryLayoutProps } from './BaseGalleryLayout';
|
||||
import type { Photo } from '../../../types';
|
||||
|
||||
@@ -12,12 +14,26 @@ interface GridPhotoProps {
|
||||
isSelectionMode: boolean;
|
||||
onClick: (e: React.MouseEvent) => void;
|
||||
onDownload: (e: React.MouseEvent) => void;
|
||||
onToggleSelect: () => void;
|
||||
animationType?: string;
|
||||
allowDownloads?: boolean;
|
||||
slug?: string;
|
||||
protectionLevel?: 'basic' | 'standard' | 'enhanced' | 'maximum';
|
||||
useEnhancedProtection?: 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> = ({
|
||||
@@ -26,13 +42,22 @@ const GridPhoto: React.FC<GridPhotoProps> = ({
|
||||
isSelectionMode,
|
||||
onClick,
|
||||
onDownload,
|
||||
onToggleSelect,
|
||||
animationType = 'fade',
|
||||
allowDownloads = true,
|
||||
slug,
|
||||
protectionLevel = 'standard',
|
||||
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({
|
||||
triggerOnce: true,
|
||||
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 && (
|
||||
<>
|
||||
<button
|
||||
@@ -101,44 +126,91 @@ const GridPhoto: React.FC<GridPhotoProps> = ({
|
||||
<Download className="w-5 h-5 text-neutral-800" />
|
||||
</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>
|
||||
|
||||
{isSelectionMode && (
|
||||
<div className={`absolute top-2 right-2 ${isSelected ? 'opacity-100' : 'opacity-0 group-hover:opacity-100'} transition-opacity`}>
|
||||
<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`}>
|
||||
{isSelected && <Check className="w-4 h-4 text-white" />}
|
||||
</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>
|
||||
|
||||
{/* Feedback Indicators */}
|
||||
{feedbackEnabled && (photo.comment_count > 0 || photo.average_rating > 0 || photo.like_count > 0) && (
|
||||
<div className="absolute top-2 left-2 flex 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>
|
||||
{/* Feedback Indicators (always visible, bottom-left). Show like immediately when user liked */}
|
||||
{(photo.comment_count > 0 || photo.average_rating > 0 || photo.like_count > 0 || liked) && (
|
||||
<div className={`absolute ${photo.type === 'collage' ? 'bottom-8' : 'bottom-2'} left-2 flex items-center gap-1 z-10`}>
|
||||
{(photo.like_count > 0 || liked) && (
|
||||
<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 && (
|
||||
<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" />
|
||||
<span className="text-xs font-medium text-neutral-700">{Number(photo.average_rating).toFixed(1)}</span>
|
||||
</div>
|
||||
</span>
|
||||
)}
|
||||
{photo.like_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`}>
|
||||
<Heart className="w-3.5 h-3.5 text-red-500" fill="currentColor" />
|
||||
<span className="text-xs font-medium text-neutral-700">{photo.like_count}</span>
|
||||
</div>
|
||||
{photo.comment_count > 0 && (
|
||||
<span className="inline-flex items-center justify-center w-6 h-6 rounded-full bg-white/90 backdrop-blur-sm" title="Commented">
|
||||
<MessageSquare className="w-3.5 h-3.5 text-primary-600" fill="currentColor" />
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{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">
|
||||
Collage
|
||||
</span>
|
||||
@@ -156,6 +228,8 @@ export const GridGalleryLayout: React.FC<BaseGalleryLayoutProps> = ({
|
||||
photos,
|
||||
slug,
|
||||
onPhotoClick,
|
||||
onOpenPhotoWithFeedback,
|
||||
onFeedbackChange,
|
||||
onDownload,
|
||||
selectedPhotos = new Set(),
|
||||
isSelectionMode = false,
|
||||
@@ -163,7 +237,8 @@ export const GridGalleryLayout: React.FC<BaseGalleryLayoutProps> = ({
|
||||
allowDownloads = true,
|
||||
protectionLevel = 'standard',
|
||||
useEnhancedProtection = false,
|
||||
feedbackEnabled = false
|
||||
feedbackEnabled = false,
|
||||
feedbackOptions
|
||||
}) => {
|
||||
const { theme } = useTheme();
|
||||
const gallerySettings = theme.gallerySettings || {};
|
||||
@@ -171,6 +246,11 @@ export const GridGalleryLayout: React.FC<BaseGalleryLayoutProps> = ({
|
||||
const spacing = gallerySettings.spacing || 'normal';
|
||||
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 gridClass = `grid ${spacingClass}
|
||||
@@ -187,13 +267,8 @@ export const GridGalleryLayout: React.FC<BaseGalleryLayoutProps> = ({
|
||||
photo={photo}
|
||||
isSelected={selectedPhotos.has(photo.id)}
|
||||
isSelectionMode={isSelectionMode}
|
||||
onClick={() => {
|
||||
if (isSelectionMode && onPhotoSelect) {
|
||||
onPhotoSelect(photo.id);
|
||||
} else {
|
||||
onPhotoClick(index);
|
||||
}
|
||||
}}
|
||||
onClick={() => onPhotoClick(index)}
|
||||
onToggleSelect={() => onPhotoSelect && onPhotoSelect(photo.id)}
|
||||
onDownload={(e) => onDownload(photo, e)}
|
||||
animationType={animation}
|
||||
allowDownloads={allowDownloads}
|
||||
@@ -201,8 +276,49 @@ export const GridGalleryLayout: React.FC<BaseGalleryLayoutProps> = ({
|
||||
protectionLevel={protectionLevel}
|
||||
useEnhancedProtection={useEnhancedProtection}
|
||||
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>
|
||||
);
|
||||
};
|
||||
};
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
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 { useTranslation } from 'react-i18next';
|
||||
import { useLocalizedDate } from '../../../hooks/useLocalizedDate';
|
||||
@@ -8,17 +8,23 @@ import { AuthenticatedImage } from '../../common';
|
||||
import type { BaseGalleryLayoutProps } from './BaseGalleryLayout';
|
||||
import type { Photo } from '../../../types';
|
||||
import { buildResourceUrl } from '../../../utils/url';
|
||||
import { FeedbackIdentityModal } from '../../gallery/FeedbackIdentityModal';
|
||||
import { feedbackService } from '../../../services/feedback.service';
|
||||
|
||||
interface HeroGalleryLayoutProps extends BaseGalleryLayoutProps {
|
||||
eventName?: string;
|
||||
eventLogo?: string | null;
|
||||
eventDate?: string;
|
||||
expiresAt?: string;
|
||||
// Use a static hero photo independent of current filter
|
||||
heroPhotoOverride?: Photo | null;
|
||||
}
|
||||
|
||||
export const HeroGalleryLayout: React.FC<HeroGalleryLayoutProps> = ({
|
||||
photos,
|
||||
slug,
|
||||
onPhotoClick,
|
||||
onOpenPhotoWithFeedback,
|
||||
onDownload,
|
||||
selectedPhotos = new Set(),
|
||||
isSelectionMode = false,
|
||||
@@ -27,15 +33,31 @@ export const HeroGalleryLayout: React.FC<HeroGalleryLayoutProps> = ({
|
||||
eventLogo,
|
||||
eventDate,
|
||||
expiresAt,
|
||||
allowDownloads = true
|
||||
heroPhotoOverride,
|
||||
allowDownloads = true,
|
||||
feedbackEnabled = false,
|
||||
feedbackOptions
|
||||
}) => {
|
||||
const { t } = useTranslation();
|
||||
const { format } = useLocalizedDate();
|
||||
const { theme } = useTheme();
|
||||
const [heroPhoto, setHeroPhoto] = useState<Photo | null>(null);
|
||||
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 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
|
||||
useEffect(() => {
|
||||
@@ -46,29 +68,28 @@ export const HeroGalleryLayout: React.FC<HeroGalleryLayoutProps> = ({
|
||||
|
||||
// Select hero photo (admin-selected or first photo only if gallery was empty)
|
||||
useEffect(() => {
|
||||
// When an override is provided, the effect above has already set the hero.
|
||||
if (heroPhotoOverride) return;
|
||||
|
||||
if (photos.length > 0) {
|
||||
const heroId = gallerySettings.heroImageId;
|
||||
// Process hero layout with provided photos
|
||||
|
||||
// If admin has selected a specific hero image, always use it
|
||||
// If admin has selected a specific hero image, always use it when available
|
||||
if (heroId) {
|
||||
const adminSelectedHero = photos.find(p => p.id === heroId);
|
||||
// Hero photo selected by admin
|
||||
if (adminSelectedHero) {
|
||||
setHeroPhoto(adminSelectedHero);
|
||||
setHasInitialized(true);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
// Only auto-select first photo on initial load when gallery was empty
|
||||
// This prevents changing the hero when new photos are uploaded
|
||||
|
||||
// Only auto-select first photo on initial load
|
||||
if (!hasInitialized) {
|
||||
setHeroPhoto(photos[0]);
|
||||
setHasInitialized(true);
|
||||
}
|
||||
}
|
||||
}, [photos, gallerySettings.heroImageId, hasInitialized]);
|
||||
}, [photos, gallerySettings.heroImageId, hasInitialized, heroPhotoOverride]);
|
||||
|
||||
if (!heroPhoto) return null;
|
||||
|
||||
@@ -76,11 +97,13 @@ export const HeroGalleryLayout: React.FC<HeroGalleryLayoutProps> = ({
|
||||
const remainingPhotos = photos;
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className="relative -mt-6">
|
||||
{/* Hero Section */}
|
||||
<div className="relative h-[60vh] sm:h-[70vh] lg:h-[80vh] -mx-4 sm:-mx-6 lg:-mx-8 mb-8">
|
||||
<AuthenticatedImage
|
||||
src={heroPhoto.url}
|
||||
fallbackSrc={heroPhoto.thumbnail_url || undefined}
|
||||
alt={heroPhoto.filename}
|
||||
className="w-full h-full object-cover"
|
||||
isGallery={true}
|
||||
@@ -152,13 +175,7 @@ export const HeroGalleryLayout: React.FC<HeroGalleryLayoutProps> = ({
|
||||
<div
|
||||
key={photo.id}
|
||||
className="relative group cursor-pointer aspect-square"
|
||||
onClick={() => {
|
||||
if (isSelectionMode && onPhotoSelect) {
|
||||
onPhotoSelect(photo.id);
|
||||
} else {
|
||||
onPhotoClick(actualIndex);
|
||||
}
|
||||
}}
|
||||
onClick={() => onPhotoClick(actualIndex)}
|
||||
>
|
||||
<AuthenticatedImage
|
||||
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" />
|
||||
</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>
|
||||
|
||||
{isSelectionMode && (
|
||||
<div className={`absolute top-2 right-2 ${selectedPhotos.has(photo.id) ? 'opacity-100' : 'opacity-0 group-hover:opacity-100'} transition-opacity`}>
|
||||
<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`}>
|
||||
{selectedPhotos.has(photo.id) && <Check className="w-4 h-4 text-white" />}
|
||||
</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>
|
||||
|
||||
{/* 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>
|
||||
@@ -210,5 +293,23 @@ export const HeroGalleryLayout: React.FC<HeroGalleryLayoutProps> = ({
|
||||
})}
|
||||
</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 { useTheme } from '../../../contexts/ThemeContext';
|
||||
import { AuthenticatedImage } from '../../common';
|
||||
import { FeedbackIdentityModal } from '../../gallery/FeedbackIdentityModal';
|
||||
import { feedbackService } from '../../../services/feedback.service';
|
||||
import type { BaseGalleryLayoutProps } from './BaseGalleryLayout';
|
||||
import type { Photo } from '../../../types';
|
||||
|
||||
@@ -11,9 +13,17 @@ interface MasonryPhotoProps {
|
||||
isSelectionMode: boolean;
|
||||
onClick: (e: React.MouseEvent) => void;
|
||||
onDownload: (e: React.MouseEvent) => void;
|
||||
onToggleSelect: () => void;
|
||||
style?: React.CSSProperties;
|
||||
allowDownloads?: boolean;
|
||||
feedbackEnabled?: boolean;
|
||||
slug?: string;
|
||||
feedbackOptions?: {
|
||||
allowLikes?: boolean;
|
||||
allowComments?: boolean;
|
||||
requireNameEmail?: boolean;
|
||||
};
|
||||
onQuickComment?: () => void;
|
||||
}
|
||||
|
||||
const MasonryPhoto: React.FC<MasonryPhotoProps> = ({
|
||||
@@ -22,11 +32,18 @@ const MasonryPhoto: React.FC<MasonryPhotoProps> = ({
|
||||
isSelectionMode,
|
||||
onClick,
|
||||
onDownload,
|
||||
onToggleSelect,
|
||||
style,
|
||||
allowDownloads = true,
|
||||
feedbackEnabled = false
|
||||
feedbackEnabled = false,
|
||||
slug,
|
||||
feedbackOptions,
|
||||
onQuickComment
|
||||
}) => {
|
||||
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
|
||||
useEffect(() => {
|
||||
@@ -100,17 +117,77 @@ const MasonryPhoto: React.FC<MasonryPhotoProps> = ({
|
||||
<Download className="w-5 h-5 text-neutral-800" />
|
||||
</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>
|
||||
|
||||
{isSelectionMode && (
|
||||
<div className={`absolute top-2 right-2 ${isSelected ? 'opacity-100' : 'opacity-0 group-hover:opacity-100'} transition-opacity`}>
|
||||
<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`}>
|
||||
{isSelected && <Check className="w-4 h-4 text-white" />}
|
||||
</div>
|
||||
{/* Identity Modal */}
|
||||
<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"
|
||||
/>
|
||||
|
||||
{/* 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' && (
|
||||
<div className="absolute bottom-2 left-2">
|
||||
@@ -125,13 +202,16 @@ const MasonryPhoto: React.FC<MasonryPhotoProps> = ({
|
||||
|
||||
export const MasonryGalleryLayout: React.FC<BaseGalleryLayoutProps> = ({
|
||||
photos,
|
||||
slug,
|
||||
onPhotoClick,
|
||||
onOpenPhotoWithFeedback,
|
||||
onDownload,
|
||||
selectedPhotos = new Set(),
|
||||
isSelectionMode = false,
|
||||
onPhotoSelect,
|
||||
allowDownloads = true,
|
||||
feedbackEnabled = false
|
||||
feedbackEnabled = false,
|
||||
feedbackOptions
|
||||
}) => {
|
||||
const { theme } = useTheme();
|
||||
const containerRef = useRef<HTMLDivElement>(null);
|
||||
@@ -182,16 +262,14 @@ export const MasonryGalleryLayout: React.FC<BaseGalleryLayoutProps> = ({
|
||||
photo={photo}
|
||||
isSelected={selectedPhotos.has(photo.id)}
|
||||
isSelectionMode={isSelectionMode}
|
||||
onClick={() => {
|
||||
if (isSelectionMode && onPhotoSelect) {
|
||||
onPhotoSelect(photo.id);
|
||||
} else {
|
||||
onPhotoClick(originalIndex);
|
||||
}
|
||||
}}
|
||||
onClick={() => onPhotoClick(originalIndex)}
|
||||
onDownload={(e) => onDownload(photo, e)}
|
||||
onToggleSelect={() => onPhotoSelect && onPhotoSelect(photo.id)}
|
||||
allowDownloads={allowDownloads}
|
||||
feedbackEnabled={feedbackEnabled}
|
||||
slug={slug}
|
||||
feedbackOptions={feedbackOptions}
|
||||
onQuickComment={() => onOpenPhotoWithFeedback && onOpenPhotoWithFeedback(originalIndex)}
|
||||
/>
|
||||
);
|
||||
})}
|
||||
@@ -199,4 +277,4 @@ export const MasonryGalleryLayout: React.FC<BaseGalleryLayoutProps> = ({
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
};
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
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 { AuthenticatedImage } from '../../common';
|
||||
import { FeedbackIdentityModal } from '../../gallery/FeedbackIdentityModal';
|
||||
import { feedbackService } from '../../../services/feedback.service';
|
||||
import type { BaseGalleryLayoutProps } from './BaseGalleryLayout';
|
||||
import type { Photo } from '../../../types';
|
||||
|
||||
@@ -11,8 +13,17 @@ interface MosaicPhotoProps {
|
||||
isSelectionMode: boolean;
|
||||
onClick: (e: React.MouseEvent) => void;
|
||||
onDownload: (e: React.MouseEvent) => void;
|
||||
onToggleSelect: () => void;
|
||||
className?: string;
|
||||
allowDownloads?: boolean;
|
||||
slug?: string;
|
||||
feedbackEnabled?: boolean;
|
||||
feedbackOptions?: {
|
||||
allowLikes?: boolean;
|
||||
allowComments?: boolean;
|
||||
requireNameEmail?: boolean;
|
||||
};
|
||||
onQuickComment?: () => void;
|
||||
}
|
||||
|
||||
const MosaicPhoto: React.FC<MosaicPhotoProps> = ({
|
||||
@@ -21,10 +32,22 @@ const MosaicPhoto: React.FC<MosaicPhotoProps> = ({
|
||||
isSelectionMode,
|
||||
onClick,
|
||||
onDownload,
|
||||
onToggleSelect,
|
||||
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 (
|
||||
<>
|
||||
<div
|
||||
className={`relative group cursor-pointer overflow-hidden rounded-lg bg-neutral-100 ${className}`}
|
||||
onClick={(e) => {
|
||||
@@ -65,18 +88,72 @@ const MosaicPhoto: React.FC<MosaicPhotoProps> = ({
|
||||
<Download className="w-5 h-5 text-neutral-800" />
|
||||
</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>
|
||||
|
||||
{isSelectionMode && (
|
||||
<div className={`absolute top-2 right-2 ${isSelected ? 'opacity-100' : 'opacity-0 group-hover:opacity-100'} transition-opacity`}>
|
||||
<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`}>
|
||||
{isSelected && <Check className="w-4 h-4 text-white" />}
|
||||
</div>
|
||||
{/* Feedback Indicators (bottom-left) */}
|
||||
{(photo.like_count > 0 || likedLocal) && (
|
||||
<div className={`absolute ${photo.type === 'collage' ? 'bottom-8' : 'bottom-2'} left-2 z-10`}>
|
||||
<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>
|
||||
</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' && (
|
||||
<div className="absolute bottom-2 left-2">
|
||||
<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>
|
||||
<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> = ({
|
||||
photos,
|
||||
slug,
|
||||
onPhotoClick,
|
||||
onOpenPhotoWithFeedback,
|
||||
onDownload,
|
||||
selectedPhotos = new Set(),
|
||||
isSelectionMode = false,
|
||||
onPhotoSelect,
|
||||
allowDownloads = true
|
||||
allowDownloads = true,
|
||||
feedbackEnabled = false,
|
||||
feedbackOptions
|
||||
}) => {
|
||||
// const { theme } = useTheme();
|
||||
// const gallerySettings = theme.gallerySettings || {};
|
||||
@@ -136,10 +235,15 @@ export const MosaicGalleryLayout: React.FC<BaseGalleryLayoutProps> = ({
|
||||
photo={photo0}
|
||||
isSelected={selectedPhotos.has(photo0.id)}
|
||||
isSelectionMode={isSelectionMode}
|
||||
onClick={() => handlePhotoClick(idx0, photo0.id)}
|
||||
onClick={() => onPhotoClick(idx0)}
|
||||
onDownload={(e) => onDownload(photo0, e)}
|
||||
onToggleSelect={() => onPhotoSelect && onPhotoSelect(photo0.id)}
|
||||
className="col-span-1"
|
||||
allowDownloads={allowDownloads}
|
||||
slug={slug}
|
||||
feedbackEnabled={feedbackEnabled}
|
||||
feedbackOptions={feedbackOptions}
|
||||
onQuickComment={() => { if (typeof onOpenPhotoWithFeedback !== 'undefined' && onOpenPhotoWithFeedback) onOpenPhotoWithFeedback(idx0); }}
|
||||
/>
|
||||
)}
|
||||
<div className="grid grid-rows-2 gap-2">
|
||||
@@ -148,22 +252,32 @@ export const MosaicGalleryLayout: React.FC<BaseGalleryLayoutProps> = ({
|
||||
photo={photo1}
|
||||
isSelected={selectedPhotos.has(photo1.id)}
|
||||
isSelectionMode={isSelectionMode}
|
||||
onClick={() => handlePhotoClick(idx1, photo1.id)}
|
||||
onClick={() => onPhotoClick(idx1)}
|
||||
onDownload={(e) => onDownload(photo1, e)}
|
||||
onToggleSelect={() => onPhotoSelect && onPhotoSelect(photo1.id)}
|
||||
className=""
|
||||
allowDownloads={allowDownloads}
|
||||
/>
|
||||
slug={slug}
|
||||
feedbackEnabled={feedbackEnabled}
|
||||
feedbackOptions={feedbackOptions}
|
||||
onQuickComment={() => { if (typeof onOpenPhotoWithFeedback !== 'undefined' && onOpenPhotoWithFeedback) onOpenPhotoWithFeedback(idx1); }}
|
||||
/>
|
||||
)}
|
||||
{photo2 && (
|
||||
<MosaicPhoto
|
||||
photo={photo2}
|
||||
isSelected={selectedPhotos.has(photo2.id)}
|
||||
isSelectionMode={isSelectionMode}
|
||||
onClick={() => handlePhotoClick(idx2, photo2.id)}
|
||||
onClick={() => onPhotoClick(idx2)}
|
||||
onDownload={(e) => onDownload(photo2, e)}
|
||||
onToggleSelect={() => onPhotoSelect && onPhotoSelect(photo2.id)}
|
||||
className=""
|
||||
allowDownloads={allowDownloads}
|
||||
/>
|
||||
slug={slug}
|
||||
feedbackEnabled={feedbackEnabled}
|
||||
feedbackOptions={feedbackOptions}
|
||||
onQuickComment={() => { if (typeof onOpenPhotoWithFeedback !== 'undefined' && onOpenPhotoWithFeedback) onOpenPhotoWithFeedback(idx2); }}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
@@ -186,6 +300,10 @@ export const MosaicGalleryLayout: React.FC<BaseGalleryLayoutProps> = ({
|
||||
onDownload={(e) => onDownload(photo, e)}
|
||||
className=""
|
||||
allowDownloads={allowDownloads}
|
||||
slug={slug}
|
||||
feedbackEnabled={feedbackEnabled}
|
||||
feedbackOptions={feedbackOptions}
|
||||
onQuickComment={() => { if (typeof onOpenPhotoWithFeedback !== 'undefined' && onOpenPhotoWithFeedback) onOpenPhotoWithFeedback(currentIndex); }}
|
||||
/>
|
||||
) : null;
|
||||
})}
|
||||
@@ -209,10 +327,15 @@ export const MosaicGalleryLayout: React.FC<BaseGalleryLayoutProps> = ({
|
||||
photo={photo0}
|
||||
isSelected={selectedPhotos.has(photo0.id)}
|
||||
isSelectionMode={isSelectionMode}
|
||||
onClick={() => handlePhotoClick(idx0, photo0.id)}
|
||||
onClick={() => onPhotoClick(idx0)}
|
||||
onDownload={(e) => onDownload(photo0, e)}
|
||||
onToggleSelect={() => onPhotoSelect && onPhotoSelect(photo0.id)}
|
||||
className="col-span-2"
|
||||
allowDownloads={allowDownloads}
|
||||
slug={slug}
|
||||
feedbackEnabled={feedbackEnabled}
|
||||
feedbackOptions={feedbackOptions}
|
||||
onQuickComment={() => { if (typeof onOpenPhotoWithFeedback !== 'undefined' && onOpenPhotoWithFeedback) onOpenPhotoWithFeedback(idx0); }}
|
||||
/>
|
||||
)}
|
||||
<div className="grid grid-rows-2 gap-2">
|
||||
@@ -221,22 +344,32 @@ export const MosaicGalleryLayout: React.FC<BaseGalleryLayoutProps> = ({
|
||||
photo={photo1}
|
||||
isSelected={selectedPhotos.has(photo1.id)}
|
||||
isSelectionMode={isSelectionMode}
|
||||
onClick={() => handlePhotoClick(idx1, photo1.id)}
|
||||
onClick={() => onPhotoClick(idx1)}
|
||||
onDownload={(e) => onDownload(photo1, e)}
|
||||
onToggleSelect={() => onPhotoSelect && onPhotoSelect(photo1.id)}
|
||||
className=""
|
||||
allowDownloads={allowDownloads}
|
||||
/>
|
||||
slug={slug}
|
||||
feedbackEnabled={feedbackEnabled}
|
||||
feedbackOptions={feedbackOptions}
|
||||
onQuickComment={() => { if (typeof onOpenPhotoWithFeedback !== 'undefined' && onOpenPhotoWithFeedback) onOpenPhotoWithFeedback(idx1); }}
|
||||
/>
|
||||
)}
|
||||
{photo2 && (
|
||||
<MosaicPhoto
|
||||
photo={photo2}
|
||||
isSelected={selectedPhotos.has(photo2.id)}
|
||||
isSelectionMode={isSelectionMode}
|
||||
onClick={() => handlePhotoClick(idx2, photo2.id)}
|
||||
onClick={() => onPhotoClick(idx2)}
|
||||
onDownload={(e) => onDownload(photo2, e)}
|
||||
onToggleSelect={() => onPhotoSelect && onPhotoSelect(photo2.id)}
|
||||
className=""
|
||||
allowDownloads={allowDownloads}
|
||||
/>
|
||||
slug={slug}
|
||||
feedbackEnabled={feedbackEnabled}
|
||||
feedbackOptions={feedbackOptions}
|
||||
onQuickComment={() => { if (typeof onOpenPhotoWithFeedback !== 'undefined' && onOpenPhotoWithFeedback) onOpenPhotoWithFeedback(idx2); }}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
@@ -263,10 +396,15 @@ export const MosaicGalleryLayout: React.FC<BaseGalleryLayoutProps> = ({
|
||||
photo={photo}
|
||||
isSelected={selectedPhotos.has(photo.id)}
|
||||
isSelectionMode={isSelectionMode}
|
||||
onClick={() => handlePhotoClick(index, photo.id)}
|
||||
onClick={() => onPhotoClick(index)}
|
||||
onDownload={(e) => onDownload(photo, e)}
|
||||
onToggleSelect={() => onPhotoSelect && onPhotoSelect(photo.id)}
|
||||
className="aspect-square"
|
||||
allowDownloads={allowDownloads}
|
||||
slug={slug}
|
||||
feedbackEnabled={feedbackEnabled}
|
||||
feedbackOptions={feedbackOptions}
|
||||
onQuickComment={() => { if (typeof onOpenPhotoWithFeedback !== 'undefined' && onOpenPhotoWithFeedback) onOpenPhotoWithFeedback(index); }}
|
||||
/>
|
||||
);
|
||||
})}
|
||||
@@ -282,4 +420,4 @@ export const MosaicGalleryLayout: React.FC<BaseGalleryLayoutProps> = ({
|
||||
{renderMosaicLayout()}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
};
|
||||
|
||||
@@ -1,24 +1,35 @@
|
||||
import React, { useMemo } from 'react';
|
||||
import { Download, Maximize2, Check, Calendar } from 'lucide-react';
|
||||
import React, { useMemo, useState } from 'react';
|
||||
import { Download, Maximize2, Check, Calendar, Heart, MessageSquare } from 'lucide-react';
|
||||
import { format, parseISO, startOfDay, startOfWeek, startOfMonth } from 'date-fns';
|
||||
import { useTheme } from '../../../contexts/ThemeContext';
|
||||
import { AuthenticatedImage } from '../../common';
|
||||
import type { BaseGalleryLayoutProps } from './BaseGalleryLayout';
|
||||
import type { Photo } from '../../../types';
|
||||
import { FeedbackIdentityModal } from '../../gallery/FeedbackIdentityModal';
|
||||
import { feedbackService } from '../../../services/feedback.service';
|
||||
|
||||
export const TimelineGalleryLayout: React.FC<BaseGalleryLayoutProps> = ({
|
||||
photos,
|
||||
slug,
|
||||
onPhotoClick,
|
||||
onOpenPhotoWithFeedback,
|
||||
onDownload,
|
||||
selectedPhotos = new Set(),
|
||||
isSelectionMode = false,
|
||||
onPhotoSelect,
|
||||
allowDownloads = true
|
||||
allowDownloads = true,
|
||||
feedbackEnabled = false,
|
||||
feedbackOptions
|
||||
}) => {
|
||||
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 grouping = gallerySettings.timelineGrouping || 'day';
|
||||
const showDates = gallerySettings.timelineShowDates !== false;
|
||||
const canQuickComment = Boolean(feedbackEnabled && feedbackOptions?.allowComments && onOpenPhotoWithFeedback);
|
||||
|
||||
// Group photos by date
|
||||
const groupedPhotos = useMemo(() => {
|
||||
@@ -90,13 +101,7 @@ export const TimelineGalleryLayout: React.FC<BaseGalleryLayoutProps> = ({
|
||||
<div
|
||||
key={photo.id}
|
||||
className="relative group cursor-pointer aspect-square"
|
||||
onClick={() => {
|
||||
if (isSelectionMode && onPhotoSelect) {
|
||||
onPhotoSelect(photo.id);
|
||||
} else {
|
||||
onPhotoClick(actualIndex);
|
||||
}
|
||||
}}
|
||||
onClick={() => onPhotoClick(actualIndex)}
|
||||
>
|
||||
<AuthenticatedImage
|
||||
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" />
|
||||
</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>
|
||||
|
||||
{isSelectionMode && (
|
||||
<div className={`absolute top-2 right-2 ${selectedPhotos.has(photo.id) ? 'opacity-100' : 'opacity-0 group-hover:opacity-100'} transition-opacity`}>
|
||||
<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`}>
|
||||
{selectedPhotos.has(photo.id) && <Check className="w-4 h-4 text-white" />}
|
||||
</div>
|
||||
{(photo.like_count > 0 || likedIds.has(photo.id)) && (
|
||||
<div className={`absolute ${photo.type === 'collage' ? 'bottom-8' : 'bottom-2'} left-2 z-10`}>
|
||||
<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>
|
||||
</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>
|
||||
);
|
||||
})}
|
||||
@@ -155,6 +213,23 @@ export const TimelineGalleryLayout: 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"
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
};
|
||||
|
||||
@@ -1,9 +1,4 @@
|
||||
import axios, { AxiosHeaders } from 'axios';
|
||||
import Cookies from 'js-cookie';
|
||||
|
||||
// Cookie keys
|
||||
export const ADMIN_TOKEN_KEY = 'admin_token';
|
||||
export const GALLERY_TOKEN_KEY = 'gallery_token';
|
||||
import axios from 'axios';
|
||||
|
||||
// Maintenance mode callback
|
||||
let maintenanceModeCallback: ((enabled: boolean) => void) | null = null;
|
||||
@@ -18,65 +13,12 @@ export const api = axios.create({
|
||||
headers: {
|
||||
'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(
|
||||
(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 gallerySlug = galleryMatch[1];
|
||||
// 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}`;
|
||||
}
|
||||
} 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) {
|
||||
delete config.headers?.['Content-Type'];
|
||||
}
|
||||
@@ -95,10 +37,9 @@ api.interceptors.response.use(
|
||||
// Handle maintenance mode (503)
|
||||
if (error.response?.status === 503) {
|
||||
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
|
||||
if (!isAdminRoute || !hasAdminAuth) {
|
||||
if (!isAdminRoute) {
|
||||
if (maintenanceModeCallback) {
|
||||
maintenanceModeCallback(true);
|
||||
}
|
||||
@@ -111,8 +52,6 @@ api.interceptors.response.use(
|
||||
const currentPath = window.location.pathname;
|
||||
|
||||
if (isAdminRoute) {
|
||||
// Clear admin token on unauthorized
|
||||
Cookies.remove(ADMIN_TOKEN_KEY);
|
||||
// Only redirect if we're not already on the admin login page
|
||||
if (!currentPath.includes('/admin/login')) {
|
||||
window.location.href = '/admin/login';
|
||||
@@ -129,8 +68,7 @@ api.interceptors.response.use(
|
||||
// Don't clear tokens for image requests - they might just need a retry
|
||||
if (!isImageRequest && galleryMatch && galleryMatch[1]) {
|
||||
const gallerySlug = galleryMatch[1];
|
||||
localStorage.removeItem(`gallery_token_${gallerySlug}`);
|
||||
localStorage.removeItem(`gallery_event_${gallerySlug}`);
|
||||
sessionStorage.removeItem(`gallery_event_${gallerySlug}`);
|
||||
}
|
||||
// Don't redirect - let the component handle the auth state
|
||||
} else if (galleryMatch) {
|
||||
@@ -144,21 +82,3 @@ api.interceptors.response.use(
|
||||
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 type { ReactNode } from 'react';
|
||||
import { getAuthToken } from '../config/api';
|
||||
import { api } from '../config/api';
|
||||
import { authService } from '../services';
|
||||
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
|
||||
const checkAuth = async () => {
|
||||
try {
|
||||
const token = getAuthToken(true);
|
||||
if (token) {
|
||||
// For now, just assume the token is valid
|
||||
// TODO: Validate token with backend and get user info
|
||||
const storedUser = sessionStorage.getItem('admin_user');
|
||||
if (storedUser) {
|
||||
try {
|
||||
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);
|
||||
} else {
|
||||
sessionStorage.removeItem('admin_user');
|
||||
setIsAuthenticated(false);
|
||||
setUser(null);
|
||||
}
|
||||
} catch (error) {
|
||||
// Auth check failed - user needs to login
|
||||
setError('Failed to check authentication');
|
||||
sessionStorage.removeItem('admin_user');
|
||||
setIsAuthenticated(false);
|
||||
setUser(null);
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
@@ -63,9 +79,11 @@ export const AdminAuthProvider: React.FC<AdminAuthProviderProps> = ({ children }
|
||||
setError(null);
|
||||
setIsAuthenticated(true);
|
||||
setMustChangePassword(user.mustChangePassword || false);
|
||||
sessionStorage.setItem('admin_user', JSON.stringify(user));
|
||||
};
|
||||
|
||||
const logout = () => {
|
||||
sessionStorage.removeItem('admin_user');
|
||||
authService.adminLogout();
|
||||
setIsAuthenticated(false);
|
||||
setUser(null);
|
||||
@@ -79,6 +97,10 @@ export const AdminAuthProvider: React.FC<AdminAuthProviderProps> = ({ children }
|
||||
...user,
|
||||
mustChangePassword: false
|
||||
});
|
||||
sessionStorage.setItem('admin_user', JSON.stringify({
|
||||
...user,
|
||||
mustChangePassword: false
|
||||
}));
|
||||
}
|
||||
};
|
||||
|
||||
@@ -98,4 +120,4 @@ export const AdminAuthProvider: React.FC<AdminAuthProviderProps> = ({ children }
|
||||
{children}
|
||||
</AdminAuthContext.Provider>
|
||||
);
|
||||
};
|
||||
};
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import React, { createContext, useContext, useState, useEffect } 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';
|
||||
|
||||
interface GalleryEvent {
|
||||
@@ -52,36 +53,81 @@ export const GalleryAuthProvider: React.FC<GalleryAuthProviderProps> = ({ childr
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
// Clean up old authentication data on mount
|
||||
cleanupOldGalleryAuth();
|
||||
|
||||
// Check if user has a valid token on mount
|
||||
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) {
|
||||
|
||||
const initialise = async () => {
|
||||
const currentSlug = getCurrentGallerySlug();
|
||||
|
||||
if (!currentSlug) {
|
||||
setIsLoading(false);
|
||||
return;
|
||||
}
|
||||
|
||||
const storedEvent = sessionStorage.getItem(`gallery_event_${currentSlug}`);
|
||||
if (storedEvent) {
|
||||
try {
|
||||
const eventData = JSON.parse(storedEvent);
|
||||
// Verify the stored event matches the current gallery slug
|
||||
if (eventData && eventData.id) {
|
||||
setEvent(eventData);
|
||||
setIsAuthenticated(true);
|
||||
} else {
|
||||
// Clear invalid data
|
||||
localStorage.removeItem(`gallery_event_${currentSlug}`);
|
||||
localStorage.removeItem(`gallery_token_${currentSlug}`);
|
||||
const parsed = JSON.parse(storedEvent);
|
||||
if (parsed && parsed.id) {
|
||||
setEvent(parsed);
|
||||
}
|
||||
} catch (error) {
|
||||
// Invalid stored data - clear it
|
||||
localStorage.removeItem(`gallery_event_${currentSlug}`);
|
||||
localStorage.removeItem(`gallery_token_${currentSlug}`);
|
||||
} catch (err) {
|
||||
sessionStorage.removeItem(`gallery_event_${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) => {
|
||||
@@ -92,9 +138,8 @@ export const GalleryAuthProvider: React.FC<GalleryAuthProviderProps> = ({ childr
|
||||
setEvent(response.event);
|
||||
setIsAuthenticated(true);
|
||||
|
||||
// Store event data and token in localStorage with slug-specific key
|
||||
localStorage.setItem(`gallery_event_${slug}`, JSON.stringify(response.event));
|
||||
localStorage.setItem(`gallery_token_${slug}`, response.token);
|
||||
// Store event data for quick reloads (non-sensitive)
|
||||
sessionStorage.setItem(`gallery_event_${slug}`, JSON.stringify(response.event));
|
||||
} catch (err: any) {
|
||||
setError(err.response?.data?.error || 'Invalid password');
|
||||
throw err;
|
||||
@@ -106,13 +151,13 @@ export const GalleryAuthProvider: React.FC<GalleryAuthProviderProps> = ({ childr
|
||||
const logout = () => {
|
||||
const currentSlug = getCurrentGallerySlug();
|
||||
if (currentSlug) {
|
||||
localStorage.removeItem(`gallery_event_${currentSlug}`);
|
||||
localStorage.removeItem(`gallery_token_${currentSlug}`);
|
||||
sessionStorage.removeItem(`gallery_event_${currentSlug}`);
|
||||
}
|
||||
authService.galleryLogout();
|
||||
authService.galleryLogout(currentSlug || undefined);
|
||||
setIsAuthenticated(false);
|
||||
setEvent(null);
|
||||
};
|
||||
}
|
||||
;
|
||||
|
||||
return (
|
||||
<GalleryAuthContext.Provider
|
||||
@@ -128,4 +173,4 @@ export const GalleryAuthProvider: React.FC<GalleryAuthProviderProps> = ({ childr
|
||||
{children}
|
||||
</GalleryAuthContext.Provider>
|
||||
);
|
||||
};
|
||||
};
|
||||
|
||||
@@ -11,10 +11,16 @@ export const useGalleryInfo = (slug: string, token?: string) => {
|
||||
});
|
||||
};
|
||||
|
||||
export const useGalleryPhotos = (slug: string, enabled: boolean = true) => {
|
||||
export const useGalleryPhotos = (
|
||||
slug: string,
|
||||
filter?: 'liked' | 'commented' | 'rated' | 'all',
|
||||
guestId?: string,
|
||||
enabled: boolean = true
|
||||
) => {
|
||||
return useQuery({
|
||||
queryKey: ['gallery-photos', slug],
|
||||
queryFn: () => galleryService.getGalleryPhotos(slug),
|
||||
queryKey: ['gallery-photos', slug, filter, guestId],
|
||||
// Pass guestId so backend can filter per-guest views when needed
|
||||
queryFn: () => galleryService.getGalleryPhotos(slug, filter, guestId),
|
||||
enabled,
|
||||
retry: 1,
|
||||
staleTime: 5 * 60 * 1000, // 5 minutes
|
||||
@@ -63,4 +69,4 @@ export const useDownloadAllPhotos = () => {
|
||||
toast.error('Failed to download photos');
|
||||
},
|
||||
});
|
||||
};
|
||||
};
|
||||
|
||||
@@ -36,6 +36,11 @@
|
||||
"customize": "Anpassen",
|
||||
"hide": "Ausblenden",
|
||||
"unknown": "Unbekannt",
|
||||
"notSet": "Nicht festgelegt",
|
||||
"of": "von",
|
||||
"up": "Nach oben",
|
||||
"select": "Auswählen",
|
||||
"selected": "Ausgewählt",
|
||||
"chunk": "Teil"
|
||||
},
|
||||
"upload": {
|
||||
@@ -50,6 +55,10 @@
|
||||
"uploadFailed": "Upload fehlgeschlagen",
|
||||
"someFilesFailed": "Einige Dateien konnten nicht hochgeladen werden",
|
||||
"uploadPhotos": "Fotos hochladen",
|
||||
"importExternal": "Aus externem Ordner importieren",
|
||||
"externalImportInfo": "Alle Bilder aus dem ausgewählten Ordner werden importiert.",
|
||||
"selectExternalFolder": "Externen Ordner unter /external-media auswählen",
|
||||
"importFromSelectedFolder": "Ausgewählten Ordner importieren",
|
||||
"maxFilesReached": "Maximal 500 Dateien erlaubt",
|
||||
"someFilesSkipped": "Einige Dateien wurden übersprungen (500 Dateien Limit)",
|
||||
"tooManyFiles": "Maximal 500 Dateien können gleichzeitig hochgeladen werden",
|
||||
@@ -66,6 +75,342 @@
|
||||
"backup": "Backup & Wiederherstellung",
|
||||
"cmsPages": "CMS-Seiten"
|
||||
},
|
||||
"backup": {
|
||||
"external": {
|
||||
"warning": {
|
||||
"title": "Externe Medien ausgeschlossen",
|
||||
"body": "Diese Installation referenziert Fotos aus /external-media. Diese Originale sind von Backups ausgeschlossen. Thumbnails und Datenbank werden weiterhin gesichert."
|
||||
}
|
||||
},
|
||||
"title": "Backup-Verwaltung",
|
||||
"subtitle": "System-Backups verwalten, automatische Backups konfigurieren und aus früheren Backups wiederherstellen.",
|
||||
"tabs": {
|
||||
"dashboard": "Dashboard",
|
||||
"configuration": "Konfiguration",
|
||||
"history": "Backup-Verlauf",
|
||||
"restore": "Wiederherstellen"
|
||||
},
|
||||
"status": {
|
||||
"inProgress": "Backup wird ausgeführt...",
|
||||
"lastBackup": "Letztes Backup",
|
||||
"noBackups": "Keine Backups gefunden",
|
||||
"nextBackup": "Nächstes Backup",
|
||||
"notScheduled": "Nicht geplant",
|
||||
"enabled": "Aktiviert",
|
||||
"disabled": "Deaktiviert"
|
||||
},
|
||||
"actions": {
|
||||
"runBackupNow": "Backup jetzt starten",
|
||||
"starting": "Starte...",
|
||||
"running": "Läuft...",
|
||||
"testConnection": "Verbindung testen",
|
||||
"save": "Konfiguration speichern",
|
||||
"delete": "Löschen",
|
||||
"view": "Details anzeigen",
|
||||
"download": "Herunterladen",
|
||||
"refresh": "Aktualisieren"
|
||||
},
|
||||
"dashboard": {
|
||||
"backupHealth": "Backup-Gesundheit",
|
||||
"health": {
|
||||
"title": "Backup-Gesundheit"
|
||||
},
|
||||
"healthMessages": {
|
||||
"noBackups": "Keine Backups gefunden",
|
||||
"lastBackupFailed": "Letztes Backup fehlgeschlagen",
|
||||
"upToDate": "Backup ist aktuell",
|
||||
"recent": "Backup ist kürzlich",
|
||||
"gettingOld": "Backup wird alt",
|
||||
"outdated": "Backup ist veraltet"
|
||||
},
|
||||
"stats": {
|
||||
"totalBackups": "Gesamt-Backups",
|
||||
"backupSize": "Backup-Größe",
|
||||
"lastDuration": "Letzte Dauer",
|
||||
"backupStatus": "Backup-Status",
|
||||
"last": "Letztes",
|
||||
"files": "Dateien",
|
||||
"minutes": "{{count}}m",
|
||||
"active": "Aktiv",
|
||||
"inactive": "Inaktiv",
|
||||
"noBackupsYet": "Noch keine Backups"
|
||||
},
|
||||
"recentActivity": {
|
||||
"title": "Letzte Backup-Aktivitäten"
|
||||
},
|
||||
"notConfigured": {
|
||||
"title": "Backup nicht konfiguriert",
|
||||
"message": "Bitte konfigurieren Sie die Backup-Einstellungen im Tab \"Konfiguration\", bevor Sie Backups ausführen."
|
||||
},
|
||||
"coverage": {
|
||||
"title": "Backup-Abdeckung",
|
||||
"database": "Datenbank",
|
||||
"photos": "Fotos",
|
||||
"archives": "Archive",
|
||||
"systemFiles": "Systemdateien",
|
||||
"included": "Enthalten",
|
||||
"excluded": "Ausgeschlossen",
|
||||
"optional": "Optional"
|
||||
},
|
||||
"storageDestination": "Speicherziel",
|
||||
"nextScheduledBackup": "Nächstes geplantes Backup",
|
||||
"backupType": "{{type}}-Backup",
|
||||
"noDestinationSet": "Kein Ziel gesetzt"
|
||||
},
|
||||
"configuration": {
|
||||
"enableBackup": "Automatische Backups aktivieren",
|
||||
"enableBackupHelp": "Backups automatisch gemäß Zeitplan erstellen",
|
||||
"destinationType": "Backup-Ziel",
|
||||
"destinationTypes": {
|
||||
"local": {
|
||||
"name": "Lokaler Speicher",
|
||||
"description": "Backups auf dem lokalen Dateisystem speichern"
|
||||
},
|
||||
"rsync": {
|
||||
"name": "Remote-Server (Rsync)",
|
||||
"description": "Backups per SSH/Rsync auf einen entfernten Server synchronisieren"
|
||||
},
|
||||
"s3": {
|
||||
"name": "S3-kompatibler Speicher",
|
||||
"description": "Backups in Amazon S3 oder kompatiblen Objektspeicher ablegen"
|
||||
}
|
||||
},
|
||||
"fields": {
|
||||
"destinationPath": "Zielpfad",
|
||||
"destinationPathHelp": "Lokaler Verzeichnispfad für Backups",
|
||||
"destinationPathPlaceholder": "/pfad/zum/backup/verzeichnis",
|
||||
"rsyncHost": "Remote Host",
|
||||
"rsyncHostPlaceholder": "backup.example.com",
|
||||
"rsyncUser": "Benutzer",
|
||||
"rsyncUserPlaceholder": "backupuser",
|
||||
"rsyncPath": "Remote-Pfad",
|
||||
"rsyncPathPlaceholder": "/pfad/auf/server",
|
||||
"rsyncSshKey": "SSH-Schlüssel",
|
||||
"rsyncSshKeyPlaceholder": "Privater SSH-Schlüssel (PEM)",
|
||||
"rsyncSshKeyHelp": "Fügen Sie den privaten SSH-Schlüssel im PEM-Format ein.",
|
||||
"s3Endpoint": "S3-Endpunkt-URL",
|
||||
"s3EndpointHelp": "z. B. https://s3.amazonaws.com oder Ihr MinIO-Endpunkt",
|
||||
"s3Bucket": "Bucket-Name",
|
||||
"s3Region": "Region",
|
||||
"s3AccessKey": "Access Key ID",
|
||||
"s3SecretKey": "Secret Access Key"
|
||||
},
|
||||
"schedule": {
|
||||
"title": "Zeitplan",
|
||||
"scheduleType": "Zeitplantyp",
|
||||
"customCron": "Eigener Cron-Ausdruck",
|
||||
"customCronHelp": "Cron-Ausdruck für benutzerdefinierten Zeitplan",
|
||||
"retention": "Aufbewahrung (Tage)",
|
||||
"retentionHelp": "Anzahl der Tage, nach denen alte Backups automatisch gelöscht werden"
|
||||
},
|
||||
"whatToBackup": {
|
||||
"title": "Was soll gesichert werden",
|
||||
"database": "Datenbank",
|
||||
"databaseHelp": "Datenbank (Einstellungen, Events, Benutzer)",
|
||||
"photos": "Fotos",
|
||||
"photosHelp": "Aktive Galeriefotos sichern",
|
||||
"archives": "Archive",
|
||||
"archivesHelp": "Archivierte ZIP-Dateien",
|
||||
"thumbnails": "Thumbnails",
|
||||
"thumbnailsHelp": "Generierte Vorschaubilder"
|
||||
},
|
||||
"advancedOptions": {
|
||||
"title": "Erweiterte Optionen",
|
||||
"compression": "Kompression",
|
||||
"compressionHelp": "Backups komprimieren, um Speicherplatz zu sparen",
|
||||
"encryption": "Verschlüsselung",
|
||||
"encryptionHelp": "Backups mit einer Passphrase verschlüsseln",
|
||||
"encryptionPassphrase": "Verschlüsselungs-Passphrase",
|
||||
"encryptionPassphraseHelp": "Passphrase zum Verschlüsseln/Entschlüsseln der Backups"
|
||||
},
|
||||
"savingSettings": "Einstellungen werden gespeichert...",
|
||||
"saveSettings": "Einstellungen speichern"
|
||||
},
|
||||
"history": {
|
||||
"columns": {
|
||||
"status": "Status",
|
||||
"dateTime": "Datum & Uhrzeit",
|
||||
"type": "Typ",
|
||||
"size": "Größe",
|
||||
"duration": "Dauer",
|
||||
"actions": "Aktionen"
|
||||
},
|
||||
"details": "Details",
|
||||
"statistics": "Statistiken",
|
||||
"errors": "Fehler",
|
||||
"backupDetails": {
|
||||
"backupId": "Backup-ID",
|
||||
"startTime": "Startzeit",
|
||||
"endTime": "Endzeit",
|
||||
"destination": "Ziel",
|
||||
"filesProcessed": "Verarbeitete Dateien",
|
||||
"totalSize": "Gesamtgröße",
|
||||
"compressionRatio": "Kompressionsrate",
|
||||
"errorLog": "Fehlerprotokoll",
|
||||
"noErrors": "Keine Fehler aufgetreten"
|
||||
},
|
||||
"pagination": {
|
||||
"showing": "Zeige {{from}}–{{to}} von {{total}} Backups",
|
||||
"previous": "Zurück",
|
||||
"next": "Weiter"
|
||||
},
|
||||
"filter": {
|
||||
"allStatus": "Alle Status",
|
||||
"completed": "Abgeschlossen",
|
||||
"failed": "Fehlgeschlagen",
|
||||
"running": "Läuft",
|
||||
"partial": "Teilweise"
|
||||
},
|
||||
"noBackupsFound": "Keine Backups gefunden",
|
||||
"backupsWillAppear": "Backups erscheinen hier, sobald sie erstellt wurden",
|
||||
"messages": {
|
||||
"deleteSuccess": "Backup erfolgreich gelöscht"
|
||||
}
|
||||
},
|
||||
"restore": {
|
||||
"steps": {
|
||||
"selectSource": "Quelle auswählen",
|
||||
"chooseBackup": "Backup wählen",
|
||||
"restoreOptions": "Wiederherstellungsoptionen",
|
||||
"reviewConfirm": "Prüfen & Bestätigen",
|
||||
"progress": "Fortschritt"
|
||||
},
|
||||
"source": {
|
||||
"title": "Backup-Quelle auswählen",
|
||||
"subtitle": "Wählen Sie, woher das Backup wiederhergestellt werden soll",
|
||||
"local": {
|
||||
"name": "Lokales Backup",
|
||||
"description": "Vom lokalen Dateisystem wiederherstellen"
|
||||
},
|
||||
"s3": {
|
||||
"name": "S3-Speicher",
|
||||
"description": "Aus S3-Bucket wiederherstellen"
|
||||
},
|
||||
"upload": {
|
||||
"name": "Backup hochladen",
|
||||
"description": "Eine Backup-Datei hochladen",
|
||||
"comingSoon": "Upload-Funktion folgt in Kürze"
|
||||
},
|
||||
"configuration": {
|
||||
"s3": "S3-Konfiguration",
|
||||
"endpoint": "S3-Endpunkt-URL",
|
||||
"bucket": "Bucket-Name",
|
||||
"accessKey": "Access Key ID",
|
||||
"secretKey": "Secret Access Key"
|
||||
}
|
||||
},
|
||||
"backup": {
|
||||
"title": "Backup zum Wiederherstellen wählen",
|
||||
"subtitle": "Aus verfügbaren Backups auswählen",
|
||||
"noBackupsFound": "Keine Backups in der gewählten Quelle gefunden",
|
||||
"encrypted": "Verschlüsseltes Backup",
|
||||
"encryptedMessage": "Zum Wiederherstellen dieses Backups wird die Verschlüsselungs-Passphrase benötigt.",
|
||||
"enterPassphrase": "Verschlüsselungs-Passphrase eingeben",
|
||||
"at": "um"
|
||||
},
|
||||
"restoreTypes": {
|
||||
"full": {
|
||||
"name": "Vollständige Wiederherstellung",
|
||||
"description": "Alles wiederherstellen (Datenbank, Fotos und Archive)",
|
||||
"warning": "Dies ersetzt alle aktuellen Daten"
|
||||
},
|
||||
"database": {
|
||||
"name": "Nur Datenbank",
|
||||
"description": "Nur die Datenbank wiederherstellen (Einstellungen, Events, Benutzer)",
|
||||
"warning": "Aktuelle Datenbank wird ersetzt"
|
||||
},
|
||||
"files": {
|
||||
"name": "Nur Dateien",
|
||||
"description": "Nur Fotos und Archive wiederherstellen",
|
||||
"warning": "Vorhandene Dateien können überschrieben werden"
|
||||
},
|
||||
"selective": {
|
||||
"name": "Selektive Wiederherstellung",
|
||||
"description": "Bestimmte Elemente zur Wiederherstellung auswählen",
|
||||
"warning": "Es werden nur ausgewählte Elemente wiederhergestellt"
|
||||
}
|
||||
},
|
||||
"options": {
|
||||
"title": "Wiederherstellungsoptionen",
|
||||
"subtitle": "Auswählen, was wiederhergestellt werden soll",
|
||||
"additionalOptions": {
|
||||
"title": "Zusätzliche Optionen",
|
||||
"skipPreBackup": "Vorab-Backup überspringen",
|
||||
"skipPreBackupHelp": "Standardmäßig wird vor der Wiederherstellung ein Backup erstellt. Aktivieren, um dies zu überspringen.",
|
||||
"force": "Wiederherstellung erzwingen",
|
||||
"forceHelp": "Sicherheitsprüfungen und Warnungen überschreiben (mit Vorsicht verwenden)"
|
||||
}
|
||||
},
|
||||
"confirmation": {
|
||||
"title": "Prüfen & Bestätigen",
|
||||
"subtitle": "Bitte prüfen Sie Ihre Wiederherstellungskonfiguration",
|
||||
"validation": {
|
||||
"passed": "Validierung bestanden",
|
||||
"failed": "Validierung fehlgeschlagen",
|
||||
"checking": "Wiederherstellungskonfiguration wird geprüft..."
|
||||
},
|
||||
"spaceCheck": {
|
||||
"title": "Speicherplatz",
|
||||
"required": "Erforderlich",
|
||||
"available": "Verfügbar",
|
||||
"insufficient": "Nicht genügend Speicherplatz"
|
||||
},
|
||||
"summary": {
|
||||
"title": "Zusammenfassung",
|
||||
"source": "Quelle",
|
||||
"backupDate": "Backup-Datum",
|
||||
"restoreType": "Art der Wiederherstellung",
|
||||
"preBackup": "Vorab-Backup",
|
||||
"enabled": "Aktiviert",
|
||||
"skipped": "Übersprungen"
|
||||
},
|
||||
"warning": {
|
||||
"title": "Wichtiger Hinweis",
|
||||
"message": "Diese Wiederherstellung ersetzt bestehende Daten. Stellen Sie sicher, dass Sie ein aktuelles Backup haben. Dieser Vorgang kann nicht rückgängig gemacht werden."
|
||||
}
|
||||
},
|
||||
"progress": {
|
||||
"title": "Fortschritt der Wiederherstellung",
|
||||
"inProgress": "Wiederherstellung läuft...",
|
||||
"completed": "Wiederherstellung abgeschlossen",
|
||||
"overallProgress": "Gesamtfortschritt",
|
||||
"current": "Aktuell",
|
||||
"statusDetails": "Statusdetails",
|
||||
"restoreLogs": "Wiederherstellungs-Logs",
|
||||
"steps": {
|
||||
"completed": "Abgeschlossen",
|
||||
"running": "Läuft",
|
||||
"failed": "Fehlgeschlagen",
|
||||
"pending": "Ausstehend"
|
||||
},
|
||||
"success": {
|
||||
"title": "Wiederherstellung erfolgreich abgeschlossen",
|
||||
"message": "Ihre Daten wurden wiederhergestellt. Bitte prüfen Sie, ob alles korrekt funktioniert."
|
||||
}
|
||||
},
|
||||
"actions": {
|
||||
"back": "Zurück",
|
||||
"next": "Weiter",
|
||||
"startRestore": "Wiederherstellung starten",
|
||||
"starting": "Starte...",
|
||||
"validating": "Validiere...",
|
||||
"startNewRestore": "Neue Wiederherstellung starten"
|
||||
},
|
||||
"messages": {
|
||||
"restoreStarted": "Wiederherstellung erfolgreich gestartet"
|
||||
}
|
||||
},
|
||||
"messages": {
|
||||
"backupStarted": "Backup erfolgreich gestartet",
|
||||
"backupFailed": "Backup konnte nicht gestartet werden",
|
||||
"configUpdated": "Backup-Konfiguration aktualisiert",
|
||||
"configUpdateFailed": "Konfiguration konnte nicht aktualisiert werden",
|
||||
"backupDeleted": "Backup erfolgreich gelöscht",
|
||||
"deleteFailed": "Backup konnte nicht gelöscht werden",
|
||||
"testEmailSent": "Verbindung erfolgreich getestet!",
|
||||
"testEmailFailed": "Verbindungstest fehlgeschlagen"
|
||||
}
|
||||
},
|
||||
"archives": {
|
||||
"title": "Archive",
|
||||
"subtitle": "Archivierte Fotogalerien verwalten",
|
||||
@@ -134,7 +479,6 @@
|
||||
"sortByName": "Nach Name sortieren",
|
||||
"sortBySize": "Nach Größe sortieren",
|
||||
"allPhotos": "Alle Fotos",
|
||||
"downloadSelected": "Ausgewählte herunterladen",
|
||||
"shareGallery": "Galerie teilen",
|
||||
"needHelp": "Hilfe benötigt? Kontaktieren Sie uns unter",
|
||||
"noPhotosFound": "Keine Fotos gefunden",
|
||||
@@ -735,6 +1079,24 @@
|
||||
"bulk_download": "{{count}} Fotos heruntergeladen von {{eventName}}",
|
||||
"gallery_password_entry": "Passwort eingegeben 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",
|
||||
"event_updated": "Veranstaltung aktualisiert: {{eventName}}",
|
||||
"event_deleted": "Veranstaltung gelöscht: {{eventName}}",
|
||||
@@ -1438,4 +1800,4 @@
|
||||
"poweredBy": "Bereitgestellt von PicPeak",
|
||||
"devModeHint": "Entwicklungsmodus: E-Mail: admin@example.com, Passwort: admin123"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -36,6 +36,11 @@
|
||||
"customize": "Customize",
|
||||
"hide": "Hide",
|
||||
"unknown": "Unknown",
|
||||
"notSet": "Not set",
|
||||
"of": "of",
|
||||
"up": "Up",
|
||||
"select": "Select",
|
||||
"selected": "Selected",
|
||||
"chunk": "Chunk"
|
||||
},
|
||||
"upload": {
|
||||
@@ -50,6 +55,10 @@
|
||||
"uploadFailed": "Upload failed",
|
||||
"someFilesFailed": "Some files failed to upload",
|
||||
"uploadPhotos": "Upload Photos",
|
||||
"importExternal": "Import from External Folder",
|
||||
"externalImportInfo": "All pictures from the selected folder will be imported.",
|
||||
"selectExternalFolder": "Select external folder under /external-media",
|
||||
"importFromSelectedFolder": "Import from selected folder",
|
||||
"maxFilesReached": "Maximum 500 files allowed",
|
||||
"someFilesSkipped": "Some files were skipped (500 file limit)",
|
||||
"tooManyFiles": "Maximum 500 files can be uploaded at once",
|
||||
@@ -134,6 +143,12 @@
|
||||
"sortByName": "Sort by Name",
|
||||
"sortBySize": "Sort by Size",
|
||||
"allPhotos": "All Photos",
|
||||
"filter": "Filter",
|
||||
"feedbackFilter": "Feedback Filter",
|
||||
"all": "All",
|
||||
"liked": "Liked",
|
||||
"favorited": "Favorited",
|
||||
"favorites": "Favorites",
|
||||
"downloadSelected": "Download Selected",
|
||||
"shareGallery": "Share Gallery",
|
||||
"needHelp": "Need help? Contact us at",
|
||||
@@ -806,6 +821,24 @@
|
||||
"bulk_download": "{{count}} photos downloaded from {{eventName}}",
|
||||
"gallery_password_entry": "Password entered 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",
|
||||
"event_updated": "Event updated: {{eventName}}",
|
||||
"event_deleted": "Event deleted: {{eventName}}",
|
||||
@@ -967,6 +1000,12 @@
|
||||
"pageUpdated": "Page updated successfully"
|
||||
},
|
||||
"backup": {
|
||||
"external": {
|
||||
"warning": {
|
||||
"title": "External media excluded",
|
||||
"body": "This installation references photos from /external-media. These originals are excluded from backups. Thumbnails and database are still backed up."
|
||||
}
|
||||
},
|
||||
"title": "Backup Management",
|
||||
"subtitle": "Manage system backups, configure automated backups, and restore from previous backups.",
|
||||
"tabs": {
|
||||
@@ -1490,4 +1529,4 @@
|
||||
"poweredBy": "Powered by PicPeak",
|
||||
"devModeHint": "Development Mode: Use email: admin@example.com, password: admin123"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -268,13 +268,13 @@ export const AdminDashboard: React.FC = () => {
|
||||
categoryName: activity.metadata?.category_name || ''
|
||||
};
|
||||
|
||||
// Check if translation exists
|
||||
const translated = t(translationKey, params);
|
||||
if (typeof translated === 'string') {
|
||||
return translated;
|
||||
// Translate; if key missing i18n returns the key string itself
|
||||
const translated = t(translationKey, params) as string;
|
||||
if (!translated || translated === translationKey) {
|
||||
// Fallback: format a readable English message
|
||||
return adminService.formatActivityMessage(activity);
|
||||
}
|
||||
// Fallback to unknown activity if translation not found
|
||||
return t('admin.activities.unknown') as string;
|
||||
return translated;
|
||||
};
|
||||
|
||||
return (
|
||||
@@ -302,4 +302,4 @@ export const AdminDashboard: React.FC = () => {
|
||||
);
|
||||
};
|
||||
|
||||
AdminDashboard.displayName = 'AdminDashboard';
|
||||
AdminDashboard.displayName = 'AdminDashboard';
|
||||
|
||||