Self-hosted personal gallery application with online photo management and albums, supporting Live/Motion Photos, EXIF parsing, geolocation recognition, and an explore map.
TypeScript albumsexif-extractiongeocodinglive-photomotion-photophoto-galleryphoto-sharingwebgl-viewer
chore(style): reformat code
Timothy Yinc07aac74ba67
diff --git a/.github/copilot-instructions.md b/.github/copilot-instructions.mdindex 0982fe3b..39270a0c 100644--- a/.github/copilot-instructions.md+++ b/.github/copilot-instructions.md@@ -5,12 +5,14 @@ ChronoFrame is a high-performance photo management and gallery application built## Architecture Overview### Core Components+- **Frontend**: Nuxt 4 app with Vue 3, TypeScript, and TailwindCSS- **Backend**: Nitro server with SQLite (Drizzle ORM) and multi-provider storage- **WebGL Package**: Custom `@chronoframe/webgl-image` for hardware-accelerated viewing- **Processing Pipeline**: Async photo processing with EXIF, thumbnails, and geolocation### Key Directories+- `app/`: Nuxt 4 application (components, pages, composables)- `server/`: API routes and backend services- `packages/webgl-image/`: Standalone WebGL image viewer package@@ -19,6 +21,7 @@ ChronoFrame is a high-performance photo management and gallery application built## Development Workflow### Essential Commands+```bash# Development with dependency buildingpnpm dev:deps@@ -35,22 +38,27 @@ pnpm build```### Monorepo Structure+This is a pnpm workspace with the WebGL package as a local dependency. Always use `pnpm dev:deps` for development to ensure the WebGL package builds alongside the main app.## Storage Architecture### Multi-Provider System+Storage providers are abstracted through `server/services/storage/interfaces.ts`:+- **S3**: AWS S3-compatible storage (primary)- **HubR2**: Cloudflare R2 via NuxtHub- **GitHub**: Git-based storage (experimental)### Key Pattern+All storage operations go through `useStorageProvider(event)` in API routes. The provider is configured via `NUXT_STORAGE_PROVIDER` environment variable.## Photo Processing Pipeline### Async Processing Pattern+Photos are processed via `execPhotoPipelineAsync()` in `server/services/photo/pipeline-async.ts`:1. **Preprocessing**: HEIC conversion to JPEG, buffer management@@ -61,6 +69,7 @@ Photos are processed via `execPhotoPipelineAsync()` in `server/services/photo/pi6. **LivePhoto**: Video companion file detection and processing### Critical Implementation Details+- Use `setImmediate()` for non-blocking async operations- Always handle HEIC → JPEG conversion for Apple photos- EXIF processing requires temporary file writes (see `server/services/image/exif.ts`)@@ -73,23 +82,28 @@ Photos are processed via `execPhotoPipelineAsync()` in `server/services/photo/pi- All components are auto imported via Nuxt (eg. `/app/components/photo/PhotoItem.client.vue` can be used directly as `<PhotoPhotoItem />`)### Vue Composables+- `usePhotos()`: Central photo data management with injection/provide pattern- `usePhotoFilters()`: Client-side filtering with reactive state- `useLivePhotoProcessor()`: WebGL-based MOV to MP4 conversion- `useWebGLWorkState()`: Performance monitoring for WebGL operations### Masonry Grid System+The `app/components/masonry/Root.vue` implements a CSS-based masonry layout:+- Auto-responsive column counts based on viewport- Intersection Observer for performance and date range tracking- Background LivePhoto processing for visible items only### WebGL Integration+Register WebGL components via plugin (`app/plugins/chrono-webgl-image.ts`). The package provides hardware-accelerated zooming and panning for large images.## Database Operations### Core Database Pattern+**ALWAYS use `useDB()` from `server/utils/db.ts` for all database operations:**```typescript@@ -116,13 +130,16 @@ await useDB()```### Database Configuration+- Uses **better-sqlite3** with Drizzle ORM-- Database file: `data/app.sqlite3`+- Database file: `data/app.sqlite3`- Schema exports types: `User`, `Photo` from `useDB`- Import patterns: `eq`, `and`, `or`, `sql` from the same file### Photo Model Schema+Key fields in `server/database/schema.ts`:+- `storageKey`: Original file path in storage- `originalUrl`: Public URL (may point to JPEG version for HEIC)- `thumbnailUrl`/`thumbnailHash`: WebP thumbnail with ThumbHash@@ -131,21 +148,26 @@ Key fields in `server/database/schema.ts`:- `isLivePhoto`: Boolean with optional video companion file### Migration Pattern+Use Drizzle migrations for schema changes. Initial user setup is handled in migration files.## API Conventions### Authentication+All photo management APIs require `await requireUserSession(event)` using nuxt-auth-utils with GitHub OAuth.### Upload Flow+1. POST `/api/photos` → Get presigned URL2. Direct upload to storage provider3. POST `/api/photos/process` → Trigger async processing4. Background pipeline processes and saves to database### Background Processing+Use this pattern for long-running operations:+```typescript// Return immediately, process in backgroundprocessPhotoInBackground(fileKey, storageObject)@@ -155,23 +177,27 @@ return { message: 'Processing started' }## Environment Configuration### Required Variables+- `NUXT_STORAGE_PROVIDER`: `s3` | `hub-r2` | `github`- `NUXT_SESSION_PASSWORD`: 32-character random string- `NUXT_OAUTH_GITHUB_CLIENT_ID/SECRET`: GitHub OAuth app- `MAPBOX_TOKEN`: For map functionality### Storage Provider Config+Each provider has specific env vars (see README). S3 is most commonly used with CDN support via `NUXT_PROVIDER_S3_CDN_URL`.## Performance Considerations### Image Processing+- Large images are processed asynchronously to avoid blocking- HEIC files automatically get JPEG versions uploaded- Thumbnails use WebP format for optimal size/quality- Use Sharp for all image manipulation### WebGL Viewer+- Monitors work state via `useWebGLWorkState()`- Automatically falls back for unsupported devices- Lazy loads textures for large images@@ -179,20 +205,23 @@ Each provider has specific env vars (see README). S3 is most commonly used with## Code Style### Database Operations+- **CRITICAL**: Always use `useDB()` from `server/utils/db.ts` - never import Drizzle directly- Import query helpers: `import { useDB, tables, eq, and, or } from '~~/server/utils/db'`- Use `tables.photos`, `tables.users` for schema references- Database file is `data/app.sqlite3` (better-sqlite3 + Drizzle ORM)### TypeScript+- Strict typing with shared types in `shared/types/`- Use Drizzle schema types for database operations- Avoid `any` except for complex EXIF data structures### Vue/Nuxt+- Composition API throughout- Use `definePageMeta()` for layouts- Server-side components for data fetching- Client-side `.vue` files for interactive components (see `PhotoItem.client.vue`)-When working on this codebase, prioritize understanding the async processing pipeline and storage abstraction layer, as these are the most complex architectural decisions that impact all photo operations.\ No newline at end of file+When working on this codebase, prioritize understanding the async processing pipeline and storage abstraction layer, as these are the most complex architectural decisions that impact all photo operations.diff --git a/.github/dependabot.yml b/.github/dependabot.ymlindex a6627a9b..3e00b1db 100644--- a/.github/dependabot.yml+++ b/.github/dependabot.yml@@ -5,9 +5,9 @@version: 2updates:- - package-ecosystem: "npm" # See documentation for possible values+ - package-ecosystem: 'npm' # See documentation for possible valuesdirectories:- - "/"- - "packages/*"+ - '/'+ - 'packages/*'schedule:- interval: "daily"+ interval: 'daily'diff --git a/.github/workflows/announce-releases.yml b/.github/workflows/announce-releases.ymlindex 2f17abf3..7cf202ab 100644--- a/.github/workflows/announce-releases.yml+++ b/.github/workflows/announce-releases.yml@@ -15,8 +15,8 @@ jobs:uses: SethCohen/github-releases-to-discord@v1with:webhook_url: ${{ secrets.DC_WEBHOOK_URL }}- color: "2105893"- username: "GitHub Release"- avatar_url: "https://cdn.discordapp.com/avatars/1431138378203533312/59c6a41905663993a03d37c6608dea68.png"- footer_title: "Changelog"+ color: '2105893'+ username: 'GitHub Release'+ avatar_url: 'https://cdn.discordapp.com/avatars/1431138378203533312/59c6a41905663993a03d37c6608dea68.png'+ footer_title: 'Changelog'reduce_headings: truediff --git a/.oxlintrc.json b/.oxlintrc.jsonindex 161aba92..063cd073 100644--- a/.oxlintrc.json+++ b/.oxlintrc.json@@ -9,4 +9,4 @@"no-empty-object-type": "off","no-explicit-any": "off"}-}\ No newline at end of file+}diff --git a/.vscode/extensions.json b/.vscode/extensions.jsonindex b58ab0c1..99e2f7dd 100644--- a/.vscode/extensions.json+++ b/.vscode/extensions.json@@ -1,5 +1,3 @@{- "recommendations": [- "oxc.oxc-vscode"- ]-}\ No newline at end of file+ "recommendations": ["oxc.oxc-vscode"]+}diff --git a/.vscode/settings.json b/.vscode/settings.jsonindex c1642d9c..7abe7ab5 100644--- a/.vscode/settings.json+++ b/.vscode/settings.json@@ -11,20 +11,11 @@"editor.quickSuggestions": {"strings": "on"},- "tailwindCSS.classAttributes": [- "class",- "ui"- ],+ "tailwindCSS.classAttributes": ["class", "ui"],"tailwindCSS.experimental.classRegex": [- [- "ui:\\s*{([^)]*)\\s*}",- "(?:'|\"|`)([^']*)(?:'|\"|`)"- ]- ],- "i18n-ally.localesPaths": [- "i18n",- "i18n/locales"+ ["ui:\\s*{([^)]*)\\s*}", "(?:'|\"|`)([^']*)(?:'|\"|`)"]],+ "i18n-ally.localesPaths": ["i18n", "i18n/locales"],"i18n-ally.sourceLanguage": "zh-Hans","i18n-ally.keystyle": "nested","i18n-ally.extract.autoDetect": true,@@ -35,9 +26,7 @@"app/components/map/ClusterPin.vue": ["\n representativePhoto.title || `聚类 ${representativePhoto.id}`\n "],- "nuxt.config.ts": [- "简体中文"- ],+ "nuxt.config.ts": ["简体中文"],"app/components/map/SinglePhotoPin.vue": ["marker.title || `照片 ${marker.id}`"]@@ -61,4 +50,4 @@"繁体中文(香港)","English"]-}\ No newline at end of file+}diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.mdindex b9dae2a3..a59dd5d0 100644--- a/CODE_OF_CONDUCT.md+++ b/CODE_OF_CONDUCT.md@@ -17,23 +17,23 @@ diverse, inclusive, and healthy community.Examples of behavior that contributes to a positive environment for ourcommunity include:-* Demonstrating empathy and kindness toward other people-* Being respectful of differing opinions, viewpoints, and experiences-* Giving and gracefully accepting constructive feedback-* Accepting responsibility and apologizing to those affected by our mistakes,+- Demonstrating empathy and kindness toward other people+- Being respectful of differing opinions, viewpoints, and experiences+- Giving and gracefully accepting constructive feedback+- Accepting responsibility and apologizing to those affected by our mistakes,and learning from the experience-* Focusing on what is best not just for us as individuals, but for the+- Focusing on what is best not just for us as individuals, but for theoverall communityExamples of unacceptable behavior include:-* The use of sexualized language or imagery, and sexual attention or+- The use of sexualized language or imagery, and sexual attention oradvances of any kind-* Trolling, insulting or derogatory comments, and personal or political attacks-* Public or private harassment-* Publishing others' private information, such as a physical or email+- Trolling, insulting or derogatory comments, and personal or political attacks+- Public or private harassment+- Publishing others' private information, such as a physical or emailaddress, without their explicit permission-* Other conduct which could reasonably be considered inappropriate in a+- Other conduct which could reasonably be considered inappropriate in aprofessional setting## Enforcement Responsibilities@@ -106,7 +106,7 @@ Violating these terms may lead to a permanent ban.### 4. Permanent Ban**Community Impact**: Demonstrating a pattern of violation of community-standards, including sustained inappropriate behavior, harassment of an+standards, including sustained inappropriate behavior, harassment of anindividual, or aggression toward or disparagement of classes of individuals.**Consequence**: A permanent ban from any sort of public interaction withindiff --git a/CONTRIBUTING.md b/CONTRIBUTING.mdindex 3a76ee97..bcd269f8 100644--- a/CONTRIBUTING.md+++ b/CONTRIBUTING.md@@ -250,7 +250,7 @@ interface Emits {}const props = withDefaults(defineProps<Props>(), {- loading: false+ loading: false,})const emit = defineEmits<Emits>()diff --git a/README_zh.md b/README_zh.mdindex 0cef0508..e387c918 100644--- a/README_zh.md+++ b/README_zh.md@@ -99,11 +99,13 @@ NUXT_SESSION_PASSWORD=我们推荐使用预构建的 Docker 镜像进行部署,镜像托管在 GHCR 和 Docker Hub,您可以根据网络情况选择合适的源。#### [GitHub Container Registry (GHCR)](https://github.com/HoshinoSuzumi/chronoframe/pkgs/container/chronoframe)+```bashdocker pull ghcr.io/hoshinosuzumi/chronoframe:latest```#### [Docker Hub](https://hub.docker.com/r/hoshinosuzumi/chronoframe)+```bashdocker pull hoshinosuzumi/chronoframe:latest```diff --git a/app/assets/mapStyles/chronoframe_dark.json b/app/assets/mapStyles/chronoframe_dark.jsonindex bcc28ba7..b7282a6f 100644--- a/app/assets/mapStyles/chronoframe_dark.json+++ b/app/assets/mapStyles/chronoframe_dark.json@@ -11,7 +11,7 @@},"center": [116.4074, 39.9042],"zoom": 2,- "projection": {"type": "globe"},+ "projection": { "type": "globe" },"sources": {"openmaptiles": {"type": "vector",@@ -24,7 +24,7 @@{"id": "background","type": "background",- "paint": {"background-color": "rgba(51, 51, 51, 1)"}+ "paint": { "background-color": "rgba(51, 51, 51, 1)" }},{"id": "landuse-residential",@@ -36,8 +36,8 @@["==", "$type", "Polygon"],["in", "class", "residential", "suburb", "neighbourhood"]],- "layout": {"visibility": "visible"},- "paint": {"fill-color": "rgba(74, 74, 74, 0.64)", "fill-opacity": 0.7}+ "layout": { "visibility": "visible" },+ "paint": { "fill-color": "rgba(74, 74, 74, 0.64)", "fill-opacity": 0.7 }},{"id": "landcover_grass",@@ -45,7 +45,10 @@"source": "openmaptiles","source-layer": "landcover","filter": ["==", "class", "grass"],- "paint": {"fill-color": "rgba(150, 189, 109, 0.66)", "fill-opacity": 0.45}+ "paint": {+ "fill-color": "rgba(150, 189, 109, 0.66)",+ "fill-opacity": 0.45+ }},{"id": "landcover_wood",@@ -55,7 +58,13 @@"filter": ["==", "class", "wood"],"paint": {"fill-color": "rgba(94, 109, 75, 0.44)",- "fill-opacity": {"base": 1, "stops": [[8, 0.6], [22, 1]]}+ "fill-opacity": {+ "base": 1,+ "stops": [+ [8, 0.6],+ [22, 1]+ ]+ }}},{@@ -69,8 +78,8 @@["!=", "intermittent", 1],["!=", "brunnel", "tunnel"]],- "layout": {"visibility": "visible"},- "paint": {"fill-color": "rgba(148, 193, 225, 0.19)"}+ "layout": { "visibility": "visible" },+ "paint": { "fill-color": "rgba(148, 193, 225, 0.19)" }},{"id": "water_intermittent",@@ -78,8 +87,8 @@"source": "openmaptiles","source-layer": "water","filter": ["all", ["==", "$type", "Polygon"], ["==", "intermittent", 1]],- "layout": {"visibility": "visible"},- "paint": {"fill-color": "rgba(30, 30, 30, 1)", "fill-opacity": 0.7}+ "layout": { "visibility": "visible" },+ "paint": { "fill-color": "rgba(30, 30, 30, 1)", "fill-opacity": 0.7 }},{"id": "landcover-ice-shelf",@@ -87,8 +96,8 @@"source": "openmaptiles","source-layer": "landcover","filter": ["==", "subclass", "ice_shelf"],- "layout": {"visibility": "visible"},- "paint": {"fill-color": "hsl(47, 26%, 88%)", "fill-opacity": 0.8}+ "layout": { "visibility": "visible" },+ "paint": { "fill-color": "hsl(47, 26%, 88%)", "fill-opacity": 0.8 }},{"id": "landcover-glacier",@@ -96,10 +105,16 @@"source": "openmaptiles","source-layer": "landcover","filter": ["==", "subclass", "glacier"],- "layout": {"visibility": "visible"},+ "layout": { "visibility": "visible" },"paint": {"fill-color": "rgba(90, 90, 90, 1)",- "fill-opacity": {"base": 1, "stops": [[0, 1], [8, 0.5]]}+ "fill-opacity": {+ "base": 1,+ "stops": [+ [0, 1],+ [8, 0.5]+ ]+ }}},{@@ -121,8 +136,8 @@"source": "openmaptiles","source-layer": "landuse","filter": ["==", "class", "agriculture"],- "layout": {"visibility": "visible"},- "paint": {"fill-color": "#eae0d0"}+ "layout": { "visibility": "visible" },+ "paint": { "fill-color": "#eae0d0" }},{"id": "landuse_overlay_national_park",@@ -132,7 +147,13 @@"filter": ["==", "class", "national_park"],"paint": {"fill-color": "#E1EBB0",- "fill-opacity": {"base": 1, "stops": [[5, 0], [9, 0.75]]}+ "fill-opacity": {+ "base": 1,+ "stops": [+ [5, 0],+ [9, 0.75]+ ]+ }}},{@@ -145,13 +166,24 @@["==", "$type", "LineString"],["==", "brunnel", "tunnel"]],- "layout": {"visibility": "visible"},+ "layout": { "visibility": "visible" },"paint": {"line-color": "hsl(205, 56%, 73%)","line-dasharray": [3, 3],- "line-gap-width": {"stops": [[12, 0], [20, 6]]},+ "line-gap-width": {+ "stops": [+ [12, 0],+ [20, 6]+ ]+ },"line-opacity": 1,- "line-width": {"base": 1.4, "stops": [[8, 1], [20, 2]]}+ "line-width": {+ "base": 1.4,+ "stops": [+ [8, 1],+ [20, 2]+ ]+ }}},{@@ -165,11 +197,17 @@["!in", "brunnel", "tunnel", "bridge"],["!=", "intermittent", 1]],- "layout": {"visibility": "visible"},+ "layout": { "visibility": "visible" },"paint": {"line-color": "rgba(148, 193, 225, 0.35)","line-opacity": 1,- "line-width": {"base": 1.4, "stops": [[8, 1], [20, 8]]}+ "line-width": {+ "base": 1.4,+ "stops": [+ [8, 1],+ [20, 8]+ ]+ }}},{@@ -183,12 +221,18 @@["!in", "brunnel", "tunnel", "bridge"],["==", "intermittent", 1]],- "layout": {"visibility": "visible"},+ "layout": { "visibility": "visible" },"paint": {"line-color": "hsl(205, 56%, 73%)","line-dasharray": [2, 1],"line-opacity": 1,- "line-width": {"base": 1.4, "stops": [[8, 1], [20, 8]]}+ "line-width": {+ "base": 1.4,+ "stops": [+ [8, 1],+ [20, 8]+ ]+ }}},{@@ -203,11 +247,17 @@["==", "brunnel", "tunnel"],["==", "class", "transit"]],- "layout": {"line-cap": "butt", "line-join": "miter"},+ "layout": { "line-cap": "butt", "line-join": "miter" },"paint": {"line-color": "hsl(34, 12%, 66%)","line-dasharray": [3, 3],- "line-opacity": {"base": 1, "stops": [[11, 0], [16, 1]]}+ "line-opacity": {+ "base": 1,+ "stops": [+ [11, 0],+ [16, 1]+ ]+ }}},{@@ -215,11 +265,17 @@"type": "fill","source": "openmaptiles","source-layer": "building",- "layout": {"visibility": "visible"},+ "layout": { "visibility": "visible" },"paint": {"fill-antialias": true,"fill-color": "rgba(135, 135, 135, 1)",- "fill-opacity": {"base": 1, "stops": [[13, 0], [15, 1]]},+ "fill-opacity": {+ "base": 1,+ "stops": [+ [13, 0],+ [15, 1]+ ]+ },"fill-outline-color": {"stops": [[15, "rgba(212, 177, 146, 0)"],@@ -240,7 +296,7 @@"text-font": ["Noto Sans Regular"],"text-size": 10},- "paint": {"text-color": "rgba(212, 177, 146, 1)"}+ "paint": { "text-color": "rgba(212, 177, 146, 1)" }},{"id": "road_area_pier",@@ -249,8 +305,8 @@"source": "openmaptiles","source-layer": "transportation","filter": ["all", ["==", "$type", "Polygon"], ["==", "class", "pier"]],- "layout": {"visibility": "visible"},- "paint": {"fill-antialias": true, "fill-color": "hsl(47, 26%, 88%)"}+ "layout": { "visibility": "visible" },+ "paint": { "fill-antialias": true, "fill-color": "hsl(47, 26%, 88%)" }},{"id": "road_pier",@@ -266,7 +322,13 @@},"paint": {"line-color": "hsl(47, 26%, 88%)",- "line-width": {"base": 1.2, "stops": [[15, 1], [17, 4]]}+ "line-width": {+ "base": 1.2,+ "stops": [+ [15, 1],+ [17, 4]+ ]+ }}},{@@ -279,8 +341,8 @@["==", "$type", "Polygon"],["in", "brunnel", "bridge"]],- "layout": {"visibility": "visible"},- "paint": {"fill-color": "rgba(90, 90, 90, 0.56)", "fill-opacity": 0.5}+ "layout": { "visibility": "visible" },+ "paint": { "fill-color": "rgba(90, 90, 90, 0.56)", "fill-opacity": 0.5 }},{"id": "road_path",@@ -300,7 +362,13 @@"paint": {"line-color": "rgba(125, 125, 125, 1)","line-dasharray": [1, 1],- "line-width": {"base": 1.55, "stops": [[4, 0.25], [20, 10]]}+ "line-width": {+ "base": 1.55,+ "stops": [+ [4, 0.25],+ [20, 10]+ ]+ }}},{@@ -321,7 +389,13 @@},"paint": {"line-color": "rgba(88, 88, 88, 1)",- "line-width": {"base": 1.55, "stops": [[4, 0.25], [20, 30]]}+ "line-width": {+ "base": 1.55,+ "stops": [+ [4, 0.25],+ [20, 30]+ ]+ }}},{@@ -335,11 +409,17 @@["==", "brunnel", "tunnel"],["==", "class", "minor_road"]],- "layout": {"line-cap": "butt", "line-join": "miter"},+ "layout": { "line-cap": "butt", "line-join": "miter" },"paint": {"line-color": "#efefef","line-dasharray": [0.36, 0.18],- "line-width": {"base": 1.55, "stops": [[4, 0.25], [20, 30]]}+ "line-width": {+ "base": 1.55,+ "stops": [+ [4, 0.25],+ [20, 30]+ ]+ }}},{@@ -353,17 +433,23 @@["==", "brunnel", "tunnel"],["in", "class", "primary", "secondary", "tertiary", "trunk"]],- "layout": {"line-cap": "butt", "line-join": "miter"},+ "layout": { "line-cap": "butt", "line-join": "miter" },"paint": {"line-color": "#fff","line-dasharray": [0.28, 0.14],- "line-width": {"base": 1.4, "stops": [[6, 0.5], [20, 30]]}+ "line-width": {+ "base": 1.4,+ "stops": [+ [6, 0.5],+ [20, 30]+ ]+ }}},{"id": "aeroway-area","type": "fill",- "metadata": {"mapbox:group": "1444849345966.4436"},+ "metadata": { "mapbox:group": "1444849345966.4436" },"source": "openmaptiles","source-layer": "aeroway","minzoom": 4,@@ -372,16 +458,22 @@["==", "$type", "Polygon"],["in", "class", "runway", "taxiway"]],- "layout": {"visibility": "visible"},+ "layout": { "visibility": "visible" },"paint": {"fill-color": "rgba(80, 80, 80, 1)",- "fill-opacity": {"base": 1, "stops": [[13, 0], [14, 1]]}+ "fill-opacity": {+ "base": 1,+ "stops": [+ [13, 0],+ [14, 1]+ ]+ }}},{"id": "aeroway-taxiway","type": "line",- "metadata": {"mapbox:group": "1444849345966.4436"},+ "metadata": { "mapbox:group": "1444849345966.4436" },"source": "openmaptiles","source-layer": "aeroway","minzoom": 12,@@ -398,13 +490,19 @@"paint": {"line-color": "rgba(103, 89, 41, 1)","line-opacity": 1,- "line-width": {"base": 1.5, "stops": [[12, 1], [17, 10]]}+ "line-width": {+ "base": 1.5,+ "stops": [+ [12, 1],+ [17, 10]+ ]+ }}},{"id": "aeroway-runway","type": "line",- "metadata": {"mapbox:group": "1444849345966.4436"},+ "metadata": { "mapbox:group": "1444849345966.4436" },"source": "openmaptiles","source-layer": "aeroway","minzoom": 4,@@ -421,7 +519,13 @@"paint": {"line-color": "rgba(80, 80, 80, 1)","line-opacity": 1,- "line-width": {"base": 1.5, "stops": [[11, 4], [17, 50]]}+ "line-width": {+ "base": 1.5,+ "stops": [+ [11, 4],+ [17, 50]+ ]+ }}},{@@ -441,7 +545,13 @@},"paint": {"line-color": "rgba(88, 88, 88, 1)",- "line-width": {"base": 1.4, "stops": [[6, 0.5], [20, 30]]}+ "line-width": {+ "base": 1.4,+ "stops": [+ [6, 0.5],+ [20, 30]+ ]+ }}},{@@ -461,7 +571,13 @@},"paint": {"line-color": "rgba(88, 88, 88, 1)",- "line-width": {"base": 1.4, "stops": [[6, 0.5], [20, 20]]}+ "line-width": {+ "base": 1.4,+ "stops": [+ [6, 0.5],+ [20, 20]+ ]+ }}},{@@ -482,7 +598,13 @@"paint": {"line-color": "rgba(88, 88, 88, 1)","line-offset": 0,- "line-width": {"base": 1.4, "stops": [[8, 1], [16, 10]]}+ "line-width": {+ "base": 1.4,+ "stops": [+ [8, 1],+ [16, 10]+ ]+ }}},{@@ -495,10 +617,16 @@["==", "class", "transit"],["!=", "brunnel", "tunnel"]],- "layout": {"visibility": "visible"},+ "layout": { "visibility": "visible" },"paint": {"line-color": "hsl(34, 12%, 66%)",- "line-opacity": {"base": 1, "stops": [[11, 0], [16, 1]]}+ "line-opacity": {+ "base": 1,+ "stops": [+ [11, 0],+ [16, 1]+ ]+ }}},{@@ -507,10 +635,16 @@"source": "openmaptiles","source-layer": "transportation","filter": ["==", "class", "rail"],- "layout": {"visibility": "visible"},+ "layout": { "visibility": "visible" },"paint": {"line-color": "hsl(34, 12%, 66%)",- "line-opacity": {"base": 1, "stops": [[11, 0], [16, 1]]}+ "line-opacity": {+ "base": 1,+ "stops": [+ [11, 0],+ [16, 1]+ ]+ }}},{@@ -523,11 +657,23 @@["==", "$type", "LineString"],["==", "brunnel", "bridge"]],- "layout": {"line-cap": "butt", "line-join": "miter"},+ "layout": { "line-cap": "butt", "line-join": "miter" },"paint": {"line-color": "#bbbbbb",- "line-gap-width": {"base": 1.55, "stops": [[4, 0.25], [20, 30]]},- "line-width": {"base": 1.6, "stops": [[12, 0.5], [20, 10]]}+ "line-gap-width": {+ "base": 1.55,+ "stops": [+ [4, 0.25],+ [20, 30]+ ]+ },+ "line-width": {+ "base": 1.6,+ "stops": [+ [12, 0.5],+ [20, 10]+ ]+ }}},{@@ -540,10 +686,16 @@["==", "$type", "LineString"],["==", "brunnel", "bridge"]],- "layout": {"line-cap": "round", "line-join": "round"},+ "layout": { "line-cap": "round", "line-join": "round" },"paint": {"line-color": "hsl(205, 56%, 73%)",- "line-width": {"base": 1.55, "stops": [[4, 0.25], [20, 30]]}+ "line-width": {+ "base": 1.55,+ "stops": [+ [4, 0.25],+ [20, 30]+ ]+ }}},{@@ -557,11 +709,23 @@["==", "brunnel", "bridge"],["==", "class", "minor_road"]],- "layout": {"line-cap": "butt", "line-join": "miter"},+ "layout": { "line-cap": "butt", "line-join": "miter" },"paint": {"line-color": "#dedede",- "line-gap-width": {"base": 1.55, "stops": [[4, 0.25], [20, 30]]},- "line-width": {"base": 1.6, "stops": [[12, 0.5], [20, 10]]}+ "line-gap-width": {+ "base": 1.55,+ "stops": [+ [4, 0.25],+ [20, 30]+ ]+ },+ "line-width": {+ "base": 1.6,+ "stops": [+ [12, 0.5],+ [20, 10]+ ]+ }}},{@@ -582,8 +746,20 @@},"paint": {"line-color": "rgba(154, 154, 154, 1)",- "line-gap-width": {"base": 1.55, "stops": [[4, 0.25], [20, 30]]},- "line-width": {"base": 1.6, "stops": [[12, 0.5], [20, 10]]}+ "line-gap-width": {+ "base": 1.55,+ "stops": [+ [4, 0.25],+ [20, 30]+ ]+ },+ "line-width": {+ "base": 1.6,+ "stops": [+ [12, 0.5],+ [20, 10]+ ]+ }}},{@@ -604,7 +780,13 @@},"paint": {"line-color": "rgba(135, 135, 135, 1)",- "line-width": {"base": 1.55, "stops": [[4, 0.25], [20, 30]]}+ "line-width": {+ "base": 1.55,+ "stops": [+ [4, 0.25],+ [20, 30]+ ]+ }}},{@@ -625,7 +807,13 @@},"paint": {"line-color": "rgba(119, 119, 119, 1)",- "line-width": {"base": 1.4, "stops": [[6, 0.5], [20, 30]]}+ "line-width": {+ "base": 1.4,+ "stops": [+ [6, 0.5],+ [20, 30]+ ]+ }}},{@@ -634,8 +822,11 @@"source": "openmaptiles","source-layer": "boundary","filter": ["in", "admin_level", 4, 6, 8],- "layout": {"visibility": "visible"},- "paint": {"line-color": "hsla(0, 0%, 60%, 0.5)", "line-dasharray": [2, 1]}+ "layout": { "visibility": "visible" },+ "paint": {+ "line-color": "hsla(0, 0%, 60%, 0.5)",+ "line-dasharray": [2, 1]+ }},{"id": "admin_country_z0-4",@@ -657,7 +848,13 @@},"paint": {"line-color": "hsl(0, 0%, 60%)",- "line-width": {"base": 1.3, "stops": [[3, 0.5], [22, 15]]}+ "line-width": {+ "base": 1.3,+ "stops": [+ [3, 0.5],+ [22, 15]+ ]+ }}},{@@ -678,7 +875,13 @@},"paint": {"line-color": "hsl(0, 0%, 60%)",- "line-width": {"base": 1.3, "stops": [[3, 0.5], [22, 15]]}+ "line-width": {+ "base": 1.3,+ "stops": [+ [3, 0.5],+ [22, 15]+ ]+ }}},{@@ -742,7 +945,13 @@"text-font": ["Noto Sans Regular"],"text-letter-spacing": 0.1,"text-rotation-alignment": "map",- "text-size": {"base": 1.4, "stops": [[10, 8], [20, 14]]},+ "text-size": {+ "base": 1.4,+ "stops": [+ [10, 8],+ [20, 14]+ ]+ },"text-transform": "uppercase","visibility": "visible"},@@ -768,7 +977,12 @@"text-field": "{name:nonlatin}","text-font": ["Noto Sans Regular"],"text-max-width": 6,- "text-size": {"stops": [[6, 10], [12, 14]]},+ "text-size": {+ "stops": [+ [6, 10],+ [12, 14]+ ]+ },"visibility": "visible"},"paint": {@@ -794,7 +1008,12 @@"text-field": "{name:nonlatin}","text-font": ["Noto Sans Regular"],"text-max-width": 10,- "text-size": {"stops": [[3, 14], [8, 20]]},+ "text-size": {+ "stops": [+ [3, 14],+ [8, 20]+ ]+ },"symbol-sort-key": 10},"paint": {@@ -827,7 +1046,12 @@"text-field": "台湾省","text-font": ["Noto Sans Regular"],"text-max-width": 10,- "text-size": {"stops": [[3, 14], [8, 20]]},+ "text-size": {+ "stops": [+ [3, 14],+ [8, 20]+ ]+ },"symbol-sort-key": 10},"paint": {@@ -849,7 +1073,12 @@"text-field": "{name:nonlatin}","text-font": ["Noto Sans Regular"],"text-max-width": 10,- "text-size": {"stops": [[6, 12], [10, 16]]},+ "text-size": {+ "stops": [+ [6, 12],+ [10, 16]+ ]+ },"symbol-sort-key": 1},"paint": {@@ -875,7 +1104,12 @@"text-field": "{name:latin}","text-font": ["Noto Sans Regular"],"text-max-width": 10,- "text-size": {"stops": [[3, 12], [8, 22]]},+ "text-size": {+ "stops": [+ [3, 12],+ [8, 22]+ ]+ },"visibility": "visible"},"paint": {@@ -902,7 +1136,12 @@"text-field": "{name:latin}","text-font": ["Noto Sans Bold"],"text-max-width": 10,- "text-size": {"stops": [[3, 15], [8, 22]]},+ "text-size": {+ "stops": [+ [3, 15],+ [8, 22]+ ]+ },"visibility": "visible"},"paint": {@@ -915,4 +1154,4 @@],"id": "basic","owner": "ChronoFrame"-}\ No newline at end of file+}diff --git a/app/assets/mapStyles/chronoframe_light.json b/app/assets/mapStyles/chronoframe_light.jsonindex ede84d5a..378d4565 100644--- a/app/assets/mapStyles/chronoframe_light.json+++ b/app/assets/mapStyles/chronoframe_light.json@@ -11,7 +11,7 @@},"center": [116.4074, 39.9042],"zoom": 2,- "projection": {"type": "globe"},+ "projection": { "type": "globe" },"sources": {"openmaptiles": {"type": "vector",@@ -24,7 +24,7 @@{"id": "background","type": "background",- "paint": {"background-color": "hsl(47, 26%, 88%)"}+ "paint": { "background-color": "hsl(47, 26%, 88%)" }},{"id": "landuse-residential",@@ -36,8 +36,8 @@["==", "$type", "Polygon"],["in", "class", "residential", "suburb", "neighbourhood"]],- "layout": {"visibility": "visible"},- "paint": {"fill-color": "hsl(47, 13%, 86%)", "fill-opacity": 0.7}+ "layout": { "visibility": "visible" },+ "paint": { "fill-color": "hsl(47, 13%, 86%)", "fill-opacity": 0.7 }},{"id": "landcover_grass",@@ -45,7 +45,7 @@"source": "openmaptiles","source-layer": "landcover","filter": ["==", "class", "grass"],- "paint": {"fill-color": "hsl(82, 46%, 72%)", "fill-opacity": 0.45}+ "paint": { "fill-color": "hsl(82, 46%, 72%)", "fill-opacity": 0.45 }},{"id": "landcover_wood",@@ -55,7 +55,13 @@"filter": ["==", "class", "wood"],"paint": {"fill-color": "hsl(82, 46%, 72%)",- "fill-opacity": {"base": 1, "stops": [[8, 0.6], [22, 1]]}+ "fill-opacity": {+ "base": 1,+ "stops": [+ [8, 0.6],+ [22, 1]+ ]+ }}},{@@ -69,8 +75,8 @@["!=", "intermittent", 1],["!=", "brunnel", "tunnel"]],- "layout": {"visibility": "visible"},- "paint": {"fill-color": "hsl(205, 56%, 73%)"}+ "layout": { "visibility": "visible" },+ "paint": { "fill-color": "hsl(205, 56%, 73%)" }},{"id": "water_intermittent",@@ -78,8 +84,8 @@"source": "openmaptiles","source-layer": "water","filter": ["all", ["==", "$type", "Polygon"], ["==", "intermittent", 1]],- "layout": {"visibility": "visible"},- "paint": {"fill-color": "hsl(205, 56%, 73%)", "fill-opacity": 0.7}+ "layout": { "visibility": "visible" },+ "paint": { "fill-color": "hsl(205, 56%, 73%)", "fill-opacity": 0.7 }},{"id": "landcover-ice-shelf",@@ -87,8 +93,8 @@"source": "openmaptiles","source-layer": "landcover","filter": ["==", "subclass", "ice_shelf"],- "layout": {"visibility": "visible"},- "paint": {"fill-color": "hsl(47, 26%, 88%)", "fill-opacity": 0.8}+ "layout": { "visibility": "visible" },+ "paint": { "fill-color": "hsl(47, 26%, 88%)", "fill-opacity": 0.8 }},{"id": "landcover-glacier",@@ -96,10 +102,16 @@"source": "openmaptiles","source-layer": "landcover","filter": ["==", "subclass", "glacier"],- "layout": {"visibility": "visible"},+ "layout": { "visibility": "visible" },"paint": {"fill-color": "hsl(47, 22%, 94%)",- "fill-opacity": {"base": 1, "stops": [[0, 1], [8, 0.5]]}+ "fill-opacity": {+ "base": 1,+ "stops": [+ [0, 1],+ [8, 0.5]+ ]+ }}},{@@ -121,8 +133,8 @@"source": "openmaptiles","source-layer": "landuse","filter": ["==", "class", "agriculture"],- "layout": {"visibility": "visible"},- "paint": {"fill-color": "#eae0d0"}+ "layout": { "visibility": "visible" },+ "paint": { "fill-color": "#eae0d0" }},{"id": "landuse_overlay_national_park",@@ -132,7 +144,13 @@"filter": ["==", "class", "national_park"],"paint": {"fill-color": "#E1EBB0",- "fill-opacity": {"base": 1, "stops": [[5, 0], [9, 0.75]]}+ "fill-opacity": {+ "base": 1,+ "stops": [+ [5, 0],+ [9, 0.75]+ ]+ }}},{@@ -145,13 +163,24 @@["==", "$type", "LineString"],["==", "brunnel", "tunnel"]],- "layout": {"visibility": "visible"},+ "layout": { "visibility": "visible" },"paint": {"line-color": "hsl(205, 56%, 73%)","line-dasharray": [3, 3],- "line-gap-width": {"stops": [[12, 0], [20, 6]]},+ "line-gap-width": {+ "stops": [+ [12, 0],+ [20, 6]+ ]+ },"line-opacity": 1,- "line-width": {"base": 1.4, "stops": [[8, 1], [20, 2]]}+ "line-width": {+ "base": 1.4,+ "stops": [+ [8, 1],+ [20, 2]+ ]+ }}},{@@ -165,11 +194,17 @@["!in", "brunnel", "tunnel", "bridge"],["!=", "intermittent", 1]],- "layout": {"visibility": "visible"},+ "layout": { "visibility": "visible" },"paint": {"line-color": "hsl(205, 56%, 73%)","line-opacity": 1,- "line-width": {"base": 1.4, "stops": [[8, 1], [20, 8]]}+ "line-width": {+ "base": 1.4,+ "stops": [+ [8, 1],+ [20, 8]+ ]+ }}},{@@ -183,12 +218,18 @@["!in", "brunnel", "tunnel", "bridge"],["==", "intermittent", 1]],- "layout": {"visibility": "visible"},+ "layout": { "visibility": "visible" },"paint": {"line-color": "hsl(205, 56%, 73%)","line-dasharray": [2, 1],"line-opacity": 1,- "line-width": {"base": 1.4, "stops": [[8, 1], [20, 8]]}+ "line-width": {+ "base": 1.4,+ "stops": [+ [8, 1],+ [20, 8]+ ]+ }}},{@@ -203,11 +244,17 @@["==", "brunnel", "tunnel"],["==", "class", "transit"]],- "layout": {"line-cap": "butt", "line-join": "miter"},+ "layout": { "line-cap": "butt", "line-join": "miter" },"paint": {"line-color": "hsl(34, 12%, 66%)","line-dasharray": [3, 3],- "line-opacity": {"base": 1, "stops": [[11, 0], [16, 1]]}+ "line-opacity": {+ "base": 1,+ "stops": [+ [11, 0],+ [16, 1]+ ]+ }}},{@@ -218,7 +265,13 @@"paint": {"fill-antialias": true,"fill-color": "rgba(222, 211, 190, 1)",- "fill-opacity": {"base": 1, "stops": [[13, 0], [15, 1]]},+ "fill-opacity": {+ "base": 1,+ "stops": [+ [13, 0],+ [15, 1]+ ]+ },"fill-outline-color": {"stops": [[15, "rgba(212, 177, 146, 0)"],@@ -239,7 +292,7 @@"text-font": ["Noto Sans Regular"],"text-size": 10},- "paint": {"text-color": "rgba(212, 177, 146, 1)"}+ "paint": { "text-color": "rgba(212, 177, 146, 1)" }},{"id": "road_area_pier",@@ -248,8 +301,8 @@"source": "openmaptiles","source-layer": "transportation","filter": ["all", ["==", "$type", "Polygon"], ["==", "class", "pier"]],- "layout": {"visibility": "visible"},- "paint": {"fill-antialias": true, "fill-color": "hsl(47, 26%, 88%)"}+ "layout": { "visibility": "visible" },+ "paint": { "fill-antialias": true, "fill-color": "hsl(47, 26%, 88%)" }},{"id": "road_pier",@@ -258,10 +311,16 @@"source": "openmaptiles","source-layer": "transportation","filter": ["all", ["==", "$type", "LineString"], ["in", "class", "pier"]],- "layout": {"line-cap": "round", "line-join": "round"},+ "layout": { "line-cap": "round", "line-join": "round" },"paint": {"line-color": "hsl(47, 26%, 88%)",- "line-width": {"base": 1.2, "stops": [[15, 1], [17, 4]]}+ "line-width": {+ "base": 1.2,+ "stops": [+ [15, 1],+ [17, 4]+ ]+ }}},{@@ -275,7 +334,7 @@["in", "brunnel", "bridge"]],"layout": {},- "paint": {"fill-color": "hsl(47, 26%, 88%)", "fill-opacity": 0.5}+ "paint": { "fill-color": "hsl(47, 26%, 88%)", "fill-opacity": 0.5 }},{"id": "road_path",@@ -287,11 +346,17 @@["==", "$type", "LineString"],["in", "class", "path", "track"]],- "layout": {"line-cap": "square", "line-join": "bevel"},+ "layout": { "line-cap": "square", "line-join": "bevel" },"paint": {"line-color": "hsl(0, 0%, 97%)","line-dasharray": [1, 1],- "line-width": {"base": 1.55, "stops": [[4, 0.25], [20, 10]]}+ "line-width": {+ "base": 1.55,+ "stops": [+ [4, 0.25],+ [20, 10]+ ]+ }}},{@@ -305,10 +370,16 @@["==", "$type", "LineString"],["in", "class", "minor", "service"]],- "layout": {"line-cap": "round", "line-join": "round"},+ "layout": { "line-cap": "round", "line-join": "round" },"paint": {"line-color": "hsl(0, 0%, 97%)",- "line-width": {"base": 1.55, "stops": [[4, 0.25], [20, 30]]}+ "line-width": {+ "base": 1.55,+ "stops": [+ [4, 0.25],+ [20, 30]+ ]+ }}},{@@ -322,11 +393,17 @@["==", "brunnel", "tunnel"],["==", "class", "minor_road"]],- "layout": {"line-cap": "butt", "line-join": "miter"},+ "layout": { "line-cap": "butt", "line-join": "miter" },"paint": {"line-color": "#efefef","line-dasharray": [0.36, 0.18],- "line-width": {"base": 1.55, "stops": [[4, 0.25], [20, 30]]}+ "line-width": {+ "base": 1.55,+ "stops": [+ [4, 0.25],+ [20, 30]+ ]+ }}},{@@ -340,17 +417,23 @@["==", "brunnel", "tunnel"],["in", "class", "primary", "secondary", "tertiary", "trunk"]],- "layout": {"line-cap": "butt", "line-join": "miter"},+ "layout": { "line-cap": "butt", "line-join": "miter" },"paint": {"line-color": "#fff","line-dasharray": [0.28, 0.14],- "line-width": {"base": 1.4, "stops": [[6, 0.5], [20, 30]]}+ "line-width": {+ "base": 1.4,+ "stops": [+ [6, 0.5],+ [20, 30]+ ]+ }}},{"id": "aeroway-area","type": "fill",- "metadata": {"mapbox:group": "1444849345966.4436"},+ "metadata": { "mapbox:group": "1444849345966.4436" },"source": "openmaptiles","source-layer": "aeroway","minzoom": 4,@@ -359,16 +442,22 @@["==", "$type", "Polygon"],["in", "class", "runway", "taxiway"]],- "layout": {"visibility": "visible"},+ "layout": { "visibility": "visible" },"paint": {"fill-color": "rgba(255, 255, 255, 1)",- "fill-opacity": {"base": 1, "stops": [[13, 0], [14, 1]]}+ "fill-opacity": {+ "base": 1,+ "stops": [+ [13, 0],+ [14, 1]+ ]+ }}},{"id": "aeroway-taxiway","type": "line",- "metadata": {"mapbox:group": "1444849345966.4436"},+ "metadata": { "mapbox:group": "1444849345966.4436" },"source": "openmaptiles","source-layer": "aeroway","minzoom": 12,@@ -385,13 +474,19 @@"paint": {"line-color": "rgba(255, 255, 255, 1)","line-opacity": 1,- "line-width": {"base": 1.5, "stops": [[12, 1], [17, 10]]}+ "line-width": {+ "base": 1.5,+ "stops": [+ [12, 1],+ [17, 10]+ ]+ }}},{"id": "aeroway-runway","type": "line",- "metadata": {"mapbox:group": "1444849345966.4436"},+ "metadata": { "mapbox:group": "1444849345966.4436" },"source": "openmaptiles","source-layer": "aeroway","minzoom": 4,@@ -408,7 +503,13 @@"paint": {"line-color": "rgba(255, 255, 255, 1)","line-opacity": 1,- "line-width": {"base": 1.5, "stops": [[11, 4], [17, 50]]}+ "line-width": {+ "base": 1.5,+ "stops": [+ [11, 4],+ [17, 50]+ ]+ }}},{@@ -421,10 +522,16 @@["==", "$type", "LineString"],["in", "class", "trunk", "primary"]],- "layout": {"line-cap": "round", "line-join": "round"},+ "layout": { "line-cap": "round", "line-join": "round" },"paint": {"line-color": "#fff",- "line-width": {"base": 1.4, "stops": [[6, 0.5], [20, 30]]}+ "line-width": {+ "base": 1.4,+ "stops": [+ [6, 0.5],+ [20, 30]+ ]+ }}},{@@ -437,10 +544,16 @@["==", "$type", "LineString"],["in", "class", "secondary", "tertiary"]],- "layout": {"line-cap": "round", "line-join": "round"},+ "layout": { "line-cap": "round", "line-join": "round" },"paint": {"line-color": "#fff",- "line-width": {"base": 1.4, "stops": [[6, 0.5], [20, 20]]}+ "line-width": {+ "base": 1.4,+ "stops": [+ [6, 0.5],+ [20, 20]+ ]+ }}},{@@ -453,11 +566,17 @@["==", "$type", "LineString"],["==", "class", "motorway"]],- "layout": {"line-cap": "round", "line-join": "round"},+ "layout": { "line-cap": "round", "line-join": "round" },"paint": {"line-color": "hsl(0, 0%, 100%)","line-offset": 0,- "line-width": {"base": 1.4, "stops": [[8, 1], [16, 10]]}+ "line-width": {+ "base": 1.4,+ "stops": [+ [8, 1],+ [16, 10]+ ]+ }}},{@@ -470,10 +589,16 @@["==", "class", "transit"],["!=", "brunnel", "tunnel"]],- "layout": {"visibility": "visible"},+ "layout": { "visibility": "visible" },"paint": {"line-color": "hsl(34, 12%, 66%)",- "line-opacity": {"base": 1, "stops": [[11, 0], [16, 1]]}+ "line-opacity": {+ "base": 1,+ "stops": [+ [11, 0],+ [16, 1]+ ]+ }}},{@@ -482,10 +607,16 @@"source": "openmaptiles","source-layer": "transportation","filter": ["==", "class", "rail"],- "layout": {"visibility": "visible"},+ "layout": { "visibility": "visible" },"paint": {"line-color": "hsl(34, 12%, 66%)",- "line-opacity": {"base": 1, "stops": [[11, 0], [16, 1]]}+ "line-opacity": {+ "base": 1,+ "stops": [+ [11, 0],+ [16, 1]+ ]+ }}},{@@ -498,11 +629,23 @@["==", "$type", "LineString"],["==", "brunnel", "bridge"]],- "layout": {"line-cap": "butt", "line-join": "miter"},+ "layout": { "line-cap": "butt", "line-join": "miter" },"paint": {"line-color": "#bbbbbb",- "line-gap-width": {"base": 1.55, "stops": [[4, 0.25], [20, 30]]},- "line-width": {"base": 1.6, "stops": [[12, 0.5], [20, 10]]}+ "line-gap-width": {+ "base": 1.55,+ "stops": [+ [4, 0.25],+ [20, 30]+ ]+ },+ "line-width": {+ "base": 1.6,+ "stops": [+ [12, 0.5],+ [20, 10]+ ]+ }}},{@@ -515,10 +658,16 @@["==", "$type", "LineString"],["==", "brunnel", "bridge"]],- "layout": {"line-cap": "round", "line-join": "round"},+ "layout": { "line-cap": "round", "line-join": "round" },"paint": {"line-color": "hsl(205, 56%, 73%)",- "line-width": {"base": 1.55, "stops": [[4, 0.25], [20, 30]]}+ "line-width": {+ "base": 1.55,+ "stops": [+ [4, 0.25],+ [20, 30]+ ]+ }}},{@@ -532,11 +681,23 @@["==", "brunnel", "bridge"],["==", "class", "minor_road"]],- "layout": {"line-cap": "butt", "line-join": "miter"},+ "layout": { "line-cap": "butt", "line-join": "miter" },"paint": {"line-color": "#dedede",- "line-gap-width": {"base": 1.55, "stops": [[4, 0.25], [20, 30]]},- "line-width": {"base": 1.6, "stops": [[12, 0.5], [20, 10]]}+ "line-gap-width": {+ "base": 1.55,+ "stops": [+ [4, 0.25],+ [20, 30]+ ]+ },+ "line-width": {+ "base": 1.6,+ "stops": [+ [12, 0.5],+ [20, 10]+ ]+ }}},{@@ -550,11 +711,23 @@["==", "brunnel", "bridge"],["in", "class", "primary", "secondary", "tertiary", "trunk"]],- "layout": {"line-cap": "butt", "line-join": "miter"},+ "layout": { "line-cap": "butt", "line-join": "miter" },"paint": {"line-color": "#dedede",- "line-gap-width": {"base": 1.55, "stops": [[4, 0.25], [20, 30]]},- "line-width": {"base": 1.6, "stops": [[12, 0.5], [20, 10]]}+ "line-gap-width": {+ "base": 1.55,+ "stops": [+ [4, 0.25],+ [20, 30]+ ]+ },+ "line-width": {+ "base": 1.6,+ "stops": [+ [12, 0.5],+ [20, 10]+ ]+ }}},{@@ -568,10 +741,16 @@["==", "brunnel", "bridge"],["==", "class", "minor_road"]],- "layout": {"line-cap": "round", "line-join": "round"},+ "layout": { "line-cap": "round", "line-join": "round" },"paint": {"line-color": "#efefef",- "line-width": {"base": 1.55, "stops": [[4, 0.25], [20, 30]]}+ "line-width": {+ "base": 1.55,+ "stops": [+ [4, 0.25],+ [20, 30]+ ]+ }}},{@@ -585,10 +764,16 @@["==", "brunnel", "bridge"],["in", "class", "primary", "secondary", "tertiary", "trunk"]],- "layout": {"line-cap": "round", "line-join": "round"},+ "layout": { "line-cap": "round", "line-join": "round" },"paint": {"line-color": "#fff",- "line-width": {"base": 1.4, "stops": [[6, 0.5], [20, 30]]}+ "line-width": {+ "base": 1.4,+ "stops": [+ [6, 0.5],+ [20, 30]+ ]+ }}},{@@ -597,8 +782,11 @@"source": "openmaptiles","source-layer": "boundary","filter": ["in", "admin_level", 4, 6, 8],- "layout": {"visibility": "visible"},- "paint": {"line-color": "hsla(0, 0%, 60%, 0.5)", "line-dasharray": [2, 1]}+ "layout": { "visibility": "visible" },+ "paint": {+ "line-color": "hsla(0, 0%, 60%, 0.5)",+ "line-dasharray": [2, 1]+ }},{"id": "admin_country_z0-4",@@ -620,7 +808,13 @@},"paint": {"line-color": "hsl(0, 0%, 60%)",- "line-width": {"base": 1.3, "stops": [[3, 0.5], [22, 15]]}+ "line-width": {+ "base": 1.3,+ "stops": [+ [3, 0.5],+ [22, 15]+ ]+ }}},{@@ -641,7 +835,13 @@},"paint": {"line-color": "hsl(0, 0%, 60%)",- "line-width": {"base": 1.3, "stops": [[3, 0.5], [22, 15]]}+ "line-width": {+ "base": 1.3,+ "stops": [+ [3, 0.5],+ [22, 15]+ ]+ }}},{@@ -705,7 +905,13 @@"text-font": ["Noto Sans Regular"],"text-letter-spacing": 0.1,"text-rotation-alignment": "map",- "text-size": {"base": 1.4, "stops": [[10, 8], [20, 14]]},+ "text-size": {+ "base": 1.4,+ "stops": [+ [10, 8],+ [20, 14]+ ]+ },"text-transform": "uppercase","visibility": "visible"},@@ -731,7 +937,12 @@"text-field": "{name:nonlatin}","text-font": ["Noto Sans Regular"],"text-max-width": 6,- "text-size": {"stops": [[6, 10], [12, 14]]},+ "text-size": {+ "stops": [+ [6, 10],+ [12, 14]+ ]+ },"visibility": "visible"},"paint": {@@ -757,7 +968,12 @@"text-field": "{name:nonlatin}","text-font": ["Noto Sans Regular"],"text-max-width": 10,- "text-size": {"stops": [[3, 14], [8, 20]]},+ "text-size": {+ "stops": [+ [3, 14],+ [8, 20]+ ]+ },"symbol-sort-key": 10},"paint": {@@ -790,7 +1006,12 @@"text-field": "台湾省","text-font": ["Noto Sans Regular"],"text-max-width": 10,- "text-size": {"stops": [[3, 14], [8, 20]]},+ "text-size": {+ "stops": [+ [3, 14],+ [8, 20]+ ]+ },"symbol-sort-key": 10},"paint": {@@ -812,7 +1033,12 @@"text-field": "{name:nonlatin}","text-font": ["Noto Sans Regular"],"text-max-width": 10,- "text-size": {"stops": [[6, 12], [10, 16]]},+ "text-size": {+ "stops": [+ [6, 12],+ [10, 16]+ ]+ },"symbol-sort-key": 1},"paint": {@@ -838,7 +1064,12 @@"text-field": "{name:latin}","text-font": ["Noto Sans Regular"],"text-max-width": 10,- "text-size": {"stops": [[3, 12], [8, 22]]},+ "text-size": {+ "stops": [+ [3, 12],+ [8, 22]+ ]+ },"visibility": "visible"},"paint": {@@ -865,7 +1096,12 @@"text-field": "{name:latin}","text-font": ["Noto Sans Bold"],"text-max-width": 10,- "text-size": {"stops": [[3, 12], [8, 22]]},+ "text-size": {+ "stops": [+ [3, 12],+ [8, 22]+ ]+ },"visibility": "visible"},"paint": {@@ -878,4 +1114,4 @@],"id": "basic","owner": "ChronoFrame"-}\ No newline at end of file+}diff --git a/app/components/Histogram.vue b/app/components/Histogram.vueindex 4591c881..acd18484 100644--- a/app/components/Histogram.vue+++ b/app/components/Histogram.vue@@ -41,7 +41,7 @@ watchEffect(() => {const img = new Image()currentImage = imgimg.crossOrigin = 'anonymous'-+const url = new URL(props.thumbnailUrl, window.location.origin)url.searchParams.set('_cors', Date.now().toString())img.src = url.toString()diff --git a/app/components/Wizard/Button.vue b/app/components/Wizard/Button.vueindex c39d80d3..1d01c326 100644--- a/app/components/Wizard/Button.vue+++ b/app/components/Wizard/Button.vue@@ -1,6 +1,6 @@<script setup lang="ts">defineOptions({- inheritAttrs: false+ inheritAttrs: false,})</script>@@ -11,14 +11,22 @@ defineOptions({base: 'transition-all duration-300 font-medium',rounded: 'rounded-xl',variant: {- solid: 'bg-linear-to-r from-primary-600 to-primary-500 hover:from-primary-500 hover:to-primary-400 text-white shadow-lg shadow-primary-500/20 hover:shadow-primary-500/40 border border-white/10',- outline: 'bg-white/5 hover:bg-white/10 text-white border border-white/10 hover:border-white/20',- ghost: 'text-neutral-400 hover:text-white hover:bg-white/5'- }+ solid:+ 'bg-linear-to-r from-primary-600 to-primary-500 hover:from-primary-500 hover:to-primary-400 text-white shadow-lg shadow-primary-500/20 hover:shadow-primary-500/40 border border-white/10',+ outline:+ 'bg-white/5 hover:bg-white/10 text-white border border-white/10 hover:border-white/20',+ ghost: 'text-neutral-400 hover:text-white hover:bg-white/5',+ },}">- <template v-for="(_, name) in $slots" #[name]="slotData">- <slot :name="name" v-bind="slotData" />+ <template+ v-for="(_, name) in $slots"+ #[name]="slotData"+ >+ <slot+ :name="name"+ v-bind="slotData"+ /></template></UButton></template>diff --git a/app/components/Wizard/Checkbox.vue b/app/components/Wizard/Checkbox.vueindex 34706744..9fda2920 100644--- a/app/components/Wizard/Checkbox.vue+++ b/app/components/Wizard/Checkbox.vue@@ -1,6 +1,6 @@<script setup lang="ts">defineOptions({- inheritAttrs: false+ inheritAttrs: false,})const props = defineProps<{@@ -11,7 +11,7 @@ const emit = defineEmits(['update:modelValue'])const value = computed({get: () => props.modelValue,- set: (val) => emit('update:modelValue', val)+ set: (val) => emit('update:modelValue', val),})</script>@@ -21,11 +21,17 @@ const value = computed({v-model="value":ui="{base: 'border-white/10 bg-white/5 data-[state=checked]:bg-primary-500 data-[state=checked]:border-primary-500 text-white',- label: 'text-neutral-300 font-medium'+ label: 'text-neutral-300 font-medium',}">- <template v-for="(_, name) in $slots" #[name]="slotData">- <slot :name="name" v-bind="slotData" />+ <template+ v-for="(_, name) in $slots"+ #[name]="slotData"+ >+ <slot+ :name="name"+ v-bind="slotData"+ /></template></UCheckbox></template>diff --git a/app/components/Wizard/FormField.vue b/app/components/Wizard/FormField.vueindex b0c9c367..4790aaa1 100644--- a/app/components/Wizard/FormField.vue+++ b/app/components/Wizard/FormField.vue@@ -1,6 +1,6 @@<script setup lang="ts">defineOptions({- inheritAttrs: false+ inheritAttrs: false,})</script>@@ -11,11 +11,17 @@ defineOptions({label: 'text-neutral-300 font-medium mb-1.5',description: 'text-neutral-500 text-xs mt-1',error: 'text-red-400 text-xs mt-1',- hint: 'text-neutral-500 text-xs'+ hint: 'text-neutral-500 text-xs',}">- <template v-for="(_, name) in $slots" #[name]="slotData">- <slot :name="name" v-bind="slotData" />+ <template+ v-for="(_, name) in $slots"+ #[name]="slotData"+ >+ <slot+ :name="name"+ v-bind="slotData"+ /></template></UFormField></template>diff --git a/app/components/Wizard/Input.vue b/app/components/Wizard/Input.vueindex 80564881..32d3d6d0 100644--- a/app/components/Wizard/Input.vue+++ b/app/components/Wizard/Input.vue@@ -1,6 +1,6 @@<script setup lang="ts">defineOptions({- inheritAttrs: false+ inheritAttrs: false,})const props = defineProps<{@@ -11,7 +11,7 @@ const emit = defineEmits(['update:modelValue'])const value = computed({get: () => props.modelValue,- set: (val) => emit('update:modelValue', val)+ set: (val) => emit('update:modelValue', val),})</script>@@ -24,13 +24,19 @@ const value = computed({base: 'w-full bg-white/5 border border-white/10 text-white placeholder:text-neutral-500 focus:ring-2 focus:ring-primary-500/20 focus:border-primary-500 transition-all duration-200 rounded-lg',padding: { sm: 'px-3 py-2.5', md: 'px-4 py-3', lg: 'px-5 py-4' },variant: {- outline: 'shadow-sm'- }+ outline: 'shadow-sm',+ },}"variant="none">- <template v-for="(_, name) in $slots" #[name]="slotData">- <slot :name="name" v-bind="slotData" />+ <template+ v-for="(_, name) in $slots"+ #[name]="slotData"+ >+ <slot+ :name="name"+ v-bind="slotData"+ /></template></UInput></template>diff --git a/app/components/Wizard/ProviderSelector.vue b/app/components/Wizard/ProviderSelector.vueindex d5b17172..02978038 100644--- a/app/components/Wizard/ProviderSelector.vue+++ b/app/components/Wizard/ProviderSelector.vue@@ -27,25 +27,45 @@ defineEmits<{:class="[modelValue === option.value? 'bg-primary-500/10 border-primary-500 ring-1 ring-primary-500/50'- : 'bg-white/5 border-white/10 hover:bg-white/10 hover:border-white/20'+ : 'bg-white/5 border-white/10 hover:bg-white/10 hover:border-white/20',]"@click="$emit('update:modelValue', option.value)"><div class="flex items-start justify-between mb-3">- <div+ <divv-if="option.icon"class="size-10 flex items-center justify-center rounded-lg transition-colors"- :class="modelValue === option.value ? 'bg-primary-500 text-white' : 'bg-white/10 text-neutral-400 group-hover:text-white'"+ :class="+ modelValue === option.value+ ? 'bg-primary-500 text-white'+ : 'bg-white/10 text-neutral-400 group-hover:text-white'+ ">- <UIcon :name="option.icon" class="size-6" />+ <UIcon+ :name="option.icon"+ class="size-6"+ /></div>- <div v-if="modelValue === option.value" class="text-primary-400">- <UIcon name="tabler:circle-check" class="size-6" />+ <div+ v-if="modelValue === option.value"+ class="text-primary-400"+ >+ <UIcon+ name="tabler:circle-check"+ class="size-6"+ /></div></div>-- <h3 class="font-medium text-white mb-1">{{ $t(option.label) || option.label }}</h3>- <p v-if="option.description" class="text-xs text-neutral-400 leading-relaxed">{{ $t(option.description) || option.description }}</p>++ <h3 class="font-medium text-white mb-1">+ {{ $t(option.label) || option.label }}+ </h3>+ <p+ v-if="option.description"+ class="text-xs text-neutral-400 leading-relaxed"+ >+ {{ $t(option.description) || option.description }}+ </p></div></div></template>diff --git a/app/components/Wizard/Step.vue b/app/components/Wizard/Step.vueindex 9f5f03b4..92746e06 100644--- a/app/components/Wizard/Step.vue+++ b/app/components/Wizard/Step.vue@@ -21,7 +21,10 @@ defineProps<{<h1 class="text-3xl font-bold tracking-tight text-white">{{ title }}</h1>- <p v-if="description" class="text-lg text-neutral-400">+ <p+ v-if="description"+ class="text-lg text-neutral-400"+ >{{ description }}</p></div>@@ -35,7 +38,10 @@ defineProps<{</div><!-- Footer -->- <div v-if="$slots.actions" class="shrink-0 px-6 lg:px-12 py-6 border-t border-white/10">+ <div+ v-if="$slots.actions"+ class="shrink-0 px-6 lg:px-12 py-6 border-t border-white/10"+ ><div class="max-w-2xl mx-auto flex items-center justify-end gap-4"><slot name="actions" /></div>diff --git a/app/components/icon/TablerStar.vue b/app/components/icon/TablerStar.vueindex c4a44aa0..91990dde 100644--- a/app/components/icon/TablerStar.vue+++ b/app/components/icon/TablerStar.vue@@ -1,10 +1,24 @@-<template>- <svg xmlns="http://www.w3.org/2000/svg" width="1em" height="1em" viewBox="0 0 24 24"><!-- Icon from Tabler Icons by Paweł Kuna - https://github.com/tabler/tabler-icons/blob/master/LICENSE --><path fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="m12 17.75l-6.172 3.245l1.179-6.873l-5-4.867l6.9-1l3.086-6.253l3.086 6.253l6.9 1l-5 4.867l1.179 6.873z" /></svg>+ <svg+ xmlns="http://www.w3.org/2000/svg"+ width="1em"+ height="1em"+ viewBox="0 0 24 24"+ >+ <!-- Icon from Tabler Icons by Paweł Kuna - https://github.com/tabler/tabler-icons/blob/master/LICENSE -->+ <path+ fill="none"+ stroke="currentColor"+ stroke-linecap="round"+ stroke-linejoin="round"+ stroke-width="2"+ d="m12 17.75l-6.172 3.245l1.179-6.873l-5-4.867l6.9-1l3.086-6.253l3.086 6.253l6.9 1l-5 4.867l1.179 6.873z"+ />+ </svg></template><script>export default {- name: 'TablerStar'+ name: 'TablerStar',}-</script>\ No newline at end of file+</script>diff --git a/app/components/icon/TablerStarFilled.vue b/app/components/icon/TablerStarFilled.vueindex 959bb018..bd487aa8 100644--- a/app/components/icon/TablerStarFilled.vue+++ b/app/components/icon/TablerStarFilled.vue@@ -1,10 +1,20 @@-<template>- <svg xmlns="http://www.w3.org/2000/svg" width="1em" height="1em" viewBox="0 0 24 24"><!-- Icon from Tabler Icons by Paweł Kuna - https://github.com/tabler/tabler-icons/blob/master/LICENSE --><path fill="currentColor" d="m8.243 7.34l-6.38.925l-.113.023a1 1 0 0 0-.44 1.684l4.622 4.499l-1.09 6.355l-.013.11a1 1 0 0 0 1.464.944l5.706-3l5.693 3l.1.046a1 1 0 0 0 1.352-1.1l-1.091-6.355l4.624-4.5l.078-.085a1 1 0 0 0-.633-1.62l-6.38-.926l-2.852-5.78a1 1 0 0 0-1.794 0z" /></svg>+ <svg+ xmlns="http://www.w3.org/2000/svg"+ width="1em"+ height="1em"+ viewBox="0 0 24 24"+ >+ <!-- Icon from Tabler Icons by Paweł Kuna - https://github.com/tabler/tabler-icons/blob/master/LICENSE -->+ <path+ fill="currentColor"+ d="m8.243 7.34l-6.38.925l-.113.023a1 1 0 0 0-.44 1.684l4.622 4.499l-1.09 6.355l-.013.11a1 1 0 0 0 1.464.944l5.706-3l5.693 3l.1.046a1 1 0 0 0 1.352-1.1l-1.091-6.355l4.624-4.5l.078-.085a1 1 0 0 0-.633-1.62l-6.38-.926l-2.852-5.78a1 1 0 0 0-1.794 0z"+ />+ </svg></template><script>export default {- name: 'TablerStarFilled'+ name: 'TablerStarFilled',}-</script>\ No newline at end of file+</script>diff --git a/app/components/icon/TablerStarHalfFilled.vue b/app/components/icon/TablerStarHalfFilled.vueindex 08d2eefb..6e41a6bd 100644--- a/app/components/icon/TablerStarHalfFilled.vue+++ b/app/components/icon/TablerStarHalfFilled.vue@@ -1,10 +1,20 @@-<template>- <svg xmlns="http://www.w3.org/2000/svg" width="1em" height="1em" viewBox="0 0 24 24"><!-- Icon from Tabler Icons by Paweł Kuna - https://github.com/tabler/tabler-icons/blob/master/LICENSE --><path fill="currentColor" d="M12 1a1 1 0 0 1 .823.443l.067.116l2.852 5.781l6.38.925c.741.108 1.08.94.703 1.526l-.07.095l-.078.086l-4.624 4.499l1.09 6.355a1 1 0 0 1-1.249 1.135l-.101-.035l-.101-.046l-5.693-3l-5.706 3q-.158.082-.32.106l-.106.01a1.003 1.003 0 0 1-1.038-1.06l.013-.11l1.09-6.355l-4.623-4.5a1 1 0 0 1 .328-1.647l.113-.036l.114-.023l6.379-.925l2.853-5.78A.97.97 0 0 1 12 1m0 3.274V16.75a1 1 0 0 1 .239.029l.115.036l.112.05l4.363 2.299l-.836-4.873a1 1 0 0 1 .136-.696l.07-.099l.082-.09l3.546-3.453l-4.891-.708a1 1 0 0 1-.62-.344l-.073-.097l-.06-.106z" /></svg>+ <svg+ xmlns="http://www.w3.org/2000/svg"+ width="1em"+ height="1em"+ viewBox="0 0 24 24"+ >+ <!-- Icon from Tabler Icons by Paweł Kuna - https://github.com/tabler/tabler-icons/blob/master/LICENSE -->+ <path+ fill="currentColor"+ d="M12 1a1 1 0 0 1 .823.443l.067.116l2.852 5.781l6.38.925c.741.108 1.08.94.703 1.526l-.07.095l-.078.086l-4.624 4.499l1.09 6.355a1 1 0 0 1-1.249 1.135l-.101-.035l-.101-.046l-5.693-3l-5.706 3q-.158.082-.32.106l-.106.01a1.003 1.003 0 0 1-1.038-1.06l.013-.11l1.09-6.355l-4.623-4.5a1 1 0 0 1 .328-1.647l.113-.036l.114-.023l6.379-.925l2.853-5.78A.97.97 0 0 1 12 1m0 3.274V16.75a1 1 0 0 1 .239.029l.115.036l.112.05l4.363 2.299l-.836-4.873a1 1 0 0 1 .136-.696l.07-.099l.082-.09l3.546-3.453l-4.891-.708a1 1 0 0 1-.62-.344l-.073-.097l-.06-.106z"+ />+ </svg></template><script>export default {- name: 'TablerStarHalfFilled'+ name: 'TablerStarHalfFilled',}-</script>\ No newline at end of file+</script>diff --git a/app/components/map/ClusterPin.vue b/app/components/map/ClusterPin.vueindex 5144703d..8e4c64c7 100644--- a/app/components/map/ClusterPin.vue+++ b/app/components/map/ClusterPin.vue@@ -136,7 +136,9 @@ const sizeDelta = computed(() => {<!-- Cluster preview --><div class="relative overflow-hidden p-3 space-y-3"><div class="flex items-center justify-between">- <h3 class="text-sm font-semibold text-neutral-900 dark:text-white">+ <h3+ class="text-sm font-semibold text-neutral-900 dark:text-white"+ >{{$t('map.cluster.nearbyPhotos', [clusteredPhotos.length])}}@@ -185,7 +187,10 @@ const sizeDelta = computed(() => {<divclass="rounded-full bg-white/80 dark:bg-black/50 p-2 backdrop-blur-sm flex justify-center items-center">- <Icon name="tabler:external-link" class="text-neutral-700 dark:text-white" />+ <Icon+ name="tabler:external-link"+ class="text-neutral-700 dark:text-white"+ /></div></div><!-- Show +N overlay for the last image if there are more -->@@ -196,7 +201,9 @@ const sizeDelta = computed(() => {"class="absolute inset-0 bg-white/80 dark:bg-black/60 flex items-center justify-center cursor-pointer pointer-events-none">- <span class="text-neutral-800 dark:text-white text-lg font-bold">+ <span+ class="text-neutral-800 dark:text-white text-lg font-bold"+ >+{{ clusteredPhotos.length - clusterCount }}</span></div>diff --git a/app/components/map/LocationPicker.vue b/app/components/map/LocationPicker.vueindex fd95f6be..35943ce0 100644--- a/app/components/map/LocationPicker.vue+++ b/app/components/map/LocationPicker.vue@@ -26,7 +26,9 @@ const { locale } = useI18n()let clickHandler: ((event: any) => void) | null = null-const syncFromProps = (value: { latitude: number; longitude: number } | null) => {+const syncFromProps = (+ value: { latitude: number; longitude: number } | null,+) => {if (value) {markerCoordinates.value = [value.longitude, value.latitude]if (mapInstance.value) {@@ -71,9 +73,9 @@ const handleMapClick = (event: any) => {return}const latitude =- typeof point.lat === 'number' ? point.lat : point.latitude ?? point[1]+ typeof point.lat === 'number' ? point.lat : (point.latitude ?? point[1])const longitude =- typeof point.lng === 'number' ? point.lng : point.longitude ?? point[0]+ typeof point.lng === 'number' ? point.lng : (point.longitude ?? point[0])if (typeof latitude !== 'number' || typeof longitude !== 'number') {return}@@ -107,12 +109,16 @@ onBeforeUnmount(() => {</script><template>- <div :class="['relative w-full h-64 rounded-xl overflow-hidden', $props.class]">+ <div+ :class="['relative w-full h-64 rounded-xl overflow-hidden', $props.class]"+ ><MapProviderclass="w-full h-full":map-id="'photo-location-picker'":center="markerCoordinates ?? undefined"- :zoom="markerCoordinates ? Math.max($props.zoom ?? 4, 4) : $props.zoom ?? 2"+ :zoom="+ markerCoordinates ? Math.max($props.zoom ?? 4, 4) : ($props.zoom ?? 2)+ ":interactive="true":language="locale"@load="onMapLoad"@@ -123,8 +129,12 @@ onBeforeUnmount(() => {><template #marker><div class="relative">- <div class="absolute inset-0 animate-ping rounded-full bg-primary/40" />- <div class="relative size-4 rounded-full bg-primary border-2 border-white shadow" />+ <div+ class="absolute inset-0 animate-ping rounded-full bg-primary/40"+ />+ <div+ class="relative size-4 rounded-full bg-primary border-2 border-white shadow"+ /></div></template></MapProviderMarker>diff --git a/app/components/map/Provider.vue b/app/components/map/Provider.vueindex cc8ab433..a2152eed 100644--- a/app/components/map/Provider.vue+++ b/app/components/map/Provider.vue@@ -42,9 +42,7 @@ const mapConfig = computed(() => {const provider = computed(() => mapConfig.value.provider || 'maplibre')const mapStyle = computed(() => {if (provider.value === 'mapbox') {- return (- mapConfig.value['mapbox.style'] || `mapbox://styles/mapbox/standard`- )+ return mapConfig.value['mapbox.style'] || `mapbox://styles/mapbox/standard`} else {const styleConfig =colorMode.value === 'dark' ? ChronoFrameDarkStyle : ChronoFrameLightStylediff --git a/app/components/masonry/item/Header.vue b/app/components/masonry/item/Header.vueindex 3f9fce3c..93ab54db 100644--- a/app/components/masonry/item/Header.vue+++ b/app/components/masonry/item/Header.vue@@ -72,7 +72,10 @@ const isRepoLinkHovering = ref(false)<Icon name="tabler:star-filled" /></div><img- :src="getSetting('app:avatarUrl') as string || '/web-app-manifest-192x192.png'"+ :src="+ (getSetting('app:avatarUrl') as string) ||+ '/web-app-manifest-192x192.png'+ "class="size-16 rounded-full object-cover":class="!loggedIn && 'cursor-pointer'"alt="Author's avatar"diff --git a/app/components/photo/GalleryThumbnail.vue b/app/components/photo/GalleryThumbnail.vueindex 6aca902a..f5be38a6 100644--- a/app/components/photo/GalleryThumbnail.vue+++ b/app/components/photo/GalleryThumbnail.vue@@ -36,9 +36,7 @@ const currentGapSize = computed(() =>)const currentPaddingSize = computed(() =>- isMobile.value- ? THUMBNAIL_CONFIG.padding.sm- : THUMBNAIL_CONFIG.padding.lg,+ isMobile.value ? THUMBNAIL_CONFIG.padding.sm : THUMBNAIL_CONFIG.padding.lg,)// 处理缩略图列表diff --git a/app/components/photo/KVRenderer.vue b/app/components/photo/KVRenderer.vueindex fcae8cd9..e165d7cc 100644--- a/app/components/photo/KVRenderer.vue+++ b/app/components/photo/KVRenderer.vue@@ -45,7 +45,9 @@ defineProps<{class="flex-1 min-w-0 flex gap-6 items-start justify-between font-medium"><div class="text-white/80 text-nowrap">{{ item!.label }}</div>- <div class="text-white text-wrap tracking-tight wrap-anywhere text-end whitespace-pre-line">+ <div+ class="text-white text-wrap tracking-tight wrap-anywhere text-end whitespace-pre-line"+ >{{ item!.value }}</div></div>diff --git a/app/components/photo/LoadingIndicator.vue b/app/components/photo/LoadingIndicator.vueindex c5ea1f22..c8fac887 100644--- a/app/components/photo/LoadingIndicator.vue+++ b/app/components/photo/LoadingIndicator.vue@@ -99,21 +99,28 @@ const loadingVariants = {<div class="flex flex-col min-w-0 gap-0.5"><template v-if="loadingState.isError"><p class="text-xs font-medium text-red-400">- {{ loadingState.errorMessage || $t('viewer.photoload.loadError')}}+ {{+ loadingState.errorMessage || $t('viewer.photoload.loadError')+ }}+ </p>+ <p class="text-xs text-white/70">+ {{ $t('viewer.photoload.loading') }}</p>- <p class="text-xs text-white/70">{{ $t('viewer.photoload.loading') }}</p></template><template v-else-if="loadingState.isConverting"><p class="text-xs font-medium text-white tabular-nums">- {{ loadingState.message || $t('viewer.photoload.converting')}}+ {{ loadingState.message || $t('viewer.photoload.converting') }}</p></template><template v-else-if="loadingState.isWebGLLoading"><div class="flex items-center gap-2"><p class="text-xs font-medium text-white">- {{ loadingState.webglMessage || $t('viewer.photoload.loadingWebGL') }}+ {{+ loadingState.webglMessage ||+ $t('viewer.photoload.loadingWebGL')+ }}</p><spanv-if="loadingState.webglQuality !== 'unknown'"@@ -132,14 +139,18 @@ const loadingVariants = {{{ loadingState.webglQuality }}</span></div>- <p class="text-xs text-white/70">{{ $t('viewer.photoload.loadingTexture') }}</p>+ <p class="text-xs text-white/70">+ {{ $t('viewer.photoload.loadingTexture') }}+ </p></template><template v-else><div class="flex items-center gap-2"><p class="text-xs font-medium text-white">{{- loadingState.isHeic ? $t('viewer.photoload.loadingHEIC') : $t('viewer.photoload.loading')+ loadingState.isHeic+ ? $t('viewer.photoload.loadingHEIC')+ : $t('viewer.photoload.loading')}}</p><span class="text-xs text-white/60 tabular-nums">diff --git a/app/components/photo/ProgressiveImage.vue b/app/components/photo/ProgressiveImage.vueindex f045948f..9b9037e7 100644--- a/app/components/photo/ProgressiveImage.vue+++ b/app/components/photo/ProgressiveImage.vue@@ -53,7 +53,9 @@ const hasError = ref(false)const currentSrc = ref<string | null>()const isDev = computed(() => import.meta.env.DEV)-const showDebugInfo = computed(() => isDev.value && import.meta.env.VITE_SHOW_DEBUG_INFO === 'true')+const showDebugInfo = computed(+ () => isDev.value && import.meta.env.VITE_SHOW_DEBUG_INFO === 'true',+)// 使用 WebGLImageViewer 的引用const webglViewerRef = ref()diff --git a/app/components/photo/ReactionConfetti.vue b/app/components/photo/ReactionConfetti.vueindex 50602a9c..de0089d8 100644--- a/app/components/photo/ReactionConfetti.vue+++ b/app/components/photo/ReactionConfetti.vue@@ -21,10 +21,10 @@ interface Particle {const particles = computed<Particle[]>(() => {if (props.triggerCount === 0) return []-+const count = 18 // 礼花数量const result: Particle[] = []-+for (let i = 0; i < count; i++) {const angle = (360 / count) * iconst distance = 80 + Math.random() * 40 // 随机距离 80-120px@@ -32,7 +32,7 @@ const particles = computed<Particle[]>(() => {const duration = 1.2 + Math.random() * 0.4 // 随机持续时间,增加到 1.2-1.6 秒const rotation = Math.random() * 360 - 180 // 减少旋转幅度到 -180~180 度const scale = 0.7 + Math.random() * 0.3 // 随机缩放 0.7-1.0-+result.push({id: props.triggerCount * 100 + i,angle,@@ -40,10 +40,10 @@ const particles = computed<Particle[]>(() => {delay,duration,rotation,- scale+ scale,})}-+return result})@@ -52,24 +52,26 @@ const getParticlePosition = (angle: number, distance: number) => {const radian = (angle * Math.PI) / 180return {x: Math.cos(radian) * distance,- y: Math.sin(radian) * distance+ y: Math.sin(radian) * distance,}}</script><template>- <div class="absolute inset-0 pointer-events-none overflow-visible flex items-center justify-center z-[9999]">+ <div+ class="absolute inset-0 pointer-events-none overflow-visible flex items-center justify-center z-[9999]"+ ><motion.divv-for="particle in particles":key="particle.id"- :initial="{- x: 0,- y: 0,- scale: 0,+ :initial="{+ x: 0,+ y: 0,+ scale: 0,opacity: 1,- rotate: 0+ rotate: 0,}"- :animate="{+ :animate="{x: getParticlePosition(particle.angle, particle.distance).x,y: getParticlePosition(particle.angle, particle.distance).y,scale: [0, particle.scale * 1.1, particle.scale, 0],@@ -78,14 +80,14 @@ const getParticlePosition = (angle: number, distance: number) => {transition: {duration: particle.duration,delay: particle.delay,- ease: [0.25, 0.46, 0.45, 0.94]- }+ ease: [0.25, 0.46, 0.45, 0.94],+ },}"class="absolute z-[9999]"style="transform-origin: center">- <Icon- :name="iconName"+ <Icon+ :name="iconName"class="text-[24px]"mode="svg"/>diff --git a/app/components/photo/ReactionPicker.vue b/app/components/photo/ReactionPicker.vueindex a4d18116..a79ffc0a 100644--- a/app/components/photo/ReactionPicker.vue+++ b/app/components/photo/ReactionPicker.vue@@ -30,18 +30,56 @@ onClickOutside(pickerRef, () => {}})--// 可用的表态选项const reactions = computed<Reaction[]>(() => [- { id: 'like', iconName: 'fluent-emoji-flat:thumbs-up', label: $t('viewer.reaction.like'), count: props.reactionCounts?.like || 0 },- { id: 'love', iconName: 'fluent-emoji-flat:red-heart', label: $t('viewer.reaction.love'), count: props.reactionCounts?.love || 0 },- { id: 'amazing', iconName: 'fluent-emoji-flat:smiling-face-with-heart-eyes', label: $t('viewer.reaction.amazing'), count: props.reactionCounts?.amazing || 0 },- { id: 'funny', iconName: 'fluent-emoji-flat:face-with-tears-of-joy', label: $t('viewer.reaction.funny'), count: props.reactionCounts?.funny || 0 },- { id: 'wow', iconName: 'fluent-emoji-flat:face-with-open-mouth', label: $t('viewer.reaction.wow'), count: props.reactionCounts?.wow || 0 },- { id: 'sad', iconName: 'fluent-emoji-flat:crying-face', label: $t('viewer.reaction.sad'), count: props.reactionCounts?.sad || 0 },- { id: 'fire', iconName: 'fluent-emoji-flat:fire', label: $t('viewer.reaction.fire'), count: props.reactionCounts?.fire || 0 },- { id: 'sparkle', iconName: 'fluent-emoji-flat:sparkles', label: $t('viewer.reaction.sparkle'), count: props.reactionCounts?.sparkle || 0 },+ {+ id: 'like',+ iconName: 'fluent-emoji-flat:thumbs-up',+ label: $t('viewer.reaction.like'),+ count: props.reactionCounts?.like || 0,+ },+ {+ id: 'love',+ iconName: 'fluent-emoji-flat:red-heart',+ label: $t('viewer.reaction.love'),+ count: props.reactionCounts?.love || 0,+ },+ {+ id: 'amazing',+ iconName: 'fluent-emoji-flat:smiling-face-with-heart-eyes',+ label: $t('viewer.reaction.amazing'),+ count: props.reactionCounts?.amazing || 0,+ },+ {+ id: 'funny',+ iconName: 'fluent-emoji-flat:face-with-tears-of-joy',+ label: $t('viewer.reaction.funny'),+ count: props.reactionCounts?.funny || 0,+ },+ {+ id: 'wow',+ iconName: 'fluent-emoji-flat:face-with-open-mouth',+ label: $t('viewer.reaction.wow'),+ count: props.reactionCounts?.wow || 0,+ },+ {+ id: 'sad',+ iconName: 'fluent-emoji-flat:crying-face',+ label: $t('viewer.reaction.sad'),+ count: props.reactionCounts?.sad || 0,+ },+ {+ id: 'fire',+ iconName: 'fluent-emoji-flat:fire',+ label: $t('viewer.reaction.fire'),+ count: props.reactionCounts?.fire || 0,+ },+ {+ id: 'sparkle',+ iconName: 'fluent-emoji-flat:sparkles',+ label: $t('viewer.reaction.sparkle'),+ count: props.reactionCounts?.sparkle || 0,+ },])// 格式化数量显示@@ -54,7 +92,7 @@ const formatCount = (count?: number): string => {}const handleSelect = (id: string) => {- const reaction = reactions.value.find(r => r.id === id)+ const reaction = reactions.value.find((r) => r.id === id)if (reaction) {emit('select', id, reaction.iconName)}@@ -69,16 +107,16 @@ const handleSelect = (id: string) => {:initial="{ opacity: 0, scale: 0.9, y: 10 }":animate="{ opacity: 1, scale: 1, y: 0 }":exit="{ opacity: 0, scale: 0.9, y: 10 }"- :transition="{- type: 'spring',- stiffness: 400,+ :transition="{+ type: 'spring',+ stiffness: 400,damping: 25,- mass: 0.8+ mass: 0.8,}"class="absolute bottom-full right-0 mb-2 z-30"@click.stop>- <div+ <divclass="bg-white/90 dark:bg-neutral-800/90 backdrop-blur-xl rounded-2xl border border-neutral-200/50 dark:border-white/10 shadow-2xl shadow-black/10 dark:shadow-black/30 p-3"><!-- 表态网格 -->@@ -88,51 +126,51 @@ const handleSelect = (id: string) => {:key="reaction.id"type="button":initial="{ scale: 0, opacity: 0 }"- :animate="{- scale: 1,+ :animate="{+ scale: 1,opacity: 1,- transition: {- type: 'spring',- stiffness: 500,+ transition: {+ type: 'spring',+ stiffness: 500,damping: 20,- delay: reactions.indexOf(reaction) * 0.03- }+ delay: reactions.indexOf(reaction) * 0.03,+ },}"- :while-hover="{+ :while-hover="{scale: 1.2,- transition: {- type: 'spring',- stiffness: 500,- damping: 20- }+ transition: {+ type: 'spring',+ stiffness: 500,+ damping: 20,+ },}"- :while-tap="{+ :while-tap="{scale: 0.9,- transition: {- type: 'spring',- stiffness: 500,- damping: 20- }+ transition: {+ type: 'spring',+ stiffness: 500,+ damping: 20,+ },}":class="['relative aspect-square w-full min-w-[48px] rounded-xl flex items-center justify-center transition-colors cursor-pointer shrink-0 group','hover:bg-neutral-100/80 dark:hover:bg-white/10','active:bg-neutral-200/80 dark:active:bg-white/20',- selectedReaction === reaction.id- ? 'bg-blue-100 dark:bg-blue-500/20 ring-2 ring-blue-500/50'- : 'bg-transparent'+ selectedReaction === reaction.id+ ? 'bg-blue-100 dark:bg-blue-500/20 ring-2 ring-blue-500/50'+ : 'bg-transparent',]":title="reaction.label"@click="handleSelect(reaction.id)">- <Icon- :name="reaction.iconName"+ <Icon+ :name="reaction.iconName"class="text-[28px] select-none"mode="svg"/>-+<!-- 数量徽章 - 右上角 -->- <motion.span+ <motion.spanv-if="reaction.count !== undefined && reaction.count > 0":initial="{ scale: 0, opacity: 0 }":animate="{ scale: 1, opacity: 1 }"@@ -146,7 +184,7 @@ const handleSelect = (id: string) => {? 'bg-blue-500 text-white': 'bg-gradient-to-br from-neutral-100 to-neutral-200 dark:from-neutral-700 dark:to-neutral-600 text-neutral-700 dark:text-neutral-100','border border-white/50 dark:border-neutral-800/50',- 'group-hover:scale-110 transition-transform duration-150'+ 'group-hover:scale-110 transition-transform duration-150',]">{{ formatCount(reaction.count) }}diff --git a/app/components/setting/SettingSection.vue b/app/components/setting/SettingSection.vueindex cf199751..e722060a 100644--- a/app/components/setting/SettingSection.vue+++ b/app/components/setting/SettingSection.vue@@ -22,9 +22,13 @@ const formRef = ref()const formState = ref<Record<string, any>>({})// 监听 props.state 的变化-watch(() => props.state, (newState) => {- formState.value = { ...newState }-}, { immediate: true })+watch(+ () => props.state,+ (newState) => {+ formState.value = { ...newState }+ },+ { immediate: true },+)/*** 处理表单提交@@ -38,10 +42,17 @@ const handleSubmit = async (event: any) => {<UCard variant="outline"><template #header><div class="flex items-center gap-2">- <UIcon v-if="icon" :name="icon" size="lg" />+ <UIcon+ v-if="icon"+ :name="icon"+ size="lg"+ /><div><p class="font-semibold">{{ title }}</p>- <p v-if="description" class="text-xs text-gray-500">+ <p+ v-if="description"+ class="text-xs text-gray-500"+ >{{ description }}</p></div>diff --git a/app/components/ui/DateRangeIndicator.vue b/app/components/ui/DateRangeIndicator.vueindex 5c0f90b2..f721a3d5 100644--- a/app/components/ui/DateRangeIndicator.vue+++ b/app/components/ui/DateRangeIndicator.vue@@ -54,8 +54,15 @@ const mobileVariants = {bounce: 0.15,}">- <span class="text-white text-4xl font-black leading-normal tracking-wide">{{ dateRange }}</span>- <span v-if="locations" class="text-white/80 text-xl font-bold">{{ locations }}</span>+ <span+ class="text-white text-4xl font-black leading-normal tracking-wide"+ >{{ dateRange }}</span+ >+ <span+ v-if="locations"+ class="text-white/80 text-xl font-bold"+ >{{ locations }}</span+ ></motion.div><!-- Mobile Date Range Indicator -->@@ -75,12 +82,15 @@ const mobileVariants = {class="bg-black/60 backdrop-blur-3xl border-b border-white/10 px-4 py-2 shadow-2xl flex flex-col"><span class="text-white text-lg font-medium">{{ dateRange }}</span>- <span v-if="locations" class="text-white/80 text-xs">{{ locations }}</span>+ <span+ v-if="locations"+ class="text-white/80 text-xs"+ >{{ locations }}</span+ ></div></motion.div></AnimatePresence></div></template>-<style scoped>-</style>+<style scoped></style>diff --git a/app/components/ui/GlassButton.vue b/app/components/ui/GlassButton.vueindex 2a604499..ea3c5be8 100644--- a/app/components/ui/GlassButton.vue+++ b/app/components/ui/GlassButton.vue@@ -55,7 +55,9 @@ const iconSizeClasses = {<Iconv-if="icon":name="icon"- :class="twMerge('inline-block shrink-0 -mt-0.5', iconSizeClasses[$props.size!])"+ :class="+ twMerge('inline-block shrink-0 -mt-0.5', iconSizeClasses[$props.size!])+ "/><slot /></motion.button>diff --git a/app/components/ui/UploadQueuePanel.vue b/app/components/ui/UploadQueuePanel.vueindex 63f42c8e..aee49d6d 100644--- a/app/components/ui/UploadQueuePanel.vue+++ b/app/components/ui/UploadQueuePanel.vue@@ -164,7 +164,8 @@ const clearAllFiles = () => {'text-blue-600 dark:text-blue-400': statusColor === 'primary','text-green-600 dark:text-green-400': statusColor === 'success','text-red-600 dark:text-red-400': statusColor === 'error',- 'text-yellow-600 dark:text-yellow-400': statusColor === 'warning',+ 'text-yellow-600 dark:text-yellow-400':+ statusColor === 'warning','text-neutral-600 dark:text-neutral-400':statusColor === 'neutral',}"@@ -323,7 +324,7 @@ const clearAllFiles = () => {>清除全部</UButton>-+<UButtonsize="xs"variant="ghost"diff --git a/app/composables/useImageLoader.ts b/app/composables/useImageLoader.tsindex 03b532c7..38c87fda 100644--- a/app/composables/useImageLoader.ts+++ b/app/composables/useImageLoader.ts@@ -1,5 +1,5 @@-import type { LoadingIndicatorRef } from "~/components/photo/LoadingIndicator.vue";-import { ImageLoaderManager } from "~/libs/image-loader-manager";+import type { LoadingIndicatorRef } from '~/components/photo/LoadingIndicator.vue'+import { ImageLoaderManager } from '~/libs/image-loader-manager'export const useImageLoader = (src: string,@@ -13,7 +13,7 @@ export const useImageLoader = (updateHighResLoaded?: (highResLoaded: boolean) => void,updateError?: (error: boolean) => void,updateHighResImageRendered?: (isRendered: boolean) => void,- onImageLoaded?: () => void+ onImageLoaded?: () => void,) => {if (highResLoaded || !isCurrentImage || error) return null@@ -45,7 +45,7 @@ export const useImageLoader = (loadingIndicatorRef?.updateLoadingState({isVisible: true,isError: true,- message: "载入图片失败"+ message: '载入图片失败',})}}@@ -54,4 +54,4 @@ export const useImageLoader = (loadImage()return loaderManager-}\ No newline at end of file+}diff --git a/app/composables/useLivePhotoProcessor.ts b/app/composables/useLivePhotoProcessor.tsindex d4929242..11d37161 100644--- a/app/composables/useLivePhotoProcessor.ts+++ b/app/composables/useLivePhotoProcessor.ts@@ -6,11 +6,13 @@ interface LivePhotoProcessingState {mp4Blob: Blob | nullerror: string | nulllastProcessed?: number // 添加时间戳用于缓存管理- retryCount?: number // 添加重试计数+ retryCount?: number // 添加重试计数}// 全局存储已转换的实况照片-const processedLivePhotos = ref<Map<string, LivePhotoProcessingState>>(new Map())+const processedLivePhotos = ref<Map<string, LivePhotoProcessingState>>(+ new Map(),+)export const useLivePhotoProcessor = () => {/**@@ -18,25 +20,32 @@ export const useLivePhotoProcessor = () => {* @param movUrl MOV 文件的 URL* @param photoId 照片 ID*/- const convertMovToMp4 = async (movUrl: string, photoId: string): Promise<Blob | null> => {+ const convertMovToMp4 = async (+ movUrl: string,+ photoId: string,+ ): Promise<Blob | null> => {// 检查缓存状态const existing = processedLivePhotos.value.get(photoId)if (existing) {// 检查缓存是否过期(24小时)const now = Date.now()const cacheExpiry = 24 * 60 * 60 * 1000 // 24小时-- if (existing.mp4Blob && existing.lastProcessed && (now - existing.lastProcessed) < cacheExpiry) {++ if (+ existing.mp4Blob &&+ existing.lastProcessed &&+ now - existing.lastProcessed < cacheExpiry+ ) {return existing.mp4Blob}-+if (existing.isProcessing) {// 使用Promise而不是轮询,提高性能return new Promise((resolve) => {const timeout = setTimeout(() => {resolve(null) // 超时返回null}, 30000) // 30秒超时-+const checkInterval = setInterval(() => {const current = processedLivePhotos.value.get(photoId)if (current && !current.isProcessing) {@@ -52,7 +61,7 @@ export const useLivePhotoProcessor = () => {// 初始化处理状态,包含重试逻辑const maxRetries = 3const currentRetry = existing?.retryCount || 0-+if (currentRetry >= maxRetries) {console.warn(`Max retries reached for LivePhoto ${photoId}`)return null@@ -64,7 +73,7 @@ export const useLivePhotoProcessor = () => {mp4Blob: null,error: null,retryCount: currentRetry,- lastProcessed: Date.now()+ lastProcessed: Date.now(),}processedLivePhotos.value.set(photoId, state)@@ -77,21 +86,23 @@ export const useLivePhotoProcessor = () => {// 下载 MOV 文件,支持断点续传updateProgress(10)-+const controller = new AbortController()const timeoutId = setTimeout(() => controller.abort(), 30000) // 30秒超时-+const response = await fetch(movUrl, {signal: controller.signal,headers: {'Cache-Control': 'max-age=3600', // 缓存1小时- }+ },})-+clearTimeout(timeoutId)-+if (!response.ok) {- throw new Error(`Failed to fetch MOV file: ${response.status} ${response.statusText}`)+ throw new Error(+ `Failed to fetch MOV file: ${response.status} ${response.statusText}`,+ )}updateProgress(30)@@ -101,16 +112,18 @@ export const useLivePhotoProcessor = () => {if (!reader) throw new Error('Failed to get response reader')const chunks: Uint8Array[] = []- const contentLength = parseInt(response.headers.get('content-length') || '0')+ const contentLength = parseInt(+ response.headers.get('content-length') || '0',+ )let receivedLength = 0while (true) {const { done, value } = await reader.read()if (done) break-+chunks.push(value)receivedLength += value.length-+// 更新下载进度if (contentLength > 0) {const downloadProgress = 30 + (receivedLength / contentLength) * 40 // 30-70%@@ -128,12 +141,12 @@ export const useLivePhotoProcessor = () => {// 更快的格式验证:只检查元数据const videoUrl = URL.createObjectURL(mp4Blob)const video = document.createElement('video')-+await new Promise<void>((resolve, reject) => {const timeout = setTimeout(() => {reject(new Error('Video validation timeout'))}, 5000) // 5秒验证超时-+video.onloadedmetadata = () => {clearTimeout(timeout)resolve()@@ -159,29 +172,36 @@ export const useLivePhotoProcessor = () => {return mp4Blob} catch (error) {- const errorMessage = error instanceof Error ? error.message : 'Unknown error'-+ const errorMessage =+ error instanceof Error ? error.message : 'Unknown error'+// 增加重试逻辑if (currentRetry < maxRetries - 1) {- console.warn(`LivePhoto processing failed (attempt ${currentRetry + 1}/${maxRetries}), retrying...`, errorMessage)+ console.warn(+ `LivePhoto processing failed (attempt ${currentRetry + 1}/${maxRetries}), retrying...`,+ errorMessage,+ )state.retryCount = currentRetry + 1state.isProcessing = falsestate.error = `Retrying... (${currentRetry + 1}/${maxRetries})`processedLivePhotos.value.set(photoId, { ...state })-+// 指数退避重试const retryDelay = Math.min(1000 * Math.pow(2, currentRetry), 5000)- await new Promise(resolve => setTimeout(resolve, retryDelay))-+ await new Promise((resolve) => setTimeout(resolve, retryDelay))+return convertMovToMp4(movUrl, photoId) // 递归重试}-+// 最终失败state.isProcessing = falsestate.error = errorMessagestate.lastProcessed = Date.now()processedLivePhotos.value.set(photoId, { ...state })- console.error(`Failed to convert MOV to MP4 after ${maxRetries} attempts:`, error)+ console.error(+ `Failed to convert MOV to MP4 after ${maxRetries} attempts:`,+ error,+ )return null}}@@ -197,27 +217,37 @@ export const useLivePhotoProcessor = () => {* 智能预加载:基于视口和用户行为预测*/const preloadLivePhotosInViewport = async (- photos: Array<{ id: string; livePhotoVideoUrl?: string | null; isVisible?: boolean }>,+ photos: Array<{+ id: string+ livePhotoVideoUrl?: string | null+ isVisible?: boolean+ }>,options: {maxConcurrent?: numberprioritizeVisible?: booleanprefetchDistance?: number- } = {}+ } = {},) => {- const { maxConcurrent = 2, prioritizeVisible = true, prefetchDistance = 3 } = options-- const livePhotos = photos.filter(photo => photo.livePhotoVideoUrl)-+ const {+ maxConcurrent = 2,+ prioritizeVisible = true,+ prefetchDistance = 3,+ } = options++ const livePhotos = photos.filter((photo) => photo.livePhotoVideoUrl)+if (prioritizeVisible) {// 优先处理可见的LivePhoto- const visiblePhotos = livePhotos.filter(photo => photo.isVisible)- const nearbyPhotos = livePhotos.filter(photo => !photo.isVisible).slice(0, prefetchDistance)-+ const visiblePhotos = livePhotos.filter((photo) => photo.isVisible)+ const nearbyPhotos = livePhotos+ .filter((photo) => !photo.isVisible)+ .slice(0, prefetchDistance)+// 先处理可见的if (visiblePhotos.length > 0) {await processPhotoBatch(visiblePhotos, maxConcurrent)}-+// 然后预加载附近的if (nearbyPhotos.length > 0) {processPhotoBatch(nearbyPhotos, Math.min(maxConcurrent, 1)) // 降低并发数@@ -226,23 +256,25 @@ export const useLivePhotoProcessor = () => {await processPhotoBatch(livePhotos, maxConcurrent)}}-+/*** 处理照片批次的辅助函数*/const processPhotoBatch = async (photos: Array<{ id: string; livePhotoVideoUrl: string }>,- maxConcurrent: number+ maxConcurrent: number,) => {for (let i = 0; i < photos.length; i += maxConcurrent) {const batch = photos.slice(i, i + maxConcurrent)await Promise.allSettled(- batch.map(photo => convertMovToMp4(photo.livePhotoVideoUrl, photo.id))+ batch.map((photo) =>+ convertMovToMp4(photo.livePhotoVideoUrl, photo.id),+ ),)-+// 添加小延迟避免过度占用资源if (i + maxConcurrent < photos.length) {- await new Promise(resolve => setTimeout(resolve, 100))+ await new Promise((resolve) => setTimeout(resolve, 100))}}}@@ -250,7 +282,9 @@ export const useLivePhotoProcessor = () => {/*** 批量处理视口内的实况照片(保持兼容性)*/- const batchProcessLivePhotos = async (photos: Array<{ id: string; livePhotoVideoUrl?: string | null }>) => {+ const batchProcessLivePhotos = async (+ photos: Array<{ id: string; livePhotoVideoUrl?: string | null }>,+ ) => {await preloadLivePhotosInViewport(photos, { maxConcurrent: 3 })}@@ -261,19 +295,19 @@ export const useLivePhotoProcessor = () => {const now = Date.now()const cacheExpiry = 24 * 60 * 60 * 1000 // 24小时const maxCacheSize = 50 // 最大缓存50个LivePhoto-+const entries = Array.from(processedLivePhotos.value.entries())const expiredEntries: string[] = []-+// 查找过期的条目entries.forEach(([photoId, state]) => {- if (state.lastProcessed && (now - state.lastProcessed) > cacheExpiry) {+ if (state.lastProcessed && now - state.lastProcessed > cacheExpiry) {expiredEntries.push(photoId)}})-+// 清理过期条目- expiredEntries.forEach(photoId => {+ expiredEntries.forEach((photoId) => {const state = processedLivePhotos.value.get(photoId)if (state?.mp4Blob) {// 这里可以安全地清理,因为已过期@@ -281,14 +315,17 @@ export const useLivePhotoProcessor = () => {}processedLivePhotos.value.delete(photoId)})-+// 如果缓存仍然太大,清理最老的条目if (processedLivePhotos.value.size > maxCacheSize) {const sortedEntries = entries.filter(([photoId]) => !expiredEntries.includes(photoId)).sort((a, b) => (a[1].lastProcessed || 0) - (b[1].lastProcessed || 0))-- const toRemove = sortedEntries.slice(0, processedLivePhotos.value.size - maxCacheSize)++ const toRemove = sortedEntries.slice(+ 0,+ processedLivePhotos.value.size - maxCacheSize,+ )toRemove.forEach(([photoId, state]) => {if (state.mp4Blob) {state.mp4Blob = null@@ -296,8 +333,10 @@ export const useLivePhotoProcessor = () => {processedLivePhotos.value.delete(photoId)})}-- console.log(`Cleaned up ${expiredEntries.length} expired LivePhoto cache entries`)++ console.log(+ `Cleaned up ${expiredEntries.length} expired LivePhoto cache entries`,+ )}/**@@ -309,8 +348,8 @@ export const useLivePhotoProcessor = () => {let processing = 0let failed = 0let totalSize = 0-- processedLivePhotos.value.forEach(state => {++ processedLivePhotos.value.forEach((state) => {if (state.mp4Blob) {processed++totalSize += state.mp4Blob.size@@ -320,13 +359,13 @@ export const useLivePhotoProcessor = () => {failed++}})-+return {total,processed,processing,failed,- totalSizeMB: Math.round(totalSize / (1024 * 1024) * 100) / 100+ totalSizeMB: Math.round((totalSize / (1024 * 1024)) * 100) / 100,}}@@ -357,6 +396,6 @@ export const useLivePhotoProcessor = () => {cleanupExpiredCache,getCacheStats,clearProcessedCache,- processedLivePhotos: readonly(processedLivePhotos)+ processedLivePhotos: readonly(processedLivePhotos),}}diff --git a/app/composables/usePhotoFilters.ts b/app/composables/usePhotoFilters.tsindex 19a35410..d0e1c82f 100644--- a/app/composables/usePhotoFilters.ts+++ b/app/composables/usePhotoFilters.ts@@ -22,13 +22,13 @@ const globalFilters = ref<FilterOptions>({lenses: [],cities: [],ratings: 0,- search: ''+ search: '',})export function usePhotoFilters() {const { photos } = usePhotos()const { sortedPhotos } = usePhotoSort()-+// 使用全局筛选状态const activeFilters = globalFilters@@ -39,13 +39,13 @@ export function usePhotoFilters() {cameras: new Map(),lenses: new Map(),cities: new Map(),- ratings: new Map()+ ratings: new Map(),}- photos.value.forEach(photo => {+ photos.value.forEach((photo) => {// 标签统计if (photo.tags && Array.isArray(photo.tags)) {- photo.tags.forEach(tag => {+ photo.tags.forEach((tag) => {stats.tags.set(tag, (stats.tags.get(tag) || 0) + 1)})}@@ -113,14 +113,14 @@ export function usePhotoFilters() {lenses: activeFilters.value.lenses.length,cities: activeFilters.value.cities.length,ratings: activeFilters.value.ratings > 0 ? 1 : 0,- search: activeFilters.value.search.length > 0 ? 1 : 0+ search: activeFilters.value.search.length > 0 ? 1 : 0,}})// 筛选后的照片(应用排序)const filteredPhotos = computed(() => {// 先获取排序后的照片,再应用筛选- return sortedPhotos.value.filter(photo => {+ return sortedPhotos.value.filter((photo) => {// 搜索筛选if (activeFilters.value.search) {const searchTerm = activeFilters.value.search.toLowerCase()@@ -136,7 +136,9 @@ export function usePhotoFilters() {photo.description || '',photo.storageKey || '',photo.locationName || '',- ].join(' ').toLowerCase()+ ]+ .join(' ')+ .toLowerCase()if (!searchableFields.includes(searchTerm)) {return false@@ -146,27 +148,32 @@ export function usePhotoFilters() {// 标签筛选if (activeFilters.value.tags.length > 0) {const photoTags = photo.tags || []- const hasMatchingTag = activeFilters.value.tags.some(tag =>- photoTags.includes(tag)+ const hasMatchingTag = activeFilters.value.tags.some((tag) =>+ photoTags.includes(tag),)if (!hasMatchingTag) return false}// 相机筛选if (activeFilters.value.cameras.length > 0) {- const photoCamera = photo.exif?.Make && photo.exif?.Model- ? `${photo.exif.Make} ${photo.exif.Model}`- : null- if (!photoCamera || !activeFilters.value.cameras.includes(photoCamera)) {+ const photoCamera =+ photo.exif?.Make && photo.exif?.Model+ ? `${photo.exif.Make} ${photo.exif.Model}`+ : null+ if (+ !photoCamera ||+ !activeFilters.value.cameras.includes(photoCamera)+ ) {return false}}// 镜头筛选if (activeFilters.value.lenses.length > 0) {- const photoLens = photo.exif?.LensMake && photo.exif?.LensModel- ? `${photo.exif.LensMake} ${photo.exif.LensModel}`- : photo.exif?.LensModel || null+ const photoLens =+ photo.exif?.LensMake && photo.exif?.LensModel+ ? `${photo.exif.LensMake} ${photo.exif.LensModel}`+ : photo.exif?.LensModel || nullif (!photoLens || !activeFilters.value.lenses.includes(photoLens)) {return false}@@ -195,7 +202,7 @@ export function usePhotoFilters() {const toggleFilter = (type: keyof FilterOptions, value: string | number) => {const filters = activeFilters.value[type] as any[]const index = filters.indexOf(value)-+if (index === -1) {filters.push(value)} else {@@ -211,32 +218,37 @@ export function usePhotoFilters() {lenses: [],cities: [],ratings: 0,- search: ''+ search: '',}}// 清除指定类型的筛选const clearFilterType = (type: keyof FilterOptions) => {if (type === 'ratings' || type === 'search') {- (activeFilters.value as any)[type] = type === 'ratings' ? 0 : ''+ ;(activeFilters.value as any)[type] = type === 'ratings' ? 0 : ''} else {- (activeFilters.value as any)[type] = []+ ;(activeFilters.value as any)[type] = []}}// 检查筛选项是否被选中- const isFilterSelected = (type: keyof FilterOptions, value: string | number) => {+ const isFilterSelected = (+ type: keyof FilterOptions,+ value: string | number,+ ) => {return (activeFilters.value[type] as any[]).includes(value)}// 检查是否有任何筛选项被激活const hasActiveFilters = computed(() => {- return activeFilters.value.tags.length > 0 ||- activeFilters.value.cameras.length > 0 ||- activeFilters.value.lenses.length > 0 ||- activeFilters.value.cities.length > 0 ||- activeFilters.value.ratings > 0 ||- activeFilters.value.search.length > 0+ return (+ activeFilters.value.tags.length > 0 ||+ activeFilters.value.cameras.length > 0 ||+ activeFilters.value.lenses.length > 0 ||+ activeFilters.value.cities.length > 0 ||+ activeFilters.value.ratings > 0 ||+ activeFilters.value.search.length > 0+ )})return {@@ -248,6 +260,6 @@ export function usePhotoFilters() {toggleFilter,clearAllFilters,clearFilterType,- isFilterSelected+ isFilterSelected,}}diff --git a/app/composables/usePhotoSort.ts b/app/composables/usePhotoSort.tsindex 7a2cdd2a..167bc464 100644--- a/app/composables/usePhotoSort.ts+++ b/app/composables/usePhotoSort.ts@@ -155,12 +155,12 @@ export function usePhotoSort() {const shufflePhotos = () => {// 创建一个特殊的排序方式用于打乱globalSortState.value.currentSort = 'shuffle'-+// 更新可用排序中的 shuffle 选项const shuffleIndex = globalSortState.value.availableSorts.findIndex((sort) => sort.key === 'shuffle',)-+if (shuffleIndex === -1) {// 如果没有 shuffle 排序选项,则添加它globalSortState.value.availableSorts.push({diff --git a/app/composables/usePhotos.ts b/app/composables/usePhotos.tsindex 58191014..b44c399b 100644--- a/app/composables/usePhotos.ts+++ b/app/composables/usePhotos.ts@@ -1,4 +1,4 @@-import type { AsyncDataRequestStatus } from "#app"+import type { AsyncDataRequestStatus } from '#app'interface PhotosContext {photos: Ref<Photo[]>diff --git a/app/composables/useSettingsForm.ts b/app/composables/useSettingsForm.tsindex c7e8add3..0c244e73 100644--- a/app/composables/useSettingsForm.ts+++ b/app/composables/useSettingsForm.ts@@ -1,4 +1,7 @@-import type { FieldDescriptor, SettingsFieldsResponse } from '~~/shared/types/settings'+import type {+ FieldDescriptor,+ SettingsFieldsResponse,+} from '~~/shared/types/settings'/*** Settings Form Composablediff --git a/app/composables/useWizardForm.ts b/app/composables/useWizardForm.tsindex 8db26394..aa1599cd 100644--- a/app/composables/useWizardForm.ts+++ b/app/composables/useWizardForm.ts@@ -1,4 +1,7 @@-import type { FieldDescriptor, SettingsFieldsResponse } from '~~/shared/types/settings'+import type {+ FieldDescriptor,+ SettingsFieldsResponse,+} from '~~/shared/types/settings'import { useWizardStore } from '~/stores/wizard'/**@@ -18,53 +21,68 @@ export function useWizardForm(namespace: string) {const state = computed({get: () => {switch (namespace) {- case 'admin': return store.admin- case 'app': return store.site- case 'storage': return store.storage- case 'map': return store.map- default: return {}+ case 'admin':+ return store.admin+ case 'app':+ return store.site+ case 'storage':+ return store.storage+ case 'map':+ return store.map+ default:+ return {}}},set: (val) => {switch (namespace) {- case 'admin': store.updateAdmin(val); break- case 'app': store.updateSite(val); break- case 'storage': store.updateStorage(val); break- case 'map': store.updateMap(val); break+ case 'admin':+ store.updateAdmin(val)+ break+ case 'app':+ store.updateSite(val)+ break+ case 'storage':+ store.updateStorage(val)+ break+ case 'map':+ store.updateMap(val)+ break}- }+ },})const fetchSchema = async () => {loading.value = trueerror.value = nulltry {- const response = await $fetch<SettingsFieldsResponse>('/api/wizard/schema', {- query: { namespace }- })+ const response = await $fetch<SettingsFieldsResponse>(+ '/api/wizard/schema',+ {+ query: { namespace },+ },+ )fields.value = response.fields-+// Initialize state from schema if store is empty// We create a temporary object to hold default valuesconst defaults: Record<string, any> = {}- response.fields.forEach(field => {+ response.fields.forEach((field) => {defaults[field.key] = field.value ?? field.defaultValue ?? ''})-+// Merge defaults with existing store state// Existing store state takes precedenceconst currentState = state.valueconst newState = { ...defaults, ...currentState }-+// Update storestate.value = newState-} catch (e: any) {error.value = e.messagetoast.add({title: 'Failed to load wizard schema',description: e.message,- color: 'error'+ color: 'error',})} finally {loading.value = false@@ -78,7 +96,7 @@ export function useWizardForm(namespace: string) {}// Helper to get field by key- const getField = (key: string) => fields.value.find(f => f.key === key)+ const getField = (key: string) => fields.value.find((f) => f.key === key)onMounted(() => {fetchSchema()@@ -91,6 +109,6 @@ export function useWizardForm(namespace: string) {error,isFieldVisible,fetchSchema,- getField+ getField,}}diff --git a/app/libs/lru.ts b/app/libs/lru.tsindex d9441206..898f2e06 100644--- a/app/libs/lru.ts+++ b/app/libs/lru.ts@@ -10,10 +10,7 @@ export class LRUCache<K, V> {private readonly storage = new Map<K, V>()private readonly onEvict?: CleanupHandler<K, V>- constructor(- maxSize = 10,- cleanupFn?: CleanupHandler<K, V>,- ) {+ constructor(maxSize = 10, cleanupFn?: CleanupHandler<K, V>) {this.capacity = Math.max(1, maxSize)this.onEvict = cleanupFn}@@ -61,11 +58,11 @@ export class LRUCache<K, V> {clear(): void {const itemCount = this.storage.size-+for (const [key, item] of this.storage.entries()) {this.executeCleanup(item, key, `清空缓存: ${String(key)}`)}-+this.storage.clear()console.info(`缓存已清空,共释放 ${itemCount} 个项目`)}@@ -98,7 +95,11 @@ export class LRUCache<K, V> {const oldestKey = this.storage.keys().next().valueif (oldestKey !== undefined) {const oldestValue = this.storage.get(oldestKey)!- this.executeCleanup(oldestValue, oldestKey, `容量限制淘汰: ${String(oldestKey)}`)+ this.executeCleanup(+ oldestValue,+ oldestKey,+ `容量限制淘汰: ${String(oldestKey)}`,+ )this.storage.delete(oldestKey)}}@@ -169,4 +170,4 @@ export function useLRUCache<K, V>(})return cacheInstance.value-}\ No newline at end of file+}diff --git a/app/pages/onboarding/admin.vue b/app/pages/onboarding/admin.vueindex 9aee45aa..4723b8ed 100644--- a/app/pages/onboarding/admin.vue+++ b/app/pages/onboarding/admin.vue@@ -8,20 +8,27 @@ definePageMeta({const router = useRouter()// Use the wizard form composable-const { fields, state, loading: fetchingSchema, isFieldVisible } = useWizardForm('admin')+const {+ fields,+ state,+ loading: fetchingSchema,+ isFieldVisible,+} = useWizardForm('admin')-// Construct schema dynamically or keep it static?-// For admin, static is safer for the specific password logic,+// Construct schema dynamically or keep it static?+// For admin, static is safer for the specific password logic,// but we can make it partial to allow extra fields if API adds them.-const schema = z.object({- username: z.string().min(2, 'Username must be at least 2 characters'),- email: z.email('Invalid email address'),- password: z.string().min(6, 'Password must be at least 6 characters'),- confirmPassword: z.string()-}).refine((data) => data.password === data.confirmPassword, {- message: "Passwords don't match",- path: ["confirmPassword"],-})+const schema = z+ .object({+ username: z.string().min(2, 'Username must be at least 2 characters'),+ email: z.email('Invalid email address'),+ password: z.string().min(6, 'Password must be at least 6 characters'),+ confirmPassword: z.string(),+ })+ .refine((data) => data.password === data.confirmPassword, {+ message: "Passwords don't match",+ path: ['confirmPassword'],+ })function onSubmit() {// Validation passed, data is already in the store via useWizardForm binding@@ -34,28 +41,37 @@ function onSubmit() {title="管理员账户"description="创建一个管理员账户">- <div v-if="fetchingSchema" class="flex justify-center py-8">- <UIcon name="tabler:loader" class="animate-spin w-8 h-8 text-gray-400" />+ <div+ v-if="fetchingSchema"+ class="flex justify-center py-8"+ >+ <UIcon+ name="tabler:loader"+ class="animate-spin w-8 h-8 text-gray-400"+ /></div>- <UForm+ <UFormv-else- id="admin-form"- :schema="schema"- :state="state"- class="space-y-4"+ id="admin-form"+ :schema="schema"+ :state="state"+ class="space-y-4"@submit="onSubmit">- <template v-for="field in fields" :key="field.key">- <WizardFormField+ <template+ v-for="field in fields"+ :key="field.key"+ >+ <WizardFormFieldv-if="isFieldVisible(field)"- :label="$t(field.label || '')"- :name="field.key"+ :label="$t(field.label || '')"+ :name="field.key":required="field.ui.required":help="$t(field.ui.help || '')">- <WizardInput- v-model="state[field.key]"+ <WizardInput+ v-model="state[field.key]":type="field.ui.type === 'password' ? 'password' : 'text'":placeholder="field.ui.placeholder"/>diff --git a/app/stores/wizard.ts b/app/stores/wizard.tsindex b0056f6c..12ead8da 100644--- a/app/stores/wizard.ts+++ b/app/stores/wizard.ts@@ -4,7 +4,9 @@ import { useLocalStorage } from '@vueuse/core'export const useWizardStore = defineStore('wizard', () => {const admin = ref(useLocalStorage<Record<string, any>>('wizard-admin', {}))const site = ref(useLocalStorage<Record<string, any>>('wizard-site', {}))- const storage = ref(useLocalStorage<Record<string, any>>('wizard-storage', {}))+ const storage = ref(+ useLocalStorage<Record<string, any>>('wizard-storage', {}),+ )const map = ref(useLocalStorage<Record<string, any>>('wizard-map', {}))const updateAdmin = (data: Record<string, any>) => {diff --git a/app/utils/camera.ts b/app/utils/camera.tsindex ccea3947..112dcef7 100644--- a/app/utils/camera.ts+++ b/app/utils/camera.ts@@ -8,28 +8,28 @@ export function formatCameraInfo(make?: string, model?: string): string {// 常见品牌名称映射(包括各种可能的变体)const brandMap: Record<string, string[]> = {- 'Canon': ['canon', 'eos'],- 'Nikon': ['nikon'],- 'Sony': ['sony', 'ilce', 'dsc'],- 'Fujifilm': ['fujifilm', 'fuji', 'x-'],- 'Olympus': ['olympus', 'om-', 'e-'],- 'Panasonic': ['panasonic', 'lumix', 'dc-', 'dmc-'],- 'Leica': ['leica'],- 'Pentax': ['pentax', 'k-'],- 'Ricoh': ['ricoh', 'gr'],- 'Hasselblad': ['hasselblad'],+ Canon: ['canon', 'eos'],+ Nikon: ['nikon'],+ Sony: ['sony', 'ilce', 'dsc'],+ Fujifilm: ['fujifilm', 'fuji', 'x-'],+ Olympus: ['olympus', 'om-', 'e-'],+ Panasonic: ['panasonic', 'lumix', 'dc-', 'dmc-'],+ Leica: ['leica'],+ Pentax: ['pentax', 'k-'],+ Ricoh: ['ricoh', 'gr'],+ Hasselblad: ['hasselblad'],'Phase One': ['phase one'],- 'Mamiya': ['mamiya'],- 'Apple': ['apple'],- 'Samsung': ['samsung', 'galaxy', 'sm-'],- 'Google': ['pixel'],- 'Xiaomi': ['xiaomi', 'mi ', 'redmi'],- 'Huawei': ['huawei', 'p30', 'p40', 'p50', 'mate'],- 'OnePlus': ['oneplus'],- 'OPPO': ['oppo'],- 'Vivo': ['vivo'],- 'Realme': ['realme'],- 'Honor': ['honor'],+ Mamiya: ['mamiya'],+ Apple: ['apple'],+ Samsung: ['samsung', 'galaxy', 'sm-'],+ Google: ['pixel'],+ Xiaomi: ['xiaomi', 'mi ', 'redmi'],+ Huawei: ['huawei', 'p30', 'p40', 'p50', 'mate'],+ OnePlus: ['oneplus'],+ OPPO: ['oppo'],+ Vivo: ['vivo'],+ Realme: ['realme'],+ Honor: ['honor'],}const makeNormalized = make.toLowerCase().trim()@@ -37,8 +37,8 @@ export function formatCameraInfo(make?: string, model?: string): string {// 检查型号中是否已经包含品牌信息const brandKeywords = brandMap[make] || [makeNormalized]- const modelContainsBrand = brandKeywords.some(keyword =>- modelNormalized.includes(keyword.toLowerCase())+ const modelContainsBrand = brandKeywords.some((keyword) =>+ modelNormalized.includes(keyword.toLowerCase()),)if (modelContainsBrand) {@@ -60,19 +60,19 @@ export function formatLensInfo(lensMake?: string, lensModel?: string): string {// 镜头品牌映射const lensBrandMap: Record<string, string[]> = {- 'Canon': ['canon', 'ef', 'rf'],- 'Nikon': ['nikon', 'nikkor'],- 'Sony': ['sony', 'fe', 'e '],- 'Sigma': ['sigma'],- 'Tamron': ['tamron'],- 'Tokina': ['tokina'],- 'Samyang': ['samyang'],- 'Zeiss': ['zeiss'],- 'Voigtländer': ['voigtlander', 'voigtländer'],- 'Leica': ['leica'],- 'Panasonic': ['panasonic', 'lumix'],- 'Olympus': ['olympus', 'zuiko'],- 'Fujifilm': ['fujifilm', 'fujinon', 'xf', 'xc'],+ Canon: ['canon', 'ef', 'rf'],+ Nikon: ['nikon', 'nikkor'],+ Sony: ['sony', 'fe', 'e '],+ Sigma: ['sigma'],+ Tamron: ['tamron'],+ Tokina: ['tokina'],+ Samyang: ['samyang'],+ Zeiss: ['zeiss'],+ Voigtländer: ['voigtlander', 'voigtländer'],+ Leica: ['leica'],+ Panasonic: ['panasonic', 'lumix'],+ Olympus: ['olympus', 'zuiko'],+ Fujifilm: ['fujifilm', 'fujinon', 'xf', 'xc'],}const lensMakeNormalized = lensMake.toLowerCase().trim()@@ -80,8 +80,8 @@ export function formatLensInfo(lensMake?: string, lensModel?: string): string {// 检查镜头型号中是否已经包含品牌信息const brandKeywords = lensBrandMap[lensMake] || [lensMakeNormalized]- const modelContainsBrand = brandKeywords.some(keyword =>- lensModelNormalized.includes(keyword.toLowerCase())+ const modelContainsBrand = brandKeywords.some((keyword) =>+ lensModelNormalized.includes(keyword.toLowerCase()),)if (modelContainsBrand) {diff --git a/docs/.develop/queue-api.md b/docs/.develop/queue-api.mdindex ee679491..f41a3a65 100644--- a/docs/.develop/queue-api.md+++ b/docs/.develop/queue-api.md@@ -5,12 +5,15 @@## API 概览### 1. 添加单个任务+**POST** `/api/queue/add-task`-### 2. 批量添加任务+### 2. 批量添加任务+**POST** `/api/queue/add-tasks`### 3. 查看队列状态+**GET** `/api/queue/status`## 使用示例@@ -26,11 +29,11 @@ const response = await fetch('/api/queue/add-task', {},body: JSON.stringify({payload: {- storageKey: 'photos/2024/IMG_1234.HEIC'+ storageKey: 'photos/2024/IMG_1234.HEIC',},- priority: 5, // 可选,优先级 0-10,默认 0- maxAttempts: 3 // 可选,最大重试次数 1-5,默认 3- })+ priority: 5, // 可选,优先级 0-10,默认 0+ maxAttempts: 3, // 可选,最大重试次数 1-5,默认 3+ }),})const result = await response.json()@@ -61,20 +64,20 @@ const response = await fetch('/api/queue/add-tasks', {tasks: [{payload: { storageKey: 'photos/2024/IMG_1234.HEIC' },- priority: 8+ priority: 8,},{payload: { storageKey: 'photos/2024/IMG_1235.HEIC' },- priority: 5+ priority: 5,},{- payload: { storageKey: 'photos/2024/IMG_1236.HEIC' }+ payload: { storageKey: 'photos/2024/IMG_1236.HEIC' },// 使用默认优先级和重试次数- }+ },],- defaultPriority: 3, // 可选,默认优先级- defaultMaxAttempts: 3 // 可选,默认最大重试次数- })+ defaultPriority: 3, // 可选,默认优先级+ defaultMaxAttempts: 3, // 可选,默认最大重试次数+ }),})const result = await response.json()@@ -123,7 +126,7 @@ console.log('队列状态:', status)// "successRate": 93.75// },// {-// "workerId": "worker-2",+// "workerId": "worker-2",// "isProcessing": true,// "processedCount": 18,// "errorCount": 0,@@ -152,21 +155,25 @@ console.log('队列状态:', status)## 系统特性### 多消费者并发处理+- **3个工作器**:同时处理不同的任务- **错开轮询**:工作器使用不同的轮询间隔,减少数据库竞争- **负载均衡**:自动检测和重启有问题的工作器### 任务优先级+- 优先级范围:0-9(9为最高优先级)- 高优先级任务会被优先处理- 相同优先级按照创建时间排序### 错误处理和重试+- 自动重试机制:任务失败时会自动重试- 可配置重试次数:1-5次- 渐进式退避:重试间隔逐渐增加### 实时监控+- **工作器状态**:查看每个工作器的处理统计- **队列统计**:查看待处理、处理中、已完成、失败的任务数量- **性能指标**:成功率、处理速度、运行时间等@@ -179,18 +186,18 @@ console.log('队列状态:', status)// 在 server/api/photos/process.post.ts 中export default defineEventHandler(async (event) => {const { storageKey } = await readBody(event)-+// 获取工作器池并添加任务const workerPool = (globalThis as any).__workerPoolif (workerPool) {const taskId = await workerPool.addTask({ storageKey },- { priority: 5 } // 用户上传的照片给予中等优先级+ { priority: 5 }, // 用户上传的照片给予中等优先级)-- return {++ return {message: 'Photo processing started',- taskId+ taskId,}}})@@ -205,12 +212,15 @@ import { QueueManager } from '~~/server/services/pipeline-queue'const worker = QueueManager.getInstance('worker-1')// 添加任务-const taskId = await worker.addTask({- storageKey: 'photos/example.jpg'-}, {- priority: 8,- maxAttempts: 5-})+const taskId = await worker.addTask(+ {+ storageKey: 'photos/example.jpg',+ },+ {+ priority: 8,+ maxAttempts: 5,+ },+)```## 配置说明@@ -219,10 +229,10 @@ const taskId = await worker.addTask({```typescriptconst workerPoolConfig = {- workerCount: 3, // 消费者数量- intervalMs: 2000, // 基础轮询间隔- intervalOffset: 667, // 错开时间- enableLoadBalancing: true, // 启用负载均衡- statsReportInterval: 60000, // 统计报告间隔+ workerCount: 3, // 消费者数量+ intervalMs: 2000, // 基础轮询间隔+ intervalOffset: 667, // 错开时间+ enableLoadBalancing: true, // 启用负载均衡+ statsReportInterval: 60000, // 统计报告间隔}-```\ No newline at end of file+```diff --git a/docs/.develop/queue-task-api.md b/docs/.develop/queue-task-api.mdindex 2377da64..bb12d586 100644--- a/docs/.develop/queue-task-api.md+++ b/docs/.develop/queue-task-api.md@@ -9,6 +9,7 @@获取队列中所有任务的列表**响应示例:**+```json[{@@ -32,6 +33,7 @@重试一个指定的失败状态任务。只有状态为 `failed` 的任务才能被重试。**请求体:**+```json{"taskId": 123@@ -39,6 +41,7 @@```**响应示例:**+```json{"success": true,@@ -52,6 +55,7 @@```**错误情况:**+- 404: 任务不存在- 400: 任务不是失败状态@@ -60,16 +64,18 @@批量重试多个失败的任务,或重试所有失败的任务。**请求体:**+```json{- "taskIds": [123, 124, 125], // 可选,指定任务ID列表- "retryAll": false // 可选,是否重试所有失败任务+ "taskIds": [123, 124, 125], // 可选,指定任务ID列表+ "retryAll": false // 可选,是否重试所有失败任务}```**注意:** `taskIds` 和 `retryAll` 必须提供其中一个。**响应示例:**+```json{"success": true,@@ -103,11 +109,13 @@清理已完成和/或失败的任务,可选择性地按时间范围过滤。**查询参数:**+- `includeCompleted` (可选): 是否包含已完成的任务,默认为 "true"-- `includeFailed` (可选): 是否包含失败的任务,默认为 "true"+- `includeFailed` (可选): 是否包含失败的任务,默认为 "true"- `olderThanDays` (可选): 只清理指定天数之前的任务**响应示例:**+```json{"success": true,@@ -131,8 +139,9 @@## 错误处理所有API都遵循统一的错误处理模式:+- 参数验证错误返回 400 状态码-- 资源不存在返回 404 状态码+- 资源不存在返回 404 状态码- 服务器内部错误返回 500 状态码- 错误响应包含 `statusMessage` 字段描述具体错误@@ -142,4 +151,4 @@2. **故障恢复**: 使用 `/task/retry` 或 `/task/retry-batch` 重试失败的任务3. **维护清理**: 使用 `/task/clear` 定期清理已完成的旧任务,保持队列整洁-这些API与现有的队列管理系统完全集成,遵循项目的架构设计原则和代码规范。\ No newline at end of file+这些API与现有的队列管理系统完全集成,遵循项目的架构设计原则和代码规范。diff --git a/docs/.develop/retry-mechanism.md b/docs/.develop/retry-mechanism.mdindex 4a9bc3f4..1d2369af 100644--- a/docs/.develop/retry-mechanism.md+++ b/docs/.develop/retry-mechanism.md@@ -13,7 +13,7 @@ import { withRetry, RetryPresets, RetryConditions } from '../utils/retry'const result = await withRetry(() => someAsyncOperation(),RetryPresets.standard,- logger+ logger,)```@@ -21,12 +21,12 @@ const result = await withRetry(```typescriptconst customOptions = {- maxAttempts: 5, // 最大重试次数- baseDelay: 1000, // 基础延迟时间- maxDelay: 30000, // 最大延迟时间- timeout: 15000, // 操作超时时间+ maxAttempts: 5, // 最大重试次数+ baseDelay: 1000, // 基础延迟时间+ maxDelay: 30000, // 最大延迟时间+ timeout: 15000, // 操作超时时间delayStrategy: 'exponential', // 延迟策略- retryCondition: (error) => !error.message.includes('400')+ retryCondition: (error) => !error.message.includes('400'),}```@@ -59,20 +59,26 @@ export const extractExifData = async (logger?: Logger[keyof Logger],): Promise<NeededExif | null> => {try {- return await withRetry(async () => {- // 核心处理逻辑- const metadata = await sharp(imageBuffer).metadata()- // ... 其他处理- return result- }, {- ...RetryPresets.standard,- timeout: 15000,- retryCondition: (error) => {- return RetryConditions.fileSystemErrors(error) ||- RetryConditions.resourceErrors(error) ||- error.message.includes('timeout')- }- }, logger)+ return await withRetry(+ async () => {+ // 核心处理逻辑+ const metadata = await sharp(imageBuffer).metadata()+ // ... 其他处理+ return result+ },+ {+ ...RetryPresets.standard,+ timeout: 15000,+ retryCondition: (error) => {+ return (+ RetryConditions.fileSystemErrors(error) ||+ RetryConditions.resourceErrors(error) ||+ error.message.includes('timeout')+ )+ },+ },+ logger,+ )} catch (error) {logger?.error('EXIF extraction failed after all retries:', error)return null@@ -87,12 +93,12 @@ async reverseGeocode(lat: number, lon: number): Promise<LocationInfo | null> {try {return await withRetry(async () => {await this.applyRateLimit()-+const response = await fetch(url.toString())if (!response.ok) {throw new Error(`API error: ${response.status}`)}-+return processResponse(response)}, {...RetryPresets.network,@@ -113,35 +119,45 @@ export const generateThumbnailAndHash = async (buffer: Buffer,logger?: Logger[keyof Logger],) => {- return await withRetry(async () => {- const thumbnailBuffer = await sharp(buffer)- .resize(600, null)- .webp({ quality })- .toBuffer()-- const thumbnailHash = await generateBlurHash(thumbnailBuffer, logger)-- return { thumbnailBuffer, thumbnailHash }- }, {- ...RetryPresets.standard,- timeout: 15000,- delayStrategy: 'linear' // 图像处理适合线性退避- }, logger)+ return await withRetry(+ async () => {+ const thumbnailBuffer = await sharp(buffer)+ .resize(600, null)+ .webp({ quality })+ .toBuffer()++ const thumbnailHash = await generateBlurHash(thumbnailBuffer, logger)++ return { thumbnailBuffer, thumbnailHash }+ },+ {+ ...RetryPresets.standard,+ timeout: 15000,+ delayStrategy: 'linear', // 图像处理适合线性退避+ },+ logger,+ )}```## 延迟策略### 指数退避 (Exponential)+适用于网络请求,避免对服务器造成冲击:+- 1s → 2s → 4s → 8s...### 线性增长 (Linear)+适用于资源竞争场景,平缓增加等待时间:+- 1s → 2s → 3s → 4s...### 固定延迟 (Fixed)+适用于已知的固定限制场景:+- 1s → 1s → 1s → 1s...## 最佳实践@@ -180,11 +196,11 @@ retryCondition: () => true // 可能导致无意义的重试```typescript// ✅ 推荐:根据操作复杂度设置超时const options = {- timeout: operation === 'thumbnail' ? 15000 : 5000+ timeout: operation === 'thumbnail' ? 15000 : 5000,}// ❌ 避免:超时时间过短或过长-timeout: 1000 // 太短,可能导致正常操作超时+timeout: 1000 // 太短,可能导致正常操作超时timeout: 300000 // 太长,用户体验差```@@ -218,6 +234,7 @@ await withRetry(operation, options, logger) // 没有错误处理### 性能监控建议添加以下指标监控:+- 重试成功率- 平均重试次数- 重试操作的延迟分布@@ -236,17 +253,13 @@ for (let attempt = 1; attempt <= maxRetries; attempt++) {return result} catch (error) {if (attempt < maxRetries) {- await new Promise(resolve => setTimeout(resolve, 1000 * attempt))+ await new Promise((resolve) => setTimeout(resolve, 1000 * attempt))}}}// 新的实现 ✅-return await withRetry(- () => operation(),- RetryPresets.standard,- logger-)+return await withRetry(() => operation(), RetryPresets.standard, logger)```-这种统一的重试机制设计不仅提高了代码的可维护性,还通过智能的重试条件和延迟策略,显著提升了系统的稳定性和用户体验。\ No newline at end of file+这种统一的重试机制设计不仅提高了代码的可维护性,还通过智能的重试条件和延迟策略,显著提升了系统的稳定性和用户体验。diff --git a/docs/configuration/storage-providers.md b/docs/configuration/storage-providers.mdindex ddb63bda..540022f9 100644--- a/docs/configuration/storage-providers.md+++ b/docs/configuration/storage-providers.md@@ -128,18 +128,18 @@ NUXT_PROVIDER_LOCAL_BASE_URL=/storageOpenList is a file listing program that supports multiple cloud storage services.-| Environment Variable | Type | Required | Default | Description |-|---|---|---|---|---|-| `NUXT_PROVIDER_OPENLIST_BASE_URL` | string | Yes | - | Base URL of the OpenList service |-| `NUXT_PROVIDER_OPENLIST_ROOT_PATH` | string | Yes | - | Root storage path |-| `NUXT_PROVIDER_OPENLIST_TOKEN` | string | Required | - | Authentication token (required for authentication) |-| `NUXT_PROVIDER_OPENLIST_ENDPOINT_UPLOAD` | string | Optional | `/api/fs/put` | Upload endpoint |-| `NUXT_PROVIDER_OPENLIST_ENDPOINT_DOWNLOAD` | string | Optional | - | Download endpoint |-| `NUXT_PROVIDER_OPENLIST_ENDPOINT_LIST` | string | Optional | - | List endpoint |-| `NUXT_PROVIDER_OPENLIST_ENDPOINT_DELETE` | string | Optional | `/api/fs/remove` | Delete endpoint |-| `NUXT_PROVIDER_OPENLIST_ENDPOINT_META` | string | Optional | `/api/fs/get` | Metadata endpoint |-| `NUXT_PROVIDER_OPENLIST_PATH_FIELD` | string | Optional | `path` | Path field name |-| `NUXT_PROVIDER_OPENLIST_CDN_URL` | string | Optional | - | CDN URL |+| Environment Variable | Type | Required | Default | Description |+| ------------------------------------------ | ------ | -------- | ---------------- | -------------------------------------------------- |+| `NUXT_PROVIDER_OPENLIST_BASE_URL` | string | Yes | - | Base URL of the OpenList service |+| `NUXT_PROVIDER_OPENLIST_ROOT_PATH` | string | Yes | - | Root storage path |+| `NUXT_PROVIDER_OPENLIST_TOKEN` | string | Required | - | Authentication token (required for authentication) |+| `NUXT_PROVIDER_OPENLIST_ENDPOINT_UPLOAD` | string | Optional | `/api/fs/put` | Upload endpoint |+| `NUXT_PROVIDER_OPENLIST_ENDPOINT_DOWNLOAD` | string | Optional | - | Download endpoint |+| `NUXT_PROVIDER_OPENLIST_ENDPOINT_LIST` | string | Optional | - | List endpoint |+| `NUXT_PROVIDER_OPENLIST_ENDPOINT_DELETE` | string | Optional | `/api/fs/remove` | Delete endpoint |+| `NUXT_PROVIDER_OPENLIST_ENDPOINT_META` | string | Optional | `/api/fs/get` | Metadata endpoint |+| `NUXT_PROVIDER_OPENLIST_PATH_FIELD` | string | Optional | `path` | Path field name |+| `NUXT_PROVIDER_OPENLIST_CDN_URL` | string | Optional | - | CDN URL |**Authentication:**diff --git a/docs/development/contributing.md b/docs/development/contributing.mdindex 9229a716..4514137b 100644--- a/docs/development/contributing.md+++ b/docs/development/contributing.md@@ -253,7 +253,7 @@ interface Emits {}const props = withDefaults(defineProps<Props>(), {- loading: false+ loading: false,})const emit = defineEmits<Emits>()@@ -349,4 +349,4 @@ Look for Issues labeled with:### Community Resources- [GitHub Issues](https://github.com/HoshinoSuzumi/chronoframe/issues)-- [GitHub Discussions](https://github.com/HoshinoSuzumi/chronoframe/discussions)\ No newline at end of file+- [GitHub Discussions](https://github.com/HoshinoSuzumi/chronoframe/discussions)diff --git a/docs/development/how-to-add-setting.md b/docs/development/how-to-add-setting.mdindex ef313af8..0c33518a 100644--- a/docs/development/how-to-add-setting.md+++ b/docs/development/how-to-add-setting.md@@ -18,12 +18,14 @@```字段说明(必需):+- `namespace`: 设置所属的命名空间 (app, map, location, storage, system 等)- `key`: 字段的唯一键- `type`: 类型 (string, number, boolean 等)- `defaultValue`: 默认值字段说明(可选):+- `isPublic`: 是否公开- `isReadonly`: 是否只读- `isSecret`: 是否为机密字段(如密码)@@ -39,10 +41,10 @@export const APP_SETTINGS_UI: Record<string, FieldUIConfig> = {// ... 其他配置foo: {- type: 'input', // 字段类型:input, password, url, textarea, select, radio, tabs, toggle, number+ type: 'input', // 字段类型:input, password, url, textarea, select, radio, tabs, toggle, numberplaceholder: 'Enter foo value',- help: 'settings.app.foo.help', // 翻译键,可选- required: true, // 是否必需,可选+ help: 'settings.app.foo.help', // 翻译键,可选+ required: true, // 是否必需,可选},}```diff --git a/docs/guide/getting-started.md b/docs/guide/getting-started.mdindex 64e3485e..c5341a4d 100644--- a/docs/guide/getting-started.md+++ b/docs/guide/getting-started.md@@ -210,11 +210,11 @@ services:env_file:- .envlabels:- - "traefik.enable=true"- - "traefik.http.routers.chronoframe.rule=Host(`your-domain.com`)"- - "traefik.http.routers.chronoframe.entrypoints=websecure"- - "traefik.http.routers.chronoframe.tls.certresolver=letsencrypt"- - "traefik.http.services.chronoframe.loadbalancer.server.port=3000"+ - 'traefik.enable=true'+ - 'traefik.http.routers.chronoframe.rule=Host(`your-domain.com`)'+ - 'traefik.http.routers.chronoframe.entrypoints=websecure'+ - 'traefik.http.routers.chronoframe.tls.certresolver=letsencrypt'+ - 'traefik.http.services.chronoframe.loadbalancer.server.port=3000'networks:- traefik@@ -226,6 +226,7 @@ networks:## Common Issues:::details How do I generate a random `NUXT_SESSION_PASSWORD`?+```bash# Linux / macOSopenssl rand -base64 32@@ -233,4 +234,5 @@ openssl rand -base64 32# Windows (PowerShell)[Convert]::ToBase64String((1..32|%{[byte](Get-Random -Max 256)}))```+:::diff --git a/docs/guide/updates.md b/docs/guide/updates.mdindex 028da229..9e491cdf 100644--- a/docs/guide/updates.md+++ b/docs/guide/updates.md@@ -7,6 +7,7 @@ This document will guide you through safely updating and upgrading ChronoFrame t### View Current Version#### Through Web Interface+1. Login to ChronoFrame admin dashboard2. Go to "Dashboard" page3. Check version number in "Runtime Information" panel@@ -16,6 +17,7 @@ This document will guide you through safely updating and upgrading ChronoFrame t### Preparation#### 1. Data Backup+```bash# Stop servicedocker-compose down@@ -25,7 +27,9 @@ ts=$(date +%Y%m%d-%H%M%S) && mkdir -p backups/$ts && cp -r data/ .env docker-com```#### 2. Check Compatibility+Review [Release Notes](https://github.com/HoshinoSuzumi/chronoframe/releases) to understand:+- Breaking changes- New environment variables- Feature deprecation notices@@ -62,7 +66,7 @@ If you need to update to a specific version:# docker-compose.ymlservices:chronoframe:- image: ghcr.io/hoshinosuzumi/chronoframe:v1.2.3 # Specify version+ image: ghcr.io/hoshinosuzumi/chronoframe:v1.2.3 # Specify version# ... other configurations```@@ -110,4 +114,4 @@ docker exec -it chronoframe sh# Execute migrationnpx drizzle-kit migrate-```\ No newline at end of file+```diff --git a/docs/index.md b/docs/index.mdindex a1e7c8b5..00d1ab41 100644--- a/docs/index.md+++ b/docs/index.md@@ -3,13 +3,13 @@layout: homehero:- name: "ChronoFrame"- text: "Self-hosted Personal Gallery"- tagline: "Manage photos online with multi-storage backends, LivePhoto, and globe view"+ name: 'ChronoFrame'+ text: 'Self-hosted Personal Gallery'+ tagline: 'Manage photos online with multi-storage backends, LivePhoto, and globe view'image:src: /logo.pngalt: ChronoFrame- style: "filter: drop-shadow(0 0 30px rgba(168, 85, 247, 0.7)) drop-shadow(0 0 60px rgba(59, 130, 246, 0.5)) drop-shadow(0 0 100px rgba(168, 85, 247, 0.3)); width: 300px; height: 300px;"+ style: 'filter: drop-shadow(0 0 30px rgba(168, 85, 247, 0.7)) drop-shadow(0 0 60px rgba(59, 130, 246, 0.5)) drop-shadow(0 0 100px rgba(168, 85, 247, 0.3)); width: 300px; height: 300px;'actions:- theme: brandtext: Getting Started@@ -40,7 +40,6 @@ features:- title: Live/Motion Photo Supporticon: 🎬details: Full support for Apple LivePhoto format and Google-standard Motion Photo, automatically detect and process MOV video files, preserve dynamic photo effects.----## 🌍 Demo Sitesdiff --git a/docs/zh/configuration/storage-providers.md b/docs/zh/configuration/storage-providers.mdindex 1cca6cf9..81eddc74 100644--- a/docs/zh/configuration/storage-providers.md+++ b/docs/zh/configuration/storage-providers.md@@ -128,18 +128,18 @@ NUXT_PROVIDER_LOCAL_BASE_URL=/storageOpenList 是一个开源的文件管理系统,提供对各种云存储服务的 API 访问。此提供程序允许您使用与 OpenList 兼容的服务作为照片存储后端。-| 环境变量 | 类型 | 必需 | 默认值 | 描述 |-|---|---|---|---|---|-| `NUXT_PROVIDER_OPENLIST_BASE_URL` | string | 是 | - | OpenList 服务的基础 URL |-| `NUXT_PROVIDER_OPENLIST_ROOT_PATH` | string | 是 | - | 根存储路径 |-| `NUXT_PROVIDER_OPENLIST_TOKEN` | string | 必需 | - | 认证令牌(认证时必需) |-| `NUXT_PROVIDER_OPENLIST_ENDPOINT_UPLOAD` | string | 可选 | `/api/fs/put` | 上传端点 |-| `NUXT_PROVIDER_OPENLIST_ENDPOINT_DOWNLOAD` | string | 可选 | - | 下载端点 |-| `NUXT_PROVIDER_OPENLIST_ENDPOINT_LIST` | string | 可选 | - | 列表端点 |-| `NUXT_PROVIDER_OPENLIST_ENDPOINT_DELETE` | string | 可选 | `/api/fs/remove` | 删除端点 |-| `NUXT_PROVIDER_OPENLIST_ENDPOINT_META` | string | 可选 | `/api/fs/get` | 元数据端点 |-| `NUXT_PROVIDER_OPENLIST_PATH_FIELD` | string | 可选 | `path` | 路径字段名 |-| `NUXT_PROVIDER_OPENLIST_CDN_URL` | string | 可选 | - | CDN URL |+| 环境变量 | 类型 | 必需 | 默认值 | 描述 |+| ------------------------------------------ | ------ | ---- | ---------------- | ----------------------- |+| `NUXT_PROVIDER_OPENLIST_BASE_URL` | string | 是 | - | OpenList 服务的基础 URL |+| `NUXT_PROVIDER_OPENLIST_ROOT_PATH` | string | 是 | - | 根存储路径 |+| `NUXT_PROVIDER_OPENLIST_TOKEN` | string | 必需 | - | 认证令牌(认证时必需) |+| `NUXT_PROVIDER_OPENLIST_ENDPOINT_UPLOAD` | string | 可选 | `/api/fs/put` | 上传端点 |+| `NUXT_PROVIDER_OPENLIST_ENDPOINT_DOWNLOAD` | string | 可选 | - | 下载端点 |+| `NUXT_PROVIDER_OPENLIST_ENDPOINT_LIST` | string | 可选 | - | 列表端点 |+| `NUXT_PROVIDER_OPENLIST_ENDPOINT_DELETE` | string | 可选 | `/api/fs/remove` | 删除端点 |+| `NUXT_PROVIDER_OPENLIST_ENDPOINT_META` | string | 可选 | `/api/fs/get` | 元数据端点 |+| `NUXT_PROVIDER_OPENLIST_PATH_FIELD` | string | 可选 | `path` | 路径字段名 |+| `NUXT_PROVIDER_OPENLIST_CDN_URL` | string | 可选 | - | CDN URL |**认证:**@@ -173,6 +173,7 @@ NUXT_PROVIDER_OPENLIST_CDN_URL=```### 配置示例+#### OpenList(理论上Alist也可行)```bashdiff --git a/docs/zh/development/contributing.md b/docs/zh/development/contributing.mdindex a56f636d..4b5e7661 100644--- a/docs/zh/development/contributing.md+++ b/docs/zh/development/contributing.md@@ -253,7 +253,7 @@ interface Emits {}const props = withDefaults(defineProps<Props>(), {- loading: false+ loading: false,})const emit = defineEmits<Emits>()diff --git a/docs/zh/guide/getting-started.md b/docs/zh/guide/getting-started.mdindex 65c5da55..d6dcd58f 100644--- a/docs/zh/guide/getting-started.md+++ b/docs/zh/guide/getting-started.md@@ -28,11 +28,13 @@我们推荐使用预构建的 Docker 镜像进行部署,镜像托管在 GHCR 和 Docker Hub,您可以根据网络情况选择合适的源。#### [GitHub Container Registry (GHCR)](https://github.com/HoshinoSuzumi/chronoframe/pkgs/container/chronoframe)+```bashdocker pull ghcr.io/hoshinosuzumi/chronoframe:latest```#### [Docker Hub](https://hub.docker.com/r/hoshinosuzumi/chronoframe)+```bashdocker pull hoshinosuzumi/chronoframe:latest```@@ -154,7 +156,7 @@ docker compose up -dserver {listen 80;server_name your-domain.com;-+# HTTPS 重定向return 301 https://$server_name$request_uri;}@@ -162,19 +164,19 @@ server {server {listen 443 ssl http2;server_name your-domain.com;-+# SSL 证书配置ssl_certificate /path/to/your/certificate.crt;ssl_certificate_key /path/to/your/private.key;-+# SSL 安全配置ssl_protocols TLSv1.2 TLSv1.3;ssl_ciphers ECDHE-RSA-AES128-GCM-SHA256:ECDHE-RSA-AES256-GCM-SHA384;ssl_prefer_server_ciphers off;-+# 上传大小限制client_max_body_size 100M;-+location / {proxy_pass http://localhost:3000;proxy_http_version 1.1;@@ -185,17 +187,17 @@ server {proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;proxy_set_header X-Forwarded-Proto $scheme;proxy_cache_bypass $http_upgrade;-+# WebSocket 支持proxy_set_header Connection "upgrade";proxy_set_header Upgrade $http_upgrade;-+# 超时设置proxy_connect_timeout 60s;proxy_send_timeout 60s;proxy_read_timeout 60s;}-+# 静态资源缓存location ~* \.(jpg|jpeg|png|gif|webp|svg|css|js|ico|woff|woff2|ttf|eot)$ {proxy_pass http://localhost:3000;@@ -221,11 +223,11 @@ services:env_file:- .envlabels:- - "traefik.enable=true"- - "traefik.http.routers.chronoframe.rule=Host(`your-domain.com`)"- - "traefik.http.routers.chronoframe.entrypoints=websecure"- - "traefik.http.routers.chronoframe.tls.certresolver=letsencrypt"- - "traefik.http.services.chronoframe.loadbalancer.server.port=3000"+ - 'traefik.enable=true'+ - 'traefik.http.routers.chronoframe.rule=Host(`your-domain.com`)'+ - 'traefik.http.routers.chronoframe.entrypoints=websecure'+ - 'traefik.http.routers.chronoframe.tls.certresolver=letsencrypt'+ - 'traefik.http.services.chronoframe.loadbalancer.server.port=3000'networks:- traefik@@ -237,6 +239,7 @@ networks:## 常见问题:::details 如何生成随机的 `NUXT_SESSION_PASSWORD`?+```bash# Linux / macOSopenssl rand -base64 32@@ -244,4 +247,5 @@ openssl rand -base64 32# Windows (pwsh)[Convert]::ToBase64String((1..32|%{[byte](Get-Random -Max 256)}))```+:::diff --git a/docs/zh/guide/updates.md b/docs/zh/guide/updates.mdindex f2190d10..6f8f3cfd 100644--- a/docs/zh/guide/updates.md+++ b/docs/zh/guide/updates.md@@ -7,6 +7,7 @@### 查看当前版本#### 通过 Web 界面+1. 登录 ChronoFrame 管理后台2. 进入「仪表板」页面3. 查看「运行信息」面板中的版本号@@ -16,6 +17,7 @@### 准备工作#### 1. 数据备份+```bash# 停止服务docker-compose down@@ -25,7 +27,9 @@ ts=$(date +%Y%m%d-%H%M%S) && mkdir -p backups/$ts && cp -r data/ .env docker-com```#### 2. 检查兼容性+查看 [发布说明](https://github.com/HoshinoSuzumi/chronoframe/releases) 了解:+- 破坏性变更- 新增环境变量- 功能弃用通知@@ -62,7 +66,7 @@ docker-compose logs -f chronoframe# docker-compose.ymlservices:chronoframe:- image: ghcr.io/hoshinosuzumi/chronoframe:v1.2.3 # 指定版本+ image: ghcr.io/hoshinosuzumi/chronoframe:v1.2.3 # 指定版本# ... 其他配置```@@ -110,4 +114,4 @@ docker exec -it chronoframe sh# 执行迁移npx drizzle-kit migrate-```\ No newline at end of file+```diff --git a/docs/zh/index.md b/docs/zh/index.mdindex a4734e8c..c841e222 100644--- a/docs/zh/index.md+++ b/docs/zh/index.md@@ -3,13 +3,13 @@layout: homehero:- name: "ChronoFrame"- text: "自部署个人画廊"- tagline: "在线管理照片,多存储后端、LivePhoto、地球仪视图"+ name: 'ChronoFrame'+ text: '自部署个人画廊'+ tagline: '在线管理照片,多存储后端、LivePhoto、地球仪视图'image:src: /logo.pngalt: ChronoFrame- style: "filter: drop-shadow(0 0 30px rgba(168, 85, 247, 0.7)) drop-shadow(0 0 60px rgba(59, 130, 246, 0.5)) drop-shadow(0 0 100px rgba(168, 85, 247, 0.3)); width: 300px; height: 300px;"+ style: 'filter: drop-shadow(0 0 30px rgba(168, 85, 247, 0.7)) drop-shadow(0 0 60px rgba(59, 130, 246, 0.5)) drop-shadow(0 0 100px rgba(168, 85, 247, 0.3)); width: 300px; height: 300px;'actions:- theme: brandtext: 快速开始@@ -40,7 +40,6 @@ features:- title: Live/Motion Photo 支持icon: 🎬details: 完整支持 Apple LivePhoto 格式和 Google 标准的 Motion Photo,自动检测和处理 MOV 视频文件,保留动态照片效果。----## 🌍 演示站点diff --git a/drizzle.config.ts b/drizzle.config.tsindex 51142b74..9e1396de 100644--- a/drizzle.config.ts+++ b/drizzle.config.ts@@ -5,6 +5,6 @@ export default defineConfig({schema: './server/database/schema.ts',out: './server/database/migrations',dbCredentials: {- url: 'file:./data/app.sqlite3'- }+ url: 'file:./data/app.sqlite3',+ },})diff --git a/i18n/i18n.config.ts b/i18n/i18n.config.tsindex 3520fcf2..1e2bdd45 100644--- a/i18n/i18n.config.ts+++ b/i18n/i18n.config.ts@@ -3,12 +3,12 @@ export default defineI18nConfig(() => {fallbackLocale: {'zh-CN': ['zh-Hans'],'zh-SG': ['zh-Hans'],- 'zh': ['zh-Hans'],+ zh: ['zh-Hans'],'zh-Hant': ['zh-Hant-TW', 'zh-Hant-HK'],'zh-TW': ['zh-Hant-TW'],'zh-HK': ['zh-Hant-HK'],'zh-MO': ['zh-Hant-HK'],- 'default': ['en'],+ default: ['en'],},}})diff --git a/nuxt.config.ts b/nuxt.config.tsindex 182a25a3..a972f333 100644--- a/nuxt.config.ts+++ b/nuxt.config.ts@@ -45,12 +45,12 @@ export default defineNuxtConfig({map: {provider: 'maplibre' as 'mapbox' | 'maplibre',mapbox: {- style: ''+ style: '',},maplibre: {token: '',style: '',- }+ },},analytics: {matomo: {@@ -102,18 +102,18 @@ export default defineNuxtConfig({pathField: 'path',cdnUrl: '',} as {- baseUrl: string;- rootPath: string;- token: string;+ baseUrl: string+ rootPath: string+ token: stringendpoints: {- upload: string;- download: string;- list: string;- delete: string;- meta: string;- };- pathField: string;- cdnUrl: string;+ upload: string+ download: string+ list: string+ delete: string+ meta: string+ }+ pathField: string+ cdnUrl: string},},upload: {diff --git a/package.json b/package.jsonindex a09a6a2e..da5535f7 100644--- a/package.json+++ b/package.json@@ -126,4 +126,4 @@"sharp"]}-}\ No newline at end of file+}diff --git a/packages/webgl-image/package.json b/packages/webgl-image/package.jsonindex f571ec60..a2d4e1dd 100644--- a/packages/webgl-image/package.json+++ b/packages/webgl-image/package.json@@ -61,4 +61,4 @@"vite-plugin-dts": "^4.0.0","vue-tsc": "^2.0.0"}-}\ No newline at end of file+}diff --git a/packages/webgl-image/src/core/utils.ts b/packages/webgl-image/src/core/utils.tsindex acb5fb67..1d531bd3 100644--- a/packages/webgl-image/src/core/utils.ts+++ b/packages/webgl-image/src/core/utils.ts@@ -83,10 +83,7 @@ export function debounce<T extends (...args: any[]) => any>(let timeoutId: numberreturn (...args: Parameters<T>) => {clearTimeout(timeoutId)- timeoutId = setTimeout(- () => func(...args),- delay,- ) as unknown as number+ timeoutId = setTimeout(() => func(...args), delay) as unknown as number}}diff --git a/packages/webgl-image/src/shaders.ts b/packages/webgl-image/src/shaders.tsindex 8931c5ff..0fee09ef 100644--- a/packages/webgl-image/src/shaders.ts+++ b/packages/webgl-image/src/shaders.ts@@ -65,23 +65,26 @@ export const FRAGMENT_SHADER_SOURCE = `export function createShader(gl: WebGLRenderingContext,type: number,- source: string+ source: string,): WebGLShader | null {const shader = gl.createShader(type)if (!shader) {console.error('Unable to create shader')return null}-+gl.shaderSource(shader, source)gl.compileShader(shader)-+if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {- console.error('An error occurred compiling the shaders:', gl.getShaderInfoLog(shader))+ console.error(+ 'An error occurred compiling the shaders:',+ gl.getShaderInfoLog(shader),+ )gl.deleteShader(shader)return null}-+return shader}@@ -91,23 +94,26 @@ export function createShader(export function createShaderProgram(gl: WebGLRenderingContext,vertexShader: WebGLShader,- fragmentShader: WebGLShader+ fragmentShader: WebGLShader,): WebGLProgram | null {const shaderProgram = gl.createProgram()if (!shaderProgram) {console.error('Unable to create shader program')return null}-+gl.attachShader(shaderProgram, vertexShader)gl.attachShader(shaderProgram, fragmentShader)gl.linkProgram(shaderProgram)-+if (!gl.getProgramParameter(shaderProgram, gl.LINK_STATUS)) {- console.error('Unable to initialize the shader program:', gl.getProgramInfoLog(shaderProgram))+ console.error(+ 'Unable to initialize the shader program:',+ gl.getProgramInfoLog(shaderProgram),+ )return null}-+return shaderProgram}@@ -116,17 +122,21 @@ export function createShaderProgram(*/export function createProgram(gl: WebGLRenderingContext): WebGLProgram | null {const vertexShader = createShader(gl, gl.VERTEX_SHADER, VERTEX_SHADER_SOURCE)- const fragmentShader = createShader(gl, gl.FRAGMENT_SHADER, FRAGMENT_SHADER_SOURCE)-+ const fragmentShader = createShader(+ gl,+ gl.FRAGMENT_SHADER,+ FRAGMENT_SHADER_SOURCE,+ )+if (!vertexShader || !fragmentShader) {return null}-+const program = createShaderProgram(gl, vertexShader, fragmentShader)-+// 清理着色器对象gl.deleteShader(vertexShader)gl.deleteShader(fragmentShader)-+return program}diff --git a/packages/webgl-image/src/workers/image-decoder.worker.js b/packages/webgl-image/src/workers/image-decoder.worker.jsindex a1cf0d43..11b58deb 100644--- a/packages/webgl-image/src/workers/image-decoder.worker.js+++ b/packages/webgl-image/src/workers/image-decoder.worker.js@@ -14,9 +14,14 @@ self.onmessage = async (event) => {try {let src = payload.srctry {- const absolute = new URL(src, self.location?.origin || 'http://localhost')+ const absolute = new URL(+ src,+ self.location?.origin || 'http://localhost',+ )src = absolute.toString()- } catch { /* empty */ }+ } catch {+ /* empty */+ }const response = await fetch(src, { mode: 'cors' })if (!response.ok) {throw new Error(`Failed to fetch image: ${response.status}`)diff --git a/packages/webgl-image/tsconfig.json b/packages/webgl-image/tsconfig.jsonindex fcdc4fe4..248908c4 100644--- a/packages/webgl-image/tsconfig.json+++ b/packages/webgl-image/tsconfig.json@@ -2,11 +2,7 @@"compilerOptions": {"target": "ES2020","module": "ESNext",- "lib": [- "ES2020",- "DOM",- "DOM.Iterable"- ],+ "lib": ["ES2020", "DOM", "DOM.Iterable"],"moduleResolution": "bundler","resolveJsonModule": true,"allowImportingTsExtensions": true,@@ -24,21 +20,10 @@"ignoreDeprecations": "6.0","baseUrl": ".","paths": {- "@/*": [- "src/*"- ]+ "@/*": ["src/*"]},- "types": [- "vite/client"- ]+ "types": ["vite/client"]},- "include": [- "src/**/*",- "vite.config.ts"- ],- "exclude": [- "node_modules",- "dist",- "tests"- ]-}\ No newline at end of file+ "include": ["src/**/*", "vite.config.ts"],+ "exclude": ["node_modules", "dist", "tests"]+}diff --git a/packages/webgl-image/vite.config.ts b/packages/webgl-image/vite.config.tsindex 3160a500..6d87629c 100644--- a/packages/webgl-image/vite.config.ts+++ b/packages/webgl-image/vite.config.ts@@ -19,7 +19,7 @@ export default defineConfig({copyDtsFiles: true,}),],-+build: {lib: {entry: {@@ -34,13 +34,9 @@ export default defineConfig({return `${entryName}.${ext}`},},-+rollupOptions: {- external: [- 'vue',- '@vue/runtime-core',- '@vue/shared',- ],+ external: ['vue', '@vue/runtime-core', '@vue/shared'],output: {globals: {vue: 'Vue',@@ -50,24 +46,24 @@ export default defineConfig({manualChunks: undefined,},},-+target: 'esnext',minify: true,emptyOutDir: true,-+cssCodeSplit: false,},-+resolve: {alias: {'@': resolve(__dirname, 'src'),},},-+optimizeDeps: {include: ['vue'],},-+define: {'process.env.NODE_ENV': '"production"',},diff --git a/public/site.webmanifest b/public/site.webmanifestindex ccf313a3..981d97f1 100755--- a/public/site.webmanifest+++ b/public/site.webmanifest@@ -18,4 +18,4 @@"theme_color": "#ffffff","background_color": "#ffffff","display": "standalone"-}\ No newline at end of file+}diff --git a/server/api/logout.get.ts b/server/api/logout.get.tsindex 93c563cc..4b5cdbed 100644--- a/server/api/logout.get.ts+++ b/server/api/logout.get.ts@@ -1,3 +1,3 @@export default eventHandler(async (event) => {await clearUserSession(event)-})\ No newline at end of file+})diff --git a/server/api/photos/[photoId]/livephoto.get.ts b/server/api/photos/[photoId]/livephoto.get.tsindex 2646ee10..677cc699 100644--- a/server/api/photos/[photoId]/livephoto.get.ts+++ b/server/api/photos/[photoId]/livephoto.get.ts@@ -2,9 +2,9 @@ import { eq } from 'drizzle-orm'export default eventHandler(async (event) => {await requireUserSession(event)-+const photoId = getRouterParam(event, 'photoId')-+if (!photoId) {throw createError({statusCode: 400,@@ -14,23 +14,23 @@ export default eventHandler(async (event) => {try {const db = useDB()-+// 查询照片信息const photos = await db.select().from(tables.photos).where(eq(tables.photos.id, photoId)).limit(1)-+if (photos.length === 0) {throw createError({statusCode: 404,statusMessage: 'Photo not found',})}-+const photo = photos[0]-+return {id: photo.id,title: photo.title,diff --git a/server/api/photos/[photoId]/reactions.ts b/server/api/photos/[photoId]/reactions.tsindex c0fed731..57e60488 100644--- a/server/api/photos/[photoId]/reactions.ts+++ b/server/api/photos/[photoId]/reactions.ts@@ -1,7 +1,16 @@import type { H3Event } from 'h3'import { eq, and, sql } from 'drizzle-orm'-const REACTION_TYPES = ['like', 'love', 'amazing', 'funny', 'wow', 'sad', 'fire', 'sparkle'] as const+const REACTION_TYPES = [+ 'like',+ 'love',+ 'amazing',+ 'funny',+ 'wow',+ 'sad',+ 'fire',+ 'sparkle',+] as constconst RATE_LIMIT_WINDOW = 60 * 1000 // 1分钟const MAX_REACTIONS_PER_WINDOW = 10 // 每分钟最多10次表态@@ -12,10 +21,10 @@ function generateFingerprint(event: H3Event): string {const userAgent = headers['user-agent'] || 'unknown'const acceptLanguage = headers['accept-language'] || 'unknown'const acceptEncoding = headers['accept-encoding'] || 'unknown'-+// 组合多个特征const fingerprint = `${ip}|${userAgent}|${acceptLanguage}|${acceptEncoding}`-+// 使用简单的哈希return Buffer.from(fingerprint).toString('base64')}@@ -25,34 +34,34 @@ async function checkRateLimit(fingerprint: string): Promise<boolean> {const db = useDB()const now = Date.now()const windowStart = new Date(now - RATE_LIMIT_WINDOW)-+const recentReactions = await db.select({ count: sql<number>`count(*)` }).from(tables.photoReactions).where(and(eq(tables.photoReactions.fingerprint, fingerprint),- sql`${tables.photoReactions.createdAt} > ${Math.floor(windowStart.getTime() / 1000)}`- )+ sql`${tables.photoReactions.createdAt} > ${Math.floor(windowStart.getTime() / 1000)}`,+ ),).get()-+return (recentReactions?.count || 0) < MAX_REACTIONS_PER_WINDOW}export default defineEventHandler(async (event) => {const photoId = getRouterParam(event, 'photoId')-+if (!photoId) {throw createError({statusCode: 400,message: 'Photo ID is required',})}-+const db = useDB()const method = event.method-+// GET: 获取照片的表态统计if (method === 'GET') {const reactions = await db@@ -64,7 +73,7 @@ export default defineEventHandler(async (event) => {.where(eq(tables.photoReactions.photoId, photoId)).groupBy(tables.photoReactions.reactionType).all()-+// 获取当前用户的表态const fingerprint = generateFingerprint(event)const userReaction = await db@@ -73,44 +82,44 @@ export default defineEventHandler(async (event) => {.where(and(eq(tables.photoReactions.photoId, photoId),- eq(tables.photoReactions.fingerprint, fingerprint)- )+ eq(tables.photoReactions.fingerprint, fingerprint),+ ),).get()-+// 格式化返回数据const reactionCounts: Record<string, number> = {}for (const type of REACTION_TYPES) {reactionCounts[type] = 0}-+reactions.forEach((r) => {if (r.reactionType) {reactionCounts[r.reactionType] = r.count}})-+return {photoId,reactions: reactionCounts,userReaction: userReaction?.reactionType || null,}}-+// POST: 添加或更新表态if (method === 'POST') {const body = await readBody(event)const { reactionType } = body-+if (!reactionType || !REACTION_TYPES.includes(reactionType)) {throw createError({statusCode: 400,message: 'Invalid reaction type',})}-+const fingerprint = generateFingerprint(event)-+// 检查速率限制const canReact = await checkRateLimit(fingerprint)if (!canReact) {@@ -119,26 +128,26 @@ export default defineEventHandler(async (event) => {message: 'Too many reactions. Please try again later.',})}-+// 检查照片是否存在const photo = await db.select().from(tables.photos).where(eq(tables.photos.id, photoId)).get()-+if (!photo) {throw createError({statusCode: 404,message: 'Photo not found',})}-+// 获取额外信息用于审计const headers = getHeaders(event)const ipAddress = getRequestIP(event, { xForwardedFor: true })const userAgent = headers['user-agent']-+// 检查用户是否已经对该照片表态const existingReaction = await db.select()@@ -146,11 +155,11 @@ export default defineEventHandler(async (event) => {.where(and(eq(tables.photoReactions.photoId, photoId),- eq(tables.photoReactions.fingerprint, fingerprint)- )+ eq(tables.photoReactions.fingerprint, fingerprint),+ ),).get()-+if (existingReaction) {// 更新现有表态await db@@ -160,7 +169,7 @@ export default defineEventHandler(async (event) => {updatedAt: new Date(),}).where(eq(tables.photoReactions.id, existingReaction.id))-+return {success: true,action: 'updated',@@ -168,16 +177,14 @@ export default defineEventHandler(async (event) => {}} else {// 创建新表态- await db- .insert(tables.photoReactions)- .values({- photoId,- reactionType,- fingerprint,- ipAddress,- userAgent,- })-+ await db.insert(tables.photoReactions).values({+ photoId,+ reactionType,+ fingerprint,+ ipAddress,+ userAgent,+ })+return {success: true,action: 'created',@@ -185,39 +192,39 @@ export default defineEventHandler(async (event) => {}}}-+// DELETE: 删除表态if (method === 'DELETE') {const fingerprint = generateFingerprint(event)-+const existingReaction = await db.select().from(tables.photoReactions).where(and(eq(tables.photoReactions.photoId, photoId),- eq(tables.photoReactions.fingerprint, fingerprint)- )+ eq(tables.photoReactions.fingerprint, fingerprint),+ ),).get()-+if (!existingReaction) {throw createError({statusCode: 404,message: 'Reaction not found',})}-+await db.delete(tables.photoReactions).where(eq(tables.photoReactions.id, existingReaction.id))-+return {success: true,action: 'deleted',}}-+throw createError({statusCode: 405,message: 'Method not allowed',diff --git a/server/api/photos/check-duplicate.post.ts b/server/api/photos/check-duplicate.post.tsindex c596aac6..16e4d6da 100644--- a/server/api/photos/check-duplicate.post.ts+++ b/server/api/photos/check-duplicate.post.ts@@ -26,7 +26,9 @@ export default defineEventHandler(async (event) => {statusMessage: t('upload.error.required.title'),data: {title: t('upload.error.required.title'),- message: t('upload.error.required.message', { field: 'fileNames or storageKeys' }),+ message: t('upload.error.required.message', {+ field: 'fileNames or storageKeys',+ }),},})}@@ -99,7 +101,7 @@ export default defineEventHandler(async (event) => {}}- const duplicatesFound = results.filter(r => r.exists).length+ const duplicatesFound = results.filter((r) => r.exists).lengthreturn {success: true,@@ -107,9 +109,9 @@ export default defineEventHandler(async (event) => {duplicatesFound,summary: {title: t('upload.success.check.title'),- message: t('upload.success.check.message', {- total: results.length,- duplicates: duplicatesFound+ message: t('upload.success.check.message', {+ total: results.length,+ duplicates: duplicatesFound,}),},}diff --git a/server/api/photos/index.post.ts b/server/api/photos/index.post.tsindex b584b022..ae84047d 100644--- a/server/api/photos/index.post.ts+++ b/server/api/photos/index.post.ts@@ -3,10 +3,7 @@ import { useStorageProvider } from '~~/server/utils/useStorageProvider'import { eq } from 'drizzle-orm'import { generateSafePhotoId } from '~~/server/utils/file-utils'-const VIDEO_EXTENSIONS = new Set([- '.mov',- '.mp4',-])+const VIDEO_EXTENSIONS = new Set(['.mov', '.mp4'])const IMAGE_EXTENSIONS = new Set(['.avif',@@ -22,7 +19,10 @@ const IMAGE_EXTENSIONS = new Set(['.webp',])-const isVideoFile = (fileName: string, contentType?: string | null): boolean => {+const isVideoFile = (+ fileName: string,+ contentType?: string | null,+): boolean => {if (contentType?.toLowerCase().startsWith('video/')) {return true}@@ -82,7 +82,11 @@ export default eventHandler(async (event) => {.where(eq(tables.photos.id, photoId)).get()- if (existingPhoto && isVideoUpload && isLikelyImageKey(existingPhoto.storageKey)) {+ if (+ existingPhoto &&+ isVideoUpload &&+ isLikelyImageKey(existingPhoto.storageKey)+ ) {existingPhoto = null}diff --git a/server/api/photos/livephoto/manage.post.ts b/server/api/photos/livephoto/manage.post.tsindex 17b9f0f1..32a00b87 100644--- a/server/api/photos/livephoto/manage.post.ts+++ b/server/api/photos/livephoto/manage.post.ts@@ -22,7 +22,8 @@ export default eventHandler(async (event) => {try {switch (action) {- case 'scan': { // 扫描现有文件+ case 'scan': {+ // 扫描现有文件const scanResults = await scanAndProcessExistingLivePhotos()return {message: 'Scan completed',@@ -30,7 +31,8 @@ export default eventHandler(async (event) => {}}- case 'detect': { // 批量检测现有照片的 LivePhoto 视频+ case 'detect': {+ // 批量检测现有照片的 LivePhoto 视频const results = await batchTestLivePhotoDetection(photoIds)return {message: 'Batch LivePhoto detection completed',@@ -38,7 +40,8 @@ export default eventHandler(async (event) => {}}- case 'process': { // 处理特定文件+ case 'process': {+ // 处理特定文件if (!videoKey) {throw createError({statusCode: 400,@@ -56,8 +59,7 @@ export default eventHandler(async (event) => {}}- case 'update-photo': // 为特定照片检查和更新 LivePhoto 状态- {+ case 'update-photo': { // 为特定照片检查和更新 LivePhoto 状态if (!photoId) {throw createError({statusCode: 400,diff --git a/server/api/photos/reactions.get.ts b/server/api/photos/reactions.get.tsindex bb5106fc..60b3666b 100644--- a/server/api/photos/reactions.get.ts+++ b/server/api/photos/reactions.get.ts@@ -3,37 +3,37 @@ import { sql, inArray } from 'drizzle-orm'export default defineEventHandler(async (event) => {const query = getQuery(event)const photoIds = query.ids-+if (!photoIds) {throw createError({statusCode: 400,message: 'Photo IDs are required',})}-+// 支持单个或多个 IDconst ids = Array.isArray(photoIds) ? photoIds : [photoIds]-+if (ids.length === 0) {return {}}-+const db = useDB()-+// 获取所有照片的表态统计const reactions = db.select({photoId: tables.photoReactions.photoId,reactionType: tables.photoReactions.reactionType,- count: sql<number> `count(*)`,+ count: sql<number>`count(*)`,}).from(tables.photoReactions).where(inArray(tables.photoReactions.photoId, ids as string[])).groupBy(tables.photoReactions.photoId, tables.photoReactions.reactionType).all()-+const result: Record<string, Record<string, number>> = {}-+ids.forEach((id) => {result[id as string] = {like: 0,@@ -46,13 +46,13 @@ export default defineEventHandler(async (event) => {sparkle: 0,}})-+// 填充实际的计数reactions.forEach((r) => {if (r.photoId && r.reactionType) {result[r.photoId][r.reactionType] = r.count}})-+return result})diff --git a/server/api/photos/status.get.ts b/server/api/photos/status.get.tsindex f09fae81..e6b44531 100644--- a/server/api/photos/status.get.ts+++ b/server/api/photos/status.get.ts@@ -2,9 +2,9 @@ import { photos } from '~~/server/database/schema'export default eventHandler(async (event) => {await requireUserSession(event)-+const method = getMethod(event)-+if (method === 'GET') {// 获取最新处理完成的照片const recentPhotos = await useDB()@@ -13,10 +13,10 @@ export default eventHandler(async (event) => {.orderBy(photos.lastModified).limit(10).all()-+return {recentPhotos,- timestamp: new Date().toISOString()+ timestamp: new Date().toISOString(),}} else {throw createError({diff --git a/server/api/photos/upload.put.ts b/server/api/photos/upload.put.tsindex f275c867..7ac369b6 100644--- a/server/api/photos/upload.put.ts+++ b/server/api/photos/upload.put.ts@@ -19,18 +19,22 @@ export default eventHandler(async (event) => {})}- const contentType = getHeader(event, 'content-type') || 'application/octet-stream'-+ const contentType =+ getHeader(event, 'content-type') || 'application/octet-stream'+// MIME 类型白名单验证(可通过环境变量配置)const config = useRuntimeConfig(event)const whitelistEnabled = config.upload.mime.whitelistEnabled-+if (whitelistEnabled) {const whitelistStr = config.upload.mime.whitelistconst allowedTypes = whitelistStr- ? whitelistStr.split(',').map((type: string) => type.trim()).filter(Boolean)+ ? whitelistStr+ .split(',')+ .map((type: string) => type.trim())+ .filter(Boolean): []-+if (allowedTypes.length > 0 && !allowedTypes.includes(contentType)) {throw createError({statusCode: 415,@@ -38,12 +42,14 @@ export default eventHandler(async (event) => {data: {title: t('upload.error.invalidType.title'),message: t('upload.error.invalidType.message', { type: contentType }),- suggestion: t('upload.error.invalidType.suggestion', { allowed: allowedTypes.join(', ') }),+ suggestion: t('upload.error.invalidType.suggestion', {+ allowed: allowedTypes.join(', '),+ }),},})}}-+// 使用流式处理而不是一次性读取整个文件到内存const raw = await readRawBody(event, false)if (!raw || !(raw instanceof Buffer)) {@@ -56,7 +62,7 @@ export default eventHandler(async (event) => {},})}-+// 简单大小限制(例如 128MB)const maxBytes = 128 * 1024 * 1024if (raw.byteLength > maxBytes) {@@ -88,4 +94,3 @@ export default eventHandler(async (event) => {return { ok: true, key }})-diff --git a/server/api/queue/task/clear.delete.ts b/server/api/queue/task/clear.delete.tsindex 2c7ae124..3ac51e75 100644--- a/server/api/queue/task/clear.delete.ts+++ b/server/api/queue/task/clear.delete.ts@@ -12,12 +12,14 @@ export default defineEventHandler(async (event) => {const {includeCompleted = 'true',includeFailed = 'true',- olderThanDays- } = await z.object({- includeCompleted: z.string().optional().default('true'),- includeFailed: z.string().optional().default('true'),- olderThanDays: z.string().optional()- }).parseAsync(query)+ olderThanDays,+ } = await z+ .object({+ includeCompleted: z.string().optional().default('true'),+ includeFailed: z.string().optional().default('true'),+ olderThanDays: z.string().optional(),+ })+ .parseAsync(query)const shouldIncludeCompleted = includeCompleted === 'true'const shouldIncludeFailed = includeFailed === 'true'@@ -25,7 +27,8 @@ export default defineEventHandler(async (event) => {if (!shouldIncludeCompleted && !shouldIncludeFailed) {throw createError({statusCode: 400,- statusMessage: 'At least one of includeCompleted or includeFailed must be true'+ statusMessage:+ 'At least one of includeCompleted or includeFailed must be true',})}@@ -48,13 +51,15 @@ export default defineEventHandler(async (event) => {if (isNaN(daysThreshold) || daysThreshold < 0) {throw createError({statusCode: 400,- statusMessage: 'olderThanDays must be a non-negative integer'+ statusMessage: 'olderThanDays must be a non-negative integer',})}- const thresholdTimestamp = Math.floor((Date.now() - daysThreshold * 24 * 60 * 60 * 1000) / 1000)+ const thresholdTimestamp = Math.floor(+ (Date.now() - daysThreshold * 24 * 60 * 60 * 1000) / 1000,+ )const timeCondition = sql`${tables.pipelineQueue.createdAt} < ${thresholdTimestamp}`-+whereCondition = sql`(${whereCondition}) AND ${timeCondition}`}@@ -64,7 +69,7 @@ export default defineEventHandler(async (event) => {id: tables.pipelineQueue.id,status: tables.pipelineQueue.status,payload: tables.pipelineQueue.payload,- createdAt: tables.pipelineQueue.createdAt+ createdAt: tables.pipelineQueue.createdAt,}).from(tables.pipelineQueue).where(whereCondition)@@ -76,21 +81,22 @@ export default defineEventHandler(async (event) => {deletedCount: 0,breakdown: {completed: 0,- failed: 0- }+ failed: 0,+ },}}// 执行删除操作- await db- .delete(tables.pipelineQueue)- .where(whereCondition)+ await db.delete(tables.pipelineQueue).where(whereCondition)// 统计删除的任务- const breakdown = tasksToDelete.reduce((acc, task) => {- acc[task.status] = (acc[task.status] || 0) + 1- return acc- }, {} as Record<string, number>)+ const breakdown = tasksToDelete.reduce(+ (acc, task) => {+ acc[task.status] = (acc[task.status] || 0) + 1+ return acc+ },+ {} as Record<string, number>,+ )return {success: true,@@ -98,24 +104,26 @@ export default defineEventHandler(async (event) => {deletedCount: tasksToDelete.length,breakdown: {completed: breakdown.completed || 0,- failed: breakdown.failed || 0+ failed: breakdown.failed || 0,},...(olderThanDays && {filter: {olderThanDays: parseInt(olderThanDays),- thresholdDate: new Date(Date.now() - parseInt(olderThanDays) * 24 * 60 * 60 * 1000).toISOString()- }- })+ thresholdDate: new Date(+ Date.now() - parseInt(olderThanDays) * 24 * 60 * 60 * 1000,+ ).toISOString(),+ },+ }),}} catch (error) {if (error && typeof error === 'object' && 'statusCode' in error) {throw error}-+console.error('Failed to clear tasks:', error)throw createError({statusCode: 500,- statusMessage: 'Failed to clear tasks'+ statusMessage: 'Failed to clear tasks',})}-})\ No newline at end of file+})diff --git a/server/api/queue/task/list.get.ts b/server/api/queue/task/list.get.tsindex bd6d25b0..6529554c 100644--- a/server/api/queue/task/list.get.ts+++ b/server/api/queue/task/list.get.ts@@ -9,12 +9,11 @@ export default defineEventHandler(async (event) => {try {const query = getQuery(event)- const {- status,- type,- } = await z+ const { status, type } = await z.object({- status: z.enum(['pending', 'in-stages', 'completed', 'failed']).optional(),+ status: z+ .enum(['pending', 'in-stages', 'completed', 'failed'])+ .optional(),type: z.enum(['photo', 'live-photo-video', 'photo-reverse-geocoding']).optional(),@@ -25,17 +24,20 @@ export default defineEventHandler(async (event) => {// 构建查询条件const conditions = []-+if (status) {conditions.push(eq(tables.pipelineQueue.status, status))}-+if (type) {- conditions.push(eq(sql`json_extract(${tables.pipelineQueue.payload}, '$.type')`, type))+ conditions.push(+ eq(sql`json_extract(${tables.pipelineQueue.payload}, '$.type')`, type),+ )}- const whereCondition = conditions.length > 0 ? and(...conditions) : undefined-+ const whereCondition =+ conditions.length > 0 ? and(...conditions) : undefined+// 构建查询const queryBuilder = db.select({diff --git a/server/api/queue/task/retry-batch.post.ts b/server/api/queue/task/retry-batch.post.tsindex d771d904..64a5ec3b 100644--- a/server/api/queue/task/retry-batch.post.ts+++ b/server/api/queue/task/retry-batch.post.ts@@ -12,14 +12,14 @@ export default defineEventHandler(async (event) => {event,z.object({taskIds: z.array(z.number().int().positive()).optional(),- retryAll: z.boolean().optional().default(false)- }).parse+ retryAll: z.boolean().optional().default(false),+ }).parse,)if (!retryAll && (!taskIds || taskIds.length === 0)) {throw createError({statusCode: 400,- statusMessage: 'Either taskIds array or retryAll flag must be provided'+ statusMessage: 'Either taskIds array or retryAll flag must be provided',})}@@ -38,22 +38,24 @@ export default defineEventHandler(async (event) => {.from(tables.pipelineQueue).where(whereCondition)- const failedTasks = tasksToRetry.filter(task => task.status === 'failed')-+ const failedTasks = tasksToRetry.filter((task) => task.status === 'failed')+if (failedTasks.length === 0) {return {success: true,message: 'No failed tasks found to retry',retriedCount: 0,- skippedCount: retryAll ? 0 : (taskIds?.length || 0)+ skippedCount: retryAll ? 0 : taskIds?.length || 0,}}- const nonFailedTasks = tasksToRetry.filter(task => task.status !== 'failed')+ const nonFailedTasks = tasksToRetry.filter(+ (task) => task.status !== 'failed',+ )// 批量重置失败任务的状态- const failedTaskIds = failedTasks.map(task => task.id)-+ const failedTaskIds = failedTasks.map((task) => task.id)+await db.update(tables.pipelineQueue).set({@@ -61,7 +63,7 @@ export default defineEventHandler(async (event) => {statusStage: null,errorMessage: null,attempts: 0, // 重置尝试次数- createdAt: new Date() // 更新创建时间以便重新调度+ createdAt: new Date(), // 更新创建时间以便重新调度}).where(inArray(tables.pipelineQueue.id, failedTaskIds))@@ -70,26 +72,26 @@ export default defineEventHandler(async (event) => {message: `Successfully reset ${failedTasks.length} failed tasks for retry`,retriedCount: failedTasks.length,skippedCount: nonFailedTasks.length,- retriedTasks: failedTasks.map(task => ({+ retriedTasks: failedTasks.map((task) => ({id: task.id,type: task.payload.type,- storageKey: task.payload.storageKey+ storageKey: task.payload.storageKey,})),- skippedTasks: nonFailedTasks.map(task => ({+ skippedTasks: nonFailedTasks.map((task) => ({id: task.id,status: task.status,- reason: `Task is not in failed status (current: ${task.status})`- }))+ reason: `Task is not in failed status (current: ${task.status})`,+ })),}} catch (error) {if (error && typeof error === 'object' && 'statusCode' in error) {throw error}-+console.error('Failed to batch retry tasks:', error)throw createError({statusCode: 500,- statusMessage: 'Failed to batch retry tasks'+ statusMessage: 'Failed to batch retry tasks',})}-})\ No newline at end of file+})diff --git a/server/api/queue/task/retry.post.ts b/server/api/queue/task/retry.post.tsindex 2816284f..f4478b87 100644--- a/server/api/queue/task/retry.post.ts+++ b/server/api/queue/task/retry.post.ts@@ -11,8 +11,8 @@ export default defineEventHandler(async (event) => {const { taskId } = await readValidatedBody(event,z.object({- taskId: z.number().int().positive()- }).parse+ taskId: z.number().int().positive(),+ }).parse,)const db = useDB()@@ -27,14 +27,14 @@ export default defineEventHandler(async (event) => {if (!task) {throw createError({statusCode: 404,- statusMessage: 'Task not found'+ statusMessage: 'Task not found',})}if (task.status !== 'failed') {throw createError({statusCode: 400,- statusMessage: `Task is not in failed status, current status: ${task.status}`+ statusMessage: `Task is not in failed status, current status: ${task.status}`,})}@@ -46,7 +46,7 @@ export default defineEventHandler(async (event) => {statusStage: null,errorMessage: null,attempts: 0, // 重置尝试次数- createdAt: new Date() // 更新创建时间以便重新调度+ createdAt: new Date(), // 更新创建时间以便重新调度}).where(eq(tables.pipelineQueue.id, taskId))@@ -56,18 +56,18 @@ export default defineEventHandler(async (event) => {taskId,payload: {type: task.payload.type,- storageKey: task.payload.storageKey- }+ storageKey: task.payload.storageKey,+ },}} catch (error) {if (error && typeof error === 'object' && 'statusCode' in error) {throw error}-+console.error('Failed to retry task:', error)throw createError({statusCode: 500,- statusMessage: 'Failed to retry task'+ statusMessage: 'Failed to retry task',})}-})\ No newline at end of file+})diff --git a/server/api/system/logs.ts b/server/api/system/logs.tsindex 88be11a2..ab6181c1 100644--- a/server/api/system/logs.ts+++ b/server/api/system/logs.ts@@ -7,7 +7,7 @@ export default defineEventHandler(async (event) => {const eventStream = createEventStream(event)const logFilePath = path.join(process.cwd(), 'data', 'logs', 'app.log')-+// 跟踪已发送的日志行数,避免重复推送let lastSentLineCount = 0@@ -16,15 +16,20 @@ export default defineEventHandler(async (event) => {// 发送现有日志if (fs.existsSync(logFilePath)) {const logContent = fs.readFileSync(logFilePath, 'utf-8')- const recentLogs = logContent.split('\n').filter(line => line.trim()).slice(-512)-- const validLines = recentLogs.filter(line => line.trim())+ const recentLogs = logContent+ .split('\n')+ .filter((line) => line.trim())+ .slice(-512)++ const validLines = recentLogs.filter((line) => line.trim())for (const line of validLines) {await eventStream.push(line)- await new Promise(resolve => setTimeout(resolve, 15))+ await new Promise((resolve) => setTimeout(resolve, 15))}-- lastSentLineCount = logContent.split('\n').filter(line => line.trim()).length++ lastSentLineCount = logContent+ .split('\n')+ .filter((line) => line.trim()).length}} catch (error) {console.error('Error initializing log stream:', error)@@ -34,19 +39,19 @@ export default defineEventHandler(async (event) => {const listener = async () => {if (fs.existsSync(logFilePath)) {const logContent = fs.readFileSync(logFilePath, 'utf-8')- const allLines = logContent.split('\n').filter(line => line.trim())+ const allLines = logContent.split('\n').filter((line) => line.trim())const currentLineCount = allLines.length-+// 只推送新增的日志行if (currentLineCount > lastSentLineCount) {const newLines = allLines.slice(lastSentLineCount)-+for (const line of newLines) {if (line.trim()) {await eventStream.push(line)}}-+lastSentLineCount = currentLineCount}}diff --git a/server/api/system/settings/batch.put.ts b/server/api/system/settings/batch.put.tsindex 1c6434c8..715b34c9 100644--- a/server/api/system/settings/batch.put.ts+++ b/server/api/system/settings/batch.put.ts@@ -34,17 +34,15 @@ export default eventHandler(async (event) => {const body = await readValidatedBody(event,- z- .object({- updates: z.array(- z.object({- namespace: z.enum([...settingNamespaces]),- key: z.enum([...settingKeys]),- value: z.any(),- }),- ),- })- .parse,+ z.object({+ updates: z.array(+ z.object({+ namespace: z.enum([...settingNamespaces]),+ key: z.enum([...settingKeys]),+ value: z.any(),+ }),+ ),+ }).parse,)try {diff --git a/server/api/system/settings/fields.get.ts b/server/api/system/settings/fields.get.tsindex fff19cf7..9662fefd 100644--- a/server/api/system/settings/fields.get.ts+++ b/server/api/system/settings/fields.get.ts@@ -16,11 +16,9 @@ import type { SettingsFieldsResponse } from '~~/shared/types/settings'export default eventHandler(async (event) => {const query = await getValidatedQuery(event,- z- .object({- namespace: z.string().min(1),- })- .parse,+ z.object({+ namespace: z.string().min(1),+ }).parse,)const session = await requireUserSession(event)@@ -69,7 +67,8 @@ export default eventHandler(async (event) => {}throw createError({statusCode: 500,- statusMessage: (error as Error).message || 'Failed to fetch settings fields',+ statusMessage:+ (error as Error).message || 'Failed to fetch settings fields',})}})diff --git a/server/api/system/stats.get.ts b/server/api/system/stats.get.tsindex 541b713f..ac4bcb42 100644--- a/server/api/system/stats.get.ts+++ b/server/api/system/stats.get.ts@@ -89,17 +89,17 @@ async function getMemoryStats() {// 系统信息映射函数function mapSystemInfo(distribution: string): string {if (!distribution) return 'unknown'-+// 转换为小写以便匹配const distro = distribution.toLowerCase()-+// Windows 系统映射if (distro.includes('windows') || distro.includes('microsoft')) {if (distro.includes('11')) return 'windows11'if (distro.includes('10')) return 'windows10'return 'windows'}-+// Linux 发行版映射if (distro.includes('ubuntu')) return 'ubuntu'if (distro.includes('debian')) return 'debian'@@ -109,10 +109,10 @@ function mapSystemInfo(distribution: string): string {if (distro.includes('arch')) return 'arch'if (distro.includes('alpine')) return 'alpine'if (distro.includes('suse') || distro.includes('opensuse')) return 'opensuse'-+// macOS 系统映射if (distro.includes('macos') || distro.includes('darwin')) return 'macos'-+// 其他情况返回原始值(处理未知系统)return 'unknown'}diff --git a/server/api/wizard/admin.post.ts b/server/api/wizard/admin.post.tsindex fd21123c..9c700797 100644--- a/server/api/wizard/admin.post.ts+++ b/server/api/wizard/admin.post.ts@@ -20,31 +20,35 @@ export default eventHandler(async (event) => {// Or throw error.// Let's throw error for now to be safe, or maybe just allow updating the first user if it matches.if (existingUser.email === email) {- // Update existing- await db.update(tables.users)- .set({- password: await hashPassword(password),- username,- isAdmin: 1- })- .where(eq(tables.users.id, existingUser.id))- .run()- return { success: true }+ // Update existing+ await db+ .update(tables.users)+ .set({+ password: await hashPassword(password),+ username,+ isAdmin: 1,+ })+ .where(eq(tables.users.id, existingUser.id))+ .run()+ return { success: true }}-+throw createError({statusCode: 400,message: 'User already exists',})}- await db.insert(tables.users).values({- email,- username,- password: await hashPassword(password),- isAdmin: 1,- createdAt: new Date(),- }).run()+ await db+ .insert(tables.users)+ .values({+ email,+ username,+ password: await hashPassword(password),+ isAdmin: 1,+ createdAt: new Date(),+ })+ .run()return { success: true }})diff --git a/server/api/wizard/map.post.ts b/server/api/wizard/map.post.tsindex eb9d3d85..7c341530 100644--- a/server/api/wizard/map.post.ts+++ b/server/api/wizard/map.post.ts@@ -12,13 +12,14 @@ export default eventHandler(async (event) => {)await settingsManager.set('map', 'provider', body.provider)-+if (body.provider === 'mapbox') {await settingsManager.set('map', 'mapbox.token', body.token)if (body.style) await settingsManager.set('map', 'mapbox.style', body.style)} else {await settingsManager.set('map', 'maplibre.token', body.token)- if (body.style) await settingsManager.set('map', 'maplibre.style', body.style)+ if (body.style)+ await settingsManager.set('map', 'maplibre.style', body.style)}return { success: true }diff --git a/server/api/wizard/schema.get.ts b/server/api/wizard/schema.get.tsindex c850c692..8f5d9e4e 100644--- a/server/api/wizard/schema.get.ts+++ b/server/api/wizard/schema.get.ts@@ -21,7 +21,7 @@ export default eventHandler(async (event) => {defaultValue: 'admin',value: 'admin',label: 'wizard.admin.username.label',- ui: { type: 'input', required: true, placeholder: 'admin' }+ ui: { type: 'input', required: true, placeholder: 'admin' },},{namespace: 'admin',@@ -30,7 +30,7 @@ export default eventHandler(async (event) => {defaultValue: '',value: '',label: 'wizard.admin.email.label',- ui: { type: 'input', required: true, placeholder: '[email protected]' }+ ui: { type: 'input', required: true, placeholder: '[email protected]' },},{namespace: 'admin',@@ -39,7 +39,7 @@ export default eventHandler(async (event) => {defaultValue: '',value: '',label: 'wizard.admin.password.label',- ui: { type: 'password', required: true }+ ui: { type: 'password', required: true },},{namespace: 'admin',@@ -48,8 +48,8 @@ export default eventHandler(async (event) => {defaultValue: '',value: '',label: 'wizard.admin.confirmPassword.label',- ui: { type: 'password', required: true }- }+ ui: { type: 'password', required: true },+ },] as any[]return { namespace: 'admin', fields }@@ -58,36 +58,156 @@ export default eventHandler(async (event) => {// 2. Storage Schema (Custom for Wizard)if (query.namespace === 'storage') {const storageFields = [- { key: 'provider', type: 'string', defaultValue: 'local', label: 'settings.storage.provider.label' },- { key: 'name', type: 'string', defaultValue: 'Default Storage', label: 'settings.storage.name.label' },+ {+ key: 'provider',+ type: 'string',+ defaultValue: 'local',+ label: 'settings.storage.provider.label',+ },+ {+ key: 'name',+ type: 'string',+ defaultValue: 'Default Storage',+ label: 'settings.storage.name.label',+ },// Local- { key: 'local.basePath', type: 'string', defaultValue: './data/storage', label: 'settings.storage.local.basePath.label' },- { key: 'local.baseUrl', type: 'string', defaultValue: '/storage', label: 'settings.storage.local.baseUrl.label' },- { key: 'local.prefix', type: 'string', defaultValue: 'photos/', label: 'settings.storage.local.prefix.label' },+ {+ key: 'local.basePath',+ type: 'string',+ defaultValue: './data/storage',+ label: 'settings.storage.local.basePath.label',+ },+ {+ key: 'local.baseUrl',+ type: 'string',+ defaultValue: '/storage',+ label: 'settings.storage.local.baseUrl.label',+ },+ {+ key: 'local.prefix',+ type: 'string',+ defaultValue: 'photos/',+ label: 'settings.storage.local.prefix.label',+ },// S3- { key: 's3.endpoint', type: 'string', defaultValue: '', label: 'settings.storage.s3.endpoint.label' },- { key: 's3.bucket', type: 'string', defaultValue: '', label: 'settings.storage.s3.bucket.label' },- { key: 's3.region', type: 'string', defaultValue: 'auto', label: 'settings.storage.s3.region.label' },- { key: 's3.accessKeyId', type: 'string', defaultValue: '', label: 'settings.storage.s3.accessKeyId.label' },- { key: 's3.secretAccessKey', type: 'string', defaultValue: '', label: 'settings.storage.s3.secretAccessKey.label' },- { key: 's3.prefix', type: 'string', defaultValue: '/photos', label: 'settings.storage.s3.prefix.label' },- { key: 's3.cdnUrl', type: 'string', defaultValue: '', label: 'settings.storage.s3.cdnUrl.label' },- { key: 's3.forcePathStyle', type: 'boolean', defaultValue: false, label: 'settings.storage.s3.forcePathStyle.label' },- { key: 's3.maxKeys', type: 'number', defaultValue: 1000, label: 'settings.storage.s3.maxKeys.label' },+ {+ key: 's3.endpoint',+ type: 'string',+ defaultValue: '',+ label: 'settings.storage.s3.endpoint.label',+ },+ {+ key: 's3.bucket',+ type: 'string',+ defaultValue: '',+ label: 'settings.storage.s3.bucket.label',+ },+ {+ key: 's3.region',+ type: 'string',+ defaultValue: 'auto',+ label: 'settings.storage.s3.region.label',+ },+ {+ key: 's3.accessKeyId',+ type: 'string',+ defaultValue: '',+ label: 'settings.storage.s3.accessKeyId.label',+ },+ {+ key: 's3.secretAccessKey',+ type: 'string',+ defaultValue: '',+ label: 'settings.storage.s3.secretAccessKey.label',+ },+ {+ key: 's3.prefix',+ type: 'string',+ defaultValue: '/photos',+ label: 'settings.storage.s3.prefix.label',+ },+ {+ key: 's3.cdnUrl',+ type: 'string',+ defaultValue: '',+ label: 'settings.storage.s3.cdnUrl.label',+ },+ {+ key: 's3.forcePathStyle',+ type: 'boolean',+ defaultValue: false,+ label: 'settings.storage.s3.forcePathStyle.label',+ },+ {+ key: 's3.maxKeys',+ type: 'number',+ defaultValue: 1000,+ label: 'settings.storage.s3.maxKeys.label',+ },// OpenList- { key: 'openlist.baseUrl', type: 'string', defaultValue: '', label: 'settings.storage.openlist.baseUrl.label' },- { key: 'openlist.rootPath', type: 'string', defaultValue: '/photos', label: 'settings.storage.openlist.rootPath.label' },- { key: 'openlist.token', type: 'string', defaultValue: '', label: 'settings.storage.openlist.token.label' },- { key: 'openlist.cdnUrl', type: 'string', defaultValue: '', label: 'settings.storage.openlist.cdnUrl.label' },- { key: 'openlist.uploadEndpoint', type: 'string', defaultValue: '/api/fs/put', label: 'settings.storage.openlist.uploadEndpoint.label' },- { key: 'openlist.downloadEndpoint', type: 'string', defaultValue: '', label: 'settings.storage.openlist.downloadEndpoint.label' },- { key: 'openlist.listEndpoint', type: 'string', defaultValue: '', label: 'settings.storage.openlist.listEndpoint.label' },- { key: 'openlist.deleteEndpoint', type: 'string', defaultValue: '/api/fs/remove', label: 'settings.storage.openlist.deleteEndpoint.label' },- { key: 'openlist.metaEndpoint', type: 'string', defaultValue: '/api/fs/get', label: 'settings.storage.openlist.metaEndpoint.label' },- { key: 'openlist.pathField', type: 'string', defaultValue: 'path', label: 'settings.storage.openlist.pathField.label' },+ {+ key: 'openlist.baseUrl',+ type: 'string',+ defaultValue: '',+ label: 'settings.storage.openlist.baseUrl.label',+ },+ {+ key: 'openlist.rootPath',+ type: 'string',+ defaultValue: '/photos',+ label: 'settings.storage.openlist.rootPath.label',+ },+ {+ key: 'openlist.token',+ type: 'string',+ defaultValue: '',+ label: 'settings.storage.openlist.token.label',+ },+ {+ key: 'openlist.cdnUrl',+ type: 'string',+ defaultValue: '',+ label: 'settings.storage.openlist.cdnUrl.label',+ },+ {+ key: 'openlist.uploadEndpoint',+ type: 'string',+ defaultValue: '/api/fs/put',+ label: 'settings.storage.openlist.uploadEndpoint.label',+ },+ {+ key: 'openlist.downloadEndpoint',+ type: 'string',+ defaultValue: '',+ label: 'settings.storage.openlist.downloadEndpoint.label',+ },+ {+ key: 'openlist.listEndpoint',+ type: 'string',+ defaultValue: '',+ label: 'settings.storage.openlist.listEndpoint.label',+ },+ {+ key: 'openlist.deleteEndpoint',+ type: 'string',+ defaultValue: '/api/fs/remove',+ label: 'settings.storage.openlist.deleteEndpoint.label',+ },+ {+ key: 'openlist.metaEndpoint',+ type: 'string',+ defaultValue: '/api/fs/get',+ label: 'settings.storage.openlist.metaEndpoint.label',+ },+ {+ key: 'openlist.pathField',+ type: 'string',+ defaultValue: 'path',+ label: 'settings.storage.openlist.pathField.label',+ },]- const fields = storageFields.map(field => {+ const fields = storageFields.map((field) => {const ui = getSettingUIConfig('storage', field.key)return {namespace: 'storage',@@ -96,7 +216,7 @@ export default eventHandler(async (event) => {defaultValue: field.defaultValue,value: field.defaultValue,label: field.label,- ui: ui || { type: 'input' }+ ui: ui || { type: 'input' },}}) as FieldDescriptor[]@@ -112,29 +232,29 @@ export default eventHandler(async (event) => {const fields = namespaceSettings.map((setting) => {const uiConfig = getSettingUIConfig(query.namespace, setting.key)-+// Patch for Wizard Map Provider to use rich selectorif (query.namespace === 'map' && setting.key === 'provider') {- return {- ...setting,- ui: {- type: 'custom',- options: [- {- label: 'wizard.map.provider.mapbox.label',- value: 'mapbox',- icon: 'simple-icons:mapbox',- description: 'wizard.map.provider.mapbox.description'- },- {- label: 'wizard.map.provider.maplibre.label',- value: 'maplibre',- icon: 'simple-icons:maplibre',- description: 'wizard.map.provider.maplibre.description'- },- ]- }- }+ return {+ ...setting,+ ui: {+ type: 'custom',+ options: [+ {+ label: 'wizard.map.provider.mapbox.label',+ value: 'mapbox',+ icon: 'simple-icons:mapbox',+ description: 'wizard.map.provider.mapbox.description',+ },+ {+ label: 'wizard.map.provider.maplibre.label',+ value: 'maplibre',+ icon: 'simple-icons:maplibre',+ description: 'wizard.map.provider.maplibre.description',+ },+ ],+ },+ }}return {diff --git a/server/api/wizard/site.post.ts b/server/api/wizard/site.post.tsindex 57f14654..d167ecc0 100644--- a/server/api/wizard/site.post.ts+++ b/server/api/wizard/site.post.ts@@ -14,7 +14,8 @@ export default eventHandler(async (event) => {await settingsManager.set('app', 'title', body.title)if (body.slogan) await settingsManager.set('app', 'slogan', body.slogan)- if (body.avatarUrl) await settingsManager.set('app', 'avatarUrl', body.avatarUrl)+ if (body.avatarUrl)+ await settingsManager.set('app', 'avatarUrl', body.avatarUrl)if (body.author) await settingsManager.set('app', 'author', body.author)return { success: true }diff --git a/server/api/wizard/submit.post.ts b/server/api/wizard/submit.post.tsindex 91d886cf..cf5cfd07 100644--- a/server/api/wizard/submit.post.ts+++ b/server/api/wizard/submit.post.ts@@ -36,14 +36,15 @@ export default eventHandler(async (event) => {const existingUser = db.select().from(tables.users).limit(1).get()if (existingUser) {if (existingUser.email === body.admin.email) {- await db.update(tables.users)- .set({- password: await hashPassword(body.admin.password),- username: body.admin.username,- isAdmin: 1- })- .where(eq(tables.users.id, existingUser.id))- .run()+ await db+ .update(tables.users)+ .set({+ password: await hashPassword(body.admin.password),+ username: body.admin.username,+ isAdmin: 1,+ })+ .where(eq(tables.users.id, existingUser.id))+ .run()} else {throw createError({statusCode: 400,@@ -51,20 +52,26 @@ export default eventHandler(async (event) => {})}} else {- await db.insert(tables.users).values({- email: body.admin.email,- username: body.admin.username,- password: await hashPassword(body.admin.password),- isAdmin: 1,- createdAt: new Date(),- }).run()+ await db+ .insert(tables.users)+ .values({+ email: body.admin.email,+ username: body.admin.username,+ password: await hashPassword(body.admin.password),+ isAdmin: 1,+ createdAt: new Date(),+ })+ .run()}// 2. Handle Site Settingsawait settingsManager.set('app', 'title', body.site.title)- if (body.site.slogan) await settingsManager.set('app', 'slogan', body.site.slogan)- if (body.site.avatarUrl) await settingsManager.set('app', 'avatarUrl', body.site.avatarUrl)- if (body.site.author) await settingsManager.set('app', 'author', body.site.author)+ if (body.site.slogan)+ await settingsManager.set('app', 'slogan', body.site.slogan)+ if (body.site.avatarUrl)+ await settingsManager.set('app', 'avatarUrl', body.site.avatarUrl)+ if (body.site.author)+ await settingsManager.set('app', 'author', body.site.author)// 3. Handle Storage Settings// Check if provider already exists to avoid duplicates if re-running?@@ -80,10 +87,12 @@ export default eventHandler(async (event) => {await settingsManager.set('map', 'provider', body.map.provider)if (body.map.provider === 'mapbox') {await settingsManager.set('map', 'mapbox.token', body.map.token)- if (body.map.style) await settingsManager.set('map', 'mapbox.style', body.map.style)+ if (body.map.style)+ await settingsManager.set('map', 'mapbox.style', body.map.style)} else {await settingsManager.set('map', 'maplibre.token', body.map.token)- if (body.map.style) await settingsManager.set('map', 'maplibre.style', body.map.style)+ if (body.map.style)+ await settingsManager.set('map', 'maplibre.style', body.map.style)}// 5. Mark Completediff --git a/server/database/migrations/meta/0000_snapshot.json b/server/database/migrations/meta/0000_snapshot.jsonindex 59df546d..97a823df 100644--- a/server/database/migrations/meta/0000_snapshot.json+++ b/server/database/migrations/meta/0000_snapshot.json@@ -116,9 +116,7 @@"indexes": {"photos_id_unique": {"name": "photos_id_unique",- "columns": [- "id"- ],+ "columns": ["id"],"isUnique": true}},@@ -184,16 +182,12 @@"indexes": {"users_name_unique": {"name": "users_name_unique",- "columns": [- "name"- ],+ "columns": ["name"],"isUnique": true},"users_email_unique": {"name": "users_email_unique",- "columns": [- "email"- ],+ "columns": ["email"],"isUnique": true}},@@ -213,4 +207,4 @@"internal": {"indexes": {}}-}\ No newline at end of file+}diff --git a/server/database/migrations/meta/0001_snapshot.json b/server/database/migrations/meta/0001_snapshot.jsonindex 5efa3c8c..e4a5e432 100644--- a/server/database/migrations/meta/0001_snapshot.json+++ b/server/database/migrations/meta/0001_snapshot.json@@ -151,9 +151,7 @@"indexes": {"photos_id_unique": {"name": "photos_id_unique",- "columns": [- "id"- ],+ "columns": ["id"],"isUnique": true}},@@ -219,16 +217,12 @@"indexes": {"users_name_unique": {"name": "users_name_unique",- "columns": [- "name"- ],+ "columns": ["name"],"isUnique": true},"users_email_unique": {"name": "users_email_unique",- "columns": [- "email"- ],+ "columns": ["email"],"isUnique": true}},@@ -248,4 +242,4 @@"internal": {"indexes": {}}-}\ No newline at end of file+}diff --git a/server/database/migrations/meta/0002_snapshot.json b/server/database/migrations/meta/0002_snapshot.jsonindex 3531caa2..529b4b48 100644--- a/server/database/migrations/meta/0002_snapshot.json+++ b/server/database/migrations/meta/0002_snapshot.json@@ -173,9 +173,7 @@"indexes": {"photos_id_unique": {"name": "photos_id_unique",- "columns": [- "id"- ],+ "columns": ["id"],"isUnique": true}},@@ -241,16 +239,12 @@"indexes": {"users_name_unique": {"name": "users_name_unique",- "columns": [- "name"- ],+ "columns": ["name"],"isUnique": true},"users_email_unique": {"name": "users_email_unique",- "columns": [- "email"- ],+ "columns": ["email"],"isUnique": true}},@@ -270,4 +264,4 @@"internal": {"indexes": {}}-}\ No newline at end of file+}diff --git a/server/database/migrations/meta/0003_snapshot.json b/server/database/migrations/meta/0003_snapshot.jsonindex 38b04591..77e93321 100644--- a/server/database/migrations/meta/0003_snapshot.json+++ b/server/database/migrations/meta/0003_snapshot.json@@ -180,9 +180,7 @@"indexes": {"photos_id_unique": {"name": "photos_id_unique",- "columns": [- "id"- ],+ "columns": ["id"],"isUnique": true}},@@ -248,16 +246,12 @@"indexes": {"users_name_unique": {"name": "users_name_unique",- "columns": [- "name"- ],+ "columns": ["name"],"isUnique": true},"users_email_unique": {"name": "users_email_unique",- "columns": [- "email"- ],+ "columns": ["email"],"isUnique": true}},@@ -277,4 +271,4 @@"internal": {"indexes": {}}-}\ No newline at end of file+}diff --git a/server/database/migrations/meta/0004_snapshot.json b/server/database/migrations/meta/0004_snapshot.jsonindex 26185166..3a2e8610 100644--- a/server/database/migrations/meta/0004_snapshot.json+++ b/server/database/migrations/meta/0004_snapshot.json@@ -180,9 +180,7 @@"indexes": {"photos_id_unique": {"name": "photos_id_unique",- "columns": [- "id"- ],+ "columns": ["id"],"isUnique": true}},@@ -326,16 +324,12 @@"indexes": {"users_name_unique": {"name": "users_name_unique",- "columns": [- "name"- ],+ "columns": ["name"],"isUnique": true},"users_email_unique": {"name": "users_email_unique",- "columns": [- "email"- ],+ "columns": ["email"],"isUnique": true}},@@ -355,4 +349,4 @@"internal": {"indexes": {}}-}\ No newline at end of file+}diff --git a/server/database/migrations/meta/0005_snapshot.json b/server/database/migrations/meta/0005_snapshot.jsonindex 732ebb60..b8ce54df 100644--- a/server/database/migrations/meta/0005_snapshot.json+++ b/server/database/migrations/meta/0005_snapshot.json@@ -180,9 +180,7 @@"indexes": {"photos_id_unique": {"name": "photos_id_unique",- "columns": [- "id"- ],+ "columns": ["id"],"isUnique": true}},@@ -333,16 +331,12 @@"indexes": {"users_name_unique": {"name": "users_name_unique",- "columns": [- "name"- ],+ "columns": ["name"],"isUnique": true},"users_email_unique": {"name": "users_email_unique",- "columns": [- "email"- ],+ "columns": ["email"],"isUnique": true}},@@ -362,4 +356,4 @@"internal": {"indexes": {}}-}\ No newline at end of file+}diff --git a/server/database/migrations/meta/0006_snapshot.json b/server/database/migrations/meta/0006_snapshot.jsonindex 00ac497c..76d234b3 100644--- a/server/database/migrations/meta/0006_snapshot.json+++ b/server/database/migrations/meta/0006_snapshot.json@@ -180,9 +180,7 @@"indexes": {"photos_id_unique": {"name": "photos_id_unique",- "columns": [- "id"- ],+ "columns": ["id"],"isUnique": true}},@@ -334,16 +332,12 @@"indexes": {"users_name_unique": {"name": "users_name_unique",- "columns": [- "name"- ],+ "columns": ["name"],"isUnique": true},"users_email_unique": {"name": "users_email_unique",- "columns": [- "email"- ],+ "columns": ["email"],"isUnique": true}},@@ -363,4 +357,4 @@"internal": {"indexes": {}}-}\ No newline at end of file+}diff --git a/server/database/migrations/meta/0007_snapshot.json b/server/database/migrations/meta/0007_snapshot.jsonindex 83411c66..8617b392 100644--- a/server/database/migrations/meta/0007_snapshot.json+++ b/server/database/migrations/meta/0007_snapshot.json@@ -72,12 +72,8 @@"name": "photo_reactions_photo_id_photos_id_fk","tableFrom": "photo_reactions","tableTo": "photos",- "columnsFrom": [- "photo_id"- ],- "columnsTo": [- "id"- ],+ "columnsFrom": ["photo_id"],+ "columnsTo": ["id"],"onDelete": "cascade","onUpdate": "no action"}@@ -262,9 +258,7 @@"indexes": {"photos_id_unique": {"name": "photos_id_unique",- "columns": [- "id"- ],+ "columns": ["id"],"isUnique": true}},@@ -416,16 +410,12 @@"indexes": {"users_name_unique": {"name": "users_name_unique",- "columns": [- "name"- ],+ "columns": ["name"],"isUnique": true},"users_email_unique": {"name": "users_email_unique",- "columns": [- "email"- ],+ "columns": ["email"],"isUnique": true}},@@ -445,4 +435,4 @@"internal": {"indexes": {}}-}\ No newline at end of file+}diff --git a/server/database/migrations/meta/0008_snapshot.json b/server/database/migrations/meta/0008_snapshot.jsonindex 87679f67..c8975a51 100644--- a/server/database/migrations/meta/0008_snapshot.json+++ b/server/database/migrations/meta/0008_snapshot.json@@ -51,12 +51,8 @@"name": "album_photos_album_id_albums_id_fk","tableFrom": "album_photos","tableTo": "albums",- "columnsFrom": [- "album_id"- ],- "columnsTo": [- "id"- ],+ "columnsFrom": ["album_id"],+ "columnsTo": ["id"],"onDelete": "cascade","onUpdate": "no action"},@@ -64,12 +60,8 @@"name": "album_photos_photo_id_photos_id_fk","tableFrom": "album_photos","tableTo": "photos",- "columnsFrom": [- "photo_id"- ],- "columnsTo": [- "id"- ],+ "columnsFrom": ["photo_id"],+ "columnsTo": ["id"],"onDelete": "cascade","onUpdate": "no action"}@@ -132,12 +124,8 @@"name": "albums_cover_photo_id_photos_id_fk","tableFrom": "albums","tableTo": "photos",- "columnsFrom": [- "cover_photo_id"- ],- "columnsTo": [- "id"- ],+ "columnsFrom": ["cover_photo_id"],+ "columnsTo": ["id"],"onDelete": "set null","onUpdate": "no action"}@@ -214,12 +202,8 @@"name": "photo_reactions_photo_id_photos_id_fk","tableFrom": "photo_reactions","tableTo": "photos",- "columnsFrom": [- "photo_id"- ],- "columnsTo": [- "id"- ],+ "columnsFrom": ["photo_id"],+ "columnsTo": ["id"],"onDelete": "cascade","onUpdate": "no action"}@@ -404,9 +388,7 @@"indexes": {"photos_id_unique": {"name": "photos_id_unique",- "columns": [- "id"- ],+ "columns": ["id"],"isUnique": true}},@@ -558,16 +540,12 @@"indexes": {"users_name_unique": {"name": "users_name_unique",- "columns": [- "name"- ],+ "columns": ["name"],"isUnique": true},"users_email_unique": {"name": "users_email_unique",- "columns": [- "email"- ],+ "columns": ["email"],"isUnique": true}},@@ -587,4 +565,4 @@"internal": {"indexes": {}}-}\ No newline at end of file+}diff --git a/server/database/migrations/meta/0009_snapshot.json b/server/database/migrations/meta/0009_snapshot.jsonindex ad21fe16..6529387b 100644--- a/server/database/migrations/meta/0009_snapshot.json+++ b/server/database/migrations/meta/0009_snapshot.json@@ -51,12 +51,8 @@"name": "album_photos_album_id_albums_id_fk","tableFrom": "album_photos","tableTo": "albums",- "columnsFrom": [- "album_id"- ],- "columnsTo": [- "id"- ],+ "columnsFrom": ["album_id"],+ "columnsTo": ["id"],"onDelete": "cascade","onUpdate": "no action"},@@ -64,12 +60,8 @@"name": "album_photos_photo_id_photos_id_fk","tableFrom": "album_photos","tableTo": "photos",- "columnsFrom": [- "photo_id"- ],- "columnsTo": [- "id"- ],+ "columnsFrom": ["photo_id"],+ "columnsTo": ["id"],"onDelete": "cascade","onUpdate": "no action"}@@ -132,12 +124,8 @@"name": "albums_cover_photo_id_photos_id_fk","tableFrom": "albums","tableTo": "photos",- "columnsFrom": [- "cover_photo_id"- ],- "columnsTo": [- "id"- ],+ "columnsFrom": ["cover_photo_id"],+ "columnsTo": ["id"],"onDelete": "set null","onUpdate": "no action"}@@ -214,12 +202,8 @@"name": "photo_reactions_photo_id_photos_id_fk","tableFrom": "photo_reactions","tableTo": "photos",- "columnsFrom": [- "photo_id"- ],- "columnsTo": [- "id"- ],+ "columnsFrom": ["photo_id"],+ "columnsTo": ["id"],"onDelete": "cascade","onUpdate": "no action"}@@ -404,9 +388,7 @@"indexes": {"photos_id_unique": {"name": "photos_id_unique",- "columns": [- "id"- ],+ "columns": ["id"],"isUnique": true}},@@ -611,10 +593,7 @@"indexes": {"idx_namespace_key": {"name": "idx_namespace_key",- "columns": [- "namespace",- "key"- ],+ "columns": ["namespace", "key"],"isUnique": true}},@@ -623,12 +602,8 @@"name": "settings_updated_by_users_id_fk","tableFrom": "settings","tableTo": "users",- "columnsFrom": [- "updated_by"- ],- "columnsTo": [- "id"- ],+ "columnsFrom": ["updated_by"],+ "columnsTo": ["id"],"onDelete": "set null","onUpdate": "no action"}@@ -748,16 +723,12 @@"indexes": {"users_name_unique": {"name": "users_name_unique",- "columns": [- "name"- ],+ "columns": ["name"],"isUnique": true},"users_email_unique": {"name": "users_email_unique",- "columns": [- "email"- ],+ "columns": ["email"],"isUnique": true}},@@ -777,4 +748,4 @@"internal": {"indexes": {}}-}\ No newline at end of file+}diff --git a/server/database/migrations/meta/_journal.json b/server/database/migrations/meta/_journal.jsonindex 9c6f5c5a..f192552c 100644--- a/server/database/migrations/meta/_journal.json+++ b/server/database/migrations/meta/_journal.json@@ -73,4 +73,4 @@"breakpoints": true}]-}\ No newline at end of file+}diff --git a/server/plugins/2.settings-manager.ts b/server/plugins/2.settings-manager.tsindex ada7d23f..7699010e 100644--- a/server/plugins/2.settings-manager.ts+++ b/server/plugins/2.settings-manager.ts@@ -3,15 +3,15 @@ import { settingsManager } from '../services/settings/settingsManager'export default defineNitroPlugin(async (_nitroApp) => {const _settingsManager = settingsManager-+// Mark initialization phase to prevent storage provider switch triggers// until storage manager is properly initialized in plugin 2_storage.ts_settingsManager.setInitializingFlag(true)-+try {// Initialize default settings firstawait _settingsManager.init(DEFAULT_SETTINGS)-+// Migrate existing configurations from runtimeConfig// Note: Storage manager will be initialized in the next plugin (2_storage.ts)await migrateRuntimeConfigToSettings()@@ -26,7 +26,7 @@ export default defineNitroPlugin(async (_nitroApp) => {async function migrateRuntimeConfigToSettings() {const config = useRuntimeConfig()const _logger = logger.dynamic('settings-migration')-+try {// Migrate app settingsif (config.public.app) {@@ -37,7 +37,7 @@ async function migrateRuntimeConfigToSettings() {author: config.public.app.author,avatarUrl: config.public.app.avatarUrl,}-+for (const [key, value] of Object.entries(appSettings)) {if (value) {try {@@ -49,7 +49,7 @@ async function migrateRuntimeConfigToSettings() {}}}-+// Migrate map settingsif (config.public.map) {_logger.info('Migrating map settings')@@ -60,7 +60,7 @@ async function migrateRuntimeConfigToSettings() {'maplibre.token': config.public.map.maplibre?.token || '','maplibre.style': config.public.map.maplibre?.style || '',}-+for (const [key, value] of Object.entries(mapSettings)) {if (value) {try {@@ -72,14 +72,15 @@ async function migrateRuntimeConfigToSettings() {}}}-+// Migrate storage configuration and set as active providerif (config.STORAGE_PROVIDER || config.provider) {_logger.info('Migrating storage configuration')-+const storageProvider = config.STORAGE_PROVIDER || 's3'- const providerConfig = config.provider?.[storageProvider as keyof typeof config.provider]-+ const providerConfig =+ config.provider?.[storageProvider as keyof typeof config.provider]+if (providerConfig) {try {// Check if a provider of the same type already exists@@ -87,7 +88,7 @@ async function migrateRuntimeConfigToSettings() {const sameTypeProviderExists = existingProviders.some((provider) => provider.provider === storageProvider,)-+if (sameTypeProviderExists) {_logger.info(`Storage provider of type ${storageProvider} already exists, skipping creation`,@@ -95,15 +96,21 @@ async function migrateRuntimeConfigToSettings() {} else {// Create a storage provider from the current configurationconst providerName = `Migrated ${storageProvider} Provider`-+const providerId = await settingsManager.storage.addProvider({name: providerName,provider: storageProvider as 's3' | 'local' | 'openlist',config: normalizeProviderConfig(storageProvider, providerConfig),})-+// Set this as the active provider- await settingsManager.set('storage', 'provider', providerId, undefined, true)+ await settingsManager.set(+ 'storage',+ 'provider',+ providerId,+ undefined,+ true,+ )_logger.info(`Storage provider migrated and set as active. Provider ID: ${providerId}`,)@@ -113,7 +120,7 @@ async function migrateRuntimeConfigToSettings() {}}}-+_logger.info('Configuration migration completed')} catch (error) {_logger.error('Failed to migrate configurations:', error)@@ -123,10 +130,7 @@ async function migrateRuntimeConfigToSettings() {/*** Normalize provider configuration based on provider type*/-function normalizeProviderConfig(- provider: string,- config: any,-): any {+function normalizeProviderConfig(provider: string, config: any): any {switch (provider) {case 's3':return {@@ -140,7 +144,7 @@ function normalizeProviderConfig(cdnUrl: config.cdnUrl || '',forcePathStyle: config.forcePathStyle ?? false,}-+case 'local':return {provider: 'local',@@ -148,7 +152,7 @@ function normalizeProviderConfig(baseUrl: config.baseUrl || '/storage',prefix: config.prefix || 'photos/',}-+case 'openlist': {// Support both old nested and new flat endpoint formatsconst oldEndpoints = config.endpoints || {}@@ -157,16 +161,18 @@ function normalizeProviderConfig(baseUrl: config.baseUrl || '',rootPath: config.rootPath || '',token: config.token || '',- uploadEndpoint: config.uploadEndpoint ?? oldEndpoints.upload ?? '/api/fs/put',+ uploadEndpoint:+ config.uploadEndpoint ?? oldEndpoints.upload ?? '/api/fs/put',downloadEndpoint: config.downloadEndpoint ?? oldEndpoints.download,listEndpoint: config.listEndpoint ?? oldEndpoints.list,- deleteEndpoint: config.deleteEndpoint ?? oldEndpoints.delete ?? '/api/fs/remove',+ deleteEndpoint:+ config.deleteEndpoint ?? oldEndpoints.delete ?? '/api/fs/remove',metaEndpoint: config.metaEndpoint ?? oldEndpoints.meta ?? '/api/fs/get',pathField: config.pathField ?? 'path',cdnUrl: config.cdnUrl || '',}}-+default:return config}diff --git a/server/plugins/3.storage.ts b/server/plugins/3.storage.tsindex 92eeddf3..677359c0 100644--- a/server/plugins/3.storage.ts+++ b/server/plugins/3.storage.ts@@ -23,19 +23,23 @@ export default nitroPlugin(async (nitroApp) => {// Wait for settings migration to complete if still initializing// This ensures we get the active provider after config migrationlet activeProvider = await settingsManager.storage.getActiveProvider()-+if (!activeProvider) {// Retry while settings manager is still initializinglet attempts = 0const maxAttempts = 100 // 5 seconds max with 50ms intervals-- while (!activeProvider && attempts < maxAttempts && settingsManager.isInitializing_()) {- await new Promise(resolve => setTimeout(resolve, 50))++ while (+ !activeProvider &&+ attempts < maxAttempts &&+ settingsManager.isInitializing_()+ ) {+ await new Promise((resolve) => setTimeout(resolve, 50))activeProvider = await settingsManager.storage.getActiveProvider()attempts++}}-+if (!activeProvider) {logger.storage.error('No active storage provider configured.')return@@ -89,10 +93,7 @@ export default nitroPlugin(async (nitroApp) => {if (event.provider === 'local') {try {const newProvider = await settingsManager.storage.getActiveProvider()- if (- newProvider &&- isLocalStorageProvider(newProvider.config)- ) {+ if (newProvider && isLocalStorageProvider(newProvider.config)) {const localBase = newProvider.config.basePathawait import('node:fs').then(async (m) => {const fs = m.promises as typeof import('node:fs').promisesdiff --git a/server/routes/storage/[...path].ts b/server/routes/storage/[...path].tsindex acca0b67..60b2e858 100644--- a/server/routes/storage/[...path].ts+++ b/server/routes/storage/[...path].ts@@ -42,7 +42,10 @@ export default defineEventHandler(async (event) => {const relPathRaw = Array.isArray(p) ? p.join('/') : p// handle CJK characters in URLconst decodedPath = decodeURIComponent(relPathRaw)- const relPath = decodedPath.replace(/\\/g, '/').replace(/\/+/g, '/').replace(/^\/+/, '')+ const relPath = decodedPath+ .replace(/\\/g, '/')+ .replace(/\/+/g, '/')+ .replace(/^\/+/, '')// 阻止路径穿越if (relPath.includes('..')) {@@ -76,7 +79,10 @@ export default defineEventHandler(async (event) => {// 条件请求const inm = getHeader(event, 'if-none-match')const ims = getHeader(event, 'if-modified-since')- if (inm === etag || (ims && new Date(ims).getTime() >= stat.mtime.getTime())) {+ if (+ inm === etag ||+ (ims && new Date(ims).getTime() >= stat.mtime.getTime())+ ) {event.node.res.statusCode = 304return null}@@ -90,7 +96,11 @@ export default defineEventHandler(async (event) => {const end = matches[2] ? parseInt(matches[2], 10) : stat.size - 1if (start <= end && end < stat.size) {event.node.res.statusCode = 206- setHeader(event, 'Content-Range', `bytes ${start}-${end}/${stat.size}`)+ setHeader(+ event,+ 'Content-Range',+ `bytes ${start}-${end}/${stat.size}`,+ )setHeader(event, 'Accept-Ranges', 'bytes')event.node.res.setHeader('Content-Length', String(end - start + 1))const stream = createReadStream(absolute, { start, end })diff --git a/server/routes/thumb/[...thumbnailUrl].get.ts b/server/routes/thumb/[...thumbnailUrl].get.tsindex ea5bcf36..8a8c828f 100644--- a/server/routes/thumb/[...thumbnailUrl].get.ts+++ b/server/routes/thumb/[...thumbnailUrl].get.ts@@ -6,12 +6,18 @@ export default eventHandler(async (event) => {let url = getRouterParam(event, 'thumbnailUrl')if (!url) {- throw createError({ statusCode: 400, statusMessage: 'Invalid thumbnailUrl' })+ throw createError({+ statusCode: 400,+ statusMessage: 'Invalid thumbnailUrl',+ })}url = decodeURIComponent(url)- if (storageProvider.config?.provider === 'local' && url.startsWith('/storage/')) {+ if (+ storageProvider.config?.provider === 'local' &&+ url.startsWith('/storage/')+ ) {const scheme = event.node.req.headers['x-forwarded-proto'] || 'http'url = `${scheme}://${event.node.req.headers.host}${url}`}diff --git a/server/services/image/exif.ts b/server/services/image/exif.tsindex 286cc970..3bc04d15 100644--- a/server/services/image/exif.ts+++ b/server/services/image/exif.ts@@ -293,65 +293,74 @@ export const extractExifData = async (logger?: Logger[keyof Logger],): Promise<NeededExif | null> => {try {- return await withRetry(async () => {- let tempImagePath: string | null = null-- try {- // 提取基础元数据- let metadata = await sharp(imageBuffer).metadata()-- // 如果主buffer没有EXIF,尝试原始buffer- if (!metadata.exif && rawImageBuffer) {- try {- metadata = await sharp(rawImageBuffer).metadata()- } catch (err) {- logger?.warn('Error extracting EXIF data from raw image buffer:', err)+ return await withRetry(+ async () => {+ let tempImagePath: string | null = null++ try {+ // 提取基础元数据+ let metadata = await sharp(imageBuffer).metadata()++ // 如果主buffer没有EXIF,尝试原始buffer+ if (!metadata.exif && rawImageBuffer) {+ try {+ metadata = await sharp(rawImageBuffer).metadata()+ } catch (err) {+ logger?.warn(+ 'Error extracting EXIF data from raw image buffer:',+ err,+ )+ }}- }- if (!metadata.exif) {- logger?.warn('No EXIF data found in image metadata')- return null- }+ if (!metadata.exif) {+ logger?.warn('No EXIF data found in image metadata')+ return null+ }- logger?.info('Extracting EXIF data using exiftool...')-- // 创建临时工作目录- const tempDir = path.resolve(process.cwd(), 'data/.exif_workdir')- await mkdir(tempDir, { recursive: true })- tempImagePath = path.resolve(tempDir, `${crypto.randomUUID()}.jpg`)-- // 写入临时文件- await writeFile(tempImagePath, rawImageBuffer || imageBuffer)-- // 使用 exiftool 读取详细 EXIF 数据- const exifData = await exiftool.read(tempImagePath)- const result = processExifData(exifData, metadata)-- // 记录颜色空间信息- if (result.ColorSpace) {- logger?.success(`Inferred ColorSpace: ${result.ColorSpace}`)- } else {- logger?.info('ColorSpace could not be determined')- }+ logger?.info('Extracting EXIF data using exiftool...')++ // 创建临时工作目录+ const tempDir = path.resolve(process.cwd(), 'data/.exif_workdir')+ await mkdir(tempDir, { recursive: true })+ tempImagePath = path.resolve(tempDir, `${crypto.randomUUID()}.jpg`)++ // 写入临时文件+ await writeFile(tempImagePath, rawImageBuffer || imageBuffer)- return result- } finally {- // 确保清理临时文件- if (tempImagePath) {- await unlink(tempImagePath).catch(noop)+ // 使用 exiftool 读取详细 EXIF 数据+ const exifData = await exiftool.read(tempImagePath)+ const result = processExifData(exifData, metadata)++ // 记录颜色空间信息+ if (result.ColorSpace) {+ logger?.success(`Inferred ColorSpace: ${result.ColorSpace}`)+ } else {+ logger?.info('ColorSpace could not be determined')+ }++ return result+ } finally {+ // 确保清理临时文件+ if (tempImagePath) {+ await unlink(tempImagePath).catch(noop)+ }}- }- }, {- ...RetryPresets.standard,- timeout: 15000, // EXIF 处理可能需要更长时间- retryCondition: (error) => {- // 组合多种重试条件- return RetryConditions.fileSystemErrors(error) ||- RetryConditions.resourceErrors(error) ||- error.message.includes('timeout')- }- }, logger)+ },+ {+ ...RetryPresets.standard,+ timeout: 15000, // EXIF 处理可能需要更长时间+ retryCondition: (error) => {+ // 组合多种重试条件+ return (+ RetryConditions.fileSystemErrors(error) ||+ RetryConditions.resourceErrors(error) ||+ error.message.includes('timeout')+ )+ },+ },+ logger,+ )} catch (error) {logger?.error('EXIF extraction failed after all retries:', error)return null@@ -377,7 +386,10 @@ const normalizeText = (value: unknown): string | undefined => {return text.length > 0 ? text : undefined}-const collectTextValues = (value: unknown, options?: { splitDelimited?: boolean }): string[] => {+const collectTextValues = (+ value: unknown,+ options?: { splitDelimited?: boolean },+): string[] => {const splitDelimited = options?.splitDelimited ?? falseconst results: string[] = []@@ -444,7 +456,9 @@ export const extractPhotoInfo = (tagsSet.add(tag)}- for (const tag of collectTextValues(exifData?.XPKeywords, { splitDelimited: true })) {+ for (const tag of collectTextValues(exifData?.XPKeywords, {+ splitDelimited: true,+ })) {tagsSet.add(tag)}diff --git a/server/services/image/thumbnail.ts b/server/services/image/thumbnail.tsindex db835573..ad98b0ec 100644--- a/server/services/image/thumbnail.ts+++ b/server/services/image/thumbnail.ts@@ -6,30 +6,34 @@ export const generateThumbnailAndHash = async (buffer: Buffer,logger?: Logger[keyof Logger],) => {- return await withRetry(async () => {- const sharpInst = sharp(buffer).rotate()-- // 根据文件大小调整缩略图质量- const fileSizeMB = buffer.length / (1024 * 1024)- const quality = fileSizeMB > 5 ? 85 : 100-- const thumbnailBuffer = await sharpInst- .resize(600, null, {- withoutEnlargement: true,- fastShrinkOnLoad: false // 提高质量- })- .webp({ quality })- .toBuffer()-- logger?.info(`Successfully generated thumbnail (quality: ${quality})`)-- // 生成BlurHash- const thumbnailHash = await generateBlurHash(thumbnailBuffer, logger)-- return { thumbnailBuffer, thumbnailHash }- }, {- ...RetryPresets.standard,- timeout: 15000,- delayStrategy: 'linear' // 图像处理适合线性退避- }, logger)+ return await withRetry(+ async () => {+ const sharpInst = sharp(buffer).rotate()++ // 根据文件大小调整缩略图质量+ const fileSizeMB = buffer.length / (1024 * 1024)+ const quality = fileSizeMB > 5 ? 85 : 100++ const thumbnailBuffer = await sharpInst+ .resize(600, null, {+ withoutEnlargement: true,+ fastShrinkOnLoad: false, // 提高质量+ })+ .webp({ quality })+ .toBuffer()++ logger?.info(`Successfully generated thumbnail (quality: ${quality})`)++ // 生成BlurHash+ const thumbnailHash = await generateBlurHash(thumbnailBuffer, logger)++ return { thumbnailBuffer, thumbnailHash }+ },+ {+ ...RetryPresets.standard,+ timeout: 15000,+ delayStrategy: 'linear', // 图像处理适合线性退避+ },+ logger,+ )}diff --git a/server/services/pipeline-queue/index.ts b/server/services/pipeline-queue/index.tsindex 4391b11e..777ba228 100644--- a/server/services/pipeline-queue/index.ts+++ b/server/services/pipeline-queue/index.ts@@ -1,7 +1,3 @@export { QueueManager } from './manager'export { WorkerPool } from './worker-pool'-export type {- WorkerPoolConfig,- WorkerStats,- PoolStats,-} from './worker-pool'+export type { WorkerPoolConfig, WorkerStats, PoolStats } from './worker-pool'diff --git a/server/services/pipeline-queue/manager.ts b/server/services/pipeline-queue/manager.tsindex 674578a0..e29a1294 100644--- a/server/services/pipeline-queue/manager.ts+++ b/server/services/pipeline-queue/manager.ts@@ -467,8 +467,10 @@ export class QueueManager {let longitude = payload.longitude ?? photo.longitude ?? undefinedif (- (latitude === undefined || latitude === null) ||- (longitude === undefined || longitude === null)+ latitude === undefined ||+ latitude === null ||+ longitude === undefined ||+ longitude === null) {if (photo.exif) {const coords = parseGPSCoordinates(photo.exif)@@ -507,7 +509,9 @@ export class QueueManager {)if (!locationInfo) {- throw new Error(`Failed to extract location from GPS coordinates (${latitude}, ${longitude}), maybe network issue?`)+ throw new Error(+ `Failed to extract location from GPS coordinates (${latitude}, ${longitude}), maybe network issue?`,+ )}await dbdiff --git a/server/services/settings/settingsManager.ts b/server/services/settings/settingsManager.tsindex 675b67c1..6645693d 100644--- a/server/services/settings/settingsManager.ts+++ b/server/services/settings/settingsManager.ts@@ -276,7 +276,10 @@ export class SettingsManager {// Use setImmediate to avoid blocking and handle async operationsetImmediate(() => {this.triggerStorageProviderSwitch(value as number).catch((error) => {- this._logger.error('Failed to trigger storage provider switch:', error)+ this._logger.error(+ 'Failed to trigger storage provider switch:',+ error,+ )})})}@@ -286,12 +289,15 @@ export class SettingsManager {* Trigger storage provider switch* @param providerId Provider ID to switch to*/- private async triggerStorageProviderSwitch(providerId: number): Promise<void> {+ private async triggerStorageProviderSwitch(+ providerId: number,+ ): Promise<void> {try {// Dynamically import to avoid circular dependency issues- const { getGlobalStorageManager } = await import('~~/server/services/storage/events')+ const { getGlobalStorageManager } =+ await import('~~/server/services/storage/events')const loggerModule = await import('~~/server/utils/logger')-+const storageManager = getGlobalStorageManager()if (!storageManager) {this._logger.warn(@@ -309,7 +315,7 @@ export class SettingsManager {this._logger.info(`Triggering storage provider switch to: ${newProvider.name} (ID: ${providerId})`,)-+await storageManager.registerProvider(newProvider.config,loggerModule.logger.dynamic('storage'),diff --git a/server/services/settings/ui-config.ts b/server/services/settings/ui-config.tsindex 8da69a9d..ec0f888a 100644--- a/server/services/settings/ui-config.ts+++ b/server/services/settings/ui-config.ts@@ -103,25 +103,25 @@ export const STORAGE_SETTINGS_UI: Record<string, FieldUIConfig> = {provider: {type: 'custom',options: [- {- label: 'settings.storage.provider.options.local.label',- value: 'local',+ {+ label: 'settings.storage.provider.options.local.label',+ value: 'local',icon: 'tabler:server',- description: 'settings.storage.provider.options.local.description'+ description: 'settings.storage.provider.options.local.description',},- {- label: 'settings.storage.provider.options.s3.label',- value: 's3',+ {+ label: 'settings.storage.provider.options.s3.label',+ value: 's3',icon: 'tabler:brand-aws',- description: 'settings.storage.provider.options.s3.description'+ description: 'settings.storage.provider.options.s3.description',},- {- label: 'settings.storage.provider.options.openlist.label',- value: 'openlist',+ {+ label: 'settings.storage.provider.options.openlist.label',+ value: 'openlist',icon: 'tabler:stack',- description: 'settings.storage.provider.options.openlist.description'+ description: 'settings.storage.provider.options.openlist.description',},- ]+ ],},name: {type: 'input',@@ -132,18 +132,18 @@ export const STORAGE_SETTINGS_UI: Record<string, FieldUIConfig> = {type: 'input',required: true,help: 'settings.storage.local.basePath.description',- visibleIf: { fieldKey: 'provider', value: 'local' }+ visibleIf: { fieldKey: 'provider', value: 'local' },},'local.baseUrl': {type: 'input',help: 'settings.storage.local.baseUrl.description',- visibleIf: { fieldKey: 'provider', value: 'local' }+ visibleIf: { fieldKey: 'provider', value: 'local' },},'local.prefix': {type: 'input',placeholder: 'photos/',help: 'settings.storage.local.prefix.description',- visibleIf: { fieldKey: 'provider', value: 'local' }+ visibleIf: { fieldKey: 'provider', value: 'local' },},// S3's3.endpoint': {@@ -151,52 +151,52 @@ export const STORAGE_SETTINGS_UI: Record<string, FieldUIConfig> = {required: true,placeholder: 'https://s3.amazonaws.com',help: 'settings.storage.s3.endpoint.description',- visibleIf: { fieldKey: 'provider', value: 's3' }+ visibleIf: { fieldKey: 'provider', value: 's3' },},'s3.bucket': {type: 'input',required: true,help: 'settings.storage.s3.bucket.description',- visibleIf: { fieldKey: 'provider', value: 's3' }+ visibleIf: { fieldKey: 'provider', value: 's3' },},'s3.region': {type: 'input',required: true,help: 'settings.storage.s3.region.description',- visibleIf: { fieldKey: 'provider', value: 's3' }+ visibleIf: { fieldKey: 'provider', value: 's3' },},'s3.accessKeyId': {type: 'input',required: true,help: 'settings.storage.s3.accessKeyId.description',- visibleIf: { fieldKey: 'provider', value: 's3' }+ visibleIf: { fieldKey: 'provider', value: 's3' },},'s3.secretAccessKey': {type: 'password',required: true,help: 'settings.storage.s3.secretAccessKey.description',- visibleIf: { fieldKey: 'provider', value: 's3' }+ visibleIf: { fieldKey: 'provider', value: 's3' },},'s3.prefix': {type: 'input',placeholder: '/photos',help: 'settings.storage.s3.prefix.description',- visibleIf: { fieldKey: 'provider', value: 's3' }+ visibleIf: { fieldKey: 'provider', value: 's3' },},'s3.cdnUrl': {type: 'input',help: 'settings.storage.s3.cdnUrl.description',- visibleIf: { fieldKey: 'provider', value: 's3' }+ visibleIf: { fieldKey: 'provider', value: 's3' },},'s3.forcePathStyle': {type: 'toggle',help: 'settings.storage.s3.forcePathStyle.description',- visibleIf: { fieldKey: 'provider', value: 's3' }+ visibleIf: { fieldKey: 'provider', value: 's3' },},'s3.maxKeys': {type: 'number',help: 'settings.storage.s3.maxKeys.description',- visibleIf: { fieldKey: 'provider', value: 's3' }+ visibleIf: { fieldKey: 'provider', value: 's3' },},// OpenList'openlist.baseUrl': {@@ -204,59 +204,59 @@ export const STORAGE_SETTINGS_UI: Record<string, FieldUIConfig> = {required: true,placeholder: 'https://alist.example.com',help: 'settings.storage.openlist.baseUrl.description',- visibleIf: { fieldKey: 'provider', value: 'openlist' }+ visibleIf: { fieldKey: 'provider', value: 'openlist' },},'openlist.rootPath': {type: 'input',required: true,placeholder: '/photos',help: 'settings.storage.openlist.rootPath.description',- visibleIf: { fieldKey: 'provider', value: 'openlist' }+ visibleIf: { fieldKey: 'provider', value: 'openlist' },},'openlist.token': {type: 'password',required: true,help: 'settings.storage.openlist.token.description',- visibleIf: { fieldKey: 'provider', value: 'openlist' }+ visibleIf: { fieldKey: 'provider', value: 'openlist' },},'openlist.cdnUrl': {type: 'input',help: 'settings.storage.openlist.cdnUrl.description',- visibleIf: { fieldKey: 'provider', value: 'openlist' }+ visibleIf: { fieldKey: 'provider', value: 'openlist' },},'openlist.uploadEndpoint': {type: 'input',placeholder: '/api/fs/put',help: 'settings.storage.openlist.uploadEndpoint.description',- visibleIf: { fieldKey: 'provider', value: 'openlist' }+ visibleIf: { fieldKey: 'provider', value: 'openlist' },},'openlist.downloadEndpoint': {type: 'input',help: 'settings.storage.openlist.downloadEndpoint.description',- visibleIf: { fieldKey: 'provider', value: 'openlist' }+ visibleIf: { fieldKey: 'provider', value: 'openlist' },},'openlist.listEndpoint': {type: 'input',help: 'settings.storage.openlist.listEndpoint.description',- visibleIf: { fieldKey: 'provider', value: 'openlist' }+ visibleIf: { fieldKey: 'provider', value: 'openlist' },},'openlist.deleteEndpoint': {type: 'input',placeholder: '/api/fs/remove',help: 'settings.storage.openlist.deleteEndpoint.description',- visibleIf: { fieldKey: 'provider', value: 'openlist' }+ visibleIf: { fieldKey: 'provider', value: 'openlist' },},'openlist.metaEndpoint': {type: 'input',placeholder: '/api/fs/get',help: 'settings.storage.openlist.metaEndpoint.description',- visibleIf: { fieldKey: 'provider', value: 'openlist' }+ visibleIf: { fieldKey: 'provider', value: 'openlist' },},'openlist.pathField': {type: 'input',placeholder: 'path',help: 'settings.storage.openlist.pathField.description',- visibleIf: { fieldKey: 'provider', value: 'openlist' }+ visibleIf: { fieldKey: 'provider', value: 'openlist' },},}diff --git a/server/services/storage/index.ts b/server/services/storage/index.tsindex 082f53ea..426c7279 100644--- a/server/services/storage/index.ts+++ b/server/services/storage/index.ts@@ -16,7 +16,11 @@ export {export { StorageProviderFactory, StorageManager } from './manager'-export type { StorageManagerEventType, StorageManagerEventListener, StorageManagerEvent } from './manager'+export type {+ StorageManagerEventType,+ StorageManagerEventListener,+ StorageManagerEvent,+} from './manager'export { S3StorageProvider } from './providers/s3'export { LocalStorageProvider } from './providers/local'@@ -27,4 +31,3 @@ export {getGlobalStorageManager,isStorageManagerInitialized,} from './events'-diff --git a/server/services/storage/manager.ts b/server/services/storage/manager.tsindex 73f97f36..6478985b 100644--- a/server/services/storage/manager.ts+++ b/server/services/storage/manager.ts@@ -1,4 +1,4 @@-import type { StorageConfig, StorageProvider } from '.';+import type { StorageConfig, StorageProvider } from '.'import { S3StorageProvider } from '.'import type { Logger } from '../../utils/logger'import { LocalStorageProvider } from './providers/local'@@ -39,7 +39,10 @@ export class StorageProviderFactory {export class StorageManager {private provider: StorageProviderprivate logger?: Logger['storage']- private eventListeners: Map<StorageManagerEventType, StorageManagerEventListener[]> = new Map()+ private eventListeners: Map<+ StorageManagerEventType,+ StorageManagerEventListener[]+ > = new Map()private currentProviderName?: stringconstructor(config: StorageConfig, logger?: Logger['storage']) {@@ -104,19 +107,27 @@ export class StorageManager {* @param config New storage configuration* @param logger Optional logger instance*/- async registerProvider(config: StorageConfig, logger?: Logger['storage']): Promise<void> {+ async registerProvider(+ config: StorageConfig,+ logger?: Logger['storage'],+ ): Promise<void> {try {const oldProviderName = this.currentProviderNamethis.logger = logger || this.logger-- this.logger?.info(`Switching storage provider from ${oldProviderName} to ${config.provider}`)-- const newProvider = StorageProviderFactory.createProvider(config, this.logger)++ this.logger?.info(+ `Switching storage provider from ${oldProviderName} to ${config.provider}`,+ )++ const newProvider = StorageProviderFactory.createProvider(+ config,+ this.logger,+ )this.provider = newProviderthis.currentProviderName = config.provider-+this.logger?.success(`Storage provider switched to: ${config.provider}`)-+// Emit provider-changed eventawait this.emitEvent({type: 'provider-changed',@@ -125,8 +136,11 @@ export class StorageManager {timestamp: Date.now(),})} catch (error) {- this.logger?.error(`Failed to register storage provider: ${config.provider}`, error)-+ this.logger?.error(+ `Failed to register storage provider: ${config.provider}`,+ error,+ )+// Emit provider-error eventawait this.emitEvent({type: 'provider-error',@@ -134,7 +148,7 @@ export class StorageManager {error: error as Error,timestamp: Date.now(),})-+throw error}}diff --git a/server/services/storage/providers/local.ts b/server/services/storage/providers/local.tsindex 3ccdb6cc..db69618b 100644--- a/server/services/storage/providers/local.ts+++ b/server/services/storage/providers/local.ts@@ -10,7 +10,8 @@ const ensureDir = async (dirPath: string) => {await fs.mkdir(dirPath, { recursive: true })}-const sanitizeKey = (key: string) => key.replace(/\\/g, '/').replace(/\/+/g, '/').replace(/^\/+/, '')+const sanitizeKey = (key: string) =>+ key.replace(/\\/g, '/').replace(/\/+/g, '/').replace(/^\/+/, '')const combinePrefixAndKey = (prefix: string | undefined, key: string) => {const cleanPrefix = (prefix || '').replace(/\/+$/, '')@@ -133,5 +134,3 @@ export class LocalStorageProvider implements StorageProvider {}}}--diff --git a/server/services/storage/providers/openlist.ts b/server/services/storage/providers/openlist.tsindex 1064fd85..8680a72b 100644--- a/server/services/storage/providers/openlist.ts+++ b/server/services/storage/providers/openlist.ts@@ -29,11 +29,16 @@ export class OpenListStorageProvider implements StorageProvider {this.token = this.config.tokenreturn this.token}-- throw new Error('OpenList auth requires a token. Please configure NUXT_PROVIDER_OPENLIST_TOKEN.')++ throw new Error(+ 'OpenList auth requires a token. Please configure NUXT_PROVIDER_OPENLIST_TOKEN.',+ )}- private async request(path: string, init: RequestInit = {}): Promise<Response> {+ private async request(+ path: string,+ init: RequestInit = {},+ ): Promise<Response> {const token = await this.ensureAuthToken()const url = `${this.baseUrl}${path}`const headers: Record<string, string> = {@@ -66,7 +71,11 @@ export class OpenListStorageProvider implements StorageProvider {return key.startsWith('/') ? key : `/${key}`}- async create(key: string, fileBuffer: Buffer, contentType?: string): Promise<StorageObject> {+ async create(+ key: string,+ fileBuffer: Buffer,+ contentType?: string,+ ): Promise<StorageObject> {const rootedKey = this.withRoot(key)const absoluteKey = this.toAbsolutePath(rootedKey)const uploadPath = this.config.uploadEndpoint || '/api/fs/put'@@ -83,7 +92,10 @@ export class OpenListStorageProvider implements StorageProvider {if (!resp.ok) {const text = await resp.text().catch(() => '')- this.logger?.error('OpenList upload failed', { status: resp.status, body: text })+ this.logger?.error('OpenList upload failed', {+ status: resp.status,+ body: text,+ })throw new Error(`OpenList upload failed: ${resp.status}`)}@@ -111,7 +123,9 @@ export class OpenListStorageProvider implements StorageProvider {const rootedKey = this.withRoot(key)const normalized = rootedKey.replace(/^\/+/, '')const slashIdx = normalized.lastIndexOf('/')- const dir = this.toAbsolutePath(slashIdx >= 0 ? normalized.slice(0, slashIdx) : this.normalizedRoot())+ const dir = this.toAbsolutePath(+ slashIdx >= 0 ? normalized.slice(0, slashIdx) : this.normalizedRoot(),+ )const name = slashIdx >= 0 ? normalized.slice(slashIdx + 1) : normalizedconst body = { dir, names: [name] }@@ -122,7 +136,10 @@ export class OpenListStorageProvider implements StorageProvider {})if (!resp.ok) {const text = await resp.text().catch(() => '')- this.logger?.error('OpenList delete failed', { status: resp.status, body: text })+ this.logger?.error('OpenList delete failed', {+ status: resp.status,+ body: text,+ })throw new Error(`OpenList delete failed: ${resp.status}`)}this.logger?.success(`Deleted object: ${key}`)@@ -162,7 +179,8 @@ export class OpenListStorageProvider implements StorageProvider {}async getFileMeta(key: string): Promise<StorageObject | null> {- const metaPath = this.config.metaEndpoint || this.config.downloadEndpoint || '/api/fs/get'+ const metaPath =+ this.config.metaEndpoint || this.config.downloadEndpoint || '/api/fs/get'const rootedKey = this.withRoot(key)const urlPath = metaPathconst payload: Record<string, any> = {@@ -172,10 +190,17 @@ export class OpenListStorageProvider implements StorageProvider {per_page: 0,refresh: false,}- const resp = await this.request(urlPath, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(payload) })+ const resp = await this.request(urlPath, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify(payload),+ })if (!resp.ok) {const text = await resp.text().catch(() => '')- this.logger?.error('OpenList get file meta failed', { status: resp.status, body: text })+ this.logger?.error('OpenList get file meta failed', {+ status: resp.status,+ body: text,+ })return null}@@ -202,7 +227,7 @@ export class OpenListStorageProvider implements StorageProvider {// You can configure custom list endpoint and parsing later.const listPath = this.config.listEndpointif (!listPath) return []-+const payload: Record<string, any> = {[this.pathField]: this.toAbsolutePath(this.normalizedRoot()),password: '',@@ -238,6 +263,8 @@ export class OpenListStorageProvider implements StorageProvider {async listImages(): Promise<StorageObject[]> {const all = await this.listAll()- return all.filter((obj) => /\.(jpe?g|png|webp|gif|bmp|tiff?|heic|heif)$/i.test(obj.key))+ return all.filter((obj) =>+ /\.(jpe?g|png|webp|gif|bmp|tiff?|heic|heif)$/i.test(obj.key),+ )}}diff --git a/server/services/video/livephoto.ts b/server/services/video/livephoto.tsindex bd5aa9f4..255ab5c9 100644--- a/server/services/video/livephoto.ts+++ b/server/services/video/livephoto.ts@@ -7,18 +7,20 @@ import { getStorageManager } from '~~/server/plugins/3.storage'*/export const processLivePhotoVideo = async (videoKey: string,- _videoSize: number+ _videoSize: number,): Promise<boolean> => {const storageProvider = getStorageManager().getProvider()const db = useDB()-+try {// 从视频文件名提取基础名称(去除扩展名)const videoBaseName = path.basename(videoKey, path.extname(videoKey))const videoDir = path.dirname(videoKey)-- logger.chrono.info(`Processing LivePhoto video: ${videoKey}, looking for photo with base name: ${videoBaseName}`)-++ logger.chrono.info(+ `Processing LivePhoto video: ${videoKey}, looking for photo with base name: ${videoBaseName}`,+ )+// 查找可能匹配的照片文件名模式// LivePhoto 通常会有相同的基础文件名,但照片可能是 .HEIC/.JPG 等格式const possiblePhotoKeys = [@@ -29,7 +31,7 @@ export const processLivePhotoVideo = async (path.join(videoDir, `${videoBaseName}.JPEG`).replace(/\\/g, '/'),path.join(videoDir, `${videoBaseName}.jpeg`).replace(/\\/g, '/'),]-+// 在数据库中查找匹配的照片let matchedPhoto = nullfor (const photoKey of possiblePhotoKeys) {@@ -38,22 +40,24 @@ export const processLivePhotoVideo = async (.from(tables.photos).where(eq(tables.photos.storageKey, photoKey)).limit(1)-+if (photos.length > 0) {matchedPhoto = photos[0]logger.chrono.info(`Found matching photo: ${photoKey}`)break}}-+if (!matchedPhoto) {- logger.chrono.warn(`No matching photo found for LivePhoto video: ${videoKey}`)+ logger.chrono.warn(+ `No matching photo found for LivePhoto video: ${videoKey}`,+ )return false}-+// 获取视频的公共 URLconst videoUrl = storageProvider.getPublicUrl(videoKey)-+// 更新照片记录,设置 LivePhoto 信息await db.update(tables.photos)@@ -63,10 +67,11 @@ export const processLivePhotoVideo = async (livePhotoVideoKey: videoKey,}).where(eq(tables.photos.id, matchedPhoto.id))-- logger.chrono.success(`Successfully processed LivePhoto: ${matchedPhoto.id}, video: ${videoKey}`)++ logger.chrono.success(+ `Successfully processed LivePhoto: ${matchedPhoto.id}, video: ${videoKey}`,+ )return true-} catch (error) {logger.chrono.error(`Failed to process LivePhoto video ${videoKey}:`, error)return false@@ -77,37 +82,41 @@ export const processLivePhotoVideo = async (* 检查存储桶中是否有与照片对应的 LivePhoto 视频文件*/export const findLivePhotoVideoForImage = async (- imageKey: string+ imageKey: string,): Promise<{ videoKey: string; videoSize: number } | null> => {const storageProvider = getStorageManager().getProvider()-+try {// 从图片文件名提取基础名称(去除扩展名)const imageBaseName = path.basename(imageKey, path.extname(imageKey))const imageDir = path.dirname(imageKey)-- logger.chrono.info(`Checking for LivePhoto video for image: ${imageKey}, base name: ${imageBaseName}`)-++ logger.chrono.info(+ `Checking for LivePhoto video for image: ${imageKey}, base name: ${imageBaseName}`,+ )+// 查找可能匹配的视频文件名模式const possibleVideoKeys = [path.join(imageDir, `${imageBaseName}.MOV`).replace(/\\/g, '/'),path.join(imageDir, `${imageBaseName}.mov`).replace(/\\/g, '/'),]-+// 检查存储中是否存在对应的视频文件for (const videoKey of possibleVideoKeys) {try {const videoBuffer = await storageProvider.get(videoKey)if (videoBuffer) {const videoSize = videoBuffer.length-+// 检查是否符合 LivePhoto 视频的特征const fileName = path.basename(videoKey)if (isLivePhotoVideo(fileName, videoSize)) {logger.chrono.info(`Found matching LivePhoto video: ${videoKey}`)return { videoKey, videoSize }} else {- logger.chrono.warn(`Video file found but doesn't match LivePhoto criteria: ${videoKey} (size: ${videoSize})`)+ logger.chrono.warn(+ `Video file found but doesn't match LivePhoto criteria: ${videoKey} (size: ${videoSize})`,+ )}}} catch {@@ -115,12 +124,16 @@ export const findLivePhotoVideoForImage = async (continue}}-- logger.chrono.info(`No matching LivePhoto video found for image: ${imageKey}`)++ logger.chrono.info(+ `No matching LivePhoto video found for image: ${imageKey}`,+ )return null-} catch (error) {- logger.chrono.error(`Failed to check for LivePhoto video for ${imageKey}:`, error)+ logger.chrono.error(+ `Failed to check for LivePhoto video for ${imageKey}:`,+ error,+ )return null}}@@ -137,14 +150,17 @@ export const isVideoFile = (fileName: string): boolean => {* 检查文件是否可能是 LivePhoto 的 MOV 文件* LivePhoto 的 MOV 文件通常很小(几MB以内)*/-export const isLivePhotoVideo = (fileName: string, fileSize: number): boolean => {+export const isLivePhotoVideo = (+ fileName: string,+ fileSize: number,+): boolean => {const extName = path.extname(fileName).toLowerCase()-+// 检查是否为 MOV 格式if (extName !== '.mov') {return false}-+const maxLivePhotoSize = 12 * 1024 * 1024 // 12MBreturn fileSize <= maxLivePhotoSize}diff --git a/server/services/video/motion-photo.ts b/server/services/video/motion-photo.tsindex 9d007922..6a35a055 100644--- a/server/services/video/motion-photo.ts+++ b/server/services/video/motion-photo.ts@@ -183,14 +183,8 @@ export const processMotionPhotoFromXmp = async ({if (presentationTimestampUs === null) {presentationTimestampUs =- extractXmpNumber(- xmpSegment,- 'MotionPhotoPresentationTimestampUs',- ) ??- extractXmpNumber(- xmpSegment,- 'MicroVideoPresentationTimestampUs',- ) ??+ extractXmpNumber(xmpSegment, 'MotionPhotoPresentationTimestampUs') ??+ extractXmpNumber(xmpSegment, 'MicroVideoPresentationTimestampUs') ??extractXmpAttributeNumber(xmpSegment,'MotionPhotoPresentationTimestampUs',@@ -198,7 +192,8 @@ export const processMotionPhotoFromXmp = async ({extractXmpAttributeNumber(xmpSegment,'MicroVideoPresentationTimestampUs',- ) ?? null+ ) ??+ null}}diff --git a/server/services/video/test-utils.ts b/server/services/video/test-utils.tsindex b588ca6d..137ed67b 100644--- a/server/services/video/test-utils.ts+++ b/server/services/video/test-utils.ts@@ -6,32 +6,35 @@ import { findLivePhotoVideoForImage } from '../video/livephoto'*/export const testLivePhotoDetection = async (imageKey: string) => {logger.chrono.info(`Testing LivePhoto detection for: ${imageKey}`)-+try {const result = await findLivePhotoVideoForImage(imageKey)-+if (result) {logger.chrono.success(`LivePhoto video found:`, {imageKey,videoKey: result.videoKey,- videoSize: result.videoSize+ videoSize: result.videoSize,})return {found: true,videoKey: result.videoKey,- videoSize: result.videoSize+ videoSize: result.videoSize,}} else {logger.chrono.info(`No LivePhoto video found for: ${imageKey}`)return {- found: false+ found: false,}}} catch (error) {- logger.chrono.error(`LivePhoto detection test failed for ${imageKey}:`, error)+ logger.chrono.error(+ `LivePhoto detection test failed for ${imageKey}:`,+ error,+ )return {found: false,- error: error instanceof Error ? error.message : String(error)+ error: error instanceof Error ? error.message : String(error),}}}@@ -41,10 +44,10 @@ export const testLivePhotoDetection = async (imageKey: string) => {*/export const batchTestLivePhotoDetection = async (photoIds?: string[]) => {const db = useDB()-+try {let photos-+if (photoIds && Array.isArray(photoIds) && photoIds.length > 0) {// 只处理指定的照片photos = await db@@ -53,8 +56,8 @@ export const batchTestLivePhotoDetection = async (photoIds?: string[]) => {.where(and(eq(tables.photos.isLivePhoto, 0),- inArray(tables.photos.id, photoIds)- )+ inArray(tables.photos.id, photoIds),+ ),)} else {// 获取所有还不是 LivePhoto 的照片@@ -63,31 +66,35 @@ export const batchTestLivePhotoDetection = async (photoIds?: string[]) => {.from(tables.photos).where(eq(tables.photos.isLivePhoto, 0))}-- logger.chrono.info(`Testing ${photos.length} photos for LivePhoto detection`)-++ logger.chrono.info(+ `Testing ${photos.length} photos for LivePhoto detection`,+ )+const results = []-+for (const photo of photos) {const result = await testLivePhotoDetection(photo.storageKey!)results.push({photoId: photo.id,storageKey: photo.storageKey,- ...result+ ...result,})-+// 避免过快请求存储- await new Promise(resolve => setTimeout(resolve, 100))+ await new Promise((resolve) => setTimeout(resolve, 100))}-- const foundCount = results.filter(r => r.found).length- logger.chrono.success(`LivePhoto detection test completed. Found ${foundCount} potential LivePhotos out of ${photos.length} photos`)-++ const foundCount = results.filter((r) => r.found).length+ logger.chrono.success(+ `LivePhoto detection test completed. Found ${foundCount} potential LivePhotos out of ${photos.length} photos`,+ )+return {total: photos.length,processed: photos.length,found: foundCount,- results: results.filter(r => r.found) // 只返回找到的+ results: results.filter((r) => r.found), // 只返回找到的}} catch (error) {logger.chrono.error('Batch LivePhoto detection test failed:', error)diff --git a/server/utils/file-utils.ts b/server/utils/file-utils.tsindex 9699ca51..847412e1 100644--- a/server/utils/file-utils.ts+++ b/server/utils/file-utils.ts@@ -13,33 +13,29 @@ export const sanitizeFileName = (maxLength?: numberfallbackPrefix?: stringminLength?: number- } = {}+ } = {},): string => {- const {- maxLength = 50,- fallbackPrefix = 'file',- minLength = 3- } = options+ const { maxLength = 50, fallbackPrefix = 'file', minLength = 3 } = options// 清理文件名:保留字母、数字、连字符、下划线、点号const cleanedName = fileName.replace(/[^\w\-_.]/g, '_') // 将非字母数字字符替换为下划线.replace(/_{2,}/g, '_') // 将多个连续下划线替换为单个下划线.replace(/^_+|_+$/g, '') // 移除开头和结尾的下划线-+// 如果清理后的名称太短或为空,使用后备方案if (cleanedName.length < minLength) {const hash = crypto.createHash('md5').update(fileName).digest('hex')return `${fallbackPrefix}_${hash.substring(0, 8)}`}-+// 如果清理后的名称太长,截断并添加哈希后缀以避免冲突if (cleanedName.length > maxLength) {const hash = crypto.createHash('md5').update(fileName).digest('hex')const truncateLength = maxLength - 9 // 为哈希和下划线预留空间return `${cleanedName.substring(0, truncateLength)}_${hash.substring(0, 8)}`}-+return cleanedName}@@ -53,7 +49,7 @@ export const generateSafePhotoId = (s3key: string): string => {return sanitizeFileName(baseName, {maxLength: 32,fallbackPrefix: 'photo',- minLength: 3+ minLength: 3,})}@@ -63,19 +59,22 @@ export const generateSafePhotoId = (s3key: string): string => {* @param newExtension 新的文件扩展名(包含点号,如 '.jpeg')* @returns 安全的文件键*/-export const generateSafeFileKey = (s3key: string, newExtension: string): string => {+export const generateSafeFileKey = (+ s3key: string,+ newExtension: string,+): string => {const baseName = path.basename(s3key, path.extname(s3key))const dirName = path.dirname(s3key)const safeName = sanitizeFileName(baseName, {maxLength: 100,fallbackPrefix: 'file',- minLength: 1+ minLength: 1,})-+// 如果原路径有目录结构,保持目录结构if (dirName === '.' || dirName === '') {return `${safeName}${newExtension}`}-+return `${dirName}/${safeName}${newExtension}`}diff --git a/server/utils/retry.ts b/server/utils/retry.tsindex 123a1191..4d8ec48c 100644--- a/server/utils/retry.ts+++ b/server/utils/retry.ts@@ -18,12 +18,12 @@ export interface RetryOptions {/*** 通用重试工具函数- *+ ** @param operation 要执行的异步操作* @param options 重试配置选项* @param logger 可选的日志记录器* @returns 操作结果- *+ ** @example* ```typescript* const result = await withRetry(@@ -40,7 +40,7 @@ export interface RetryOptions {export async function withRetry<T>(operation: () => Promise<T>,options: RetryOptions = {},- logger?: Logger[keyof Logger]+ logger?: Logger[keyof Logger],): Promise<T> {const {maxAttempts = 3,@@ -48,7 +48,7 @@ export async function withRetry<T>(maxDelay = 30000,timeout = 30000,retryCondition = () => true,- delayStrategy = 'exponential'+ delayStrategy = 'exponential',} = optionslet lastError: Error@@ -56,15 +56,18 @@ export async function withRetry<T>(for (let attempt = 1; attempt <= maxAttempts; attempt++) {try {logger?.info(`Operation attempt ${attempt}/${maxAttempts}`)-+// 应用超时机制const result = await Promise.race([operation(),- new Promise<never>((_, reject) =>- setTimeout(() => reject(new Error(`Operation timeout after ${timeout}ms`)), timeout)- )+ new Promise<never>((_, reject) =>+ setTimeout(+ () => reject(new Error(`Operation timeout after ${timeout}ms`)),+ timeout,+ ),+ ),])-+if (attempt > 1) {logger?.success(`Operation succeeded on attempt ${attempt}`)}@@ -72,12 +75,17 @@ export async function withRetry<T>(} catch (error) {lastError = error as Errorlogger?.warn(`Attempt ${attempt} failed:`, error)-+const shouldRetry = attempt < maxAttempts && retryCondition(lastError)if (shouldRetry) {- const delay = calculateDelay(attempt, baseDelay, maxDelay, delayStrategy)+ const delay = calculateDelay(+ attempt,+ baseDelay,+ maxDelay,+ delayStrategy,+ )logger?.info(`Retrying in ${delay}ms...`)- await new Promise(resolve => setTimeout(resolve, delay))+ await new Promise((resolve) => setTimeout(resolve, delay))}}}@@ -93,7 +101,7 @@ function calculateDelay(attempt: number,baseDelay: number,maxDelay: number,- strategy: 'exponential' | 'linear' | 'fixed'+ strategy: 'exponential' | 'linear' | 'fixed',): number {let delay: number@@ -125,51 +133,64 @@ export const RetryConditions = {networkErrors: (error: Error) => {const message = error.message.toLowerCase()// 不重试客户端错误 (4xx)- if (message.includes('400') || message.includes('401') ||- message.includes('403') || message.includes('404')) {+ if (+ message.includes('400') ||+ message.includes('401') ||+ message.includes('403') ||+ message.includes('404')+ ) {return false}// 重试网络相关错误- return message.includes('timeout') ||- message.includes('network') ||- message.includes('fetch') ||- message.includes('econnreset') ||- message.includes('enotfound') ||- message.includes('502') ||- message.includes('503') ||- message.includes('504')+ return (+ message.includes('timeout') ||+ message.includes('network') ||+ message.includes('fetch') ||+ message.includes('econnreset') ||+ message.includes('enotfound') ||+ message.includes('502') ||+ message.includes('503') ||+ message.includes('504')+ )},/** 文件系统错误重试(排除权限和不存在错误) */fileSystemErrors: (error: Error) => {const message = error.message.toLowerCase()// 不重试权限和文件不存在错误- if (message.includes('eacces') || message.includes('enoent') ||- message.includes('permission denied')) {+ if (+ message.includes('eacces') ||+ message.includes('enoent') ||+ message.includes('permission denied')+ ) {return false}// 重试临时性文件系统错误- return message.includes('ebusy') ||- message.includes('emfile') ||- message.includes('enfile') ||- message.includes('eagain')+ return (+ message.includes('ebusy') ||+ message.includes('emfile') ||+ message.includes('enfile') ||+ message.includes('eagain')+ )},/** 资源竞争错误重试 */resourceErrors: (error: Error) => {const message = error.message.toLowerCase()- return message.includes('busy') ||- message.includes('locked') ||- message.includes('resource') ||- message.includes('memory') ||- message.includes('cpu')+ return (+ message.includes('busy') ||+ message.includes('locked') ||+ message.includes('resource') ||+ message.includes('memory') ||+ message.includes('cpu')+ )},/** 始终重试 */always: () => true,/** 从不重试 */- never: () => false+ never: () => false,}/**@@ -181,7 +202,7 @@ export const RetryPresets = {maxAttempts: 3,baseDelay: 500,timeout: 5000,- delayStrategy: 'exponential' as const+ delayStrategy: 'exponential' as const,},/** 标准重试:适用于一般操作 */@@ -189,7 +210,7 @@ export const RetryPresets = {maxAttempts: 3,baseDelay: 1000,timeout: 10000,- delayStrategy: 'exponential' as const+ delayStrategy: 'exponential' as const,},/** 网络重试:适用于网络请求 */@@ -198,7 +219,7 @@ export const RetryPresets = {baseDelay: 1000,timeout: 30000,delayStrategy: 'exponential' as const,- retryCondition: RetryConditions.networkErrors+ retryCondition: RetryConditions.networkErrors,},/** 文件操作重试:适用于文件系统操作 */@@ -207,7 +228,7 @@ export const RetryPresets = {baseDelay: 500,timeout: 15000,delayStrategy: 'linear' as const,- retryCondition: RetryConditions.fileSystemErrors+ retryCondition: RetryConditions.fileSystemErrors,},/** 慢速重试:适用于重量级操作 */@@ -215,6 +236,6 @@ export const RetryPresets = {maxAttempts: 3,baseDelay: 2000,timeout: 60000,- delayStrategy: 'exponential' as const- }-}\ No newline at end of file+ delayStrategy: 'exponential' as const,+ },+}diff --git a/shared/types/global.d.ts b/shared/types/global.d.tsindex 08489f94..0df6f43b 100644--- a/shared/types/global.d.ts+++ b/shared/types/global.d.ts@@ -4,4 +4,4 @@ declare global {var __workerPool: WorkerPool | undefined}-export {}\ No newline at end of file+export {}diff --git a/shared/types/settings.ts b/shared/types/settings.tsindex 7a193770..e4892eb6 100644--- a/shared/types/settings.ts+++ b/shared/types/settings.ts@@ -1,7 +1,12 @@import type * as schema from '../../server/database/schema'export type SettingType = typeof schema.settings.$inferSelect.type-export type SettingValue = string | number | boolean | Record<string, any> | null+export type SettingValue =+ | string+ | number+ | boolean+ | Record<string, any>+ | nullexport type SettingConfig = Omit<typeof schema.settings.$inferInsert,@@ -12,8 +17,10 @@ export type SettingConfig = Omit<enum?: ReadonlyArray<string>}-export type SettingStorageProvider = typeof schema.settings_storage_providers.$inferSelect-export type NewSettingStorageProvider = typeof schema.settings_storage_providers.$inferInsert+export type SettingStorageProvider =+ typeof schema.settings_storage_providers.$inferSelect+export type NewSettingStorageProvider =+ typeof schema.settings_storage_providers.$inferInsert/*** UI 字段类型枚举