Skip to content

Self-hosted personal gallery application with online photo management and albums, supporting Live/Motion Photos, EXIF parsing, geolocation recognition, and an explore map.

chore: adjust i18n, configuration and update documents

Timothy Yinfb4a5122238d
diff --git a/.env.example b/.env.example
index 2bb892bf..285725c6 100644
--- a/.env.example
+++ b/.env.example
@@ -18,7 +18,7 @@ NUXT_PUBLIC_MAPBOX_ACCESS_TOKEN=
# Mapbox secret access token for server-side, Mapbox Search API (Reverse Geocoding)
NUXT_MAPBOX_ACCESS_TOKEN=
-# Photo files storage provider: s3
+# Storage provider (s3/local)
NUXT_STORAGE_PROVIDER=s3
# S3 storage provider configuration
NUXT_PROVIDER_S3_ENDPOINT=
@@ -29,12 +29,10 @@ NUXT_PROVIDER_S3_SECRET_ACCESS_KEY=
NUXT_PROVIDER_S3_PREFIX=photos/
NUXT_PROVIDER_S3_CDN_URL=
-# 本地存储路径(绝对路径)
-# Windows 示例:C:\Users\you\WebstormProjects\chronoframe\storage
-# Linux/macOS 示例:/app/storage
-NUXT_PROVIDER_LOCAL_PATH=
+# Local storage provider configuration
+NUXT_PROVIDER_LOCAL_PATH=./data/storage
-# 对外访问前缀(已内置路由 /storage/*)
+# external access base URL for local storage, e.g. /storage (built-in /storage route)
NUXT_PROVIDER_LOCAL_BASE_URL=/storage
# Session password for encrypting session data, 32 characters long
@@ -51,6 +49,10 @@ NUXT_ALLOW_INSECURE_COOKIE=false
# Google Analytics Measurement ID (e.g. G-XXXXXXX)
NUXT_PUBLIC_GTAG_ID=
+# Matomo Analytics configuration
+NUXT_PUBLIC_ANALYTICS_MATOMO_ENABLED=false
+NUXT_PUBLIC_ANALYTICS_MATOMO_URL=
+NUXT_PUBLIC_ANALYTICS_MATOMO_SITE_ID=
# -----------------
# Upload Configuration
diff --git a/README.md b/README.md
index 2bd8abbe..54cefb17 100644
--- a/README.md
+++ b/README.md
@@ -42,56 +42,49 @@ A smooth photo display and management application, supporting multiple image for
We recommend deploying with the prebuilt Docker image. [View the image on ghcr](https://github.com/HoshinoSuzumi/chronoframe/pkgs/container/chronoframe)
-Before deployment, create a `.env` file and configure environment variables.
+Create a `.env` file and configure environment variables.
-You can copy the example file to get started:
-```bash
-cp env.example .env
-```
-
-Then edit the `.env` file with your configuration. For complete configuration reference, see [env.example](./env.example).
+Below is a **minimal configuration** example. For complete configuration options, see [.env.example](./.env.example):
```env
-# Admin user email (required)
+# Admin email (required)
CFRAME_ADMIN_EMAIL=
-# Admin user name (default to Chronoframe, optional)
+# Admin username (optional, default: Chronoframe)
CFRAME_ADMIN_NAME=
-# Admin user password (default to CF1234@!, optional)
+# Admin password (optional, default: CF1234@!)
CFRAME_ADMIN_PASSWORD=
-# App info
+# Site title (optional)
NUXT_PUBLIC_APP_TITLE=
+# Site slogan (optional)
NUXT_PUBLIC_APP_SLOGAN=
+# Site author (optional)
NUXT_PUBLIC_APP_AUTHOR=
+# Site avatar URL (optional)
NUXT_PUBLIC_APP_AVATAR_URL=
-# Mapbox access token for map features, Mapbox GL JS (Client-side, public)
+# Mapbox access token (required)
NUXT_PUBLIC_MAPBOX_ACCESS_TOKEN=
-# Mapbox secret access token for server-side, Mapbox Search API (Reverse Geocoding)
+# Mapbox unrestricted access token (optional)
NUXT_MAPBOX_ACCESS_TOKEN=
-# Storage provider (s3/github/local)
-NUXT_STORAGE_PROVIDER=s3
-# S3 storage config
+# Storage provider (local/s3, choose one)
+NUXT_STORAGE_PROVIDER=local
+
+# S3 storage configuration
NUXT_PROVIDER_S3_ENDPOINT=
NUXT_PROVIDER_S3_BUCKET=chronoframe
NUXT_PROVIDER_S3_REGION=auto
NUXT_PROVIDER_S3_ACCESS_KEY_ID=
NUXT_PROVIDER_S3_SECRET_ACCESS_KEY=
-NUXT_PROVIDER_S3_PREFIX=photos/
NUXT_PROVIDER_S3_CDN_URL=
-# Session password (32 chars, required)
-NUXT_SESSION_PASSWORD=
-
-# GitHub OAuth
-NUXT_PUBLIC_OAUTH_GITHUB_ENABLED=false
-NUXT_OAUTH_GITHUB_CLIENT_ID=
-NUXT_OAUTH_GITHUB_CLIENT_SECRET=
+# Local storage configuration
+# (If using local storage, ensure /app/data directory is mounted)
+NUXT_PROVIDER_LOCAL_PATH=/app/data/photos
-# Upload file type whitelist (optional)
-NUXT_UPLOAD_MIME_WHITELIST_ENABLED=true
-NUXT_UPLOAD_MIME_WHITELIST=image/jpeg,image/png,image/webp,image/gif,image/bmp,image/tiff,image/heic,image/heif,video/quicktime,video/mp4
+# Session password (required, 32 random characters)
+NUXT_SESSION_PASSWORD=
```
### Docker
diff --git a/README_zh.md b/README_zh.md
index f1998629..cee974d2 100644
--- a/README_zh.md
+++ b/README_zh.md
@@ -45,55 +45,49 @@
推荐使用预构建的 docker 镜像部署,[在 ghcr 上查看镜像](https://github.com/HoshinoSuzumi/chronoframe/pkgs/container/chronoframe)
-部署前请先创建 `.env` 文件并配置环境变量。
+创建 `.env` 文件并配置。
-你可以复制示例文件开始:
-```bash
-cp env.example .env
-```
-
-然后编辑 `.env` 文件,填入你的配置。完整配置说明请参考 [env.example](./env.example)。
+下面是**最小化配置**示例,完整的配置项参考 [.env.example](./.env.example):
```env
-# Admin user email (required)
+# 管理员邮箱 (必须)
CFRAME_ADMIN_EMAIL=
-# Admin user name (default to Chronoframe, optional)
+# 管理员用户名 (可选, 默认 Chronoframe)
CFRAME_ADMIN_NAME=
-# Admin user password (default to CF1234@!, optional)
+# 管理员密码 (可选, 默认 CF1234@!)
CFRAME_ADMIN_PASSWORD=
-# 应用标题与口号
+# 站点标题 (可选)
NUXT_PUBLIC_APP_TITLE=
+# 站点口号 (可选)
NUXT_PUBLIC_APP_SLOGAN=
+# 站点作者 (可选)
NUXT_PUBLIC_APP_AUTHOR=
+# 站点头像 URL (可选)
NUXT_PUBLIC_APP_AVATAR_URL=
-# Mapbox access token for map features, Mapbox GL JS (Client-side, public)
+# Mapbox 访问令牌 (必须)
NUXT_PUBLIC_MAPBOX_ACCESS_TOKEN=
-# Mapbox secret access token for server-side, Mapbox Search API (Reverse Geocoding)
+# Mapbox 无 URL 限制访问令牌 (可选)
NUXT_MAPBOX_ACCESS_TOKEN=
-# 存储提供者(s3/github/local)
-NUXT_STORAGE_PROVIDER=s3
+# 存储提供者 (local/s3, 选其一)
+NUXT_STORAGE_PROVIDER=local
+
# S3 存储服务配置
NUXT_PROVIDER_S3_ENDPOINT=
NUXT_PROVIDER_S3_BUCKET=chronoframe
NUXT_PROVIDER_S3_REGION=auto
NUXT_PROVIDER_S3_ACCESS_KEY_ID=
NUXT_PROVIDER_S3_SECRET_ACCESS_KEY=
-NUXT_PROVIDER_S3_PREFIX=photos/
NUXT_PROVIDER_S3_CDN_URL=
-# 会话密码(32 位随机字符串,必须设置)
-NUXT_SESSION_PASSWORD=
-
-# GitHub OAuth
-NUXT_OAUTH_GITHUB_CLIENT_ID=
-NUXT_OAUTH_GITHUB_CLIENT_SECRET=
+# Local 存储配置
+# (如果使用 local 存储, 请确保挂载了 /app/data 目录)
+NUXT_PROVIDER_LOCAL_PATH=/app/data/photos
-# 上传文件类型白名单(可选)
-NUXT_UPLOAD_MIME_WHITELIST_ENABLED=true
-NUXT_UPLOAD_MIME_WHITELIST=image/jpeg,image/png,image/webp,image/gif,image/bmp,image/tiff,image/heic,image/heif,video/quicktime,video/mp4
+# 会话密码 (必须, 32 位随机字符串)
+NUXT_SESSION_PASSWORD=
```
### Docker
diff --git a/app/components/ui/UploadQueueItem.vue b/app/components/ui/UploadQueueItem.vue
index 23e1efbe..be3f980a 100644
--- a/app/components/ui/UploadQueueItem.vue
+++ b/app/components/ui/UploadQueueItem.vue
@@ -200,7 +200,7 @@ const generateParticleStyle = (index: number) => {
layout
>
<!-- 文件信息头部 -->
- <div class="flex items-start justify-between mb-3">
+ <div class="flex items-start justify-between">
<div class="flex items-center gap-3 flex-1 min-w-0">
<!-- 文件图标 -->
<motion.div
@@ -265,7 +265,7 @@ const generateParticleStyle = (index: number) => {
:transition="{ delay: 0.2, duration: 0.3, ease: 'backOut' }"
>
<Icon
- name="tabler:arrow-right"
+ name="tabler:arrow-big-right-lines"
class="size-3 text-white"
/>
</motion.div>
@@ -279,7 +279,7 @@ const generateParticleStyle = (index: number) => {
:transition="{ delay: 0.2, duration: 0.3, ease: 'backOut' }"
>
<Icon
- name="tabler:x"
+ name="tabler:cancel"
class="size-3 text-white"
/>
</motion.div>
@@ -392,7 +392,7 @@ const generateParticleStyle = (index: number) => {
:animate="{ opacity: 1, height: 'auto' }"
:exit="{ opacity: 0, height: 0 }"
:transition="{ duration: 0.3 }"
- class="space-y-2"
+ class="space-y-2 mt-3"
>
<!-- 上传进度 -->
<div
diff --git a/app/composables/useUpload.ts b/app/composables/useUpload.ts
index 616e5008..b4ff575a 100644
--- a/app/composables/useUpload.ts
+++ b/app/composables/useUpload.ts
@@ -39,7 +39,7 @@ export function useUpload(options: UseUploadOptions = {}) {
headers = {},
speedSampleSize = 5,
maxRetries = 3,
- retryDelay = 1000
+ retryDelay = 1000,
} = options
// 响应式状态
@@ -49,20 +49,22 @@ export function useUpload(options: UseUploadOptions = {}) {
loaded: 0,
total: 0,
percentage: 0,
- }
+ },
})
// 当前的 XMLHttpRequest 实例
let currentXHR: XMLHttpRequest | null = null
-
+
// 用于计算速度的数据点
const speedSamples: Array<{ timestamp: number; loaded: number }> = []
// 计算上传速度和剩余时间
- const calculateSpeed = (loaded: number): { speed: number; timeRemaining?: number } => {
+ const calculateSpeed = (
+ loaded: number,
+ ): { speed: number; timeRemaining?: number } => {
const now = Date.now()
speedSamples.push({ timestamp: now, loaded })
-
+
// 保持样本数量在限制内
if (speedSamples.length > speedSampleSize) {
speedSamples.shift()
@@ -75,14 +77,14 @@ export function useUpload(options: UseUploadOptions = {}) {
// 计算平均速度
const firstSample = speedSamples[0]
const lastSample = speedSamples[speedSamples.length - 1]
-
+
if (!firstSample || !lastSample) {
return { speed: 0 }
}
-
+
const timeDiff = (lastSample.timestamp - firstSample.timestamp) / 1000 // 转换为秒
const bytesDiff = lastSample.loaded - firstSample.loaded
-
+
const speed = timeDiff > 0 ? bytesDiff / timeDiff : 0
// 计算剩余时间
@@ -102,13 +104,13 @@ export function useUpload(options: UseUploadOptions = {}) {
const updateProgress = (loaded: number, total: number) => {
const percentage = total > 0 ? Math.round((loaded / total) * 100) : 0
const { speed, timeRemaining } = calculateSpeed(loaded)
-
+
const progress: UploadProgress = {
loaded,
total,
percentage,
speed,
- timeRemaining
+ timeRemaining,
}
updateStatus({ progress })
@@ -126,7 +128,7 @@ export function useUpload(options: UseUploadOptions = {}) {
},
error: undefined,
startTime: undefined,
- endTime: undefined
+ endTime: undefined,
})
}
@@ -135,7 +137,7 @@ export function useUpload(options: UseUploadOptions = {}) {
file: File,
signedUrl: string,
callbacks: UploadCallbacks = {},
- attempt: number = 1
+ attempt: number = 1,
): Promise<XMLHttpRequest> => {
// 重置状态(仅在第一次尝试时)
if (attempt === 1) {
@@ -181,38 +183,33 @@ export function useUpload(options: UseUploadOptions = {}) {
xhr.addEventListener('error', () => {
const endTime = Date.now()
let errorMessage = ''
- let suggestion = ''
-
+
if (xhr.status === 0) {
// 状态码 0 通常表示网络连接失败、CORS 问题或服务器不可达
errorMessage = '网络连接失败'
- suggestion = '请检查网络连接或稍后重试。如果问题持续存在,可能是服务器配置问题。'
} else if (xhr.status >= 400 && xhr.status < 500) {
errorMessage = `客户端错误 (${xhr.status})`
- suggestion = '请检查文件格式和大小是否符合要求。'
} else if (xhr.status >= 500) {
errorMessage = `服务器错误 (${xhr.status})`
- suggestion = '服务器暂时不可用,请稍后重试。'
} else {
errorMessage = `网络错误 (状态码: ${xhr.status})`
- suggestion = '请检查网络连接后重试。'
}
-
+
// 检查是否可以重试
- const canRetry = attempt < maxRetries && (
- xhr.status === 0 || // 网络错误
- xhr.status >= 500 || // 服务器错误
- xhr.status === 429 // 频率限制
- )
-
+ const canRetry =
+ attempt < maxRetries &&
+ (xhr.status === 0 || // 网络错误
+ xhr.status >= 500 || // 服务器错误
+ xhr.status === 429) // 频率限制
+
if (canRetry) {
- updateStatus({
- status: 'error',
- error: `${errorMessage} (尝试 ${attempt}/${maxRetries})`,
- endTime
+ updateStatus({
+ status: 'error',
+ error: `${errorMessage} (尝试 ${attempt}/${maxRetries})`,
+ endTime,
})
callbacks.onRetry?.(attempt, maxRetries)
-
+
// 延迟后重试
setTimeout(() => {
uploadFile(file, signedUrl, callbacks, attempt + 1)
@@ -231,19 +228,18 @@ export function useUpload(options: UseUploadOptions = {}) {
xhr.addEventListener('timeout', () => {
const endTime = Date.now()
const errorMessage = `上传超时 (${timeout}ms)`
- const suggestion = '文件可能过大或网络较慢,请尝试:1) 检查网络连接;2) 稍后重试;3) 尝试上传较小的文件。'
-
+
// 检查是否可以重试(超时也可以重试)
const canRetry = attempt < maxRetries
-
+
if (canRetry) {
- updateStatus({
- status: 'error',
- error: `${errorMessage} (尝试 ${attempt}/${maxRetries})`,
- endTime
+ updateStatus({
+ status: 'error',
+ error: `${errorMessage} (尝试 ${attempt}/${maxRetries})`,
+ endTime,
})
callbacks.onRetry?.(attempt, maxRetries)
-
+
// 延迟后重试
setTimeout(() => {
uploadFile(file, signedUrl, callbacks, attempt + 1)
@@ -276,57 +272,45 @@ export function useUpload(options: UseUploadOptions = {}) {
} else if (xhr.status >= 400) {
const endTime = Date.now()
let errorMessage = ''
- let suggestion = ''
-
+
// 根据状态码提供更友好的错误信息
switch (xhr.status) {
case 400:
errorMessage = '请求格式错误'
- suggestion = '请检查文件格式是否正确。'
break
case 401:
errorMessage = '未授权访问'
- suggestion = '请重新登录后再试。'
break
case 403:
errorMessage = '访问被拒绝'
- suggestion = '您没有权限执行此操作。'
break
case 404:
errorMessage = '上传接口不存在'
- suggestion = '请检查应用配置或联系管理员。'
break
case 409:
errorMessage = '文件冲突'
- suggestion = '文件已存在,请重命名后重新上传。'
break
case 413:
errorMessage = '文件过大'
- suggestion = '请选择更小的文件(建议小于 128MB)。'
break
case 415:
errorMessage = '不支持的文件类型'
- suggestion = '请上传支持的文件格式(JPEG、PNG、HEIC、MOV)。'
break
case 429:
errorMessage = '上传频率过高'
- suggestion = '请稍等片刻后再试。'
break
case 500:
errorMessage = '服务器内部错误'
- suggestion = '服务器暂时出现问题,请稍后重试。'
break
case 502:
case 503:
case 504:
errorMessage = '服务器暂时不可用'
- suggestion = '服务器正在维护中,请稍后重试。'
break
default:
errorMessage = `HTTP 错误: ${xhr.status}`
- suggestion = '请检查网络连接后重试。'
}
-
+
// 尝试获取服务器返回的详细错误信息
try {
const responseText = xhr.responseText
@@ -335,7 +319,6 @@ export function useUpload(options: UseUploadOptions = {}) {
const responseData = JSON.parse(responseText)
if (responseData.data?.message) {
errorMessage = responseData.data.title || errorMessage
- suggestion = responseData.data.suggestion || suggestion
}
} catch {
// 如果不是 JSON,使用原始文本
@@ -357,8 +340,11 @@ export function useUpload(options: UseUploadOptions = {}) {
xhr.open('PUT', signedUrl)
// 设置请求头
- xhr.setRequestHeader('Content-Type', file.type || 'application/octet-stream')
-
+ xhr.setRequestHeader(
+ 'Content-Type',
+ file.type || 'application/octet-stream',
+ )
+
// 设置自定义请求头
Object.entries(headers).forEach(([key, value]) => {
xhr.setRequestHeader(key, value)
@@ -388,7 +374,7 @@ export function useUpload(options: UseUploadOptions = {}) {
// 格式化时间
const formatTime = (seconds: number): string => {
if (!isFinite(seconds) || seconds < 0) return '计算中...'
-
+
const hours = Math.floor(seconds / 3600)
const minutes = Math.floor((seconds % 3600) / 60)
const secs = Math.floor(seconds % 60)
@@ -412,14 +398,15 @@ export function useUpload(options: UseUploadOptions = {}) {
// 格式化的进度信息
const formattedProgress = computed(() => {
- const { loaded, total, percentage, speed, timeRemaining } = uploadStatus.value.progress
+ const { loaded, total, percentage, speed, timeRemaining } =
+ uploadStatus.value.progress
return {
percentage,
loadedText: formatBytes(loaded),
totalText: formatBytes(total),
speedText: speed ? `${formatBytes(speed)}/s` : '',
timeRemainingText: timeRemaining ? formatTime(timeRemaining) : '',
- progressText: `${formatBytes(loaded)} / ${formatBytes(total)} (${percentage}%)`
+ progressText: `${formatBytes(loaded)} / ${formatBytes(total)} (${percentage}%)`,
}
})
@@ -430,14 +417,12 @@ export function useUpload(options: UseUploadOptions = {}) {
currentXHR = null
})
} catch {
- // 忽略在非组件 setup 上下文中调用时的生命周期注册
+ /* empty */
}
return {
- // 状态
uploadStatus: readonly(uploadStatus),
-
- // 计算属性
+
isUploading,
isIdle,
isSuccess,
@@ -445,12 +430,11 @@ export function useUpload(options: UseUploadOptions = {}) {
isAborted,
canAbort,
formattedProgress,
-
- // 方法
+
uploadFile,
abortUpload,
resetStatus,
formatBytes,
- formatTime
+ formatTime,
}
}
diff --git a/app/pages/dashboard/photos.vue b/app/pages/dashboard/photos.vue
index f544abac..83b25ba5 100644
--- a/app/pages/dashboard/photos.vue
+++ b/app/pages/dashboard/photos.vue
@@ -36,7 +36,7 @@ const reactionsLoading = ref(false)
// 获取表态数据
const fetchReactions = async (photoIds: string[]) => {
if (photoIds.length === 0) return
-
+
reactionsLoading.value = true
try {
const data = await $fetch('/api/photos/reactions', {
@@ -123,33 +123,16 @@ const uploadImage = async (file: File, existingFileId?: string) => {
})
uploadingFile.signedUrlResponse = signedUrlResponse
-
+
// 检查是否为跳过模式(重复文件)
if (signedUrlResponse.skipped) {
uploadingFile.status = 'skipped'
uploadingFile.progress = 100
uploadingFile.canAbort = false
uploadingFiles.value = new Map(uploadingFiles.value)
-
- // 显示跳过信息
- toast.add({
- title: signedUrlResponse.title || '文件已存在',
- description: signedUrlResponse.message || '文件已存在,已自动跳过上传',
- color: 'warning',
- })
return
}
-
- // 检查是否为警告模式(重复文件但继续上传)
- if (signedUrlResponse.duplicate && signedUrlResponse.warningInfo) {
- toast.add({
- title: signedUrlResponse.warningInfo.title || '检测到重复文件',
- description: signedUrlResponse.warningInfo.message || '文件已存在,继续上传将会覆盖现有照片',
- color: 'warning',
- timeout: 8000,
- })
- }
-
+
uploadingFile.status = 'uploading'
uploadingFile.canAbort = true
uploadingFile.progress = 0
@@ -232,41 +215,16 @@ const uploadImage = async (file: File, existingFileId?: string) => {
} catch (error: any) {
uploadingFile.status = 'error'
uploadingFile.canAbort = false
-
+
// 处理重复文件阻止模式的错误
if (error.statusCode === 409 && error.data?.duplicate) {
uploadingFile.status = 'blocked'
uploadingFile.error = error.data.title || '文件已存在'
-
- // 显示详细的错误信息
- toast.add({
- title: error.data.title || '文件已存在',
- description: error.data.message || '无法上传重复文件',
- color: 'error',
- timeout: 10000,
- })
-
- // 如果有建议信息,也显示
- if (error.data.suggestion) {
- setTimeout(() => {
- toast.add({
- title: '解决建议',
- description: error.data.suggestion,
- color: 'info',
- timeout: 8000,
- })
- }, 1000)
- }
} else {
// 其他错误
uploadingFile.error = error.message || '上传失败'
- toast.add({
- title: '上传失败',
- description: error.message || '上传过程中发生错误',
- color: 'error',
- })
}
-
+
uploadingFiles.value = new Map(uploadingFiles.value)
// 提供更详细的错误信息
@@ -676,11 +634,7 @@ const columns: TableColumn<Photo>[] = [
)
if (totalReactions === 0) {
- return h(
- 'span',
- { class: 'text-neutral-400 text-xs' },
- '无表态',
- )
+ return h('span', { class: 'text-neutral-400 text-xs' }, '无表态')
}
const reactionIcons: Record<string, string> = {
@@ -705,22 +659,23 @@ const columns: TableColumn<Photo>[] = [
{ class: 'flex items-center gap-2' },
[
...topReactions.map(([type, count]) =>
- h(
- 'div',
- { class: 'flex items-center gap-0.5' },
- [
- h(Icon, {
- name: reactionIcons[type] || 'fluent-emoji-flat:face-with-tears-of-joy',
- class: 'size-4',
- mode: 'svg',
- }),
- h(
- 'span',
- { class: 'text-xs font-medium text-neutral-700 dark:text-neutral-300' },
- count,
- ),
- ],
- ),
+ h('div', { class: 'flex items-center gap-0.5' }, [
+ h(Icon, {
+ name:
+ reactionIcons[type] ||
+ 'fluent-emoji-flat:face-with-tears-of-joy',
+ class: 'size-4',
+ mode: 'svg',
+ }),
+ h(
+ 'span',
+ {
+ class:
+ 'text-xs font-medium text-neutral-700 dark:text-neutral-300',
+ },
+ count,
+ ),
+ ]),
),
totalReactions > topReactions.length
? h(
@@ -1255,12 +1210,14 @@ onUnmounted(() => {
size="sm"
icon="tabler:refresh"
:loading="reactionsLoading"
- @click="async () => {
- await refresh()
- if (filteredData.length > 0) {
- await fetchReactions(filteredData.map((p: Photo) => p.id))
+ @click="
+ async () => {
+ await refresh()
+ if (filteredData.length > 0) {
+ await fetchReactions(filteredData.map((p: Photo) => p.id))
+ }
}
- }"
+ "
>
<span class="hidden sm:inline">刷新</span>
</UButton>
diff --git a/docs/guide/configuration.md b/docs/guide/configuration.md
index edcb6ad1..bf60834a 100644
--- a/docs/guide/configuration.md
+++ b/docs/guide/configuration.md
@@ -4,34 +4,39 @@ Whether using Docker or Docker Compose (.env) deployment, configuration is done
## Environment Variables List
-| Environment Variable | Description | Default | Required |
-| ---------------------------------- | --------------------------------------------------------------- | ----------- | --------------------------------------------- |
-| CFRAME_ADMIN_EMAIL | Initial admin user email | None | Yes |
-| CFRAME_ADMIN_NAME | Initial admin username | Chronoframe | No |
-| CFRAME_ADMIN_PASSWORD | Initial admin user password | CF1234@! | No |
-| NUXT_PUBLIC_APP_TITLE | Application title | ChronoFrame | No |
-| NUXT_PUBLIC_APP_SLOGAN | Application slogan | None | No |
-| NUXT_PUBLIC_APP_AUTHOR | Application author | None | No |
-| NUXT_PUBLIC_APP_AVATAR_URL | Application avatar URL | None | No |
-| NUXT_PUBLIC_MAPBOX_ACCESS_TOKEN | Mapbox access token (URL restricted), for map services | None | Yes |
-| NUXT_MAPBOX_ACCESS_TOKEN | Mapbox access token (no URL restriction), for location services | None | No |
-| NUXT_STORAGE_PROVIDER | Storage provider, supports `s3`, `github`, `local` | `s3` | Yes |
-| NUXT_PROVIDER_S3_ENDPOINT | S3 compatible storage service endpoint | None | Required when `NUXT_STORAGE_PROVIDER` is `s3` |
-| NUXT_PROVIDER_S3_BUCKET | S3 bucket name | chronoframe | Required when `NUXT_STORAGE_PROVIDER` is `s3` |
-| NUXT_PROVIDER_S3_REGION | S3 bucket region | auto | Required when `NUXT_STORAGE_PROVIDER` is `s3` |
-| NUXT_PROVIDER_S3_ACCESS_KEY_ID | S3 access key ID | None | Required when `NUXT_STORAGE_PROVIDER` is `s3` |
-| NUXT_PROVIDER_S3_SECRET_ACCESS_KEY | S3 secret access key | None | Required when `NUXT_STORAGE_PROVIDER` is `s3` |
-| NUXT_PROVIDER_S3_PREFIX | S3 storage prefix | photos/ | No |
-| NUXT_PROVIDER_S3_CDN_URL | S3 storage CDN URL | None | No |
-| NUXT_PUBLIC_OAUTH_GITHUB_ENABLED | Enable GitHub OAuth login | false | No |
-| NUXT_OAUTH_GITHUB_CLIENT_ID | GitHub OAuth app Client ID | None | No (optional, for GitHub login) |
-| NUXT_OAUTH_GITHUB_CLIENT_SECRET | GitHub OAuth app Client Secret | None | No (optional, for GitHub login) |
-| NUXT_SESSION_PASSWORD | Password for encrypting sessions, 32-character random string | None | Yes |
-| NUXT_PUBLIC_GTAG_ID | Google Analytics Tracking ID | None | No |
-| NUXT_UPLOAD_MIME_WHITELIST_ENABLED | Enable MIME type whitelist validation for uploads | true | No |
-| NUXT_UPLOAD_MIME_WHITELIST | Allowed MIME types for uploads (comma-separated) | See below | No |
-| NUXT_UPLOAD_DUPLICATE_CHECK_ENABLED | Enable duplicate file detection during upload | true | No |
-| NUXT_UPLOAD_DUPLICATE_CHECK_MODE | Duplicate handling mode: warn/block/skip | warn | No |
+| Environment Variable | Description | Default | Required |
+| -------------------------------------------- | -------------------------------------------------------------------- | ----------------------- | --------------------------------------------- |
+| CFRAME_ADMIN_EMAIL | Initial admin user email | `[email protected]` | Yes |
+| CFRAME_ADMIN_NAME | Initial admin username | `Chronoframe` | No |
+| CFRAME_ADMIN_PASSWORD | Initial admin user password | `CF1234@!` | No |
+| NUXT_PUBLIC_APP_TITLE | Application title | `ChronoFrame` | No |
+| NUXT_PUBLIC_APP_SLOGAN | Application slogan | None | No |
+| NUXT_PUBLIC_APP_AUTHOR | Application author | None | No |
+| NUXT_PUBLIC_APP_AVATAR_URL | Application avatar URL | None | No |
+| NUXT_PUBLIC_COLOR_MODE_PREFERENCE | Color mode preference, options: `light`, `dark`, `system` | `system` | No |
+| NUXT_PUBLIC_MAPBOX_ACCESS_TOKEN | Mapbox access token (URL restricted), for map services | None | Yes |
+| NUXT_MAPBOX_ACCESS_TOKEN | Mapbox access token (no URL restriction), for location services | None | No |
+| NUXT_STORAGE_PROVIDER | Storage provider, supports `s3`, `github`, `local` | `s3` | Yes |
+| NUXT_PROVIDER_S3_ENDPOINT | S3 compatible storage service endpoint | None | Required when `NUXT_STORAGE_PROVIDER` is `s3` |
+| NUXT_PROVIDER_S3_BUCKET | S3 bucket name | `chronoframe` | Required when `NUXT_STORAGE_PROVIDER` is `s3` |
+| NUXT_PROVIDER_S3_REGION | S3 bucket region | `auto` | Required when `NUXT_STORAGE_PROVIDER` is `s3` |
+| NUXT_PROVIDER_S3_ACCESS_KEY_ID | S3 access key ID | None | Required when `NUXT_STORAGE_PROVIDER` is `s3` |
+| NUXT_PROVIDER_S3_SECRET_ACCESS_KEY | S3 secret access key | None | Required when `NUXT_STORAGE_PROVIDER` is `s3` |
+| NUXT_PROVIDER_S3_PREFIX | S3 storage prefix | `photos/` | No |
+| NUXT_PROVIDER_S3_CDN_URL | S3 storage CDN URL | None | No |
+| NUXT_PUBLIC_OAUTH_GITHUB_ENABLED | Enable GitHub OAuth login | `false` | No |
+| NUXT_OAUTH_GITHUB_CLIENT_ID | GitHub OAuth app Client ID | None | No (optional, for GitHub login) |
+| NUXT_OAUTH_GITHUB_CLIENT_SECRET | GitHub OAuth app Client Secret | None | No (optional, for GitHub login) |
+| NUXT_SESSION_PASSWORD | Password for encrypting sessions, 32-character random string | None | Yes |
+| NUXT_PUBLIC_GTAG_ID | Google Analytics Tracking ID | None | No |
+| NUXT_PUBLIC_ANALYTICS_MATOMO_ENABLED | Enable Matomo analytics tracking | `false` | No |
+| NUXT_PUBLIC_ANALYTICS_MATOMO_URL | Matomo instance URL (e.g., https://matomo.example.com) | None | No (required when Matomo is enabled) |
+| NUXT_PUBLIC_ANALYTICS_MATOMO_SITE_ID | Matomo site ID | None | No (required when Matomo is enabled) |
+| NUXT_UPLOAD_MIME_WHITELIST_ENABLED | Enable MIME type whitelist validation for uploads | `true` | No |
+| NUXT_UPLOAD_MIME_WHITELIST | Allowed MIME types for uploads (comma-separated) | See below | No |
+| NUXT_UPLOAD_DUPLICATE_CHECK_ENABLED | Enable duplicate file detection during upload | `true` | No |
+| NUXT_UPLOAD_DUPLICATE_CHECK_MODE | Duplicate handling mode, options: `warn`, `block`, `skip` | `skip` | No |
+| ALLOW_INSECURE_COOKIE | Allow insecure cookies (only for development environment) | `false` | No |
## Upload File Type Whitelist
@@ -63,7 +68,18 @@ NUXT_UPLOAD_MIME_WHITELIST_ENABLED=false
`NUXT_UPLOAD_DUPLICATE_CHECK_MODE` has three modes:
-### warn (Warning Mode) - Default
+### skip (Skip Mode) - Default
+
+- Skips upload when duplicate file is detected
+- Returns existing photo info without any operations
+- Suitable for automatic deduplication during batch uploads
+
+```
+NUXT_UPLOAD_DUPLICATE_CHECK_MODE=skip
+```
+
+### warn (Warning Mode)
+
- Shows warning when duplicate file is detected
- Continues upload, will overwrite existing photo data
- Suitable for scenarios where photo updates are needed
@@ -73,6 +89,7 @@ NUXT_UPLOAD_DUPLICATE_CHECK_MODE=warn
```
### block (Block Mode)
+
- Rejects upload if duplicate file is detected
- Returns 409 error, doesn't allow overwriting
- Suitable for scenarios requiring strict duplicate prevention
@@ -81,15 +98,6 @@ NUXT_UPLOAD_DUPLICATE_CHECK_MODE=warn
NUXT_UPLOAD_DUPLICATE_CHECK_MODE=block
```
-### skip (Skip Mode)
-- Skips upload when duplicate file is detected
-- Returns existing photo info without any operations
-- Suitable for automatic deduplication during batch uploads
-
-```
-NUXT_UPLOAD_DUPLICATE_CHECK_MODE=skip
-```
-
### Completely Disable Detection
```
diff --git a/docs/zh/guide/configuration.md b/docs/zh/guide/configuration.md
index fd44c814..09463365 100644
--- a/docs/zh/guide/configuration.md
+++ b/docs/zh/guide/configuration.md
@@ -4,38 +4,44 @@
## 环境变量列表
-| 环境变量 | 说明 | 默认值 | 必需 |
-| ---------------------------------- | ---------------------------------------------- | ----------- | ----------------------------------------- |
-| CFRAME_ADMIN_EMAIL | 初始管理员用户的邮箱 | 无 | 是 |
-| CFRAME_ADMIN_NAME | 初始管理员用户的用户名 | Chronoframe | 否 |
-| CFRAME_ADMIN_PASSWORD | 初始管理员用户的密码 | CF1234@! | 否 |
-| NUXT_PUBLIC_APP_TITLE | 应用标题 | ChronoFrame | 否 |
-| NUXT_PUBLIC_APP_SLOGAN | 应用口号 | 无 | 否 |
-| NUXT_PUBLIC_APP_AUTHOR | 应用作者 | 无 | 否 |
-| NUXT_PUBLIC_APP_AVATAR_URL | 应用头像 URL | 无 | 否 |
-| NUXT_PUBLIC_MAPBOX_ACCESS_TOKEN | Mapbox 访问令牌(可限制 URL),用于地图服务 | 无 | 是 |
-| NUXT_MAPBOX_ACCESS_TOKEN | Mapbox 访问令牌(无 URL 限制),用于位置信息服务 | 无 | 否 |
-| NUXT_STORAGE_PROVIDER | 存储提供者,支持 `s3`、`github`、`local` | `s3` | 是 |
-| NUXT_PROVIDER_S3_ENDPOINT | S3 兼容存储服务的 Endpoint | 无 | 当 `NUXT_STORAGE_PROVIDER` 为 `s3` 时必需 |
-| NUXT_PROVIDER_S3_BUCKET | S3 存储桶名称 | chronoframe | 当 `NUXT_STORAGE_PROVIDER` 为 `s3` 时必需 |
-| NUXT_PROVIDER_S3_REGION | S3 存储桶区域 | auto | 当 `NUXT_STORAGE_PROVIDER` 为 `s3` 时必需 |
-| NUXT_PROVIDER_S3_ACCESS_KEY_ID | S3 访问密钥 ID | 无 | 当 `NUXT_STORAGE_PROVIDER` 为 `s3` 时必需 |
-| NUXT_PROVIDER_S3_SECRET_ACCESS_KEY | S3 访问密钥 | 无 | 当 `NUXT_STORAGE_PROVIDER` 为 `s3` 时必需 |
-| NUXT_PROVIDER_S3_PREFIX | S3 存储前缀 | photos/ | 否 |
-| NUXT_PROVIDER_S3_CDN_URL | S3 存储的 CDN 地址 | 无 | 否 |
-| NUXT_PUBLIC_OAUTH_GITHUB_ENABLED | 是否启用 GitHub OAuth 登录 | false | 否 |
-| NUXT_OAUTH_GITHUB_CLIENT_ID | GitHub OAuth 应用的 Client ID | 无 | 否(可选,用于 GitHub 登录) |
-| NUXT_OAUTH_GITHUB_CLIENT_SECRET | GitHub OAuth 应用的 Client Secret | 无 | 否(可选,用于 GitHub 登录) |
-| NUXT_SESSION_PASSWORD | 用于加密会话的密码,32 位随机字符串 | 无 | 是 |
-| NUXT_PUBLIC_GTAG_ID | Google Analytics 追踪 ID | 无 | 否 |
-| NUXT_UPLOAD_MIME_WHITELIST_ENABLED | 是否启用上传文件 MIME 类型白名单验证 | true | 否 |
-| NUXT_UPLOAD_MIME_WHITELIST | 上传文件允许的 MIME 类型列表(逗号分隔) | 见下方说明 | 否 |
-| NUXT_UPLOAD_DUPLICATE_CHECK_ENABLED | 是否启用重复文件检测 | true | 否 |
-| NUXT_UPLOAD_DUPLICATE_CHECK_MODE | 重复文件处理模式:warn/block/skip | warn | 否 |
+| 环境变量 | 说明 | 默认值 | 必需 |
+| ------------------------------------ | ---------------------------------------------------- | ----------------------- | ----------------------------------------- |
+| CFRAME_ADMIN_EMAIL | 初始管理员用户的邮箱 | `[email protected]` | 是 |
+| CFRAME_ADMIN_NAME | 初始管理员用户的用户名 | `Chronoframe` | 否 |
+| CFRAME_ADMIN_PASSWORD | 初始管理员用户的密码 | `CF1234@!` | 否 |
+| NUXT_PUBLIC_APP_TITLE | 应用标题 | `ChronoFrame` | 否 |
+| NUXT_PUBLIC_APP_SLOGAN | 应用口号 | 无 | 否 |
+| NUXT_PUBLIC_APP_AUTHOR | 应用作者 | 无 | 否 |
+| NUXT_PUBLIC_APP_AVATAR_URL | 应用头像 URL | 无 | 否 |
+| NUXT_PUBLIC_COLOR_MODE_PREFERENCE | 颜色模式偏好,可选 `light`、`dark`、`system` | system | 否 |
+| NUXT_PUBLIC_MAPBOX_ACCESS_TOKEN | Mapbox 访问令牌(可限制 URL),用于地图服务 | 无 | 是 |
+| NUXT_MAPBOX_ACCESS_TOKEN | Mapbox 访问令牌(无 URL 限制),用于位置信息服务 | 无 | 否 |
+| NUXT_STORAGE_PROVIDER | 存储提供者,支持 `s3`、`github`、`local` | `s3` | 是 |
+| NUXT_PROVIDER_S3_ENDPOINT | S3 兼容存储服务的 Endpoint | 无 | 当 `NUXT_STORAGE_PROVIDER` 为 `s3` 时必需 |
+| NUXT_PROVIDER_S3_BUCKET | S3 存储桶名称 | `chronoframe` | 当 `NUXT_STORAGE_PROVIDER` 为 `s3` 时必需 |
+| NUXT_PROVIDER_S3_REGION | S3 存储桶区域 | `auto` | 当 `NUXT_STORAGE_PROVIDER` 为 `s3` 时必需 |
+| NUXT_PROVIDER_S3_ACCESS_KEY_ID | S3 访问密钥 ID | 无 | 当 `NUXT_STORAGE_PROVIDER` 为 `s3` 时必需 |
+| NUXT_PROVIDER_S3_SECRET_ACCESS_KEY | S3 访问密钥 | 无 | 当 `NUXT_STORAGE_PROVIDER` 为 `s3` 时必需 |
+| NUXT_PROVIDER_S3_PREFIX | S3 存储前缀 | `photos/` | 否 |
+| NUXT_PROVIDER_S3_CDN_URL | S3 存储的 CDN 地址 | 无 | 否 |
+| NUXT_PUBLIC_OAUTH_GITHUB_ENABLED | 是否启用 GitHub OAuth 登录 | `false` | 否 |
+| NUXT_OAUTH_GITHUB_CLIENT_ID | GitHub OAuth 应用的 Client ID | 无 | 否(可选,用于 GitHub 登录) |
+| NUXT_OAUTH_GITHUB_CLIENT_SECRET | GitHub OAuth 应用的 Client Secret | 无 | 否(可选,用于 GitHub 登录) |
+| NUXT_SESSION_PASSWORD | 用于加密会话的密码,32 位随机字符串 | 无 | 是 |
+| NUXT_PUBLIC_GTAG_ID | Google Analytics 追踪 ID | 无 | 否 |
+| NUXT_PUBLIC_ANALYTICS_MATOMO_ENABLED | 是否启用 Matomo 分析追踪 | `false` | 否 |
+| NUXT_PUBLIC_ANALYTICS_MATOMO_URL | Matomo 实例 URL 地址(如: https://matomo.example.com) | 无 | 否(启用 Matomo 时必需) |
+| NUXT_PUBLIC_ANALYTICS_MATOMO_SITE_ID | Matomo 站点 ID | 无 | 否(启用 Matomo 时必需) |
+| NUXT_UPLOAD_MIME_WHITELIST_ENABLED | 是否启用上传文件 MIME 类型白名单验证 | `true` | 否 |
+| NUXT_UPLOAD_MIME_WHITELIST | 上传文件允许的 MIME 类型列表(逗号分隔) | 见下方说明 | 否 |
+| NUXT_UPLOAD_DUPLICATE_CHECK_ENABLED | 是否启用重复文件检测 | `true` | 否 |
+| NUXT_UPLOAD_DUPLICATE_CHECK_MODE | 重复文件处理模式,可选 `warn`、`block`、`skip` | `skip` | 否 |
+| ALLOW_INSECURE_COOKIE | 是否允许非安全 Cookie(仅在开发环境使用) | `false` | 否 |
## 上传文件类型白名单
`NUXT_UPLOAD_MIME_WHITELIST` 的默认值包含以下 MIME 类型:
+
- `image/jpeg` - JPEG 图片
- `image/png` - PNG 图片
- `image/webp` - WebP 图片
@@ -48,11 +54,13 @@
- `video/mp4` - MP4 视频
如需自定义白名单,请使用逗号分隔的 MIME 类型字符串,例如:
+
```
NUXT_UPLOAD_MIME_WHITELIST=image/jpeg,image/png,video/mp4
```
如需禁用白名单验证(允许任何文件类型),可设置:
+
```
NUXT_UPLOAD_MIME_WHITELIST_ENABLED=false
```
@@ -63,7 +71,18 @@ NUXT_UPLOAD_MIME_WHITELIST_ENABLED=false
`NUXT_UPLOAD_DUPLICATE_CHECK_MODE` 有三种模式:
-### warn(警告模式)- 默认
+### skip(跳过模式)- 默认
+
+- 检测到重复文件时跳过上传
+- 返回现有照片信息,不进行任何操作
+- 适合批量上传时自动去重
+
+```
+NUXT_UPLOAD_DUPLICATE_CHECK_MODE=skip
+```
+
+### warn(警告模式)
+
- 检测到重复文件时显示警告
- 继续上传,会覆盖现有照片数据
- 适合需要更新照片的场景
@@ -73,6 +92,7 @@ NUXT_UPLOAD_DUPLICATE_CHECK_MODE=warn
```
### block(阻止模式)
+
- 检测到重复文件时拒绝上传
- 返回 409 错误,不允许覆盖
- 适合严格防止重复的场景
@@ -81,15 +101,6 @@ NUXT_UPLOAD_DUPLICATE_CHECK_MODE=warn
NUXT_UPLOAD_DUPLICATE_CHECK_MODE=block
```
-### skip(跳过模式)
-- 检测到重复文件时跳过上传
-- 返回现有照片信息,不进行任何操作
-- 适合批量上传时自动去重
-
-```
-NUXT_UPLOAD_DUPLICATE_CHECK_MODE=skip
-```
-
### 完全禁用检测
```
@@ -97,6 +108,7 @@ NUXT_UPLOAD_DUPLICATE_CHECK_ENABLED=false
```
**注意事项**:
+
- 重复检测基于文件名,不基于文件内容
- 相同文件名会生成相同的 photoId
- 即使禁用检测,上传同名文件仍会覆盖现有数据(数据库使用 `onConflictDoUpdate`)
diff --git a/i18n/localeDetector.ts b/i18n/localeDetector.ts
new file mode 100644
index 00000000..7c7fd593
--- /dev/null
+++ b/i18n/localeDetector.ts
@@ -0,0 +1,43 @@
+// Detect based on query, cookie, header
+export default defineI18nLocaleDetector((event, config) => {
+ // Helper function to normalize locale codes
+ const normalizeLocale = (locale: string | undefined): string | undefined => {
+ if (!locale) return undefined
+
+ // Map common locale codes to our configured locales
+ const localeMap: Record<string, string> = {
+ 'zh-CN': 'zh-Hans',
+ 'zh-SG': 'zh-Hans',
+ zh: 'zh-Hans',
+ 'zh-TW': 'zh-Hant-TW',
+ 'zh-HK': 'zh-Hant-HK',
+ 'zh-MO': 'zh-Hant-HK',
+ }
+
+ return localeMap[locale] || locale
+ }
+
+ // try to get locale from query
+ const query = tryQueryLocale(event, { lang: '' }) // disable locale default value with `lang` option
+ if (query) {
+ return normalizeLocale(query.toString()) || query.toString()
+ }
+
+ // try to get locale from cookie
+ const cookie = tryCookieLocale(event, {
+ lang: '',
+ name: 'chronoframe-locale',
+ }) // disable locale default value with `lang` option
+ if (cookie) {
+ return normalizeLocale(cookie.toString()) || cookie.toString()
+ }
+
+ // try to get locale from header (`accept-header`)
+ const header = tryHeaderLocale(event, { lang: '' }) // disable locale default value with `lang` option
+ if (header) {
+ return normalizeLocale(header.toString()) || header.toString()
+ }
+
+ // If the locale cannot be resolved up to this point, it is resolved with the value `defaultLocale` of the locale config passed to the function
+ return config.defaultLocale
+})
diff --git a/i18n/locales/en.json b/i18n/locales/en.json
index f66e3619..c8909d34 100644
--- a/i18n/locales/en.json
+++ b/i18n/locales/en.json
@@ -345,6 +345,7 @@
}
},
"common": {
+ "unknown": "unknown",
"months": {
"jan": "Jan",
"feb": "Feb",
@@ -380,6 +381,56 @@
}
}
},
+ "upload": {
+ "duplicate": {
+ "block": {
+ "title": "File Already Exists",
+ "message": "Photo \"{fileName}\" already exists and duplicate uploads are not allowed",
+ "suggestion": "You can: 1) Rename the file and upload again; 2) Switch to \"warn mode\" in settings to allow overwriting"
+ },
+ "skip": {
+ "title": "Duplicate File Skipped",
+ "message": "Photo \"{fileName}\" already exists and has been automatically skipped",
+ "info": "Existing photo taken on {dateTaken}"
+ },
+ "warn": {
+ "title": "Duplicate File Detected",
+ "message": "Photo \"{fileName}\" already exists. Continuing will overwrite the existing photo",
+ "warning": "After overwriting, all information of the original photo (EXIF, tags, reactions, etc.) will be replaced",
+ "info": "Existing photo: {title}, taken on {dateTaken}"
+ }
+ },
+ "success": {
+ "upload": {
+ "single": "Photo uploaded successfully, processing...",
+ "multiple": "{count} photos uploaded successfully, processing..."
+ },
+ "check": {
+ "title": "Check Complete",
+ "message": "Checked {total} files, found {duplicates} duplicates"
+ }
+ },
+ "error": {
+ "required": {
+ "title": "Missing Required Parameter",
+ "message": "Please provide {field} parameter"
+ },
+ "invalidType": {
+ "title": "Unsupported File Type",
+ "message": "Unsupported media type: {type}",
+ "suggestion": "Allowed types: {allowed}"
+ },
+ "tooLarge": {
+ "title": "File Too Large",
+ "message": "File size {size}MB exceeds limit",
+ "suggestion": "Maximum allowed: {maxSize}MB"
+ },
+ "uploadFailed": {
+ "title": "Upload Failed",
+ "message": "An error occurred during upload, please try again later"
+ }
+ }
+ },
"dashboard": {
"overview": {
"title": "Overview",
diff --git a/i18n/locales/zh-Hans.json b/i18n/locales/zh-Hans.json
index 7ed33790..66fbcbe4 100644
--- a/i18n/locales/zh-Hans.json
+++ b/i18n/locales/zh-Hans.json
@@ -345,6 +345,7 @@
}
},
"common": {
+ "unknown": "未知",
"months": {
"jan": "一月",
"feb": "二月",
@@ -380,6 +381,56 @@
}
}
},
+ "upload": {
+ "duplicate": {
+ "block": {
+ "title": "文件已存在",
+ "message": "照片 \"{fileName}\" 已存在,无法上传重复文件",
+ "suggestion": "您可以:1) 重命名文件后重新上传;2) 在设置中切换到\"警告模式\"以允许覆盖"
+ },
+ "skip": {
+ "title": "跳过重复文件",
+ "message": "照片 \"{fileName}\" 已存在,已自动跳过上传",
+ "info": "现有照片拍摄于 {dateTaken}"
+ },
+ "warn": {
+ "title": "检测到重复文件",
+ "message": "照片 \"{fileName}\" 已存在,继续上传将会覆盖现有照片",
+ "warning": "覆盖后,原有照片的所有信息(EXIF、标签、表态等)将被替换",
+ "info": "现有照片:{title},拍摄于 {dateTaken}"
+ }
+ },
+ "success": {
+ "upload": {
+ "single": "照片已成功上传,正在处理中...",
+ "multiple": "已成功上传 {count} 张照片,正在处理中..."
+ },
+ "check": {
+ "title": "检查完成",
+ "message": "已检查 {total} 个文件,发现 {duplicates} 个重复文件"
+ }
+ },
+ "error": {
+ "required": {
+ "title": "缺少必填参数",
+ "message": "请提供 {field} 参数"
+ },
+ "invalidType": {
+ "title": "不支持的文件类型",
+ "message": "不支持的媒体类型:{type}",
+ "suggestion": "允许的类型:{allowed}"
+ },
+ "tooLarge": {
+ "title": "文件太大",
+ "message": "文件大小 {size}MB 超过限制",
+ "suggestion": "最大允许 {maxSize}MB"
+ },
+ "uploadFailed": {
+ "title": "上传失败",
+ "message": "上传过程中发生错误,请稍后重试"
+ }
+ }
+ },
"dashboard": {
"overview": {
"title": "仪表板概览",
diff --git a/nuxt.config.ts b/nuxt.config.ts
index d62781ad..020ad932 100644
--- a/nuxt.config.ts
+++ b/nuxt.config.ts
@@ -58,7 +58,7 @@ export default defineNuxtConfig({
mapbox: {
accessToken: '',
},
- STORAGE_PROVIDER: 's3',
+ STORAGE_PROVIDER: 's3' satisfies 's3' | 'local',
provider: {
s3: {
endpoint: '',
@@ -69,14 +69,24 @@ export default defineNuxtConfig({
prefix: '',
cdnUrl: '',
},
+ local: {
+ localPath: './data/storage',
+ baseUrl: '/storage',
+ prefix: 'photos/',
+ },
+ },
+ upload: {
+ mime: {
+ whitelistEnabled: true,
+ whitelist:
+ 'image/jpeg,image/png,image/webp,image/gif,image/bmp,image/tiff,image/heic,image/heif,video/quicktime,video/mp4',
+ },
+ duplicateCheck: {
+ enabled: true,
+ mode: 'skip' as 'warn' | 'block' | 'skip',
+ },
},
- ALLOW_INSECURE_COOKIE: false,
- // 上传文件类型白名单配置
- UPLOAD_MIME_WHITELIST_ENABLED: true,
- UPLOAD_MIME_WHITELIST: 'image/jpeg,image/png,image/webp,image/gif,image/bmp,image/tiff,image/heic,image/heif,video/quicktime,video/mp4',
- // 重复文件检测配置
- UPLOAD_DUPLICATE_CHECK_ENABLED: true,
- UPLOAD_DUPLICATE_CHECK_MODE: 'warn', // 'warn' | 'block' | 'skip'
+ allowInsecureCookie: false,
},
nitro: {
@@ -159,12 +169,16 @@ export default defineNuxtConfig({
},
i18n: {
+ experimental: {
+ localeDetector: 'localeDetector.ts',
+ },
detectBrowserLanguage: {
fallbackLocale: 'en',
useCookie: false,
cookieKey: 'chronoframe-locale',
},
strategy: 'no_prefix',
+ defaultLocale: 'en',
locales: [
{
code: 'zh-Hans',
diff --git a/packages/webgl-image/src/workers/image-decoder.worker.js b/packages/webgl-image/src/workers/image-decoder.worker.js
index f14cd650..a1cf0d43 100644
--- a/packages/webgl-image/src/workers/image-decoder.worker.js
+++ b/packages/webgl-image/src/workers/image-decoder.worker.js
@@ -16,7 +16,7 @@ self.onmessage = async (event) => {
try {
const absolute = new URL(src, self.location?.origin || 'http://localhost')
src = absolute.toString()
- } catch {}
+ } catch { /* empty */ }
const response = await fetch(src, { mode: 'cors' })
if (!response.ok) {
throw new Error(`Failed to fetch image: ${response.status}`)
diff --git a/server/api/auth/github.get.ts b/server/api/auth/github.get.ts
index eda64508..db3ec59f 100644
--- a/server/api/auth/github.get.ts
+++ b/server/api/auth/github.get.ts
@@ -40,7 +40,7 @@ export default defineOAuthGitHubEventHandler({
{ user: userFromEmail },
{
cookie: {
- secure: !useRuntimeConfig().ALLOW_INSECURE_COOKIE,
+ secure: !useRuntimeConfig().allowInsecureCookie,
},
},
)
diff --git a/server/api/login.post.ts b/server/api/login.post.ts
index bb7a8605..fc417776 100644
--- a/server/api/login.post.ts
+++ b/server/api/login.post.ts
@@ -34,7 +34,7 @@ export default eventHandler(async (event) => {
{ user },
{
cookie: {
- secure: !useRuntimeConfig().ALLOW_INSECURE_COOKIE,
+ secure: !useRuntimeConfig().allowInsecureCookie,
},
},
)
diff --git a/server/api/photos/check-duplicate.post.ts b/server/api/photos/check-duplicate.post.ts
index 6b665ec1..c596aac6 100644
--- a/server/api/photos/check-duplicate.post.ts
+++ b/server/api/photos/check-duplicate.post.ts
@@ -1,7 +1,6 @@
import { z } from 'zod'
import { eq } from 'drizzle-orm'
import { generateSafePhotoId } from '~~/server/utils/file-utils'
-import { getMessage, getPreferredLanguage } from '~~/server/utils/upload-messages'
/**
* 检查照片是否已存在
@@ -10,7 +9,7 @@ import { getMessage, getPreferredLanguage } from '~~/server/utils/upload-message
export default defineEventHandler(async (event) => {
await requireUserSession(event)
- const lang = getPreferredLanguage(event)
+ const t = await useTranslation(event)
try {
const { fileNames, storageKeys } = await readValidatedBody(
@@ -22,11 +21,13 @@ export default defineEventHandler(async (event) => {
)
if (!fileNames && !storageKeys) {
- const errorMsg = getMessage('error', 'required', lang, 'fileNames or storageKeys')
throw createError({
statusCode: 400,
- statusMessage: errorMsg?.title || 'Missing required parameter',
- data: errorMsg,
+ statusMessage: t('upload.error.required.title'),
+ data: {
+ title: t('upload.error.required.title'),
+ message: t('upload.error.required.message', { field: 'fileNames or storageKeys' }),
+ },
})
}
@@ -99,17 +100,17 @@ export default defineEventHandler(async (event) => {
}
const duplicatesFound = results.filter(r => r.exists).length
- const successMsg = getMessage('success', 'check', lang, results.length, duplicatesFound)
return {
success: true,
results,
duplicatesFound,
- summary: successMsg || {
- title: lang === 'zh' ? '检查完成' : 'Check Complete',
- message: lang === 'zh'
- ? `已检查 ${results.length} 个文件,发现 ${duplicatesFound} 个重复文件`
- : `Checked ${results.length} files, found ${duplicatesFound} duplicates`,
+ summary: {
+ title: t('upload.success.check.title'),
+ message: t('upload.success.check.message', {
+ total: results.length,
+ duplicates: duplicatesFound
+ }),
},
}
} catch (error: any) {
@@ -117,12 +118,13 @@ export default defineEventHandler(async (event) => {
throw error
}
- const errorMsg = getMessage('error', 'uploadFailed', lang, error.message)
throw createError({
statusCode: 500,
- statusMessage: errorMsg?.title || 'Failed to check duplicates',
- data: errorMsg,
+ statusMessage: t('upload.error.uploadFailed.title'),
+ data: {
+ title: t('upload.error.uploadFailed.title'),
+ message: error.message || t('upload.error.uploadFailed.message'),
+ },
})
}
})
-
diff --git a/server/api/photos/index.post.ts b/server/api/photos/index.post.ts
index 2f7c5e82..313d9276 100644
--- a/server/api/photos/index.post.ts
+++ b/server/api/photos/index.post.ts
@@ -1,31 +1,29 @@
import { useStorageProvider } from '~~/server/utils/useStorageProvider'
import { eq } from 'drizzle-orm'
import { generateSafePhotoId } from '~~/server/utils/file-utils'
-import { getMessage, getPreferredLanguage } from '~~/server/utils/upload-messages'
export default eventHandler(async (event) => {
await requireUserSession(event)
const { storageProvider } = useStorageProvider(event)
- const lang = getPreferredLanguage(event)
+ const config = useRuntimeConfig(event)
+ const t = await useTranslation(event)
const body = await readBody(event)
const { fileName, contentType, skipDuplicateCheck } = body
if (!fileName) {
- const errorMsg = getMessage('error', 'required', lang, 'fileName')
throw createError({
statusCode: 400,
- statusMessage: errorMsg?.title || 'Missing required parameter',
- data: errorMsg,
+ statusMessage: t('upload.error.required.title'),
})
}
try {
const objectKey = `${(storageProvider.config?.prefix || '').replace(/\/+$/, '')}/${fileName}`
- const config = useRuntimeConfig(event)
// 重复文件检测
- const duplicateCheckEnabled = config.UPLOAD_DUPLICATE_CHECK_ENABLED && !skipDuplicateCheck
+ const duplicateCheckEnabled =
+ config.upload.duplicateCheck.enabled && !skipDuplicateCheck
let existingPhoto = null
if (duplicateCheckEnabled) {
@@ -46,29 +44,33 @@ export default eventHandler(async (event) => {
.get()
if (existingPhoto) {
- const checkMode = config.UPLOAD_DUPLICATE_CHECK_MODE || 'warn'
+ const checkMode = config.upload.duplicateCheck.mode || 'skip'
if (checkMode === 'block') {
// 阻止模式:直接拒绝上传
- const blockMsg = getMessage('duplicate', 'block', lang, fileName)
throw createError({
statusCode: 409,
- statusMessage: blockMsg?.title || 'File already exists',
+ statusMessage: t('upload.duplicate.block.title'),
data: {
duplicate: true,
existingPhoto,
- ...blockMsg,
+ title: t('upload.duplicate.block.title'),
+ message: t('upload.duplicate.block.message', { fileName }),
},
})
} else if (checkMode === 'skip') {
// 跳过模式:返回现有照片信息,不上传
- const skipMsg = getMessage('duplicate', 'skip', lang, fileName, existingPhoto)
return {
skipped: true,
duplicate: true,
existingPhoto,
fileKey: objectKey,
- ...skipMsg,
+ title: t('upload.duplicate.skip.title'),
+ message: t('upload.duplicate.skip.message', { fileName }),
+ info: t('upload.duplicate.skip.info', {
+ dateTaken:
+ existingPhoto.dateTaken || t('common.unknown', 'unknown date'),
+ }),
}
}
// 'warn' 模式:继续上传但返回警告信息
@@ -77,13 +79,9 @@ export default eventHandler(async (event) => {
// 若存储提供商支持预签名 URL,返回外部直传地址
if (storageProvider.getSignedUrl) {
- const signedUrl = await storageProvider.getSignedUrl(
- objectKey,
- 3600,
- {
- contentType: contentType || 'application/octet-stream',
- },
- )
+ const signedUrl = await storageProvider.getSignedUrl(objectKey, 3600, {
+ contentType: contentType || 'application/octet-stream',
+ })
const response: any = {
signedUrl,
@@ -92,11 +90,17 @@ export default eventHandler(async (event) => {
}
if (existingPhoto) {
- const warnMsg = getMessage('duplicate', 'warn', lang, fileName, existingPhoto)
response.duplicate = true
response.existingPhoto = existingPhoto
- if (warnMsg) {
- response.warningInfo = warnMsg
+ response.warningInfo = {
+ title: t('upload.duplicate.warn.title'),
+ message: t('upload.duplicate.warn.message', { fileName }),
+ warning: t('upload.duplicate.warn.warning'),
+ info: t('upload.duplicate.warn.info', {
+ title: existingPhoto.title || fileName,
+ dateTaken:
+ existingPhoto.dateTaken || t('common.unknown', 'unknown date'),
+ }),
}
}
@@ -112,11 +116,17 @@ export default eventHandler(async (event) => {
}
if (existingPhoto) {
- const warnMsg = getMessage('duplicate', 'warn', lang, fileName, existingPhoto)
response.duplicate = true
response.existingPhoto = existingPhoto
- if (warnMsg) {
- response.warningInfo = warnMsg
+ response.warningInfo = {
+ title: t('upload.duplicate.warn.title'),
+ message: t('upload.duplicate.warn.message', { fileName }),
+ warning: t('upload.duplicate.warn.warning'),
+ info: t('upload.duplicate.warn.info', {
+ title: existingPhoto.title || fileName,
+ dateTaken:
+ existingPhoto.dateTaken || t('common.unknown', 'unknown date'),
+ }),
}
}
@@ -126,6 +136,9 @@ export default eventHandler(async (event) => {
throw error
}
logger.chrono.error('Failed to prepare upload:', error)
- throw createError({ statusCode: 500, statusMessage: 'Failed to prepare upload' })
+ throw createError({
+ statusCode: 500,
+ statusMessage: 'Failed to prepare upload',
+ })
}
-})
\ No newline at end of file
+})
diff --git a/server/api/photos/upload.put.ts b/server/api/photos/upload.put.ts
index 04cecb7c..f5b9d040 100644
--- a/server/api/photos/upload.put.ts
+++ b/server/api/photos/upload.put.ts
@@ -1,19 +1,20 @@
import { useStorageProvider } from '~~/server/utils/useStorageProvider'
-import { getMessage, getPreferredLanguage } from '~~/server/utils/upload-messages'
export default eventHandler(async (event) => {
await requireUserSession(event)
const { storageProvider } = useStorageProvider(event)
const key = getQuery(event).key as string | undefined
- const lang = getPreferredLanguage(event)
+ const t = await useTranslation(event)
if (!key) {
- const errorMsg = getMessage('error', 'required', lang, 'key')
throw createError({
statusCode: 400,
- statusMessage: errorMsg?.title || 'Missing required parameter',
- data: errorMsg,
+ statusMessage: t('upload.error.required.title'),
+ data: {
+ title: t('upload.error.required.title'),
+ message: t('upload.error.required.message', { field: 'key' }),
+ },
})
}
@@ -21,20 +22,23 @@ export default eventHandler(async (event) => {
// MIME 类型白名单验证(可通过环境变量配置)
const config = useRuntimeConfig(event)
- const whitelistEnabled = config.UPLOAD_MIME_WHITELIST_ENABLED
+ const whitelistEnabled = config.upload.mime.whitelistEnabled
if (whitelistEnabled) {
- const whitelistStr = config.UPLOAD_MIME_WHITELIST
+ const whitelistStr = config.upload.mime.whitelist
const allowedTypes = whitelistStr
? whitelistStr.split(',').map((type: string) => type.trim()).filter(Boolean)
: []
if (allowedTypes.length > 0 && !allowedTypes.includes(contentType)) {
- const errorMsg = getMessage('error', 'invalidType', lang, contentType, allowedTypes)
throw createError({
statusCode: 415,
- statusMessage: errorMsg?.title || 'Unsupported media type',
- data: errorMsg,
+ statusMessage: t('upload.error.invalidType.title'),
+ data: {
+ title: t('upload.error.invalidType.title'),
+ message: t('upload.error.invalidType.message', { type: contentType }),
+ suggestion: t('upload.error.invalidType.suggestion', { allowed: allowedTypes.join(', ') }),
+ },
})
}
}
@@ -43,18 +47,26 @@ export default eventHandler(async (event) => {
if (!raw || !(raw instanceof Buffer)) {
throw createError({
statusCode: 400,
- statusMessage: lang === 'zh' ? '请求体为空' : 'Empty request body',
+ statusMessage: t('upload.error.uploadFailed.title'),
+ data: {
+ title: t('upload.error.uploadFailed.title'),
+ message: t('upload.error.uploadFailed.message'),
+ },
})
}
// 简单大小限制(例如 128MB)
const maxBytes = 128 * 1024 * 1024
if (raw.byteLength > maxBytes) {
- const errorMsg = getMessage('error', 'tooLarge', lang, raw.byteLength, 128)
+ const sizeInMB = (raw.byteLength / 1024 / 1024).toFixed(2)
throw createError({
statusCode: 413,
- statusMessage: errorMsg?.title || 'Payload too large',
- data: errorMsg,
+ statusMessage: t('upload.error.tooLarge.title'),
+ data: {
+ title: t('upload.error.tooLarge.title'),
+ message: t('upload.error.tooLarge.message', { size: sizeInMB }),
+ suggestion: t('upload.error.tooLarge.suggestion', { maxSize: 128 }),
+ },
})
}
@@ -64,4 +76,3 @@ export default eventHandler(async (event) => {
return { ok: true, key }
})
-
diff --git a/server/plugins/storage.ts b/server/plugins/storage.ts
index e3dfd440..8e05342d 100644
--- a/server/plugins/storage.ts
+++ b/server/plugins/storage.ts
@@ -16,36 +16,31 @@ export function getStorageManager(): StorageManager {
export default nitroPlugin(async (nitroApp) => {
const config = useRuntimeConfig()
- const devConfigs: Record<'s3' | 'r2' | 'local', StorageConfig> = {
+ const storageConfiguration: Record<'s3' | 'local', StorageConfig> = {
s3: {
provider: 's3',
- bucket: config.PROVIDER_S3_BUCKET,
- region: config.PROVIDER_S3_REGION,
- endpoint: config.PROVIDER_S3_ENDPOINT,
- prefix: config.PROVIDER_S3_PREFIX,
- cdnUrl: config.PROVIDER_S3_CDN_URL,
- accessKeyId: config.PROVIDER_S3_ACCESS_KEY_ID,
- secretAccessKey: config.PROVIDER_S3_SECRET_ACCESS_KEY,
- },
- r2: {
- provider: 'hub-r2',
- prefix: 'photos/',
- cdnUrl: import.meta.dev
- ? 'http://localhost:3000/image/'
- : 'https://cdn-dev.lens.bh8.ga/',
- maxKeys: 100,
+ bucket: config.provider.s3.bucket,
+ region: config.provider.s3.region,
+ endpoint: config.provider.s3.endpoint,
+ prefix: config.provider.s3.prefix,
+ cdnUrl: config.provider.s3.cdnUrl,
+ accessKeyId: config.provider.s3.accessKeyId,
+ secretAccessKey: config.provider.s3.secretAccessKey,
},
local: {
provider: 'local',
- basePath: process.env.NUXT_PROVIDER_LOCAL_PATH || path.resolve(process.cwd(), 'storage'),
- baseUrl: process.env.NUXT_PROVIDER_LOCAL_BASE_URL || '/storage',
- prefix: 'photos/',
+ basePath:
+ config.provider.local.localPath ||
+ path.resolve(process.cwd(), 'data', 'storage'),
+ baseUrl: config.provider.local.baseUrl || '/storage',
+ prefix: config.provider.local.prefix || 'photos/',
},
}
- const selectedProvider = (config.STORAGE_PROVIDER as 's3' | 'r2' | 'local') || 's3'
+ const selectedProvider =
+ (config.STORAGE_PROVIDER as 's3' | 'local') || 'local'
const storageManager = new StorageManager(
- devConfigs[selectedProvider],
+ storageConfiguration[selectedProvider],
logger.storage,
)
@@ -58,7 +53,7 @@ export default nitroPlugin(async (nitroApp) => {
// 本地存储路径校验与创建
if (selectedProvider === 'local') {
- const localBase = (devConfigs.local as any).basePath as string
+ const localBase = (storageConfiguration.local as any).basePath as string
try {
if (!path.isAbsolute(localBase)) {
logger.storage.warn(`LOCAL basePath is not absolute: ${localBase}`)
diff --git a/server/routes/storage/[...path].ts b/server/routes/storage/[...path].ts
index 200c1f20..017b5b4e 100644
--- a/server/routes/storage/[...path].ts
+++ b/server/routes/storage/[...path].ts
@@ -1,5 +1,6 @@
import path from 'node:path'
import { createReadStream, promises as fs } from 'node:fs'
+import { getStorageManager } from '../../plugins/storage'
// lightweight: avoid TS type dep; fallback when not resolvable
const guessContentType = (filePath: string): string => {
const ext = (filePath.split('.').pop() || '').toLowerCase()
@@ -28,10 +29,8 @@ const guessContentType = (filePath: string): string => {
return 'application/octet-stream'
}
}
-import { getStorageManager } from '../../plugins/storage'
export default defineEventHandler(async (event) => {
- const config = useRuntimeConfig(event)
const manager = getStorageManager()
const provider = manager.getProvider()
@@ -104,5 +103,3 @@ export default defineEventHandler(async (event) => {
const stream = createReadStream(absolute)
return sendStream(event, stream)
})
-
-
diff --git a/server/services/image/processor.ts b/server/services/image/processor.ts
index da676ab6..177abe7d 100644
--- a/server/services/image/processor.ts
+++ b/server/services/image/processor.ts
@@ -17,12 +17,17 @@ export interface ImageMeta {
format: string
}
// Minimal JPEG size extractor as last-resort fallback
-const tryExtractJpegSize = (buffer: Buffer): { width: number; height: number } | null => {
+const tryExtractJpegSize = (
+ buffer: Buffer,
+): { width: number; height: number } | null => {
// JPEG starts with 0xFFD8
if (buffer.length < 4 || buffer[0] !== 0xff || buffer[1] !== 0xd8) return null
let offset = 2
while (offset + 9 < buffer.length) {
- if (buffer[offset] !== 0xff) { offset++; continue }
+ if (buffer[offset] !== 0xff) {
+ offset++
+ continue
+ }
const marker = buffer[offset + 1]
offset += 2
// Skip padding FFs
@@ -32,7 +37,10 @@ const tryExtractJpegSize = (buffer: Buffer): { width: number; height: number } |
const length = (buffer[offset] << 8) + buffer[offset + 1]
if (length < 2) break
// SOF0..SOF3 and SOF5..SOF7 indicate dimensions
- if ((marker >= 0xc0 && marker <= 0xc3) || (marker >= 0xc5 && marker <= 0xc7)) {
+ if (
+ (marker >= 0xc0 && marker <= 0xc3) ||
+ (marker >= 0xc5 && marker <= 0xc7)
+ ) {
if (offset + 7 >= buffer.length) break
const height = (buffer[offset + 3] << 8) + buffer[offset + 4]
const width = (buffer[offset + 5] << 8) + buffer[offset + 6]
@@ -54,67 +62,79 @@ const getMetadataWithSharp = async (
sharpInst: sharp.Sharp,
): Promise<ImageMeta | null> => {
try {
- return await withRetry(async () => {
- let metadata = await sharpInst.metadata()
-
- // Fallback 1: try rotate() which can populate dimensions for some orientations
- if (!metadata.height || !metadata.width || !metadata.format) {
- try {
- metadata = await sharpInst.clone().rotate().metadata()
- } catch {}
- }
-
- // Fallback 2: re-instantiate sharp from a fresh buffer
- if (!metadata.height || !metadata.width || !metadata.format) {
- try {
- const buf = await sharpInst.clone().toBuffer()
- metadata = await sharp(buf).metadata()
- } catch {}
- }
-
- // Fallback 3: force re-encode to JPEG then read metadata
- if (!metadata.height || !metadata.width || !metadata.format) {
- try {
- const jpegBuf = await sharpInst.clone().jpeg().toBuffer()
- metadata = await sharp(jpegBuf).metadata()
- if (!metadata.height || !metadata.width) {
- const dims = tryExtractJpegSize(jpegBuf)
- if (dims) {
- metadata.width = dims.width
- metadata.height = dims.height
- metadata.format = metadata.format || 'jpeg'
+ return await withRetry(
+ async () => {
+ let metadata = await sharpInst.metadata()
+
+ // Fallback 1: try rotate() which can populate dimensions for some orientations
+ if (!metadata.height || !metadata.width || !metadata.format) {
+ try {
+ metadata = await sharpInst.clone().rotate().metadata()
+ } catch {
+ /* empty */
+ }
+ }
+
+ // Fallback 2: re-instantiate sharp from a fresh buffer
+ if (!metadata.height || !metadata.width || !metadata.format) {
+ try {
+ const buf = await sharpInst.clone().toBuffer()
+ metadata = await sharp(buf).metadata()
+ } catch {
+ /* empty */
+ }
+ }
+
+ // Fallback 3: force re-encode to JPEG then read metadata
+ if (!metadata.height || !metadata.width || !metadata.format) {
+ try {
+ const jpegBuf = await sharpInst.clone().jpeg().toBuffer()
+ metadata = await sharp(jpegBuf).metadata()
+ if (!metadata.height || !metadata.width) {
+ const dims = tryExtractJpegSize(jpegBuf)
+ if (dims) {
+ metadata.width = dims.width
+ metadata.height = dims.height
+ metadata.format = metadata.format || 'jpeg'
+ }
}
+ } catch {
+ /* empty */
}
- } catch {}
- }
-
- if (!metadata.height || !metadata.width || !metadata.format) {
- logger.image.warn('Incomplete metadata received:', {
- hasHeight: !!metadata.height,
- hasWidth: !!metadata.width,
- hasFormat: !!metadata.format,
- })
- return null
- }
-
- const { orientation } = metadata
- let { width, height } = metadata
-
- if (orientation && [5, 6, 7, 8].includes(orientation)) {
- ;[width, height] = [height, width]
- }
-
- logger.image.info(`Successfully extracted metadata: ${width}x${height} ${metadata.format}`)
- return {
- width: width,
- height: height,
- format: metadata.format,
- }
- }, {
- ...RetryPresets.fast,
- timeout: 10000,
- retryCondition: RetryConditions.resourceErrors
- }, logger.image)
+ }
+
+ if (!metadata.height || !metadata.width || !metadata.format) {
+ logger.image.warn('Incomplete metadata received:', {
+ hasHeight: !!metadata.height,
+ hasWidth: !!metadata.width,
+ hasFormat: !!metadata.format,
+ })
+ return null
+ }
+
+ const { orientation } = metadata
+ let { width, height } = metadata
+
+ if (orientation && [5, 6, 7, 8].includes(orientation)) {
+ ;[width, height] = [height, width]
+ }
+
+ logger.image.info(
+ `Successfully extracted metadata: ${width}x${height} ${metadata.format}`,
+ )
+ return {
+ width: width,
+ height: height,
+ format: metadata.format,
+ }
+ },
+ {
+ ...RetryPresets.fast,
+ timeout: 10000,
+ retryCondition: RetryConditions.resourceErrors,
+ },
+ logger.image,
+ )
} catch (error) {
logger.image.error('All metadata extraction attempts failed:', error)
return null
@@ -122,30 +142,38 @@ const getMetadataWithSharp = async (
}
export const convertHeicToJpeg = async (heicBuffer: Buffer) => {
- return await withRetry(async () => {
- // 检查文件大小,如果太大则降低质量
- const fileSizeMB = heicBuffer.length / (1024 * 1024)
- const quality = fileSizeMB > 10 ? 0.8 : 0.95
-
- const jpegBuffer = await heicConvert({
- // @ts-expect-error idk why there is a type error here
- buffer: heicBuffer,
- format: 'JPEG',
- quality,
- })
-
- logger.image.info(`Successfully converted HEIC to JPEG (quality: ${quality})`)
- return Buffer.from(jpegBuffer as ArrayBuffer)
- }, {
- ...RetryPresets.slow, // HEIC 转换是重量级操作
- timeout: 30000,
- retryCondition: (error) => {
- // HEIC 转换错误通常是资源相关的
- return RetryConditions.resourceErrors(error) ||
- error.message.includes('memory') ||
- error.message.includes('timeout')
- }
- }, logger.image)
+ return await withRetry(
+ async () => {
+ // 检查文件大小,如果太大则降低质量
+ const fileSizeMB = heicBuffer.length / (1024 * 1024)
+ const quality = fileSizeMB > 10 ? 0.8 : 0.95
+
+ const jpegBuffer = await heicConvert({
+ // @ts-expect-error idk why there is a type error here
+ buffer: heicBuffer,
+ format: 'JPEG',
+ quality,
+ })
+
+ logger.image.info(
+ `Successfully converted HEIC to JPEG (quality: ${quality})`,
+ )
+ return Buffer.from(jpegBuffer as ArrayBuffer)
+ },
+ {
+ ...RetryPresets.slow, // HEIC 转换是重量级操作
+ timeout: 30000,
+ retryCondition: (error) => {
+ // HEIC 转换错误通常是资源相关的
+ return (
+ RetryConditions.resourceErrors(error) ||
+ error.message.includes('memory') ||
+ error.message.includes('timeout')
+ )
+ },
+ },
+ logger.image,
+ )
}
export const convertBitmapToSharpInst = async (bitmapBuffer: Buffer) => {
@@ -294,7 +322,10 @@ export const processImageMetadataAndSharp = async (
const metadata = await getMetadataWithSharp(sharpInst)
if (!metadata) {
- logger.image.error('Metadata extraction returned null (after fallbacks):', s3key)
+ logger.image.error(
+ 'Metadata extraction returned null (after fallbacks):',
+ s3key,
+ )
return null
}
diff --git a/server/services/pipeline-queue/manager.ts b/server/services/pipeline-queue/manager.ts
index 904ebfbb..905a8e0d 100644
--- a/server/services/pipeline-queue/manager.ts
+++ b/server/services/pipeline-queue/manager.ts
@@ -447,7 +447,9 @@ export class QueueManager {
this.logger.warn(
`No matching photo found for LivePhoto video: ${videoKey}`,
)
- throw new Error(`No matching photo found for LivePhoto video: ${videoKey}`)
+ throw new Error(
+ `No matching photo found for LivePhoto video: ${videoKey}`,
+ )
}
const livePhotoVideoUrl = storageProvider.getPublicUrl(videoKey)
diff --git a/server/services/storage/providers/hub-r2.ts b/server/services/storage/providers/hub-r2.ts
index d69851e2..5627f41a 100644
--- a/server/services/storage/providers/hub-r2.ts
+++ b/server/services/storage/providers/hub-r2.ts
@@ -1,19 +1,13 @@
-import type { BlobObject } from '@nuxthub/core'
import type {
HubR2StorageConfig,
StorageObject,
StorageProvider,
+ UploadOptions,
} from '../interfaces'
-const convertToStorageObject = (blob: BlobObject): StorageObject => {
- return {
- key: blob.pathname,
- size: blob.size,
- lastModified: blob.uploadedAt,
- etag: blob.httpEtag,
- }
-}
-
+/**
+ * @deprecated DO NOT use HubR2StorageProvider anymore, use S3StorageProvider instead
+ */
export class HubR2StorageProvider implements StorageProvider {
config: HubR2StorageConfig
private logger?: Logger['storage']
@@ -22,40 +16,27 @@ export class HubR2StorageProvider implements StorageProvider {
this.config = config
this.logger = logger
}
+ getSignedUrl?(_key: string, _expiresIn?: number, _options?: UploadOptions): Promise<string> {
+ throw new Error('Method not implemented.')
+ }
+ getFileMeta(_key: string): Promise<StorageObject | null> {
+ throw new Error('Method not implemented.')
+ }
async create(
- key: string,
- fileBuffer: Buffer,
+ _key: string,
+ _fileBuffer: Buffer,
_contentType?: string,
): Promise<StorageObject> {
- const file = new File([new Uint8Array(fileBuffer)], key)
-
- if (!file || !file.size) {
- throw new Error('Invalid file')
- }
-
- ensureBlob(file, {
- maxSize: '128MB',
- })
-
- const blob = await hubBlob().put(key, file, {
- prefix: this.config.prefix,
- })
-
- return convertToStorageObject(blob)
+ throw new Error('Method not implemented.')
}
- async delete(key: string): Promise<void> {
- return await hubBlob().del(key)
+ async delete(_key: string): Promise<void> {
+ throw new Error('Method not implemented.')
}
- async get(key: string): Promise<Buffer | null> {
- const blob = await hubBlob().get(key)
- if (!blob) {
- return null
- }
- const arrayBuffer = await blob.arrayBuffer()
- return Buffer.from(arrayBuffer)
+ async get(_key: string): Promise<Buffer | null> {
+ throw new Error('Method not implemented.')
}
getPublicUrl(key: string): string {
@@ -69,11 +50,7 @@ export class HubR2StorageProvider implements StorageProvider {
}
async listAll(): Promise<StorageObject[]> {
- const { blobs } = await hubBlob().list({
- prefix: this.config.prefix,
- limit: this.config.maxKeys,
- })
- return blobs.map(convertToStorageObject)
+ throw new Error('Method not implemented.')
}
listImages(): Promise<StorageObject[]> {
diff --git a/server/utils/upload-messages.ts b/server/utils/upload-messages.ts
deleted file mode 100644
index d5e23ee6..00000000
--- a/server/utils/upload-messages.ts
+++ /dev/null
@@ -1,191 +0,0 @@
-/**
- * 上传相关的提示消息
- */
-
-export const UploadMessages = {
- // 重复文件相关
- duplicate: {
- block: {
- zh: (fileName: string) => ({
- title: '文件已存在',
- message: `照片 "${fileName}" 已存在,无法上传重复文件`,
- suggestion: '您可以:1) 重命名文件后重新上传;2) 在设置中切换到"警告模式"以允许覆盖',
- }),
- en: (fileName: string) => ({
- title: 'File Already Exists',
- message: `Photo "${fileName}" already exists and duplicate uploads are not allowed`,
- suggestion: 'You can: 1) Rename the file and upload again; 2) Switch to "warn mode" in settings to allow overwriting',
- }),
- },
- skip: {
- zh: (fileName: string, photoInfo?: any) => ({
- title: '跳过重复文件',
- message: `照片 "${fileName}" 已存在,已自动跳过上传`,
- info: photoInfo ? `现有照片拍摄于 ${photoInfo.dateTaken || '未知日期'}` : undefined,
- }),
- en: (fileName: string, photoInfo?: any) => ({
- title: 'Duplicate File Skipped',
- message: `Photo "${fileName}" already exists and has been automatically skipped`,
- info: photoInfo ? `Existing photo taken on ${photoInfo.dateTaken || 'unknown date'}` : undefined,
- }),
- },
- warn: {
- zh: (fileName: string, photoInfo?: any) => ({
- title: '检测到重复文件',
- message: `照片 "${fileName}" 已存在,继续上传将会覆盖现有照片`,
- warning: '覆盖后,原有照片的所有信息(EXIF、标签、表态等)将被替换',
- info: photoInfo ? `现有照片:${photoInfo.title || fileName},拍摄于 ${photoInfo.dateTaken || '未知日期'}` : undefined,
- }),
- en: (fileName: string, photoInfo?: any) => ({
- title: 'Duplicate File Detected',
- message: `Photo "${fileName}" already exists. Continuing will overwrite the existing photo`,
- warning: 'After overwriting, all information of the original photo (EXIF, tags, reactions, etc.) will be replaced',
- info: photoInfo ? `Existing photo: ${photoInfo.title || fileName}, taken on ${photoInfo.dateTaken || 'unknown date'}` : undefined,
- }),
- },
- },
-
- // 成功消息
- success: {
- upload: {
- zh: (count: number) => ({
- title: '上传成功',
- message: count === 1
- ? '照片已成功上传,正在处理中...'
- : `已成功上传 ${count} 张照片,正在处理中...`,
- }),
- en: (count: number) => ({
- title: 'Upload Successful',
- message: count === 1
- ? 'Photo uploaded successfully, processing...'
- : `${count} photos uploaded successfully, processing...`,
- }),
- },
- check: {
- zh: (total: number, duplicates: number) => ({
- title: '检查完成',
- message: `已检查 ${total} 个文件,发现 ${duplicates} 个重复文件`,
- }),
- en: (total: number, duplicates: number) => ({
- title: 'Check Complete',
- message: `Checked ${total} files, found ${duplicates} duplicates`,
- }),
- },
- },
-
- // 错误消息
- error: {
- required: {
- zh: (field: string) => ({
- title: '缺少必填参数',
- message: `请提供 ${field} 参数`,
- }),
- en: (field: string) => ({
- title: 'Missing Required Parameter',
- message: `Please provide ${field} parameter`,
- }),
- },
- invalidType: {
- zh: (type: string, allowed: string[]) => ({
- title: '不支持的文件类型',
- message: `不支持的媒体类型:${type}`,
- suggestion: `允许的类型:${allowed.join(', ')}`,
- }),
- en: (type: string, allowed: string[]) => ({
- title: 'Unsupported File Type',
- message: `Unsupported media type: ${type}`,
- suggestion: `Allowed types: ${allowed.join(', ')}`,
- }),
- },
- tooLarge: {
- zh: (size: number, maxSize: number) => ({
- title: '文件太大',
- message: `文件大小 ${(size / 1024 / 1024).toFixed(2)}MB 超过限制`,
- suggestion: `最大允许 ${maxSize}MB`,
- }),
- en: (size: number, maxSize: number) => ({
- title: 'File Too Large',
- message: `File size ${(size / 1024 / 1024).toFixed(2)}MB exceeds limit`,
- suggestion: `Maximum allowed: ${maxSize}MB`,
- }),
- },
- uploadFailed: {
- zh: (reason?: string) => ({
- title: '上传失败',
- message: reason || '上传过程中发生错误,请稍后重试',
- }),
- en: (reason?: string) => ({
- title: 'Upload Failed',
- message: reason || 'An error occurred during upload, please try again later',
- }),
- },
- },
-}
-
-/**
- * 获取消息内容(支持语言参数)
- */
-export function getMessage(
- category: keyof typeof UploadMessages,
- type: string,
- lang: 'zh' | 'en' = 'zh',
- ...args: any[]
-) {
- try {
- const messageGroup = UploadMessages[category] as any
- if (!messageGroup || !messageGroup[type]) {
- return null
- }
-
- const messageFunc = messageGroup[type][lang]
- if (typeof messageFunc === 'function') {
- return messageFunc(...args)
- }
-
- return messageFunc
- } catch (error) {
- return null
- }
-}
-
-/**
- * 从请求头获取客户端语言偏好
- */
-export function getPreferredLanguage(event: any): 'zh' | 'en' {
- const acceptLanguage = getHeader(event, 'accept-language') || ''
-
- // 检查是否包含中文
- if (acceptLanguage.includes('zh')) {
- return 'zh'
- }
-
- return 'en'
-}
-
-/**
- * 创建格式化的错误响应
- */
-export function createFormattedError(
- statusCode: number,
- messageKey: string,
- event: any,
- ...args: any[]
-) {
- const lang = getPreferredLanguage(event)
- const [category, type] = messageKey.split('.')
- const message = getMessage(category as any, type, lang, ...args)
-
- if (message) {
- return createError({
- statusCode,
- statusMessage: message.title,
- data: message,
- })
- }
-
- return createError({
- statusCode,
- statusMessage: 'An error occurred',
- })
-}
-