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
feat(avatar): upload the site avatar to the configured storage provider
Ahmet Ömer035f056d2db4
diff --git a/.env.example b/.env.exampleindex 0da80cee..72b57d3f 100644--- a/.env.example+++ b/.env.example@@ -9,6 +9,7 @@ CFRAME_ADMIN_PASSWORD=NUXT_PUBLIC_APP_TITLE=ChronoFrameNUXT_PUBLIC_APP_SLOGAN=Mems rest within the lens.NUXT_PUBLIC_APP_AUTHOR=+# External avatar URL. Optional; you can also upload an avatar from the dashboard (stored in the configured storage provider).NUXT_PUBLIC_APP_AVATAR_URL=# Color mode preference: light, dark, or systemNUXT_PUBLIC_COLOR_MODE_PREFERENCE=lightdiff --git a/README.md b/README.mdindex 098701a4..5028e889 100644--- a/README.md+++ b/README.md@@ -74,6 +74,7 @@ CFRAME_ADMIN_PASSWORD=NUXT_PUBLIC_APP_TITLE=NUXT_PUBLIC_APP_SLOGAN=NUXT_PUBLIC_APP_AUTHOR=+# External avatar URL (optional; you can also upload an avatar from the dashboard, stored in the configured storage provider)NUXT_PUBLIC_APP_AVATAR_URL=# Map provider (maplibre/mapbox)diff --git a/README_zh.md b/README_zh.mdindex a0d6a8d0..b23eb3ac 100644--- a/README_zh.md+++ b/README_zh.md@@ -74,6 +74,7 @@ CFRAME_ADMIN_PASSWORD=NUXT_PUBLIC_APP_TITLE=NUXT_PUBLIC_APP_SLOGAN=NUXT_PUBLIC_APP_AUTHOR=+# 外部头像 URL(可选,也可在后台上传头像,存储在已配置的存储提供商中)NUXT_PUBLIC_APP_AVATAR_URL=# 地图提供器 (maplibre/mapbox)diff --git a/app/components/loader/Avatar.vue b/app/components/loader/Avatar.vueindex dd2bbf6f..b42c0fe6 100644--- a/app/components/loader/Avatar.vue+++ b/app/components/loader/Avatar.vue@@ -14,6 +14,7 @@class="w-full h-full object-cover":src="getSetting('app:avatarUrl')?.toString()":alt="$t('ui.loading')"+ @error="handleAvatarError"/><imgv-elsediff --git a/app/components/masonry/item/Header.vue b/app/components/masonry/item/Header.vueindex 2fa553cb..6e3d26a1 100644--- a/app/components/masonry/item/Header.vue+++ b/app/components/masonry/item/Header.vue@@ -74,6 +74,7 @@ const isRepoLinkHovering = ref(false):class="!loggedIn && 'cursor-pointer'":alt="$t('ui.photo.avatarAlt')"@click="!loggedIn && handleOpenLogin()"+ @error="handleAvatarError"/></div><h1diff --git a/app/components/setting/SettingAvatar.vue b/app/components/setting/SettingAvatar.vuenew file mode 100644index 00000000..bee8ba81--- /dev/null+++ b/app/components/setting/SettingAvatar.vue@@ -0,0 +1,195 @@+<script setup lang="ts">+import { settingsFieldCommitKey } from '~/composables/useSettingsForm'+import {+ AVATAR_ALLOWED_MIME_TYPES,+ AVATAR_MAX_INPUT_BYTES,+} from '~~/shared/utils/avatar'++interface Props {+ modelValue?: string | null+ fieldKey?: string+ placeholder?: string+}++const props = defineProps<Props>()++const emit = defineEmits<{+ 'update:modelValue': [value: string]+}>()++const { t } = useI18n()+const toast = useToast()+const settingsStore = useSettingsStore()+const commitField = inject(settingsFieldCommitKey, undefined)++const ACCEPT = AVATAR_ALLOWED_MIME_TYPES.join(',')++const uploading = ref(false)+const removing = ref(false)+const previewError = ref(false)+const fileInput = ref<HTMLInputElement | null>(null)++const previewSrc = computed(() =>+ typeof props.modelValue === 'string' ? props.modelValue.trim() : '',+)++const showPreview = computed(() => !!previewSrc.value && !previewError.value)++watch(+ () => props.modelValue,+ () => {+ previewError.value = false+ },+)++const urlValue = computed({+ get: () => (typeof props.modelValue === 'string' ? props.modelValue : ''),+ set: (value: string) => emit('update:modelValue', value),+})++const openFilePicker = () => fileInput.value?.click()++const showError = (title: string, err?: unknown) => {+ const data = (err as { data?: Record<string, string> })?.data+ toast.add({+ title,+ description: data?.message || data?.title || (err as Error)?.message,+ color: 'error',+ })+}++const syncAfterSave = async (value: string) => {+ emit('update:modelValue', value)+ if (props.fieldKey) {+ commitField?.(props.fieldKey, value)+ }+ await settingsStore.refreshSettings()+}++const onFileChange = async (event: Event) => {+ const input = event.target as HTMLInputElement+ const file = input.files?.[0]+ input.value = ''+ if (!file) return++ if (+ file.type &&+ !(AVATAR_ALLOWED_MIME_TYPES as readonly string[]).includes(file.type)+ ) {+ showError(t('settings.app.avatarUrl.invalidType'))+ return+ }++ if (file.size > AVATAR_MAX_INPUT_BYTES) {+ showError(+ t('settings.app.avatarUrl.tooLarge', {+ size: AVATAR_MAX_INPUT_BYTES / 1024 / 1024,+ }),+ )+ return+ }++ uploading.value = true+ try {+ const form = new FormData()+ form.append('file', file)+ const { url } = await $fetch<{ url: string }>(+ '/api/system/settings/avatar',+ { method: 'POST', body: form },+ )+ await syncAfterSave(url)+ toast.add({+ title: t('settings.app.avatarUrl.uploadSuccess'),+ color: 'success',+ })+ } catch (err) {+ showError(t('settings.app.avatarUrl.uploadFailed'), err)+ } finally {+ uploading.value = false+ }+}++const removeAvatar = async () => {+ removing.value = true+ try {+ await $fetch('/api/system/settings/avatar', { method: 'DELETE' })+ await syncAfterSave('')+ toast.add({+ title: t('settings.app.avatarUrl.removeSuccess'),+ color: 'success',+ })+ } catch (err) {+ showError(t('settings.app.avatarUrl.removeFailed'), err)+ } finally {+ removing.value = false+ }+}+</script>++<template>+ <div class="w-full space-y-3">+ <div class="flex items-center gap-4">+ <div+ class="size-16 shrink-0 overflow-hidden rounded-full border border-neutral-200 bg-neutral-100 dark:border-neutral-800 dark:bg-neutral-900"+ >+ <img+ v-if="showPreview"+ :src="previewSrc"+ class="size-full object-cover"+ :alt="t('ui.photo.avatarAlt')"+ @error="previewError = true"+ />+ <div+ v-else+ class="flex size-full items-center justify-center text-neutral-400"+ >+ <UIcon+ name="tabler:user"+ class="size-7"+ />+ </div>+ </div>++ <div class="flex flex-wrap items-center gap-2">+ <UButton+ color="neutral"+ variant="outline"+ icon="tabler:upload"+ :loading="uploading"+ @click="openFilePicker"+ >+ {{+ previewSrc+ ? t('settings.app.avatarUrl.replace')+ : t('settings.app.avatarUrl.upload')+ }}+ </UButton>+ <UButton+ v-if="previewSrc"+ color="error"+ variant="soft"+ icon="tabler:trash"+ :loading="removing"+ @click="removeAvatar"+ >+ {{ t('settings.app.avatarUrl.remove') }}+ </UButton>+ <input+ ref="fileInput"+ type="file"+ class="hidden"+ :accept="ACCEPT"+ @change="onFileChange"+ />+ </div>+ </div>++ <UInput+ v-model="urlValue"+ type="url"+ icon="tabler:link"+ class="w-full"+ :placeholder="placeholder"+ />+ </div>+</template>diff --git a/app/components/setting/SettingField.vue b/app/components/setting/SettingField.vueindex 44386b98..d162d62b 100644--- a/app/components/setting/SettingField.vue+++ b/app/components/setting/SettingField.vue@@ -24,6 +24,7 @@ const getComponentName = (uiType: FieldUIType): string => {tabs: 'UTabs',toggle: 'USwitch',number: 'UInput',+ avatar: 'SettingAvatar',custom: 'UInput', // 默认降级到 input}@@ -37,6 +38,7 @@ const URadioGroup = resolveComponent('URadioGroup')const UTabs = resolveComponent('UTabs')const USwitch = resolveComponent('USwitch')const UFormField = resolveComponent('UFormField')+const SettingAvatar = resolveComponent('SettingAvatar')const componentName = computed(() => {const name = getComponentName(props.field.ui.type)@@ -53,6 +55,8 @@ const componentName = computed(() => {return UTabscase 'USwitch':return USwitch+ case 'SettingAvatar':+ return SettingAvatardefault:return UInput}@@ -99,6 +103,9 @@ const getComponentProps = (): Record<string, any> => {case 'textarea':propsMap.rows = props.field.ui.rows ?? 3break+ case 'avatar':+ propsMap.fieldKey = props.field.key+ break}return propsMapdiff --git a/app/composables/useSettingsForm.ts b/app/composables/useSettingsForm.tsindex 69e53155..d95a9f54 100644--- a/app/composables/useSettingsForm.ts+++ b/app/composables/useSettingsForm.ts@@ -1,8 +1,13 @@+import type { InjectionKey } from 'vue'import type {FieldDescriptor,SettingsFieldsResponse,} from '~~/shared/types/settings'+export const settingsFieldCommitKey: InjectionKey<+ (fieldKey: string, value: any) => void+> = Symbol('settings-field-commit')+/*** Settings Form Composable* 统一处理获取字段描述、管理表单状态、提交更新@@ -138,6 +143,14 @@ export function useSettingsForm(namespace: string) {return state[fieldKey]}+ const commitField = (fieldKey: string, value: any) => {+ state[fieldKey] = value+ const field = fields.value.find((item) => item.key === fieldKey)+ if (field) {+ field.value = value+ }+ }+// 组件挂载时自动获取字段onMounted(() => {fetchFields()@@ -159,5 +172,6 @@ export function useSettingsForm(namespace: string) {updateField,getField,getFieldValue,+ commitField,}}diff --git a/app/pages/dashboard/settings/general.vue b/app/pages/dashboard/settings/general.vueindex faf15a96..a8643042 100644--- a/app/pages/dashboard/settings/general.vue+++ b/app/pages/dashboard/settings/general.vue@@ -1,4 +1,6 @@<script lang="ts" setup>+import { settingsFieldCommitKey } from '~/composables/useSettingsForm'+definePageMeta({layout: 'dashboard',})@@ -9,7 +11,9 @@ useHead({const colorMode = useColorMode()-const { fields, state, submit, loading } = useSettingsForm('app')+const { fields, state, submit, loading, commitField } = useSettingsForm('app')++provide(settingsFieldCommitKey, commitField)const appFields = computed(() =>fields.value.filter((f) => !f.key.startsWith('appearance.')),diff --git a/app/utils/avatar.ts b/app/utils/avatar.tsnew file mode 100644index 00000000..731e5f87--- /dev/null+++ b/app/utils/avatar.ts@@ -0,0 +1,13 @@+export const DEFAULT_AVATAR_URL = '/web-app-manifest-192x192.png'++/**+ * `<img>` error handler that swaps a broken avatar for the default image.+ * Guarded so a broken fallback cannot loop.+ */+export function handleAvatarError(event: Event): void {+ const image = event.target as HTMLImageElement | null+ if (!image || image.src.includes('web-app-manifest-192x192')) {+ return+ }+ image.src = DEFAULT_AVATAR_URL+}diff --git a/docs/guide/configuration.md b/docs/guide/configuration.mdindex b1b84575..61c9e6cb 100644--- a/docs/guide/configuration.md+++ b/docs/guide/configuration.md@@ -12,7 +12,7 @@ Whether using Docker or Docker Compose (.env) deployment, configuration is done| 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_APP_AVATAR_URL | External application avatar URL (an avatar can also be uploaded from the dashboard, stored in the configured storage provider) | None | No || NUXT_PUBLIC_COLOR_MODE_PREFERENCE | Color mode preference, options: `light`, `dark`, `system` | `system` | No || NUXT_PUBLIC_MAP_PROVIDER | Map provider, options: `mapbox`, `maplibre` | `maplibre` | No || NUXT_PUBLIC_MAPBOX_ACCESS_TOKEN | Mapbox access token (URL restricted), for map services | None | Required when `NUXT_PUBLIC_MAP_PROVIDER` is `mapbox` |diff --git a/docs/zh/guide/configuration.md b/docs/zh/guide/configuration.mdindex 6bc2ab07..9ee8efb1 100644--- a/docs/zh/guide/configuration.md+++ b/docs/zh/guide/configuration.md@@ -12,7 +12,7 @@| NUXT_PUBLIC_APP_TITLE | 应用标题 | `ChronoFrame` | 否 || NUXT_PUBLIC_APP_SLOGAN | 应用口号 | 无 | 否 || NUXT_PUBLIC_APP_AUTHOR | 应用作者 | 无 | 否 |-| NUXT_PUBLIC_APP_AVATAR_URL | 应用头像 URL | 无 | 否 |+| NUXT_PUBLIC_APP_AVATAR_URL | 外部应用头像 URL(也可在后台上传头像,存储在已配置的存储提供商中) | 无 | 否 || NUXT_PUBLIC_COLOR_MODE_PREFERENCE | 颜色模式偏好,可选 `light`、`dark`、`system` | system | 否 || NUXT_PUBLIC_MAP_PROVIDER | 地图提供者,可选 `mapbox`、`maplibre` | `maplibre` | 否 || NUXT_PUBLIC_MAPBOX_ACCESS_TOKEN | Mapbox 访问令牌(可限制 URL),用于地图服务 | 无 | 当 `NUXT_PUBLIC_MAP_PROVIDER` 为 `mapbox` 时必需 |diff --git a/i18n/locales/en.json b/i18n/locales/en.jsonindex eb867c69..7a1b9ccc 100644--- a/i18n/locales/en.json+++ b/i18n/locales/en.json@@ -1143,9 +1143,18 @@"description": "The owner name of the instance"},"avatarUrl": {- "label": "Avatar URL",- "description": "Link to the owner's avatar image",- "help": "The avatar is displayed on the loading page and homepage"+ "label": "Avatar",+ "description": "Upload an image or link to the owner's avatar",+ "help": "The avatar is displayed on the loading page and homepage",+ "upload": "Upload",+ "replace": "Replace",+ "remove": "Remove",+ "uploadSuccess": "Avatar updated",+ "uploadFailed": "Failed to upload avatar",+ "removeSuccess": "Avatar removed",+ "removeFailed": "Failed to remove avatar",+ "invalidType": "Please choose a PNG, JPEG, WebP, or GIF image",+ "tooLarge": "Image must be smaller than {size}MB"},"appearance": {"theme": {@@ -1476,6 +1485,11 @@"label": "Confirm Password"}},+ "site": {+ "avatarUrl": {+ "help": "The avatar is displayed on the loading page and homepage. You'll be able to upload an image as well after setting up a storage."+ }+ },"map": {"provider": {"mapbox": {diff --git a/i18n/locales/ja.json b/i18n/locales/ja.jsonindex c8492c3f..cf6fb064 100644--- a/i18n/locales/ja.json+++ b/i18n/locales/ja.json@@ -1069,9 +1069,18 @@"description": "インスタンスのオーナー名"},"avatarUrl": {- "label": "アバター URL",- "description": "オーナーのアバター画像へのリンク",- "help": "アバターはローディングページとホームページに表示されます"+ "label": "アバター",+ "description": "画像をアップロードするか、オーナーのアバターへのリンクを入力",+ "help": "アバターはローディングページとホームページに表示されます。",+ "upload": "アップロード",+ "replace": "変更",+ "remove": "削除",+ "uploadSuccess": "アバターを更新しました",+ "uploadFailed": "アバターのアップロードに失敗しました",+ "removeSuccess": "アバターを削除しました",+ "removeFailed": "アバターの削除に失敗しました",+ "invalidType": "PNG、JPEG、WebP、または GIF 画像を選択してください",+ "tooLarge": "画像は {size}MB 未満である必要があります"},"appearance": {"theme": {@@ -1402,6 +1411,11 @@"label": "パスワード(確認)"}},+ "site": {+ "avatarUrl": {+ "help": "アバターはローディングページとホームページに表示されます。ストレージを設定すると、画像のアップロードもできるようになります。"+ }+ },"map": {"provider": {"mapbox": {diff --git a/i18n/locales/ru.json b/i18n/locales/ru.jsonindex 5085adb6..f53b2071 100644--- a/i18n/locales/ru.json+++ b/i18n/locales/ru.json@@ -1142,9 +1142,18 @@"description": "Имя владельца приложения"},"avatarUrl": {- "label": "URL аватара",- "description": "Ссылка на изображение аватара владельца",- "help": "Аватар отображается на экране загрузки и главной странице"+ "label": "Аватар",+ "description": "Загрузите изображение или укажите ссылку на аватар владельца",+ "help": "Аватар отображается на экране загрузки и главной странице",+ "upload": "Загрузить",+ "replace": "Заменить",+ "remove": "Удалить",+ "uploadSuccess": "Аватар обновлён",+ "uploadFailed": "Не удалось загрузить аватар",+ "removeSuccess": "Аватар удалён",+ "removeFailed": "Не удалось удалить аватар",+ "invalidType": "Выберите изображение PNG, JPEG, WebP или GIF",+ "tooLarge": "Размер изображения должен быть меньше {size}МБ"},"appearance": {"theme": {@@ -1462,6 +1471,11 @@"label": "Подтверждение пароля"}},+ "site": {+ "avatarUrl": {+ "help": "Аватар отображается на экране загрузки и главной странице. После настройки хранилища вы также сможете загрузить изображение."+ }+ },"map": {"provider": {"mapbox": {diff --git a/i18n/locales/zh-Hans.json b/i18n/locales/zh-Hans.jsonindex 0692095f..349df76d 100644--- a/i18n/locales/zh-Hans.json+++ b/i18n/locales/zh-Hans.json@@ -1143,9 +1143,18 @@"description": "实例的所有者名称"},"avatarUrl": {- "label": "头像 URL",- "description": "所有者头像的图片链接",- "help": "头像显示加载页面和首页头像中"+ "label": "头像",+ "description": "上传图片或填写所有者头像的链接",+ "help": "头像会显示在加载页面和首页中。",+ "upload": "上传",+ "replace": "更换",+ "remove": "移除",+ "uploadSuccess": "头像已更新",+ "uploadFailed": "头像上传失败",+ "removeSuccess": "头像已移除",+ "removeFailed": "头像移除失败",+ "invalidType": "请选择 PNG、JPEG、WebP 或 GIF 图片",+ "tooLarge": "图片大小必须小于 {size}MB"},"appearance": {"theme": {@@ -1476,6 +1485,11 @@"label": "确认密码"}},+ "site": {+ "avatarUrl": {+ "help": "头像会显示在加载页面和首页中。设置好存储后,你还可以上传图片。"+ }+ },"map": {"provider": {"mapbox": {diff --git a/i18n/locales/zh-Hant-HK.json b/i18n/locales/zh-Hant-HK.jsonindex 12624ea7..3d0b1099 100644--- a/i18n/locales/zh-Hant-HK.json+++ b/i18n/locales/zh-Hant-HK.json@@ -1069,9 +1069,18 @@"description": "實例的所有者名稱"},"avatarUrl": {- "label": "頭像 URL",- "description": "所有者頭像的圖片連結",- "help": "頭像顯示加載頁面同首頁頭像中"+ "label": "頭像",+ "description": "上傳圖片或填寫所有者頭像嘅連結",+ "help": "頭像會顯示喺載入頁面同首頁中。",+ "upload": "上傳",+ "replace": "更換",+ "remove": "移除",+ "uploadSuccess": "頭像已更新",+ "uploadFailed": "頭像上傳失敗",+ "removeSuccess": "頭像已移除",+ "removeFailed": "頭像移除失敗",+ "invalidType": "請選擇 PNG、JPEG、WebP 或 GIF 圖片",+ "tooLarge": "圖片大小必須小於 {size}MB"},"appearance": {"theme": {@@ -1402,6 +1411,11 @@"label": "確認密碼"}},+ "site": {+ "avatarUrl": {+ "help": "頭像會顯示喺載入頁面同首頁中。設定好儲存之後,你都可以上傳圖片。"+ }+ },"map": {"provider": {"mapbox": {diff --git a/i18n/locales/zh-Hant-TW.json b/i18n/locales/zh-Hant-TW.jsonindex a1423ef6..7868202d 100644--- a/i18n/locales/zh-Hant-TW.json+++ b/i18n/locales/zh-Hant-TW.json@@ -1069,9 +1069,18 @@"description": "實例的所有者名稱"},"avatarUrl": {- "label": "頭像 URL",- "description": "所有者頭像的圖片連結",- "help": "頭像顯示加載頁面和首頁頭像中"+ "label": "頭像",+ "description": "上傳圖片或填寫所有者頭像的連結",+ "help": "頭像會顯示在載入頁面和首頁中。",+ "upload": "上傳",+ "replace": "更換",+ "remove": "移除",+ "uploadSuccess": "頭像已更新",+ "uploadFailed": "頭像上傳失敗",+ "removeSuccess": "頭像已移除",+ "removeFailed": "頭像移除失敗",+ "invalidType": "請選擇 PNG、JPEG、WebP 或 GIF 圖片",+ "tooLarge": "圖片大小必須小於 {size}MB"},"appearance": {"theme": {@@ -1402,6 +1411,11 @@"label": "確認密碼"}},+ "site": {+ "avatarUrl": {+ "help": "頭像會顯示在載入頁面和首頁中。設定好儲存空間後,你還可以上傳圖片。"+ }+ },"map": {"provider": {"mapbox": {diff --git a/server/api/system/settings/[namespace]/[key].ts b/server/api/system/settings/[namespace]/[key].tsindex 0b1a808c..61a7e32a 100644--- a/server/api/system/settings/[namespace]/[key].ts+++ b/server/api/system/settings/[namespace]/[key].ts@@ -1,5 +1,6 @@import { z } from 'zod'import {+ getHiddenSettingKeys,settingKeys,settingNamespaces,} from '~~/server/services/settings/contants'@@ -15,6 +16,13 @@ export default eventHandler(async (event) => {}).parse,)+ if (getHiddenSettingKeys(namespace).has(key)) {+ throw createError({+ statusCode: 404,+ statusMessage: `Setting ${namespace}:${key} not found`,+ })+ }+if (event.method === 'GET') {try {const value = await settingsManager.get(namespace, key)diff --git a/server/api/system/settings/avatar.delete.ts b/server/api/system/settings/avatar.delete.tsnew file mode 100644index 00000000..867fe0e0--- /dev/null+++ b/server/api/system/settings/avatar.delete.ts@@ -0,0 +1,34 @@+import { settingsManager } from '~~/server/services/settings/settingsManager'+import { useStorageProvider } from '~~/server/utils/useStorageProvider'++/**+ * DELETE /api/system/settings/avatar+ *+ * Remove the stored avatar from the active storage provider and reset+ * `app:avatarUrl` so the default fallback image is used again.+ */+export default eventHandler(async (event) => {+ const session = await requireUserSession(event)+ if (!session?.user?.isAdmin) {+ throw createError({+ statusCode: 403,+ statusMessage: 'Admin privileges required',+ })+ }++ const key = await settingsManager.get<string>('app', 'avatarStorageKey')++ if (key) {+ try {+ const { storageProvider } = useStorageProvider(event)+ await storageProvider.delete(key)+ } catch (error) {+ logger.chrono.warn(`Failed to delete avatar ${key}:`, error)+ }+ }++ await settingsManager.set('app', 'avatarStorageKey', '')+ await settingsManager.set('app', 'avatarUrl', '')++ return { ok: true }+})diff --git a/server/api/system/settings/avatar.post.ts b/server/api/system/settings/avatar.post.tsnew file mode 100644index 00000000..a1b675a3--- /dev/null+++ b/server/api/system/settings/avatar.post.ts@@ -0,0 +1,131 @@+import { fileTypeFromBuffer } from 'file-type'+import type { StorageProvider } from '~~/server/services/storage'+import { settingsManager } from '~~/server/services/settings/settingsManager'+import { useStorageProvider } from '~~/server/utils/useStorageProvider'+import { storeAvatar } from '~~/server/utils/avatar-store'+import {+ AVATAR_ALLOWED_MIME_TYPES,+ AVATAR_MAX_INPUT_BYTES,+} from '~~/shared/utils/avatar'++/**+ * POST /api/system/settings/avatar+ *+ * Process and store the application owner's avatar in the active storage+ * provider, then point `app:avatarUrl` at the public `/avatar/:file` route.+ * External URLs are still supported through the regular settings batch API.+ */+export default eventHandler(async (event) => {+ const session = await requireUserSession(event)+ if (!session?.user?.isAdmin) {+ throw createError({+ statusCode: 403,+ statusMessage: 'Admin privileges required',+ })+ }++ const t = await useTranslation(event)++ const parts = await readMultipartFormData(event)+ const file = parts?.find((part) => part.name === 'file' && part.data?.length)++ if (!file?.data?.length) {+ throw createError({+ statusCode: 400,+ statusMessage: t('upload.error.required.title'),+ data: {+ title: t('upload.error.required.title'),+ message: t('upload.error.required.message', { field: 'file' }),+ },+ })+ }++ if (file.data.length > AVATAR_MAX_INPUT_BYTES) {+ throw createError({+ statusCode: 413,+ statusMessage: t('upload.error.tooLarge.title'),+ data: {+ title: t('upload.error.tooLarge.title'),+ message: t('upload.error.tooLarge.message', {+ size: (file.data.length / 1024 / 1024).toFixed(2),+ }),+ suggestion: t('upload.error.tooLarge.suggestion', {+ maxSize: AVATAR_MAX_INPUT_BYTES / 1024 / 1024,+ }),+ },+ })+ }++ const detected = await fileTypeFromBuffer(file.data)+ const isAllowed =+ detected !== undefined &&+ (AVATAR_ALLOWED_MIME_TYPES as readonly string[]).includes(detected.mime)++ if (!isAllowed) {+ throw createError({+ statusCode: 415,+ statusMessage: t('upload.error.invalidType.title'),+ data: {+ title: t('upload.error.invalidType.title'),+ message: t('upload.error.invalidType.message', {+ type: detected?.mime ?? 'unknown',+ }),+ suggestion: t('upload.error.invalidType.suggestion', {+ allowed: AVATAR_ALLOWED_MIME_TYPES.join(', '),+ }),+ },+ })+ }++ const previousKey = await settingsManager.get<string>(+ 'app',+ 'avatarStorageKey',+ )++ let storageProvider: StorageProvider+ try {+ storageProvider = useStorageProvider(event).storageProvider+ } catch (error) {+ logger.chrono.error(+ 'Storage provider unavailable for avatar upload:',+ error,+ )+ throw createError({+ statusCode: 500,+ statusMessage: t('upload.error.uploadFailed.title'),+ data: {+ title: t('upload.error.uploadFailed.title'),+ message: t('upload.error.uploadFailed.message'),+ },+ })+ }++ let stored: { url: string; key: string }+ try {+ stored = await storeAvatar(storageProvider, file.data)+ } catch (error) {+ logger.chrono.error('Failed to store avatar:', error)+ throw createError({+ statusCode: 500,+ statusMessage: t('upload.error.uploadFailed.title'),+ data: {+ title: t('upload.error.uploadFailed.title'),+ message: t('upload.error.uploadFailed.message'),+ },+ })+ }++ await settingsManager.set('app', 'avatarStorageKey', stored.key)+ await settingsManager.set('app', 'avatarUrl', stored.url)++ if (previousKey && previousKey !== stored.key) {+ await storageProvider.delete(previousKey).catch((error) => {+ logger.chrono.warn(+ `Failed to delete previous avatar ${previousKey}:`,+ error,+ )+ })+ }++ return { url: stored.url }+})diff --git a/server/api/system/settings/batch.put.ts b/server/api/system/settings/batch.put.tsindex f8bdbb67..8139b27a 100644--- a/server/api/system/settings/batch.put.ts+++ b/server/api/system/settings/batch.put.ts@@ -1,5 +1,6 @@import { z } from 'zod'import {+ getHiddenSettingKeys,settingKeys,settingNamespaces,} from '~~/server/services/settings/contants'@@ -63,6 +64,14 @@ export default eventHandler(async (event) => {// 逐个更新设置for (const update of body.updates) {+ if (getHiddenSettingKeys(update.namespace).has(update.key)) {+ errors.push({+ namespace: update.namespace,+ key: update.key,+ error: 'Setting is not directly modifiable',+ })+ continue+ }try {await settingsManager.set(update.namespace,diff --git a/server/api/system/settings/fields.get.ts b/server/api/system/settings/fields.get.tsindex 3a357fdf..763e28e3 100644--- a/server/api/system/settings/fields.get.ts+++ b/server/api/system/settings/fields.get.ts@@ -1,6 +1,9 @@import { z } from 'zod'import { settingsManager } from '~~/server/services/settings/settingsManager'-import { DEFAULT_SETTINGS } from '~~/server/services/settings/contants'+import {+ DEFAULT_SETTINGS,+ getHiddenSettingKeys,+} from '~~/server/services/settings/contants'import { getSettingUIConfig } from '~~/server/services/settings/ui-config'import type { SettingsFieldsResponse } from '~~/shared/types/settings'@@ -34,12 +37,16 @@ export default eventHandler(async (event) => {// 获取该命名空间的所有设置const schema = await settingsManager.getSchema()const allowedKeys = new Set(- DEFAULT_SETTINGS- .filter((s) => s.namespace === query.namespace)- .map((s) => s.key),+ DEFAULT_SETTINGS.filter((s) => s.namespace === query.namespace).map(+ (s) => s.key,+ ),)+ const hiddenKeys = getHiddenSettingKeys(query.namespace)const namespaceSettings = schema.filter(- (s) => s.namespace === query.namespace && allowedKeys.has(s.key),+ (s) =>+ s.namespace === query.namespace &&+ allowedKeys.has(s.key) &&+ !hiddenKeys.has(s.key),)if (namespaceSettings.length === 0) {diff --git a/server/api/wizard/schema.get.ts b/server/api/wizard/schema.get.tsindex 2ce398d6..11e54f38 100644--- a/server/api/wizard/schema.get.ts+++ b/server/api/wizard/schema.get.ts@@ -1,5 +1,6 @@import { z } from 'zod'import { settingsManager } from '~~/server/services/settings/settingsManager'+import { getHiddenSettingKeys } from '~~/server/services/settings/contants'import { getSettingUIConfig } from '~~/server/services/settings/ui-config'import type { FieldDescriptor } from '~~/shared/types/settings'@@ -231,8 +232,9 @@ export default eventHandler(async (event) => {// 3. App & Map Schemas (From Settings Manager)try {const schema = await settingsManager.getSchema()+ const hiddenKeys = getHiddenSettingKeys(query.namespace)const namespaceSettings = schema.filter(- (s) => s.namespace === query.namespace,+ (s) => s.namespace === query.namespace && !hiddenKeys.has(s.key),)const fields = namespaceSettings.map((setting) => {@@ -275,6 +277,16 @@ export default eventHandler(async (event) => {}}+ if (query.namespace === 'app' && setting.key === 'avatarUrl') {+ return {+ ...setting,+ ui: {+ ...(uiConfig || { type: 'input' as const, required: false }),+ help: 'wizard.site.avatarUrl.help',+ },+ }+ }+return {...setting,ui: uiConfig || {diff --git a/server/routes/avatar/[file].get.ts b/server/routes/avatar/[file].get.tsnew file mode 100644index 00000000..f4b0c383--- /dev/null+++ b/server/routes/avatar/[file].get.ts@@ -0,0 +1,58 @@+import type { StorageProvider } from '~~/server/services/storage'+import { settingsManager } from '~~/server/services/settings/settingsManager'+import {+ avatarFileNameFromKey,+ isAvatarFileName,+} from '~~/server/utils/avatar-store'++/**+ * GET /avatar/:file+ *+ * Publicly serve the current avatar, fetched from the active storage provider.+ * Avatars are branding assets shown to anonymous visitors, so no session or+ * photo access check applies. Filenames are content-hashed, so responses are+ * immutable and can be cached aggressively.+ */+export default defineEventHandler(async (event) => {+ const fileName = getRouterParam(event, 'file') || ''+ if (!isAvatarFileName(fileName)) {+ throw createError({ statusCode: 404, statusMessage: 'Not Found' })+ }++ const key = await settingsManager.get<string>('app', 'avatarStorageKey')+ if (!key || avatarFileNameFromKey(key) !== fileName) {+ throw createError({ statusCode: 404, statusMessage: 'Not Found' })+ }++ let storageProvider: StorageProvider+ try {+ storageProvider = useStorageProvider(event).storageProvider+ } catch {+ throw createError({ statusCode: 404, statusMessage: 'Not Found' })+ }++ let buffer: Buffer | null+ try {+ buffer = await storageProvider.get(key)+ } catch (error) {+ logger.chrono.error('Failed to read avatar from storage:', error)+ buffer = null+ }++ if (!buffer) {+ throw createError({ statusCode: 404, statusMessage: 'Not Found' })+ }++ const etag = `"${fileName}"`+ setHeader(event, 'ETag', etag)+ setHeader(event, 'Cache-Control', 'public, max-age=31536000, immutable')+ setHeader(event, 'Content-Type', 'image/webp')++ if (getHeader(event, 'if-none-match') === etag) {+ event.node.res.statusCode = 304+ return null+ }++ setHeader(event, 'Content-Length', buffer.length)+ return buffer+})diff --git a/server/services/settings/contants.ts b/server/services/settings/contants.tsindex bc09776a..e3848095 100644--- a/server/services/settings/contants.ts+++ b/server/services/settings/contants.ts@@ -54,6 +54,13 @@ export const DEFAULT_SETTINGS = [description: 'settings.app.avatarUrl.description',isPublic: true,},+ {+ namespace: 'app',+ key: 'avatarStorageKey',+ type: 'string',+ defaultValue: '',+ hidden: true,+ },{namespace: 'app',key: 'appearance.theme',@@ -255,3 +262,12 @@ export type SettingKey<N extends SettingNamespace> = Extract<(typeof DEFAULT_SETTINGS)[number],{ namespace: N }>['key']++export function getHiddenSettingKeys(namespace: string): Set<string> {+ const settings = DEFAULT_SETTINGS as readonly SettingConfig[]+ return new Set(+ settings+ .filter((setting) => setting.namespace === namespace && setting.hidden)+ .map((setting) => setting.key),+ )+}diff --git a/server/services/settings/ui-config.ts b/server/services/settings/ui-config.tsindex f3c110f0..bc279154 100644--- a/server/services/settings/ui-config.ts+++ b/server/services/settings/ui-config.ts@@ -26,7 +26,7 @@ export const APP_SETTINGS_UI: Record<string, FieldUIConfig> = {placeholder: 'Your name',},avatarUrl: {- type: 'url',+ type: 'avatar',placeholder: 'https://example.com/avatar.jpg',help: 'settings.app.avatarUrl.help',},diff --git a/server/utils/avatar-store.ts b/server/utils/avatar-store.tsnew file mode 100644index 00000000..24bb7c9d--- /dev/null+++ b/server/utils/avatar-store.ts@@ -0,0 +1,59 @@+import { createHash } from 'node:crypto'+import type { StorageProvider } from '~~/server/services/storage'+import sharp from 'sharp'++export const AVATAR_ROUTE_PREFIX = '/avatar'++const AVATAR_DIMENSION = 512+const AVATAR_QUALITY = 90+const AVATAR_KEY_PREFIX = 'avatars'+const AVATAR_FILENAME_PATTERN = /^avatar-[a-f0-9]{16}\.webp$/++function hashBuffer(buffer: Buffer): string {+ return createHash('sha256').update(buffer).digest('hex').slice(0, 16)+}++export function isAvatarFileName(fileName: string): boolean {+ return AVATAR_FILENAME_PATTERN.test(fileName)+}++export function getAvatarPublicUrl(fileName: string): string {+ return `${AVATAR_ROUTE_PREFIX}/${fileName}`+}++export function buildAvatarObjectKey(fileName: string): string {+ return `${AVATAR_KEY_PREFIX}/${fileName}`+}++export function avatarFileNameFromKey(key: string): string {+ const segments = key.split('/')+ return segments[segments.length - 1] ?? ''+}++export async function processAvatar(+ buffer: Buffer,+): Promise<{ buffer: Buffer; fileName: string }> {+ const processed = await sharp(buffer, { limitInputPixels: 32_000_000 })+ .rotate()+ .resize(AVATAR_DIMENSION, AVATAR_DIMENSION, {+ fit: 'cover',+ position: 'center',+ })+ .webp({ quality: AVATAR_QUALITY })+ .toBuffer()++ return { buffer: processed, fileName: `avatar-${hashBuffer(processed)}.webp` }+}++export async function storeAvatar(+ provider: StorageProvider,+ buffer: Buffer,+): Promise<{ url: string; key: string }> {+ const { buffer: processed, fileName } = await processAvatar(buffer)+ const object = await provider.create(+ buildAvatarObjectKey(fileName),+ processed,+ 'image/webp',+ )+ return { url: getAvatarPublicUrl(fileName), key: object.key }+}diff --git a/shared/types/settings.ts b/shared/types/settings.tsindex 9916fa6f..d41830ed 100644--- a/shared/types/settings.ts+++ b/shared/types/settings.ts@@ -15,6 +15,11 @@ export type SettingConfig = Omit<value?: SettingValuedefaultValue: SettingValueenum?: ReadonlyArray<string>+ /**+ * Internal settings that are never rendered in the settings UI. They are+ * still stored and readable server-side, but excluded from the fields API.+ */+ hidden?: boolean}export type SettingStorageProvider =@@ -36,6 +41,7 @@ export type FieldUIType =| 'tabs' // 标签页选择| 'toggle' // 开关| 'number' // 数字输入+ | 'avatar' // 头像上传/外链| 'custom' // 自定义组件/**diff --git a/shared/utils/avatar.ts b/shared/utils/avatar.tsnew file mode 100644index 00000000..ca8c7c2f--- /dev/null+++ b/shared/utils/avatar.ts@@ -0,0 +1,13 @@+/**+ * Avatar upload constraints shared by the client-side uploader and the+ * server-side endpoint, so validation stays in sync.+ */++export const AVATAR_ALLOWED_MIME_TYPES = [+ 'image/jpeg',+ 'image/png',+ 'image/webp',+ 'image/gif',+] as const++export const AVATAR_MAX_INPUT_BYTES = 5 * 1024 * 1024 // 5 MB