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.

feat!: redesigned settings system and new setting pages (#159)

Timothy Yinbe781e9e5821
diff --git a/.github/copilot-instructions.md b/.github/copilot-instructions.md
index 8433276e..0982fe3b 100644
--- a/.github/copilot-instructions.md
+++ b/.github/copilot-instructions.md
@@ -68,6 +68,10 @@ Photos are processed via `execPhotoPipelineAsync()` in `server/services/photo/pi
## Component Patterns
+### Vue Components
+
+- All components are auto imported via Nuxt (eg. `/app/components/photo/PhotoItem.client.vue` can be used directly as `<PhotoPhotoItem />`)
+
### Vue Composables
- `usePhotos()`: Central photo data management with injection/provide pattern
- `usePhotoFilters()`: Client-side filtering with reactive state
diff --git a/app/app.config.ts b/app/app.config.ts
index 344b8541..d9d3b773 100644
--- a/app/app.config.ts
+++ b/app/app.config.ts
@@ -11,8 +11,8 @@ export default defineAppConfig({
},
button: {
slots: {
- base: 'cursor-pointer'
- }
+ base: 'cursor-pointer',
+ },
},
popover: {
slots: {
@@ -22,17 +22,25 @@ export default defineAppConfig({
},
card: {
slots: {
- header: 'p-2 sm:p-2 pb-0!',
- body: 'p-2 sm:p-2',
- footer: 'p-2 sm:p-2',
+ header: 'font-semibold',
},
variants: {
variant: {
glassmorphism: {
root: 'shadow-lg divide-y-0 divide-neutral-300/50 dark:divide-neutral-500/50',
+ header: 'p-2 sm:p-2 pb-0!',
+ body: 'p-2 sm:p-2',
+ footer: 'p-2 sm:p-2',
},
},
},
},
+ formField: {
+ slots: {
+ label: 'mb-1',
+ container: 'w-full sm:max-w-xs *:w-full',
+ help: 'mt-0.5',
+ },
+ },
},
})
diff --git a/app/app.vue b/app/app.vue
index fc27911f..b7373a63 100644
--- a/app/app.vue
+++ b/app/app.vue
@@ -4,13 +4,21 @@ import dayjsLocale_zhTW from 'dayjs/locale/zh-tw'
import dayjsLocale_zhHK from 'dayjs/locale/zh-hk'
const router = useRouter()
-const config = useRuntimeConfig()
const dayjs = useDayjs()
+const colorMode = useColorMode()
const { locale } = useI18n()
+// 初始化设置系统 - 一次性加载所有设置
+const settingsStore = useSettingsStore()
+await settingsStore.initSettings()
+
+const appTitle = useSettingRef('app:title')
+
+colorMode.preference = useSettingRef('app:appearance.theme').value as string
+
useHead({
titleTemplate: (title) =>
- `${title ? title + ' | ' : ''}${config.public.app.title}`,
+ `${title ? title + ' | ' : ''}${appTitle.value || 'ChronoFrame'}`,
})
const { data, refresh, status } = useFetch('/api/photos')
@@ -71,6 +79,7 @@ provide(
<template>
<UApp>
+ <NuxtLoadingIndicator />
<PhotosProvider
:photos="photos"
:refresh="refresh"
diff --git a/app/components/loader/Avatar.vue b/app/components/loader/Avatar.vue
index c83dbb0e..6471e1ab 100644
--- a/app/components/loader/Avatar.vue
+++ b/app/components/loader/Avatar.vue
@@ -1,6 +1,4 @@
-<script lang="ts" setup>
-const config = useRuntimeConfig()
-</script>
+<script lang="ts" setup></script>
<template>
<div class="relative size-24">
@@ -12,9 +10,9 @@ const config = useRuntimeConfig()
class="absolute inset-1 rounded-full overflow-hidden drop-shadow-xl drop-shadow-primary/10 bg-neutral-100 dark:bg-neutral-800"
>
<img
- v-if="config.public.app.avatarUrl"
+ v-if="getSetting('app:avatarUrl')"
class="w-full h-full object-cover"
- :src="config.public.app.avatarUrl"
+ :src="getSetting('app:avatarUrl')?.toString()"
alt="Loading..."
/>
<img
diff --git a/app/components/map/Provider.vue b/app/components/map/Provider.vue
index 68b2eb29..cc8ab433 100644
--- a/app/components/map/Provider.vue
+++ b/app/components/map/Provider.vue
@@ -32,27 +32,33 @@ const emit = defineEmits<{
zoom: []
}>()
-const mapConfig = useRuntimeConfig().public.map
const colorMode = useColorMode()
-const provider = computed(() => mapConfig.provider)
+const mapConfig = computed(() => {
+ const config = getSetting('map')
+ return typeof config === 'object' && config ? config : {}
+})
+
+const provider = computed(() => mapConfig.value.provider || 'maplibre')
const mapStyle = computed(() => {
if (provider.value === 'mapbox') {
- return mapConfig.mapbox.style || `mapbox://styles/mapbox/standard`
+ return (
+ mapConfig.value['mapbox.style'] || `mapbox://styles/mapbox/standard`
+ )
} else {
const styleConfig =
colorMode.value === 'dark' ? ChronoFrameDarkStyle : ChronoFrameLightStyle
return (
- mapConfig.maplibre.style ||
+ mapConfig.value['maplibre.style'] ||
({
...styleConfig,
sources: {
openmaptiles: {
...styleConfig.sources?.openmaptiles,
- url: `https://api.maptiler.com/tiles/v3-openmaptiles/tiles.json?key=${mapConfig.maplibre.token}`,
+ url: `https://api.maptiler.com/tiles/v3-openmaptiles/tiles.json?key=${mapConfig.value['maplibre.token']}`,
},
},
- glyphs: `https://api.maptiler.com/fonts/{fontstack}/{range}.pbf?key=${mapConfig.maplibre.token}`,
+ glyphs: `https://api.maptiler.com/fonts/{fontstack}/{range}.pbf?key=${mapConfig.value['maplibre.token']}`,
} as StyleSpecification)
)
}
@@ -66,7 +72,7 @@ const mapStyle = computed(() => {
v-if="provider === 'maplibre'"
class="w-full h-full"
:map-key="mapId"
- :map-style
+ :map-style="mapStyle as StyleSpecification"
:center
:zoom
:interactive
@@ -81,6 +87,7 @@ const mapStyle = computed(() => {
class="w-full h-full"
:map-id="mapId || 'cframe-mapbox-map'"
:options="{
+ accessToken: mapConfig['mapbox.token'],
style: mapStyle,
center: center,
zoom: zoom,
diff --git a/app/components/map/ProviderMarker.vue b/app/components/map/ProviderMarker.vue
index ff2109c7..7c4fe809 100644
--- a/app/components/map/ProviderMarker.vue
+++ b/app/components/map/ProviderMarker.vue
@@ -10,9 +10,12 @@ withDefaults(
},
)
-const mapConfig = useRuntimeConfig().public.map
+const mapConfig = computed(() => {
+ const config = getSetting('map')
+ return typeof config === 'object' && config ? config : {}
+})
-const provider = computed(() => mapConfig.provider)
+const provider = computed(() => mapConfig.value.provider || 'maplibre')
</script>
<template>
diff --git a/app/components/masonry/item/Header.vue b/app/components/masonry/item/Header.vue
index c18ac854..3f9fce3c 100644
--- a/app/components/masonry/item/Header.vue
+++ b/app/components/masonry/item/Header.vue
@@ -13,7 +13,7 @@ defineProps<{
}>()
const router = useRouter()
-const config = useRuntimeConfig()
+// const config = useRuntimeConfig()
const colorMode = useColorMode()
const isDark = computed({
@@ -54,7 +54,7 @@ const isRepoLinkHovering = ref(false)
<div
class="absolute inset-0 -z-10 blur-3xl scale-110 bg-cover bg-center opacity-35"
:style="{
- backgroundImage: `url(${config.public.app.avatarUrl || '/web-app-manifest-192x192.png'})`,
+ backgroundImage: `url(${getSetting('app:avatarUrl') || '/web-app-manifest-192x192.png'})`,
}"
></div>
<div
@@ -72,7 +72,7 @@ const isRepoLinkHovering = ref(false)
<Icon name="tabler:star-filled" />
</div>
<img
- :src="config.public.app.avatarUrl || '/web-app-manifest-192x192.png'"
+ :src="getSetting('app:avatarUrl') as string || '/web-app-manifest-192x192.png'"
class="size-16 rounded-full object-cover"
:class="!loggedIn && 'cursor-pointer'"
alt="Author's avatar"
@@ -82,7 +82,7 @@ const isRepoLinkHovering = ref(false)
<h1
class="text-2xl font-bold text-neutral-900 dark:text-white/90 mb-2"
>
- {{ config.public.app.title }}
+ {{ getSetting('app:title') }}
</h1>
</div>
<div
@@ -106,10 +106,10 @@ const isRepoLinkHovering = ref(false)
{{ $t('ui.stats.noPhotosTip') }}
</p>
<p
- v-if="config.public.app.slogan"
+ v-if="getSetting('app:slogan')"
class="font-[Pacifico]"
>
- {{ config.public.app.slogan }}
+ {{ getSetting('app:slogan') }}
</p>
</div>
<div
@@ -249,11 +249,11 @@ const isRepoLinkHovering = ref(false)
class="w-full px-2 pb-1 pt-1.5 bg-neutral-200/50 dark:bg-neutral-900/50 flex justify-between items-center gap-2"
>
<div
- v-if="$config.public.app.author || $config.public.app.title"
+ v-if="getSetting('app:author') || getSetting('app:title')"
class="text-xs text-neutral-500/80 dark:text-neutral-500 font-medium truncate"
>
© {{ $dayjs().format('YYYY') }}
- {{ $config.public.app.author || $config.public.app.title }}
+ {{ getSetting('app:author') || getSetting('app:title') }}
</div>
<div
class="text-xs text-neutral-500/60 dark:text-neutral-500/80 font-medium inline-flex justify-center items-center gap-0.5"
@@ -269,7 +269,7 @@ const isRepoLinkHovering = ref(false)
>
<Icon
name="mdi:github"
- class="inline-block text-sm -mt-[1px]"
+ class="inline-block text-sm -mt-px"
mode="svg"
/>
ChronoFrame
diff --git a/app/components/setting/SettingField.vue b/app/components/setting/SettingField.vue
new file mode 100644
index 00000000..b1fec8d3
--- /dev/null
+++ b/app/components/setting/SettingField.vue
@@ -0,0 +1,143 @@
+<script setup lang="ts">
+import { resolveComponent } from 'vue'
+import type { FieldDescriptor, FieldUIType } from '~~/shared/types/settings'
+
+interface Props {
+ field: FieldDescriptor
+ modelValue: any
+}
+
+const props = defineProps<Props>()
+
+const emit = defineEmits<{
+ 'update:modelValue': [value: any]
+}>()
+
+const getComponentName = (uiType: FieldUIType): string => {
+ const componentMap: Record<FieldUIType, string> = {
+ 'input': 'UInput',
+ 'password': 'UInput',
+ 'url': 'UInput',
+ 'textarea': 'UTextarea',
+ 'select': 'USelectMenu',
+ 'radio': 'URadioGroup',
+ 'tabs': 'UTabs',
+ 'toggle': 'UToggle',
+ 'number': 'UInput',
+ 'custom': 'UInput', // 默认降级到 input
+ }
+
+ return componentMap[uiType] || 'UInput'
+}
+
+const UInput = resolveComponent('UInput')
+const UTextarea = resolveComponent('UTextarea')
+const USelectMenu = resolveComponent('USelectMenu')
+const URadioGroup = resolveComponent('URadioGroup')
+const UTabs = resolveComponent('UTabs')
+const UToggle = resolveComponent('UToggle')
+const UFormField = resolveComponent('UFormField')
+
+const componentName = computed(() => {
+ const name = getComponentName(props.field.ui.type)
+ switch (name) {
+ case 'UInput':
+ return UInput
+ case 'UTextarea':
+ return UTextarea
+ case 'USelectMenu':
+ return USelectMenu
+ case 'URadioGroup':
+ return URadioGroup
+ case 'UTabs':
+ return UTabs
+ case 'UToggle':
+ return UToggle
+ default:
+ return UInput
+ }
+})
+
+/**
+ * Get extra props for the component
+ */
+const getComponentProps = (): Record<string, any> => {
+ const type = props.field.ui.type
+ const propsMap: Record<string, any> = {}
+
+ if (props.field.ui.placeholder) {
+ propsMap.placeholder = props.field.ui.placeholder
+ }
+
+ switch (type) {
+ case 'password':
+ case 'url':
+ case 'number':
+ propsMap.type = type
+ break
+ case 'select':
+ propsMap.items = props.field.ui.options ? Array.from(props.field.ui.options) : []
+ propsMap['label-key'] = 'label'
+ propsMap['value-key'] = 'value'
+ break
+ case 'radio':
+ propsMap.options = props.field.ui.options ? Array.from(props.field.ui.options) : []
+ break
+ case 'tabs':
+ propsMap.items = props.field.ui.options ? Array.from(props.field.ui.options).map((opt: any) => ({
+ label: $t(opt.label) || opt.label,
+ value: opt.value,
+ icon: opt.icon,
+ })) : []
+ break
+ case 'textarea':
+ propsMap.rows = 3
+ break
+ }
+
+ return propsMap
+}
+
+const componentProps = computed(() => getComponentProps())
+
+const handleChange = (value: any) => {
+ emit('update:modelValue', value)
+}
+
+const labelKey = computed(() => {
+ // 尝试从 label 字段获取翻译键
+ if (props.field.label) {
+ return props.field.label
+ }
+ // 否则构造一个默认的翻译键
+ return `settings.${props.field.namespace}.${props.field.key}.label`
+})
+
+const descriptionKey = computed(() => {
+ if (props.field.description) {
+ return props.field.description
+ }
+ return `settings.${props.field.namespace}.${props.field.key}.description`
+})
+</script>
+
+<template>
+ <component
+ :is="UFormField"
+ :name="field.key"
+ :label="$t(labelKey)"
+ :description="$t(descriptionKey)"
+ :help="field.ui.help ? $t(field.ui.help) : undefined"
+ :required="field.ui.required"
+ >
+ <!-- 动态渲染不同的组件 -->
+ <component
+ :is="componentName"
+ :model-value="modelValue"
+ v-bind="componentProps"
+ @update:model-value="handleChange"
+ />
+ </component>
+</template>
+
+<style scoped></style>
diff --git a/app/components/setting/SettingSection.vue b/app/components/setting/SettingSection.vue
new file mode 100644
index 00000000..cf199751
--- /dev/null
+++ b/app/components/setting/SettingSection.vue
@@ -0,0 +1,80 @@
+<script setup lang="ts">
+import type { FieldDescriptor } from '~~/shared/types/settings'
+
+interface Props {
+ title: string
+ description?: string
+ fields: FieldDescriptor[]
+ namespace: string
+ state: Record<string, any>
+ loading?: boolean
+ submitLabel?: string
+ icon?: string
+ submitIcon?: string
+}
+
+const props = defineProps<Props>()
+const emit = defineEmits<{
+ submit: [data: Record<string, any>]
+}>()
+
+const formRef = ref()
+const formState = ref<Record<string, any>>({})
+
+// 监听 props.state 的变化
+watch(() => props.state, (newState) => {
+ formState.value = { ...newState }
+}, { immediate: true })
+
+/**
+ * 处理表单提交
+ */
+const handleSubmit = async (event: any) => {
+ emit('submit', event.data)
+}
+</script>
+
+<template>
+ <UCard variant="outline">
+ <template #header>
+ <div class="flex items-center gap-2">
+ <UIcon v-if="icon" :name="icon" size="lg" />
+ <div>
+ <p class="font-semibold">{{ title }}</p>
+ <p v-if="description" class="text-xs text-gray-500">
+ {{ description }}
+ </p>
+ </div>
+ </div>
+ </template>
+
+ <UForm
+ ref="formRef"
+ :state="formState"
+ class="space-y-4"
+ @submit="handleSubmit"
+ >
+ <SettingField
+ v-for="field in fields"
+ :key="field.key"
+ :field="field"
+ :model-value="formState[field.key]"
+ @update:model-value="formState[field.key] = $event"
+ />
+ </UForm>
+
+ <template #footer>
+ <UButton
+ type="submit"
+ variant="soft"
+ :icon="submitIcon ?? 'tabler:device-floppy'"
+ :loading="loading"
+ :disabled="loading"
+ >
+ {{ submitLabel ?? '保存设置' }}
+ </UButton>
+ </template>
+ </UCard>
+</template>
+
+<style scoped></style>
diff --git a/app/components/ui/AutoForm.vue b/app/components/ui/AutoForm.vue
new file mode 100644
index 00000000..7f0aa822
--- /dev/null
+++ b/app/components/ui/AutoForm.vue
@@ -0,0 +1,301 @@
+<script lang="ts" setup>
+import type { FormSubmitEvent, FormErrorEvent } from '@nuxt/ui'
+
+interface FieldConfig {
+ hidden?: boolean
+ disabled?: boolean
+ placeholder?: string
+ label?: string
+ description?: string
+ inputProps?: Record<string, any>
+ checkboxProps?: Record<string, any>
+ selectProps?: Record<string, any>
+}
+
+interface FieldMetadata {
+ key: string
+ name: string
+ fieldType: 'text' | 'number' | 'checkbox' | 'select' | 'hidden'
+ inputType: string
+ isOptional: boolean
+ label: string
+ description?: string
+ config?: FieldConfig
+}
+
+interface Props {
+ id?: string
+ schema?: any
+ state?: Record<string, any>
+ validate?: (state: any) => any[] | Promise<any[]>
+ validateOn?: any[]
+ disabled?: boolean
+ validateOnInputDelay?: number
+ transform?: boolean
+ nested?: boolean
+ loadingAuto?: boolean
+ class?: string
+ fieldsConfig?: Record<string, FieldConfig>
+}
+
+const props = withDefaults(defineProps<Props>(), {
+ id: undefined,
+ schema: undefined,
+ state: undefined,
+ validate: undefined,
+ validateOn: undefined,
+ disabled: undefined,
+ validateOnInputDelay: undefined,
+ transform: true,
+ nested: undefined,
+ loadingAuto: true,
+ class: undefined,
+ fieldsConfig: undefined,
+})
+
+const emit = defineEmits<{
+ submit: [event: FormSubmitEvent<any>]
+ error: [event: FormErrorEvent]
+}>()
+
+const form = useTemplateRef('form')
+
+// 从 Zod schema 提取字段元数据
+const fields = computed<FieldMetadata[]>(() => {
+ if (!props.schema || !props.schema._def) return []
+
+ let shape: Record<string, any> = {}
+
+ // 处理 discriminatedUnion 类型
+ if (props.schema._def.discriminatedUnion) {
+ // 获取判别键名和当前值
+ const discriminatorKey = props.schema._def.discriminator
+ const discriminatorValue = props.state?.[discriminatorKey]
+
+ // 从 options 中找到匹配的 schema
+ const matchedSchema = props.schema._def.optionsMap?.get(discriminatorValue)
+
+ if (matchedSchema) {
+ const optShape = matchedSchema._def.shape?.()
+ shape = optShape || {}
+
+ // 调试:检查获取到的 shape
+ if (process.env.NODE_ENV === 'development') {
+ console.log(
+ '[AutoForm] discriminatedUnion shape keys:',
+ Object.keys(shape),
+ )
+ Object.entries(shape).forEach(([k, v]: any) => {
+ console.log(
+ ` ${k}: type=${v._def?.type}, typeName=${v._def?.typeName}`,
+ )
+ })
+ }
+ }
+ }
+ // 处理普通 ZodObject
+ else if (typeof props.schema._def.shape === 'function') {
+ shape = props.schema._def.shape()
+ } else if (props.schema._def.shape) {
+ shape = props.schema._def.shape
+ } else {
+ return []
+ }
+
+ return Object.entries(shape).map(([key, value]: any) => {
+ // value 是 ZodSchema 实例
+ // 在 Zod v4 中,_def.type 用于标识类型,_def.typeName 在 v3 中使用
+ const type = value._def?.type
+ const typeName = value._def?.typeName
+
+ // 检查是否为可选:Zod v4 使用 type: 'optional'
+ const isOptional = type === 'optional' || typeName === 'ZodOptional'
+
+ // 获取实际类型的 _def(如果是 optional,从 innerType 获取)
+ const actualTypeDef = isOptional ? value._def.innerType._def : value._def
+
+ // 确定字段类型
+ let fieldType: 'text' | 'number' | 'checkbox' | 'select' | 'hidden' = 'text'
+ let inputType = 'text'
+
+ // 在 Zod v4 中使用 type 而不是 typeName
+ const actualType = actualTypeDef.type || actualTypeDef.typeName
+
+ switch (actualType) {
+ case 'boolean':
+ case 'ZodBoolean': {
+ fieldType = 'checkbox'
+ break
+ }
+ case 'number':
+ case 'ZodNumber': {
+ fieldType = 'number'
+ inputType = 'number'
+ break
+ }
+ case 'enum':
+ case 'ZodEnum': {
+ fieldType = 'select'
+ break
+ }
+ case 'string':
+ case 'ZodString': {
+ // 检查是否有特殊的字符串验证(如 email, url)
+ const checks = actualTypeDef.checks || []
+ const emailCheck = checks.find((c: any) => c.kind === 'email')
+ const urlCheck = checks.find((c: any) => c.kind === 'url')
+
+ if (emailCheck) {
+ inputType = 'email'
+ } else if (urlCheck) {
+ inputType = 'url'
+ }
+ break
+ }
+ }
+
+ // 生成 label(将 camelCase 转换为 Title Case)
+ const defaultLabel = key
+ .replace(/([A-Z])/g, ' $1')
+ .replace(/^./, (str: string) => str.toUpperCase())
+ .trim()
+
+ // 应用 fieldsConfig 中的配置
+ const config = props.fieldsConfig?.[key] || {}
+
+ // 使用 config 中的 label 和 description,如果没有则使用默认值
+ const label = config.label ?? defaultLabel
+ const description = config.description
+
+ return {
+ key,
+ name: key,
+ fieldType,
+ inputType,
+ isOptional,
+ label,
+ description,
+ config,
+ }
+ })
+})
+
+const handleSubmit = (event: FormSubmitEvent<any>) => {
+ emit('submit', event)
+}
+
+const handleError = (event: FormErrorEvent) => {
+ emit('error', event)
+}
+
+defineExpose({
+ submit: () => form.value?.submit(),
+ validate: (opts?: any) => form.value?.validate(opts),
+ clear: (path?: any) => form.value?.clear(path),
+ getErrors: (path?: any) => form.value?.getErrors(path),
+ setErrors: (errors: any[], name?: any) => form.value?.setErrors(errors, name),
+ get errors() {
+ return form.value?.errors
+ },
+ get disabled() {
+ return form.value?.disabled
+ },
+ get dirty() {
+ return form.value?.dirty
+ },
+ get dirtyFields() {
+ return form.value?.dirtyFields
+ },
+ get touchedFields() {
+ return form.value?.touchedFields
+ },
+ get blurredFields() {
+ return form.value?.blurredFields
+ },
+})
+</script>
+
+<template>
+ <UForm
+ :id="id"
+ ref="form"
+ :schema="schema"
+ :state="state"
+ :validate="validate"
+ :validate-on="validateOn"
+ :disabled="disabled"
+ :validate-on-input-delay="validateOnInputDelay"
+ :transform="transform"
+ :nested="nested"
+ :loading-auto="loadingAuto"
+ @submit="handleSubmit"
+ @error="handleError"
+ >
+ <div class="space-y-4">
+ <template
+ v-for="field of fields"
+ :key="field.key"
+ >
+ <UFormField
+ v-if="field.fieldType !== 'hidden' && !field.config?.hidden"
+ :label="field.label"
+ :name="field.name"
+ :required="!field.isOptional"
+ :description="field.description"
+ :ui="{
+ container: 'sm:max-w-full',
+ }"
+ >
+ <!-- Text Input -->
+ <UInput
+ v-if="field.fieldType === 'text'"
+ v-model="state![field.key]"
+ :type="field.inputType"
+ :placeholder="
+ field.config?.placeholder ?? `${field.label.toLowerCase()}`
+ "
+ :disabled="field.config?.disabled ?? false"
+ class="w-full"
+ v-bind="field.config?.inputProps ?? {}"
+ />
+
+ <!-- Number Input -->
+ <UInput
+ v-if="field.fieldType === 'number'"
+ v-model.number="state![field.key]"
+ type="number"
+ :placeholder="
+ field.config?.placeholder ?? `${field.label.toLowerCase()}`
+ "
+ :disabled="field.config?.disabled ?? false"
+ class="w-full"
+ v-bind="field.config?.inputProps ?? {}"
+ />
+
+ <!-- Checkbox -->
+ <UCheckbox
+ v-if="field.fieldType === 'checkbox'"
+ v-model="state![field.key]"
+ :label="field.label"
+ :disabled="field.config?.disabled ?? false"
+ v-bind="field.config?.checkboxProps ?? {}"
+ />
+
+ <!-- Select -->
+ <USelect
+ v-if="field.fieldType === 'select'"
+ v-model="state![field.key]"
+ :items="[]"
+ :disabled="field.config?.disabled ?? false"
+ class="w-full"
+ v-bind="field.config?.selectProps ?? {}"
+ />
+ </UFormField>
+ </template>
+ </div>
+
+ <slot />
+ </UForm>
+</template>
+
+<style scoped></style>
diff --git a/app/composables/useSettingsForm.ts b/app/composables/useSettingsForm.ts
new file mode 100644
index 00000000..c7e8add3
--- /dev/null
+++ b/app/composables/useSettingsForm.ts
@@ -0,0 +1,155 @@
+import type { FieldDescriptor, SettingsFieldsResponse } from '~~/shared/types/settings'
+
+/**
+ * Settings Form Composable
+ * 统一处理获取字段描述、管理表单状态、提交更新
+ * 避免在各个页面中重复实现相同逻辑
+ *
+ * @param namespace 设置命名空间(如 'app', 'map', 'location', 'storage')
+ * @returns 字段列表、表单状态、加载状态、错误状态和提交函数
+ *
+ * @example
+ * const { fields, state, submit, loading } = useSettingsForm('app')
+ */
+export function useSettingsForm(namespace: string) {
+ const toast = useToast()
+
+ const fields = ref<FieldDescriptor[]>([])
+ const state = reactive<Record<string, any>>({})
+ const loading = ref(false)
+ const error = ref<string | null>(null)
+
+ /**
+ * 从 API 获取字段描述和当前值
+ */
+ const fetchFields = async () => {
+ loading.value = true
+ error.value = null
+
+ try {
+ const response = await $fetch<SettingsFieldsResponse>(
+ '/api/system/settings/fields',
+ {
+ query: { namespace },
+ },
+ )
+
+ fields.value = response.fields
+
+ // 使用 API 返回的值初始化状态
+ response.fields.forEach((field) => {
+ state[field.key] = field.value ?? field.defaultValue ?? null
+ })
+ } catch (err) {
+ const message = (err as Error).message
+ error.value = message
+ toast.add({
+ title: '加载设置失败',
+ description: message,
+ color: 'error',
+ })
+ } finally {
+ loading.value = false
+ }
+ }
+
+ /**
+ * 提交表单更新
+ * 支持单条或多条更新
+ *
+ * @param data 要更新的字段数据
+ * @example
+ * await submit({ title: 'New Title', slogan: 'New Slogan' })
+ */
+ const submit = async (data: Record<string, any>) => {
+ loading.value = true
+ error.value = null
+
+ try {
+ // 准备批量更新请求
+ const updates = Object.entries(data).map(([key, value]) => ({
+ namespace,
+ key,
+ value,
+ }))
+
+ await $fetch('/api/system/settings/batch', {
+ method: 'PUT',
+ body: { updates },
+ })
+
+ // 重新加载字段以获取最新值
+ await fetchFields()
+
+ toast.add({
+ title: '设置已保存',
+ color: 'success',
+ })
+ } catch (err) {
+ const message = (err as Error).message
+ error.value = message
+ toast.add({
+ title: '保存设置失败',
+ description: message,
+ color: 'error',
+ })
+ throw err
+ } finally {
+ loading.value = false
+ }
+ }
+
+ /**
+ * 重置表单状态为当前字段值
+ */
+ const reset = () => {
+ fields.value.forEach((field) => {
+ state[field.key] = field.value ?? field.defaultValue ?? null
+ })
+ }
+
+ /**
+ * 更新特定字段的状态
+ * 用于处理字段依赖关系或条件显示
+ */
+ const updateField = (fieldKey: string, value: any) => {
+ state[fieldKey] = value
+ }
+
+ /**
+ * 获取特定字段
+ */
+ const getField = (fieldKey: string): FieldDescriptor | undefined => {
+ return fields.value.find((f) => f.key === fieldKey)
+ }
+
+ /**
+ * 获取字段的当前值
+ */
+ const getFieldValue = (fieldKey: string): any => {
+ return state[fieldKey]
+ }
+
+ // 组件挂载时自动获取字段
+ onMounted(() => {
+ fetchFields()
+ })
+
+ return {
+ // 数据
+ fields: readonly(fields),
+ state,
+
+ // 状态
+ loading: readonly(loading),
+ error: readonly(error),
+
+ // 方法
+ submit,
+ reset,
+ fetchFields,
+ updateField,
+ getField,
+ getFieldValue,
+ }
+}
diff --git a/app/layouts/dashboard.vue b/app/layouts/dashboard.vue
index efb934c1..86bd02d0 100644
--- a/app/layouts/dashboard.vue
+++ b/app/layouts/dashboard.vue
@@ -1,7 +1,11 @@
<script lang="ts" setup>
import type { NavigationMenuItem } from '@nuxt/ui'
-const navItems = ref<NavigationMenuItem[][]>([
+const route = useRoute()
+const router = useRouter()
+const { loggedIn, user } = useUserSession()
+
+const navItems = computed<NavigationMenuItem[][]>(() => [
[
{
label: $t('title.dashboard'),
@@ -31,8 +35,30 @@ const navItems = ref<NavigationMenuItem[][]>([
{
label: $t('title.siteAdministration'),
icon: 'tabler:settings',
- to: '/dashboard/site-administration',
- disabled: true,
+ defaultOpen: route.path.startsWith('/dashboard/settings'),
+ children: [
+ {
+ label: $t('title.generalSettings'),
+ icon: 'tabler:settings-2',
+ to: '/dashboard/settings/general',
+ },
+ {
+ label: $t('title.storageSettings'),
+ icon: 'tabler:database',
+ to: '/dashboard/settings/storage',
+ },
+ {
+ label: $t('title.mapAndLocation'),
+ icon: 'tabler:map-pin',
+ to: '/dashboard/settings/map',
+ },
+ {
+ label: $t('title.systemSettings'),
+ icon: 'tabler:cpu',
+ to: '/dashboard/settings/system',
+ disabled: true,
+ },
+ ],
},
],
[
@@ -57,15 +83,10 @@ const navItems = ref<NavigationMenuItem[][]>([
],
])
-const route = useRoute()
-const router = useRouter()
-const config = useRuntimeConfig()
-const { loggedIn, user } = useUserSession()
-
useHead({
title: $t('title.dashboard'),
titleTemplate: (title) =>
- `${title ? title + ' | ' : ''}${config.public.app.title}`,
+ `${title ? title + ' | ' : ''}${getSetting('app:title')}`,
})
const handleLogin = () => {
@@ -128,7 +149,7 @@ const handleLogin = () => {
to="/"
class="text-lg font-medium line-clamp-1"
>
- {{ config.public.app.title || $t('title.dashboard') }}
+ {{ getSetting('app:title') || $t('title.dashboard') }}
</NuxtLink>
</div>
</div>
diff --git a/app/pages/[...slug].vue b/app/pages/[...slug].vue
index 81e3684f..e749c20f 100644
--- a/app/pages/[...slug].vue
+++ b/app/pages/[...slug].vue
@@ -7,7 +7,6 @@ definePageMeta({
const route = useRoute()
const router = useRouter()
-const config = useRuntimeConfig()
const { switchToIndex, closeViewer, openViewer } = useViewerState()
const { isViewerOpen } = storeToRefs(useViewerState())
@@ -22,10 +21,10 @@ const currentPhoto = computed(() =>
defineOgImageComponent('Photo', {
headline: currentPhoto.value ? 'PHOTO' : 'ChronoFrame',
- title: currentPhoto.value?.title || config.public.app.title,
+ title: currentPhoto.value?.title || getSetting('app:title'),
description: currentPhoto.value
? currentPhoto.value.description
- : config.public.app.slogan,
+ : getSetting('app:title'),
thumbnailJpegUrl:
currentPhoto.value && currentPhoto.value.thumbnailKey
? `/thumb/${encodeURIComponent(currentPhoto.value.thumbnailUrl || '')}`
diff --git a/app/pages/dashboard/settings/demo.vue b/app/pages/dashboard/settings/demo.vue
new file mode 100644
index 00000000..455f6c05
--- /dev/null
+++ b/app/pages/dashboard/settings/demo.vue
@@ -0,0 +1,384 @@
+<template>
+ <div class="space-y-6">
+ <!-- 页面标题 -->
+ <div class="border-b pb-4">
+ <h1 class="text-2xl font-bold">设置</h1>
+ <p class="text-gray-500 dark:text-gray-400 text-sm mt-1">管理应用程序设置和偏好</p>
+ </div>
+
+ <!-- 通用设置卡片 -->
+ <UCard variant="soft">
+ <template #header>
+ <div class="flex items-center gap-2">
+ <UIcon name="i-heroicons-cog-6-tooth" class="text-primary" />
+ <h2 class="text-lg font-semibold">通用设置</h2>
+ </div>
+ </template>
+
+ <div class="space-y-6">
+ <!-- 文本输入 -->
+ <UFormField label="应用名称" description="设置你的应用显示名称">
+ <UInput
+ v-model="formData.appName"
+ placeholder="输入应用名称"
+ icon="i-heroicons-pencil"
+ />
+ </UFormField>
+
+ <!-- 描述文本 -->
+ <UFormField label="应用描述" description="简要描述你的应用功能">
+ <UTextarea
+ v-model="formData.appDescription"
+ placeholder="输入应用描述..."
+ :rows="3"
+ autoresize
+ />
+ </UFormField>
+
+ <!-- 数字输入 -->
+ <UFormField label="每页显示条数" description="设置列表页每页显示的条目数">
+ <UInputNumber
+ v-model="formData.itemsPerPage"
+ :min="10"
+ :max="100"
+ :step="10"
+ />
+ </UFormField>
+
+ <!-- 下拉选择 -->
+ <UFormField label="主题" description="选择应用的主题">
+ <USelect
+ v-model="formData.theme"
+ :options="themeOptions"
+ option-attribute="label"
+ value-attribute="value"
+ placeholder="选择主题"
+ />
+ </UFormField>
+
+ <!-- 开关切换 -->
+ <UFormField>
+ <USwitch
+ v-model="formData.darkMode"
+ label="深色模式"
+ description="启用深色主题"
+ />
+ </UFormField>
+ </div>
+ </UCard>
+
+ <!-- 存储设置卡片 -->
+ <UCard variant="soft">
+ <template #header>
+ <div class="flex items-center gap-2">
+ <UIcon name="i-heroicons-cloud" class="text-primary" />
+ <h2 class="text-lg font-semibold">存储设置</h2>
+ </div>
+ </template>
+
+ <div class="space-y-6">
+ <!-- 存储提供商选择 -->
+ <UFormField label="存储提供商" description="选择要使用的存储服务">
+ <USelect
+ v-model="formData.storageProvider"
+ :options="storageProviderOptions"
+ option-attribute="label"
+ value-attribute="value"
+ placeholder="选择存储提供商"
+ />
+ </UFormField>
+
+ <!-- 存储桶名称 -->
+ <UFormField label="存储桶名称" description="存储文件的 S3 存储桶名称">
+ <UInput
+ v-model="formData.bucketName"
+ placeholder="e.g., my-bucket"
+ icon="i-heroicons-server-stack"
+ />
+ </UFormField>
+
+ <!-- 最大上传大小 -->
+ <UFormField label="最大上传大小 (MB)" description="限制单个文件的最大上传大小">
+ <UInputNumber
+ v-model="formData.maxUploadSize"
+ :min="1"
+ :max="1000"
+ :step="10"
+ />
+ </UFormField>
+
+ <!-- 自动备份开关 -->
+ <UFormField>
+ <USwitch
+ v-model="formData.autoBackup"
+ label="自动备份"
+ description="定期将数据备份到存储服务"
+ />
+ </UFormField>
+ </div>
+ </UCard>
+
+ <!-- 显示设置卡片 -->
+ <UCard variant="soft">
+ <template #header>
+ <div class="flex items-center gap-2">
+ <UIcon name="i-heroicons-eye" class="text-primary" />
+ <h2 class="text-lg font-semibold">显示设置</h2>
+ </div>
+ </template>
+
+ <div class="space-y-6">
+ <!-- 布局选择 -->
+ <UFormField label="默认布局" description="选择相册默认显示方式">
+ <USelect
+ v-model="formData.defaultLayout"
+ :options="layoutOptions"
+ option-attribute="label"
+ value-attribute="value"
+ placeholder="选择布局"
+ />
+ </UFormField>
+
+ <!-- 图片加载质量 -->
+ <UFormField label="图片加载质量" description="选择缩略图的质量等级">
+ <USelect
+ v-model="formData.imageQuality"
+ :options="qualityOptions"
+ option-attribute="label"
+ value-attribute="value"
+ placeholder="选择质量"
+ />
+ </UFormField>
+
+ <!-- 每行显示列数 -->
+ <UFormField label="每行显示列数" description="网格布局中每行显示的列数">
+ <UInputNumber
+ v-model="formData.columnsPerRow"
+ :min="2"
+ :max="10"
+ :step="1"
+ />
+ </UFormField>
+
+ <!-- 显示文件信息 -->
+ <UFormField>
+ <USwitch
+ v-model="formData.showFileInfo"
+ label="显示文件信息"
+ description="在图片下方显示文件名和大小"
+ />
+ </UFormField>
+
+ <!-- 启用图片预览 -->
+ <UFormField>
+ <USwitch
+ v-model="formData.enablePreview"
+ label="启用快速预览"
+ description="鼠标悬停时显示快速预览"
+ />
+ </UFormField>
+ </div>
+ </UCard>
+
+ <!-- 性能设置卡片 -->
+ <UCard variant="soft">
+ <template #header>
+ <div class="flex items-center gap-2">
+ <UIcon name="i-heroicons-bolt" class="text-primary" />
+ <h2 class="text-lg font-semibold">性能设置</h2>
+ </div>
+ </template>
+
+ <div class="space-y-6">
+ <!-- 缓存大小 -->
+ <UFormField label="缓存大小 (MB)" description="本地缓存的最大大小">
+ <UInputNumber
+ v-model="formData.cacheSize"
+ :min="10"
+ :max="500"
+ :step="50"
+ />
+ </UFormField>
+
+ <!-- 预加载配置 -->
+ <UFormField label="预加载条数" description="滚动时预加载的图片数量">
+ <UInputNumber
+ v-model="formData.preloadCount"
+ :min="5"
+ :max="50"
+ :step="5"
+ />
+ </UFormField>
+
+ <!-- 启用压缩 -->
+ <UFormField>
+ <USwitch
+ v-model="formData.enableCompression"
+ label="启用压缩"
+ description="传输前压缩图片以减少带宽"
+ />
+ </UFormField>
+
+ <!-- 启用缓存 -->
+ <UFormField>
+ <USwitch
+ v-model="formData.enableCache"
+ label="启用缓存"
+ description="缓存已加载的图片到本地"
+ />
+ </UFormField>
+ </div>
+ </UCard>
+
+ <!-- 通知设置卡片 -->
+ <UCard variant="soft">
+ <template #header>
+ <div class="flex items-center gap-2">
+ <UIcon name="i-heroicons-bell" class="text-primary" />
+ <h2 class="text-lg font-semibold">通知设置</h2>
+ </div>
+ </template>
+
+ <div class="space-y-6">
+ <!-- 通知频率 -->
+ <UFormField label="通知频率" description="接收应用通知的频率">
+ <USelect
+ v-model="formData.notificationFrequency"
+ :options="frequencyOptions"
+ option-attribute="label"
+ value-attribute="value"
+ placeholder="选择频率"
+ />
+ </UFormField>
+
+ <!-- 邮件通知 -->
+ <UFormField>
+ <USwitch
+ v-model="formData.emailNotification"
+ label="邮件通知"
+ description="通过邮件接收重要通知"
+ />
+ </UFormField>
+
+ <!-- 上传完成提醒 -->
+ <UFormField>
+ <USwitch
+ v-model="formData.uploadNotification"
+ label="上传完成提醒"
+ description="上传完成时显示提醒"
+ />
+ </UFormField>
+
+ <!-- 错误通知 -->
+ <UFormField>
+ <USwitch
+ v-model="formData.errorNotification"
+ label="错误通知"
+ description="发生错误时立即通知"
+ />
+ </UFormField>
+ </div>
+ </UCard>
+
+ <!-- 操作按钮 -->
+ <div class="flex gap-3 justify-end border-t pt-6">
+ <UButton variant="outline" @click="resetForm">重置</UButton>
+ <UButton @click="saveSettings">保存设置</UButton>
+ </div>
+ </div>
+</template>
+
+<script setup lang="ts">
+definePageMeta({
+ layout: 'dashboard',
+})
+
+// 定义选项
+const themeOptions = [
+ { label: '亮色', value: 'light' },
+ { label: '深色', value: 'dark' },
+ { label: '自动', value: 'auto' }
+]
+
+const storageProviderOptions = [
+ { label: 'Amazon S3', value: 's3' },
+ { label: 'Cloudflare R2', value: 'r2' },
+ { label: 'GitHub', value: 'github' },
+ { label: '本地存储', value: 'local' }
+]
+
+const layoutOptions = [
+ { label: '网格布局', value: 'grid' },
+ { label: '列表布局', value: 'list' },
+ { label: '瀑布流', value: 'masonry' },
+ { label: '时间轴', value: 'timeline' }
+]
+
+const qualityOptions = [
+ { label: '低质量 (快速)', value: 'low' },
+ { label: '中等质量', value: 'medium' },
+ { label: '高质量', value: 'high' },
+ { label: '原始质量', value: 'original' }
+]
+
+const frequencyOptions = [
+ { label: '从不', value: 'never' },
+ { label: '仅重要', value: 'important' },
+ { label: '每日摘要', value: 'daily' },
+ { label: '实时', value: 'realtime' }
+]
+
+// 表单数据
+const formData = ref({
+ // 通用设置
+ appName: 'ChronoFrame',
+ appDescription: '高性能照片管理和相册应用',
+ itemsPerPage: 20,
+ theme: 'auto',
+ darkMode: false,
+
+ // 存储设置
+ storageProvider: 's3',
+ bucketName: 'photos-bucket',
+ maxUploadSize: 100,
+ autoBackup: true,
+
+ // 显示设置
+ defaultLayout: 'masonry',
+ imageQuality: 'high',
+ columnsPerRow: 4,
+ showFileInfo: true,
+ enablePreview: true,
+
+ // 性能设置
+ cacheSize: 200,
+ preloadCount: 20,
+ enableCompression: true,
+ enableCache: true,
+
+ // 通知设置
+ notificationFrequency: 'important',
+ emailNotification: false,
+ uploadNotification: true,
+ errorNotification: true
+})
+
+// 原始表单数据备份
+const originalFormData = JSON.parse(JSON.stringify(formData.value))
+
+// 保存设置
+const saveSettings = () => {
+ console.log('保存设置:', formData.value)
+ // TODO: 接入数据保存逻辑
+}
+
+// 重置表单
+const resetForm = () => {
+ formData.value = JSON.parse(JSON.stringify(originalFormData))
+ console.log('已重置表单')
+}
+</script>
+
+<style scoped>
+/* 自定义样式可根据需要添加 */
+</style>
diff --git a/app/pages/dashboard/settings/general.vue b/app/pages/dashboard/settings/general.vue
new file mode 100644
index 00000000..4b0ddc7d
--- /dev/null
+++ b/app/pages/dashboard/settings/general.vue
@@ -0,0 +1,126 @@
+<script lang="ts" setup>
+definePageMeta({
+ layout: 'dashboard',
+})
+
+useHead({
+ title: $t('title.generalSettings'),
+})
+
+const colorMode = useColorMode()
+
+const { fields, state, submit, loading } = useSettingsForm('app')
+
+const appFields = computed(() =>
+ fields.value.filter((f) => !f.key.startsWith('appearance.')),
+)
+
+const appearanceFields = computed(() =>
+ fields.value.filter((f) => f.key.startsWith('appearance.')),
+)
+
+const handleAppSettingsSubmit = async () => {
+ const appData = Object.fromEntries(
+ appFields.value.map((f) => [f.key, state[f.key]]),
+ )
+ try {
+ await submit(appData)
+ } catch {
+ /* empty */
+ }
+}
+
+const handleAppearanceSettingsSubmit = async () => {
+ const appearanceData = Object.fromEntries(
+ appearanceFields.value.map((f) => [f.key, state[f.key]]),
+ )
+ try {
+ await submit(appearanceData)
+ if (state['appearance.theme']) {
+ colorMode.preference = state['appearance.theme']
+ }
+ } catch {
+ /* empty */
+ }
+}
+</script>
+
+<template>
+ <UDashboardPanel>
+ <template #header>
+ <UDashboardNavbar :title="$t('title.generalSettings')" />
+ </template>
+
+ <template #body>
+ <div class="space-y-6 max-w-6xl">
+ <!-- 通用设置 -->
+ <UCard variant="outline">
+ <template #header>
+ <span>{{ $t('title.generalSettings') }}</span>
+ </template>
+
+ <UForm
+ id="appSettingsForm"
+ class="space-y-4"
+ @submit="handleAppSettingsSubmit"
+ >
+ <SettingField
+ v-for="field in appFields"
+ :key="field.key"
+ :field="field"
+ :model-value="state[field.key]"
+ @update:model-value="(val) => (state[field.key] = val)"
+ />
+ </UForm>
+
+ <template #footer>
+ <UButton
+ :loading="loading"
+ type="submit"
+ form="appSettingsForm"
+ variant="soft"
+ icon="tabler:device-floppy"
+ >
+ 保存设置
+ </UButton>
+ </template>
+ </UCard>
+
+ <!-- 外观设置 -->
+ <UCard variant="outline">
+ <template #header>
+ <span>{{ $t('title.appearanceSettings') }}</span>
+ </template>
+
+ <UForm
+ id="appearanceSettingsForm"
+ class="space-y-4"
+ @submit="handleAppearanceSettingsSubmit"
+ >
+ <SettingField
+ v-for="field in appearanceFields"
+ :key="field.key"
+ :field="field"
+ :model-value="state[field.key]"
+ @update:model-value="(val) => (state[field.key] = val)"
+ />
+ </UForm>
+
+ <template #footer>
+ <UButton
+ :loading="loading"
+ type="submit"
+ form="appearanceSettingsForm"
+ variant="soft"
+ icon="tabler:device-floppy"
+ >
+ 保存设置
+ </UButton>
+ </template>
+ </UCard>
+ </div>
+ </template>
+ </UDashboardPanel>
+</template>
+
+<style scoped></style>
diff --git a/app/pages/dashboard/settings/map.vue b/app/pages/dashboard/settings/map.vue
new file mode 100644
index 00000000..67e47adb
--- /dev/null
+++ b/app/pages/dashboard/settings/map.vue
@@ -0,0 +1,135 @@
+<script lang="ts" setup>
+definePageMeta({
+ layout: 'dashboard',
+})
+
+useHead({
+ title: $t('title.mapAndLocation'),
+})
+
+const {
+ fields: mapFields,
+ state: mapState,
+ submit: submitMap,
+ loading: mapLoading,
+} = useSettingsForm('map')
+const {
+ fields: locationFields,
+ state: locationState,
+ submit: submitLocation,
+ loading: locationLoading,
+} = useSettingsForm('location')
+
+const visibleMapFields = computed(() => {
+ const provider = mapState.provider
+ return mapFields.value.filter((field) => {
+ if (!field.ui.visibleIf) return true
+ if (field.ui.visibleIf.fieldKey === 'provider') {
+ return field.ui.visibleIf.value === provider
+ }
+ return true
+ })
+})
+
+const handleMapSettingsSubmit = async () => {
+ const mapData = Object.fromEntries(
+ visibleMapFields.value.map((f) => [f.key, mapState[f.key]]),
+ )
+ try {
+ await submitMap(mapData)
+ } catch {
+ /* empty */
+ }
+}
+
+const handleLocationSettingsSubmit = async () => {
+ const locationData = Object.fromEntries(
+ locationFields.value.map((f) => [f.key, locationState[f.key]]),
+ )
+ try {
+ await submitLocation(locationData)
+ } catch {
+ /* empty */
+ }
+}
+</script>
+
+<template>
+ <UDashboardPanel>
+ <template #header>
+ <UDashboardNavbar :title="$t('title.mapAndLocation')" />
+ </template>
+
+ <template #body>
+ <div class="space-y-6 max-w-6xl">
+ <!-- 地图设置 -->
+ <UCard variant="outline">
+ <template #header>
+ <span>{{ $t('title.mapAndLocation') }}</span>
+ </template>
+
+ <UForm
+ id="mapSettingsForm"
+ class="space-y-4"
+ @submit="handleMapSettingsSubmit"
+ >
+ <SettingField
+ v-for="field in visibleMapFields"
+ :key="field.key"
+ :field="field"
+ :model-value="mapState[field.key]"
+ @update:model-value="(val) => (mapState[field.key] = val)"
+ />
+ </UForm>
+
+ <template #footer>
+ <UButton
+ :loading="mapLoading"
+ type="submit"
+ form="mapSettingsForm"
+ variant="soft"
+ icon="tabler:device-floppy"
+ >
+ 保存设置
+ </UButton>
+ </template>
+ </UCard>
+
+ <!-- 位置设置 -->
+ <UCard variant="outline">
+ <template #header>
+ <span>{{ $t('title.location') }}</span>
+ </template>
+
+ <UForm
+ id="locationSettingsForm"
+ class="space-y-4"
+ @submit="handleLocationSettingsSubmit"
+ >
+ <SettingField
+ v-for="field in locationFields"
+ :key="field.key"
+ :field="field"
+ :model-value="locationState[field.key]"
+ @update:model-value="(val) => (locationState[field.key] = val)"
+ />
+ </UForm>
+
+ <template #footer>
+ <UButton
+ :loading="locationLoading"
+ type="submit"
+ form="locationSettingsForm"
+ variant="soft"
+ icon="tabler:device-floppy"
+ >
+ 保存设置
+ </UButton>
+ </template>
+ </UCard>
+ </div>
+ </template>
+ </UDashboardPanel>
+</template>
+
+<style scoped></style>
diff --git a/app/pages/dashboard/settings/storage.vue b/app/pages/dashboard/settings/storage.vue
new file mode 100644
index 00000000..811c6375
--- /dev/null
+++ b/app/pages/dashboard/settings/storage.vue
@@ -0,0 +1,534 @@
+<script lang="ts" setup>
+import { UButton, UChip } from '#components'
+import type { TableColumn } from '@nuxt/ui'
+import {
+ s3StorageConfigSchema,
+ localStorageConfigSchema,
+ openListStorageConfigSchema,
+ type StorageConfig,
+} from '~~/shared/types/storage'
+
+definePageMeta({
+ layout: 'dashboard',
+})
+
+useHead({
+ title: $t('title.storageSettings'),
+})
+
+const toast = useToast()
+
+const { data: currentStorageProvider, refresh: refreshCurrentStorageProvider } =
+ await useFetch<{
+ namespace: string
+ key: string
+ value: SettingValue
+ }>('/api/system/settings/storage/provider')
+
+const { data: availableStorage, refresh: refreshAvailableStorage } =
+ await useFetch<SettingStorageProvider[]>(
+ '/api/system/settings/storage-config',
+ )
+
+const PROVIDER_ICON = {
+ s3: 'tabler:brand-aws',
+ local: 'tabler:database',
+ openlist: 'tabler:cloud',
+}
+
+const availableStorageColumns: TableColumn<SettingStorageProvider>[] = [
+ {
+ accessorKey: 'status',
+ header: '',
+ meta: {
+ class: {
+ th: 'w-10',
+ },
+ },
+ cell: (cell) => {
+ const isActive =
+ currentStorageProvider.value?.value === cell.row.original.id
+ return h(UChip, {
+ size: 'md',
+ inset: true,
+ standalone: true,
+ color: isActive ? 'success' : undefined,
+ ui: {
+ base: !isActive ? 'bg-neutral-200 dark:bg-neutral-700' : '',
+ },
+ })
+ },
+ },
+ { accessorKey: 'name', header: '存储名称' },
+ { accessorKey: 'provider', header: '存储类型' },
+ {
+ accessorKey: 'actions',
+ header: '操作',
+ cell: (cell) => {
+ return h('div', { class: 'flex items-center gap-2' }, [
+ h(
+ UButton,
+ {
+ size: 'sm',
+ variant: 'soft',
+ color: 'error',
+ icon: 'tabler:trash',
+ disabled:
+ currentStorageProvider.value?.value === cell.row.original.id,
+ onClick: () => onStorageDelete(cell.row.original.id),
+ },
+ { default: () => '删除' },
+ ),
+ ])
+ },
+ },
+]
+
+const storageSettingsState = reactive<{
+ storageConfigId?: number
+}>({
+ storageConfigId: currentStorageProvider.value
+ ? (currentStorageProvider.value.value as number)
+ : undefined,
+})
+
+const handleStorageSettingsSubmit = async (close?: () => void) => {
+ try {
+ await $fetch('/api/system/settings/storage/provider', {
+ method: 'PUT',
+ body: {
+ value: storageSettingsState.storageConfigId,
+ },
+ })
+ refreshCurrentStorageProvider()
+ close?.()
+ toast.add({
+ title: '设置已保存',
+ color: 'success',
+ })
+ } catch (error) {
+ toast.add({
+ title: '保存设置时出错',
+ description: (error as Error).message,
+ color: 'error',
+ })
+ }
+}
+
+const providerOptions = [
+ { label: 'AWS S3 兼容存储', value: 's3', icon: PROVIDER_ICON.s3 },
+ { label: '本地存储', value: 'local', icon: PROVIDER_ICON.local },
+ { label: 'OpenList', value: 'openlist', icon: PROVIDER_ICON.openlist },
+]
+
+const storageConfigState = reactive<{
+ name: string
+ provider: string
+ config: Partial<StorageConfig>
+}>({
+ name: '',
+ provider: 's3',
+ config: {
+ provider: 's3',
+ region: 'auto',
+ prefix: '/photos',
+ } as any,
+})
+
+// 根据 provider 值动态选择对应的 schema
+const currentStorageSchema = computed(() => {
+ const provider = storageConfigState.provider
+ switch (provider) {
+ case 'local':
+ return localStorageConfigSchema
+ case 'openlist':
+ return openListStorageConfigSchema
+ case 's3':
+ default:
+ return s3StorageConfigSchema
+ }
+})
+
+// 获取存储配置的默认值
+const getStorageConfigDefaults = (provider: string): Partial<StorageConfig> => {
+ switch (provider) {
+ case 'local':
+ return {
+ provider: 'local',
+ basePath: '/data/storage',
+ baseUrl: '/storage',
+ } as any
+ case 'openlist':
+ return {
+ provider: 'openlist',
+ uploadEndpoint: '/api/fs/put',
+ deleteEndpoint: '/api/fs/remove',
+ metaEndpoint: '/api/fs/get',
+ pathField: 'path',
+ } as any
+ case 's3':
+ default:
+ return {
+ provider: 's3',
+ region: 'auto',
+ prefix: '/photos',
+ } as any
+ }
+}
+
+// 动态生成 fields-config,包含翻译键
+const storageFieldsConfig = computed<Record<string, any>>(() => {
+ const provider = storageConfigState.provider
+ const baseKey = `settings.storage.${provider}`
+
+ switch (provider) {
+ case 'local':
+ return {
+ provider: { hidden: true },
+ basePath: {
+ label: $t(`${baseKey}.basePath.label`),
+ description: $t(`${baseKey}.basePath.description`),
+ },
+ baseUrl: {
+ label: $t(`${baseKey}.baseUrl.label`),
+ description: $t(`${baseKey}.baseUrl.description`),
+ },
+ prefix: {
+ label: $t(`${baseKey}.prefix.label`),
+ description: $t(`${baseKey}.prefix.description`),
+ },
+ }
+ case 'openlist':
+ return {
+ provider: { hidden: true },
+ baseUrl: {
+ label: $t(`${baseKey}.baseUrl.label`),
+ description: $t(`${baseKey}.baseUrl.description`),
+ },
+ rootPath: {
+ label: $t(`${baseKey}.rootPath.label`),
+ description: $t(`${baseKey}.rootPath.description`),
+ },
+ token: {
+ label: $t(`${baseKey}.token.label`),
+ description: $t(`${baseKey}.token.description`),
+ },
+ uploadEndpoint: {
+ label: $t(`${baseKey}.uploadEndpoint.label`),
+ description: $t(`${baseKey}.uploadEndpoint.description`),
+ },
+ downloadEndpoint: {
+ label: $t(`${baseKey}.downloadEndpoint.label`),
+ description: $t(`${baseKey}.downloadEndpoint.description`),
+ },
+ listEndpoint: {
+ label: $t(`${baseKey}.listEndpoint.label`),
+ description: $t(`${baseKey}.listEndpoint.description`),
+ },
+ deleteEndpoint: {
+ label: $t(`${baseKey}.deleteEndpoint.label`),
+ description: $t(`${baseKey}.deleteEndpoint.description`),
+ },
+ metaEndpoint: {
+ label: $t(`${baseKey}.metaEndpoint.label`),
+ description: $t(`${baseKey}.metaEndpoint.description`),
+ },
+ pathField: {
+ label: $t(`${baseKey}.pathField.label`),
+ description: $t(`${baseKey}.pathField.description`),
+ },
+ cdnUrl: {
+ label: $t(`${baseKey}.cdnUrl.label`),
+ description: $t(`${baseKey}.cdnUrl.description`),
+ },
+ }
+ case 's3':
+ default:
+ return {
+ provider: { hidden: true },
+ bucket: {
+ label: $t(`${baseKey}.bucket.label`),
+ description: $t(`${baseKey}.bucket.description`),
+ },
+ region: {
+ label: $t(`${baseKey}.region.label`),
+ description: $t(`${baseKey}.region.description`),
+ },
+ endpoint: {
+ label: $t(`${baseKey}.endpoint.label`),
+ description: $t(`${baseKey}.endpoint.description`),
+ },
+ prefix: {
+ label: $t(`${baseKey}.prefix.label`),
+ description: $t(`${baseKey}.prefix.description`),
+ },
+ cdnUrl: {
+ label: $t(`${baseKey}.cdnUrl.label`),
+ description: $t(`${baseKey}.cdnUrl.description`),
+ },
+ accessKeyId: {
+ label: $t(`${baseKey}.accessKeyId.label`),
+ description: $t(`${baseKey}.accessKeyId.description`),
+ },
+ secretAccessKey: {
+ label: $t(`${baseKey}.secretAccessKey.label`),
+ description: $t(`${baseKey}.secretAccessKey.description`),
+ },
+ forcePathStyle: {
+ label: $t(`${baseKey}.forcePathStyle.label`),
+ description: $t(`${baseKey}.forcePathStyle.description`),
+ },
+ maxKeys: {
+ label: $t(`${baseKey}.maxKeys.label`),
+ description: $t(`${baseKey}.maxKeys.description`),
+ },
+ }
+ }
+})
+
+const onStorageConfigSubmit = async (
+ event: { data: Partial<StorageConfig> },
+ close?: () => void,
+) => {
+ try {
+ const payload = {
+ name: storageConfigState.name,
+ provider: storageConfigState.provider,
+ config: event.data,
+ }
+
+ await $fetch('/api/system/settings/storage-config', {
+ method: 'POST',
+ body: payload,
+ })
+ refreshAvailableStorage()
+ toast.add({
+ title: '存储方案已创建',
+ color: 'success',
+ })
+ // 重置表单
+ storageConfigState.name = ''
+ storageConfigState.provider = 's3'
+ storageConfigState.config = getStorageConfigDefaults('s3')
+ close?.()
+ } catch (error) {
+ toast.add({
+ title: '创建存储方案时出错',
+ description: (error as Error).message,
+ color: 'error',
+ })
+ }
+}
+
+const onStorageDelete = async (storageId: number) => {
+ try {
+ await $fetch(`/api/system/settings/storage-config/${storageId}`, {
+ method: 'DELETE',
+ })
+ refreshAvailableStorage()
+ toast.add({
+ title: '存储方案已删除',
+ color: 'success',
+ })
+ } catch (error) {
+ toast.add({
+ title: '删除存储方案失败',
+ description: (error as Error).message,
+ color: 'error',
+ })
+ }
+}
+</script>
+
+<template>
+ <UDashboardPanel>
+ <template #header>
+ <UDashboardNavbar :title="$t('title.storageSettings')" />
+ </template>
+
+ <template #body>
+ <div class="space-y-6 max-w-6xl">
+ <UCard variant="outline">
+ <div class="space-y-4">
+ <UFormField
+ name="storageConfigId"
+ label="存储方案"
+ required
+ >
+ <USelectMenu
+ v-model="storageSettingsState.storageConfigId"
+ :icon="
+ PROVIDER_ICON[
+ availableStorage?.find(
+ (item) =>
+ item.id === storageSettingsState.storageConfigId,
+ )?.provider || 'local'
+ ] || 'tabler:database'
+ "
+ :items="
+ availableStorage?.map((item) => ({
+ icon: PROVIDER_ICON[item.provider] || 'tabler:database',
+ label: item.name,
+ value: item.id,
+ }))
+ "
+ label-key="label"
+ value-key="value"
+ placeholder="选择存储方案"
+ />
+ </UFormField>
+ </div>
+
+ <template #footer>
+ <div class="flex items-center gap-3">
+ <UModal
+ title="变更存储方案"
+ :ui="{ footer: 'justify-end' }"
+ >
+ <UButton
+ variant="soft"
+ icon="tabler:device-floppy"
+ >
+ 保存设置
+ </UButton>
+
+ <template #body>
+ <UAlert
+ color="neutral"
+ variant="subtle"
+ title="注意"
+ description="变更存储方案之后上传的文件将会存储到新的存储方案中,原方案中已有文件不会被迁移。"
+ icon="tabler:arrows-exchange"
+ />
+ </template>
+
+ <template #footer="{ close }">
+ <UButton
+ label="取消"
+ color="neutral"
+ variant="outline"
+ @click="close"
+ />
+ <UButton
+ label="继续"
+ variant="soft"
+ icon="tabler:arrows-exchange"
+ type="submit"
+ form="storageSettingsForm"
+ @click="handleStorageSettingsSubmit(close)"
+ />
+ </template>
+ </UModal>
+ </div>
+ </template>
+ </UCard>
+
+ <UCard
+ variant="outline"
+ :ui="{
+ body: 'p-0 sm:p-0',
+ }"
+ >
+ <template #header>
+ <div class="w-full flex items-center justify-between">
+ <span>存储方案管理</span>
+ <div>
+ <USlideover
+ title="创建存储方案"
+ :ui="{ footer: 'justify-end' }"
+ >
+ <UButton
+ size="sm"
+ variant="soft"
+ icon="tabler:plus"
+ >
+ 添加存储
+ </UButton>
+
+ <template #body="{ close }">
+ <div class="space-y-4">
+ <!-- Provider 选择 -->
+ <UFormField
+ label="存储类型"
+ class="w-full"
+ required
+ :ui="{
+ container: 'sm:max-w-full',
+ }"
+ >
+ <USelectMenu
+ v-model="storageConfigState.provider"
+ :icon="
+ PROVIDER_ICON[
+ storageConfigState.provider as keyof typeof PROVIDER_ICON
+ ] || 'tabler:database'
+ "
+ :items="providerOptions"
+ label-key="label"
+ value-key="value"
+ placeholder="选择存储类型"
+ @update:model-value="
+ (val: string) => {
+ storageConfigState.provider = val
+ storageConfigState.config =
+ getStorageConfigDefaults(val)
+ }
+ "
+ />
+ </UFormField>
+
+ <UFormField
+ label="存储名称"
+ required
+ :ui="{
+ container: 'sm:max-w-full',
+ }"
+ >
+ <UInput v-model="storageConfigState.name" />
+ </UFormField>
+
+ <USeparator />
+
+ <AutoForm
+ id="createStorageForm"
+ :schema="currentStorageSchema"
+ :state="storageConfigState.config"
+ :fields-config="storageFieldsConfig"
+ @submit="onStorageConfigSubmit($event, close)"
+ />
+ </div>
+ </template>
+
+ <template #footer="{ close }">
+ <UButton
+ label="取消"
+ color="neutral"
+ variant="outline"
+ @click="close"
+ />
+ <UButton
+ label="创建存储"
+ variant="soft"
+ icon="i-heroicons-check"
+ type="submit"
+ form="createStorageForm"
+ />
+ </template>
+ </USlideover>
+ </div>
+ </div>
+ </template>
+
+ <div>
+ <UTable
+ :columns="availableStorageColumns"
+ :data="availableStorage"
+ />
+ </div>
+ </UCard>
+ </div>
+ </template>
+ </UDashboardPanel>
+</template>
+
+<style scoped></style>
diff --git a/app/stores/settings.ts b/app/stores/settings.ts
new file mode 100644
index 00000000..9462c676
--- /dev/null
+++ b/app/stores/settings.ts
@@ -0,0 +1,175 @@
+import { defineStore } from 'pinia'
+
+type SettingValue = string | number | boolean | null | Record<string, any>
+
+interface SettingsState {
+ data: Record<string, Record<string, SettingValue>>
+ isInitialized: boolean
+ isLoading: boolean
+ error: Error | null
+}
+
+/**
+ * 设置存储 - 使用 Pinia
+ *
+ * 使用方式:
+ * 1. 在 app.vue 中调用 await useSettingsStore().initSettings()
+ * 2. 在任何组件中使用 getSetting() 或 useSettingRef()
+ *
+ * @example
+ * // 在 app.vue 中
+ * const settingsStore = useSettingsStore()
+ * await settingsStore.initSettings()
+ *
+ * // 在组件中
+ * const mapProvider = getSetting('map:provider')
+ * const appTitle = useSettingRef('app:title')
+ */
+export const useSettingsStore = defineStore('settings', {
+ state: (): SettingsState => ({
+ data: {},
+ isInitialized: false,
+ isLoading: false,
+ error: null,
+ }),
+
+ getters: {
+ /**
+ * 获取初始化状态
+ */
+ isReady: (state) => state.isInitialized && !state.isLoading,
+
+ /**
+ * 获取错误状态
+ */
+ getError: (state) => state.error,
+ },
+
+ actions: {
+ /**
+ * 从服务器一次性加载所有设置
+ */
+ async initSettings(): Promise<void> {
+ if (this.isInitialized) {
+ return
+ }
+
+ this.isLoading = true
+ this.error = null
+
+ try {
+ const response = await $fetch<{
+ timestamp: number
+ data: Record<string, Record<string, SettingValue>>
+ }>('/api/system/settings/all')
+
+ this.data = response.data
+ this.isInitialized = true
+ } catch (error) {
+ this.error = error as Error
+ console.error('[Settings] Failed to initialize settings:', error)
+ throw error
+ } finally {
+ this.isLoading = false
+ }
+ },
+
+ /**
+ * 同步获取单个设置或整个命名空间
+ * @param key - 'namespace:key' 格式获取单个值,或 'namespace' 格式获取整个命名空间
+ * @returns 设置值,如果不存在返回 null
+ */
+ getSetting(key: string): SettingValue {
+ if (!this.isInitialized) {
+ console.warn(
+ '[Settings] Settings not initialized yet. Call await initSettings() first.',
+ )
+ return null
+ }
+
+ // 如果包含冒号,是 'namespace:key' 格式
+ if (key.includes(':')) {
+ const parts = key.split(':')
+ const namespace = parts[0]
+ const settingKey = parts[1]
+ if (namespace && settingKey) {
+ const namespaceObj = this.data[namespace]
+ if (namespaceObj) {
+ return (namespaceObj as any)[settingKey] ?? null
+ }
+ }
+ return null
+ }
+
+ // 否则是命名空间格式,返回整个命名空间对象
+ return this.data[key] ?? null
+ },
+
+ /**
+ * 刷新设置
+ */
+ async refreshSettings(): Promise<void> {
+ this.isLoading = true
+ this.error = null
+
+ try {
+ const response = await $fetch<{
+ timestamp: number
+ data: Record<string, Record<string, SettingValue>>
+ }>('/api/system/settings/all')
+
+ this.data = response.data
+ this.isInitialized = true
+ } catch (error) {
+ this.error = error as Error
+ console.error('[Settings] Failed to refresh settings:', error)
+ throw error
+ } finally {
+ this.isLoading = false
+ }
+ },
+ },
+})
+
+/**
+ * 全局辅助函数 - 同步获取设置
+ * @param key - 'namespace:key' 或 'namespace'
+ * @returns 设置值
+ *
+ * @example
+ * getSetting('map:provider')
+ * getSetting('map')
+ */
+export function getSetting(key: string): SettingValue {
+ const store = useSettingsStore()
+ return store.getSetting(key)
+}
+
+/**
+ * 全局辅助函数 - 响应式获取设置
+ * @param key - 'namespace:key' 或 'namespace'
+ * @returns ComputedRef 响应式引用
+ *
+ * @example
+ * const appTitle = useSettingRef('app:title')
+ */
+export function useSettingRef(key: string) {
+ const store = useSettingsStore()
+ return computed(() => store.getSetting(key))
+}
+
+/**
+ * 全局辅助函数 - 检查设置是否就绪
+ */
+export function isSettingsReady(): boolean {
+ const store = useSettingsStore()
+ return store.isReady
+}
+
+/**
+ * 全局辅助函数 - 刷新设置
+ */
+export async function refreshSettings(): Promise<void> {
+ const store = useSettingsStore()
+ await store.refreshSettings()
+}
diff --git a/docs/development/how-to-add-setting.md b/docs/development/how-to-add-setting.md
new file mode 100644
index 00000000..ef313af8
--- /dev/null
+++ b/docs/development/how-to-add-setting.md
@@ -0,0 +1,110 @@
+# 如何添加一个新的设置项
+
+以在 `app` 命名空间中添加 `foo` 字段为例。
+
+## 步骤 1:在 DEFAULT_SETTINGS 中添加字段定义
+
+编辑 `server/services/settings/contants.ts`,在 `DEFAULT_SETTINGS` 中对应的命名空间部分添加:
+
+```typescript
+// NAMESPACE: app
+{
+ namespace: 'app',
+ key: 'foo',
+ type: 'string',
+ defaultValue: 'bar',
+ isPublic: true,
+},
+```
+
+字段说明(必需):
+- `namespace`: 设置所属的命名空间 (app, map, location, storage, system 等)
+- `key`: 字段的唯一键
+- `type`: 类型 (string, number, boolean 等)
+- `defaultValue`: 默认值
+
+字段说明(可选):
+- `isPublic`: 是否公开
+- `isReadonly`: 是否只读
+- `isSecret`: 是否为机密字段(如密码)
+- `enum`: 枚举值数组
+
+> 💡 **注意**:不需要在 DEFAULT_SETTINGS 中添加 `label` 和 `description`。SettingField 组件会自动生成翻译键 `settings.${namespace}.${key}.label` 和 `settings.${namespace}.${key}.description`
+
+## 步骤 2:添加 UI 配置
+
+编辑 `server/services/settings/ui-config.ts`,在对应的 UI 配置对象中添加:
+
+```typescript
+export const APP_SETTINGS_UI: Record<string, FieldUIConfig> = {
+ // ... 其他配置
+ foo: {
+ type: 'input', // 字段类型:input, password, url, textarea, select, radio, tabs, toggle, number
+ placeholder: 'Enter foo value',
+ help: 'settings.app.foo.help', // 翻译键,可选
+ required: true, // 是否必需,可选
+ },
+}
+```
+
+## 步骤 3:添加翻译
+
+编辑 `i18n/locales/` 中的翻译文件(例如 `en.json`):
+
+```json
+{
+ "settings": {
+ "app": {
+ "foo": {
+ "label": "Foo",
+ "description": "The foo setting",
+ "help": "This is the help text for foo"
+ }
+ }
+ }
+}
+```
+
+## 步骤 4:在页面中使用
+
+编辑 `app/pages/dashboard/settings/general.vue`,直接在模板中使用:
+
+```vue
+<template>
+ <UDashboardPanel>
+ <!-- ... -->
+ <UForm class="space-y-4">
+ <SettingField
+ v-for="field in fields"
+ :key="field.key"
+ :field="field"
+ :model-value="state[field.key]"
+ @update:model-value="(val) => (state[field.key] = val)"
+ />
+ </UForm>
+ </UDashboardPanel>
+</template>
+```
+
+✅ 完成!`foo` 字段会自动被 `useSettingsForm('app')` 获取并渲染。
+
+## 条件字段示例
+
+如果需要根据其他字段来显示/隐藏某个字段,在 UI 配置中添加 `visibleIf`:
+
+```typescript
+foo: {
+ type: 'input',
+ placeholder: 'Only show when bar = "baz"',
+ visibleIf: { fieldKey: 'bar', value: 'baz' },
+}
+```
+
+## 其他命名空间
+
+- `map`:地图相关设置
+- `location`:位置相关设置
+- `storage`:存储相关设置
+- `system`:系统设置
+
+流程相同,只需修改对应的 UI 配置对象(`MAP_SETTINGS_UI`、`LOCATION_SETTINGS_UI` 等)。
diff --git a/i18n/locales/en.json b/i18n/locales/en.json
index 7a0a5121..54f9ea8e 100644
--- a/i18n/locales/en.json
+++ b/i18n/locales/en.json
@@ -360,7 +360,11 @@
"queue": "Queue Management",
"logs": "System Logs",
"albums": "Albums",
- "siteAdministration": "Site settings"
+ "siteAdministration": "Site settings",
+ "location": "Location services",
+ "generalSettings": "General Settings",
+ "appearanceSettings": "Appearance Settings",
+ "mapAndLocation": "Map & Location"
},
"auth": {
"form": {
@@ -861,5 +865,177 @@
"type": "Filter by Type"
}
}
+ },
+ "settings": {
+ "app": {
+ "title": {
+ "label": "Instance Name",
+ "description": "The title of the instance"
+ },
+ "slogan": {
+ "label": "Slogan",
+ "description": "The slogan of the instance",
+ "help": "The slogan displayed below the title on the homepage"
+ },
+ "author": {
+ "label": "Owner",
+ "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"
+ },
+ "appearance": {
+ "theme": {
+ "label": "Theme",
+ "description": "Choose the application theme",
+ "help": "Users can override this in their own browsers",
+ "light": "Light",
+ "dark": "Dark",
+ "system": "System"
+ }
+ }
+ },
+ "map": {
+ "provider": {
+ "label": "Map Provider",
+ "description": "Select the map service provider"
+ },
+ "mapbox": {
+ "token": {
+ "label": "Mapbox Token",
+ "description": "Mapbox API access token",
+ "help": "Should use a token without domain restrictions"
+ },
+ "style": {
+ "label": "Mapbox Style",
+ "description": "Mapbox map style URL"
+ }
+ },
+ "maplibre": {
+ "token": {
+ "label": "MapTiler Token",
+ "description": "MapTiler API access token",
+ "help": "MapLibre uses the free map service provider MapTiler by default"
+ },
+ "style": {
+ "label": "MapLibre Style",
+ "description": "MapLibre map style URL"
+ }
+ }
+ },
+ "location": {
+ "mapbox": {
+ "token": {
+ "label": "Mapbox Token",
+ "description": "Mapbox API access token",
+ "help": "When configured, this will replace Nominatim as the location service"
+ }
+ },
+ "nominatim": {
+ "baseUrl": {
+ "label": "Nominatim Base URL",
+ "description": "Base URL for Nominatim reverse geocoding API",
+ "help": "Leave empty to use the public Nominatim service by default"
+ }
+ }
+ },
+ "storage": {
+ "s3": {
+ "bucket": {
+ "label": "Bucket Name",
+ "description": "S3 bucket name for storing photos"
+ },
+ "region": {
+ "label": "Region",
+ "description": "AWS region for the S3 bucket"
+ },
+ "endpoint": {
+ "label": "S3 Endpoint",
+ "description": "Custom S3-compatible endpoint URL (e.g., for MinIO)"
+ },
+ "prefix": {
+ "label": "Storage Prefix",
+ "description": "Prefix path for objects in the bucket"
+ },
+ "cdnUrl": {
+ "label": "CDN URL",
+ "description": "Custom CDN URL for accessing images"
+ },
+ "accessKeyId": {
+ "label": "Access Key ID",
+ "description": "AWS Access Key ID or equivalent"
+ },
+ "secretAccessKey": {
+ "label": "Secret Access Key",
+ "description": "AWS Secret Access Key or equivalent"
+ },
+ "forcePathStyle": {
+ "label": "Force Path Style",
+ "description": "Use path-style URLs instead of virtual-hosted-style"
+ },
+ "maxKeys": {
+ "label": "Max Keys",
+ "description": "Maximum number of keys to retrieve per request"
+ }
+ },
+ "local": {
+ "basePath": {
+ "label": "Storage Base Path",
+ "description": "Local filesystem path for storing photos"
+ },
+ "baseUrl": {
+ "label": "Base URL",
+ "description": "Public URL base for accessing stored photos"
+ },
+ "prefix": {
+ "label": "Storage Prefix",
+ "description": "Prefix path for organizing photos in storage"
+ }
+ },
+ "openlist": {
+ "baseUrl": {
+ "label": "OpenList Base URL",
+ "description": "Base URL of the OpenList server"
+ },
+ "rootPath": {
+ "label": "Root Path",
+ "description": "Root path for storing photos in OpenList"
+ },
+ "token": {
+ "label": "Authentication Token",
+ "description": "OpenList API authentication token"
+ },
+ "uploadEndpoint": {
+ "label": "Upload Endpoint",
+ "description": "API endpoint for uploading files (default: /api/fs/put)"
+ },
+ "downloadEndpoint": {
+ "label": "Download Endpoint",
+ "description": "API endpoint for downloading files (optional)"
+ },
+ "listEndpoint": {
+ "label": "List Endpoint",
+ "description": "API endpoint for listing files (optional)"
+ },
+ "deleteEndpoint": {
+ "label": "Delete Endpoint",
+ "description": "API endpoint for deleting files (default: /api/fs/remove)"
+ },
+ "metaEndpoint": {
+ "label": "Meta Endpoint",
+ "description": "API endpoint for retrieving file metadata (default: /api/fs/get)"
+ },
+ "pathField": {
+ "label": "Path Field Name",
+ "description": "Parameter name for file path in API requests (default: path)"
+ },
+ "cdnUrl": {
+ "label": "CDN URL",
+ "description": "Custom CDN URL for accessing images"
+ }
+ }
+ }
}
}
diff --git a/i18n/locales/ja.json b/i18n/locales/ja.json
index 0fc35f60..b2df0d97 100644
--- a/i18n/locales/ja.json
+++ b/i18n/locales/ja.json
@@ -359,7 +359,11 @@
"queue": "キュー管理",
"logs": "システムログ",
"albums": "アルバム",
- "siteAdministration": "サイト設定"
+ "siteAdministration": "サイト設定",
+ "generalSettings": "一般設定",
+ "appearanceSettings": "外観設定",
+ "mapAndLocation": "地図と場所",
+ "location": "位置情報サービス"
},
"auth": {
"form": {
@@ -804,5 +808,177 @@
"type": "タイプでフィルター"
}
}
+ },
+ "settings": {
+ "app": {
+ "title": {
+ "label": "インスタンス名",
+ "description": "インスタンスのタイトル"
+ },
+ "slogan": {
+ "label": "スローガン",
+ "description": "インスタンスのスローガン",
+ "help": "スローガンはホームページのタイトルの下に表示されます"
+ },
+ "author": {
+ "label": "オーナー",
+ "description": "インスタンスのオーナー名"
+ },
+ "avatarUrl": {
+ "label": "アバター URL",
+ "description": "オーナーのアバター画像へのリンク",
+ "help": "アバターはローディングページとホームページに表示されます"
+ },
+ "appearance": {
+ "theme": {
+ "label": "テーマ",
+ "description": "アプリケーションテーマを選択",
+ "help": "ユーザーは自分のブラウザでこれをオーバーライドできます",
+ "light": "ライト",
+ "dark": "ダーク",
+ "system": "システム"
+ }
+ }
+ },
+ "map": {
+ "provider": {
+ "label": "地図プロバイダー",
+ "description": "地図サービスプロバイダーを選択"
+ },
+ "mapbox": {
+ "token": {
+ "label": "Mapbox トークン",
+ "description": "Mapbox API アクセストークン",
+ "help": "ドメイン制限のないトークンを使用すべきです"
+ },
+ "style": {
+ "label": "Mapbox スタイル",
+ "description": "Mapbox 地図スタイル URL"
+ }
+ },
+ "maplibre": {
+ "token": {
+ "label": "MapTiler トークン",
+ "description": "MapTiler API アクセストークン",
+ "help": "MapLibre はデフォルトで無料の地図サービスプロバイダー MapTiler を使用します"
+ },
+ "style": {
+ "label": "MapLibre スタイル",
+ "description": "MapLibre 地図スタイル URL"
+ }
+ }
+ },
+ "location": {
+ "mapbox": {
+ "token": {
+ "label": "Mapbox トークン",
+ "description": "Mapbox API アクセストークン",
+ "help": "設定すると、位置情報サービスとして Nominatim に代わります"
+ }
+ },
+ "nominatim": {
+ "baseUrl": {
+ "label": "Nominatim ベース URL",
+ "description": "Nominatim リバースジオコーディング API のベース URL",
+ "help": "空のままにすると、デフォルトで公開 Nominatim サービスを使用します"
+ }
+ }
+ },
+ "storage": {
+ "s3": {
+ "bucket": {
+ "label": "バケット名",
+ "description": "S3 バケットの名前"
+ },
+ "region": {
+ "label": "リージョン",
+ "description": "S3 バケットが配置されている AWS リージョン"
+ },
+ "endpoint": {
+ "label": "エンドポイント",
+ "description": "S3 サービスのエンドポイント URL"
+ },
+ "prefix": {
+ "label": "プレフィックス",
+ "description": "S3 内の全ファイルのパスプレフィックス"
+ },
+ "cdnUrl": {
+ "label": "CDN URL",
+ "description": "ファイルにアクセスするための CDN アドレス"
+ },
+ "accessKeyId": {
+ "label": "アクセスキー ID",
+ "description": "AWS IAM アクセスキー ID"
+ },
+ "secretAccessKey": {
+ "label": "シークレットアクセスキー",
+ "description": "AWS IAM シークレットアクセスキー"
+ },
+ "forcePathStyle": {
+ "label": "パススタイルを強制",
+ "description": "仮想ホストスタイルではなく、パススタイル URL を使用"
+ },
+ "maxKeys": {
+ "label": "最大キー数",
+ "description": "S3 リスト操作ごとに返される最大オブジェクト数"
+ }
+ },
+ "local": {
+ "basePath": {
+ "label": "基本パス",
+ "description": "ローカルファイルシステムでファイルを保存するベースディレクトリパス"
+ },
+ "baseUrl": {
+ "label": "ベース URL",
+ "description": "ローカルストレージファイルにアクセスするためのベース URL"
+ },
+ "prefix": {
+ "label": "プレフィックス",
+ "description": "ローカルストレージ内の全ファイルのパスプレフィックス"
+ }
+ },
+ "openlist": {
+ "baseUrl": {
+ "label": "OpenList ベース URL",
+ "description": "OpenList サーバーのベース URL"
+ },
+ "rootPath": {
+ "label": "ルートパス",
+ "description": "OpenList で写真を保存するルートパス"
+ },
+ "token": {
+ "label": "認証トークン",
+ "description": "OpenList API の認証トークン"
+ },
+ "uploadEndpoint": {
+ "label": "アップロードエンドポイント",
+ "description": "ファイルをアップロードするための API エンドポイント(デフォルト:/api/fs/put)"
+ },
+ "downloadEndpoint": {
+ "label": "ダウンロードエンドポイント",
+ "description": "ファイルをダウンロードするための API エンドポイント(オプション)"
+ },
+ "listEndpoint": {
+ "label": "リストエンドポイント",
+ "description": "ファイルをリストアップするための API エンドポイント(オプション)"
+ },
+ "deleteEndpoint": {
+ "label": "削除エンドポイント",
+ "description": "ファイルを削除するための API エンドポイント(デフォルト:/api/fs/remove)"
+ },
+ "metaEndpoint": {
+ "label": "メタデータエンドポイント",
+ "description": "ファイルメタデータを取得するための API エンドポイント(デフォルト:/api/fs/get)"
+ },
+ "pathField": {
+ "label": "パスフィールド名",
+ "description": "API リクエストのファイルパスパラメータ名(デフォルト:path)"
+ },
+ "cdnUrl": {
+ "label": "CDN URL",
+ "description": "画像にアクセスするためのカスタム CDN URL"
+ }
+ }
+ }
}
}
diff --git a/i18n/locales/zh-Hans.json b/i18n/locales/zh-Hans.json
index a158bb6f..f8827bb1 100644
--- a/i18n/locales/zh-Hans.json
+++ b/i18n/locales/zh-Hans.json
@@ -360,7 +360,13 @@
"queue": "队列管理",
"logs": "系统日志",
"albums": "相簿",
- "siteAdministration": "站点设置"
+ "siteAdministration": "站点设置",
+ "generalSettings": "基本设置",
+ "appearanceSettings": "外观设置",
+ "storageSettings": "存储设置",
+ "systemSettings": "系统设置",
+ "mapAndLocation": "地图和位置",
+ "location": "位置服务"
},
"auth": {
"form": {
@@ -861,5 +867,177 @@
"type": "按类型筛选"
}
}
+ },
+ "settings": {
+ "app": {
+ "title": {
+ "label": "实例名称",
+ "description": "实例的标题"
+ },
+ "slogan": {
+ "label": "标语",
+ "description": "实例的标语",
+ "help": "标语显示在首页的标题下方"
+ },
+ "author": {
+ "label": "所有者",
+ "description": "实例的所有者名称"
+ },
+ "avatarUrl": {
+ "label": "头像 URL",
+ "description": "所有者头像的图片链接",
+ "help": "头像显示加载页面和首页头像中"
+ },
+ "appearance": {
+ "theme": {
+ "label": "主题",
+ "description": "选择应用主题",
+ "help": "用户可以在自己的浏览器中覆盖此项",
+ "light": "浅色",
+ "dark": "深色",
+ "system": "系统"
+ }
+ }
+ },
+ "map": {
+ "provider": {
+ "label": "地图服务商",
+ "description": "选择地图服务商提供者"
+ },
+ "mapbox": {
+ "token": {
+ "label": "Mapbox Token",
+ "description": "Mapbox API 访问令牌",
+ "help": "应当使用没有域名限制的令牌"
+ },
+ "style": {
+ "label": "Mapbox 样式",
+ "description": "Mapbox 地图样式 URL"
+ }
+ },
+ "maplibre": {
+ "token": {
+ "label": "MapTiler Token",
+ "description": "MapTiler API 访问令牌",
+ "help": "MapLibre 默认使用免费地图服务商 MapTiler"
+ },
+ "style": {
+ "label": "MapLibre 样式",
+ "description": "MapLibre 地图样式 URL"
+ }
+ }
+ },
+ "location": {
+ "mapbox": {
+ "token": {
+ "label": "Mapbox Token",
+ "description": "Mapbox API 访问令牌",
+ "help": "配置后将取代 Nominatim 作为位置信息服务"
+ }
+ },
+ "nominatim": {
+ "baseUrl": {
+ "label": "Nominatim 基础 URL",
+ "description": "Nominatim 反向地理编码 API 的基础 URL",
+ "help": "留空则默认使用公共 Nominatim 服务"
+ }
+ }
+ },
+ "storage": {
+ "s3": {
+ "bucket": {
+ "label": "存储桶名称",
+ "description": "用于存储照片的 S3 存储桶名称"
+ },
+ "region": {
+ "label": "区域",
+ "description": "S3 存储桶所在的 AWS 区域"
+ },
+ "endpoint": {
+ "label": "S3 端点",
+ "description": "自定义 S3 兼容端点 URL(例如 MinIO)"
+ },
+ "prefix": {
+ "label": "存储前缀",
+ "description": "存储桶中对象的前缀路径"
+ },
+ "cdnUrl": {
+ "label": "CDN URL",
+ "description": "用于访问图像的自定义 CDN URL"
+ },
+ "accessKeyId": {
+ "label": "访问密钥 ID",
+ "description": "AWS 访问密钥 ID 或等效项"
+ },
+ "secretAccessKey": {
+ "label": "秘密访问密钥",
+ "description": "AWS 秘密访问密钥或等效项"
+ },
+ "forcePathStyle": {
+ "label": "强制路径风格",
+ "description": "使用路径风格 URL 而不是虚拟主机风格"
+ },
+ "maxKeys": {
+ "label": "最大密钥数",
+ "description": "每个请求检索的最大密钥数"
+ }
+ },
+ "local": {
+ "basePath": {
+ "label": "存储基础路径",
+ "description": "用于存储照片的本地文件系统路径"
+ },
+ "baseUrl": {
+ "label": "基础 URL",
+ "description": "用于访问存储照片的公开 URL 基础"
+ },
+ "prefix": {
+ "label": "存储前缀",
+ "description": "用于在存储中组织照片的前缀路径"
+ }
+ },
+ "openlist": {
+ "baseUrl": {
+ "label": "OpenList 基础 URL",
+ "description": "OpenList 服务器的基础 URL"
+ },
+ "rootPath": {
+ "label": "根路径",
+ "description": "在 OpenList 中存储照片的根路径"
+ },
+ "token": {
+ "label": "身份验证令牌",
+ "description": "OpenList API 身份验证令牌"
+ },
+ "uploadEndpoint": {
+ "label": "上传端点",
+ "description": "用于上传文件的 API 端点(默认:/api/fs/put)"
+ },
+ "downloadEndpoint": {
+ "label": "下载端点",
+ "description": "用于下载文件的 API 端点(可选)"
+ },
+ "listEndpoint": {
+ "label": "列表端点",
+ "description": "用于列出文件的 API 端点(可选)"
+ },
+ "deleteEndpoint": {
+ "label": "删除端点",
+ "description": "用于删除文件的 API 端点(默认:/api/fs/remove)"
+ },
+ "metaEndpoint": {
+ "label": "元数据端点",
+ "description": "用于检索文件元数据的 API 端点(默认:/api/fs/get)"
+ },
+ "pathField": {
+ "label": "路径字段名称",
+ "description": "API 请求中文件路径的参数名称(默认:path)"
+ },
+ "cdnUrl": {
+ "label": "CDN URL",
+ "description": "用于访问图像的自定义 CDN URL"
+ }
+ }
+ }
}
}
diff --git a/i18n/locales/zh-Hant-HK.json b/i18n/locales/zh-Hant-HK.json
index 8c6dad2b..6a0883fc 100644
--- a/i18n/locales/zh-Hant-HK.json
+++ b/i18n/locales/zh-Hant-HK.json
@@ -359,7 +359,11 @@
"queue": "佇列管理",
"logs": "系統日誌",
"albums": "相簿",
- "siteAdministration": "站點設置"
+ "siteAdministration": "站點設置",
+ "generalSettings": "基本設置",
+ "appearanceSettings": "外觀設置",
+ "mapAndLocation": "地圖和位置",
+ "location": "位置服務"
},
"auth": {
"form": {
@@ -804,5 +808,177 @@
"type": "按類型篩選"
}
}
+ },
+ "settings": {
+ "app": {
+ "title": {
+ "label": "實例名稱",
+ "description": "實例的標題"
+ },
+ "slogan": {
+ "label": "標語",
+ "description": "實例的標語",
+ "help": "標語顯示喺首頁的標題下方"
+ },
+ "author": {
+ "label": "所有者",
+ "description": "實例的所有者名稱"
+ },
+ "avatarUrl": {
+ "label": "頭像 URL",
+ "description": "所有者頭像的圖片連結",
+ "help": "頭像顯示加載頁面同首頁頭像中"
+ },
+ "appearance": {
+ "theme": {
+ "label": "主題",
+ "description": "選擇應用主題",
+ "help": "使用者可以喺自己的瀏覽器中覆蓋此項",
+ "light": "淺色",
+ "dark": "深色",
+ "system": "系統"
+ }
+ }
+ },
+ "map": {
+ "provider": {
+ "label": "地圖服務商",
+ "description": "選擇地圖服務商提供者"
+ },
+ "mapbox": {
+ "token": {
+ "label": "Mapbox Token",
+ "description": "Mapbox API 訪問令牌",
+ "help": "應當使用冇域名限制嘅令牌"
+ },
+ "style": {
+ "label": "Mapbox 樣式",
+ "description": "Mapbox 地圖樣式 URL"
+ }
+ },
+ "maplibre": {
+ "token": {
+ "label": "MapTiler Token",
+ "description": "MapTiler API 訪問令牌",
+ "help": "MapLibre 預設使用免費地圖服務商 MapTiler"
+ },
+ "style": {
+ "label": "MapLibre 樣式",
+ "description": "MapLibre 地圖樣式 URL"
+ }
+ }
+ },
+ "location": {
+ "mapbox": {
+ "token": {
+ "label": "Mapbox Token",
+ "description": "Mapbox API 訪問令牌",
+ "help": "配置後將取代 Nominatim 作為位置信息服務"
+ }
+ },
+ "nominatim": {
+ "baseUrl": {
+ "label": "Nominatim 基礎 URL",
+ "description": "Nominatim 反向地理編碼 API 嘅基礎 URL",
+ "help": "留空則預設使用公開 Nominatim 服務"
+ }
+ }
+ },
+ "storage": {
+ "s3": {
+ "bucket": {
+ "label": "儲存桶名稱",
+ "description": "S3 儲存桶嘅名稱"
+ },
+ "region": {
+ "label": "地區",
+ "description": "S3 儲存桶所在嘅 AWS 地區"
+ },
+ "endpoint": {
+ "label": "端點",
+ "description": "S3 服務嘅端點 URL"
+ },
+ "prefix": {
+ "label": "前綴",
+ "description": "儲存喺桶入面嘅檔案前綴路徑"
+ },
+ "cdnUrl": {
+ "label": "CDN URL",
+ "description": "用於訪問檔案嘅 CDN 地址"
+ },
+ "accessKeyId": {
+ "label": "存取金鑰 ID",
+ "description": "AWS IAM 存取金鑰 ID"
+ },
+ "secretAccessKey": {
+ "label": "祕密存取金鑰",
+ "description": "AWS IAM 祕密存取金鑰"
+ },
+ "forcePathStyle": {
+ "label": "強制路徑方式",
+ "description": "使用路徑方式 URL 而唔係虛擬主機方式"
+ },
+ "maxKeys": {
+ "label": "最大金鑰數",
+ "description": "列舉物件時返回嘅最大數量"
+ }
+ },
+ "local": {
+ "basePath": {
+ "label": "基本路徑",
+ "description": "本地儲存嘅基本目錄路徑"
+ },
+ "baseUrl": {
+ "label": "基本 URL",
+ "description": "用於訪問本地檔案嘅基本 URL"
+ },
+ "prefix": {
+ "label": "前綴",
+ "description": "本地儲存中所有檔案嘅路徑前綴"
+ }
+ },
+ "openlist": {
+ "baseUrl": {
+ "label": "OpenList 基本 URL",
+ "description": "OpenList 伺服器嘅基本 URL"
+ },
+ "rootPath": {
+ "label": "根路徑",
+ "description": "喺 OpenList 入面儲存相片嘅根路徑"
+ },
+ "token": {
+ "label": "身份驗證令牌",
+ "description": "OpenList API 身份驗證令牌"
+ },
+ "uploadEndpoint": {
+ "label": "上傳端點",
+ "description": "用於上傳檔案嘅 API 端點(預設:/api/fs/put)"
+ },
+ "downloadEndpoint": {
+ "label": "下載端點",
+ "description": "用於下載檔案嘅 API 端點(可選)"
+ },
+ "listEndpoint": {
+ "label": "列表端點",
+ "description": "用於列出檔案嘅 API 端點(可選)"
+ },
+ "deleteEndpoint": {
+ "label": "刪除端點",
+ "description": "用於刪除檔案嘅 API 端點(預設:/api/fs/remove)"
+ },
+ "metaEndpoint": {
+ "label": "中繼資料端點",
+ "description": "用於取得檔案中繼資料嘅 API 端點(預設:/api/fs/get)"
+ },
+ "pathField": {
+ "label": "路徑欄位名稱",
+ "description": "API 請求中檔案路徑嘅參數名稱(預設:path)"
+ },
+ "cdnUrl": {
+ "label": "CDN URL",
+ "description": "用於訪問圖像嘅自訂 CDN URL"
+ }
+ }
+ }
}
}
diff --git a/i18n/locales/zh-Hant-TW.json b/i18n/locales/zh-Hant-TW.json
index 7c5680c0..4bd06e78 100644
--- a/i18n/locales/zh-Hant-TW.json
+++ b/i18n/locales/zh-Hant-TW.json
@@ -359,7 +359,11 @@
"queue": "佇列管理",
"logs": "系統日誌",
"albums": "相簿",
- "siteAdministration": "站點設置"
+ "siteAdministration": "站點設置",
+ "generalSettings": "基本設置",
+ "appearanceSettings": "外觀設置",
+ "mapAndLocation": "地圖和位置",
+ "location": "位置服務"
},
"auth": {
"form": {
@@ -804,5 +808,177 @@
"type": "按類型篩選"
}
}
+ },
+ "settings": {
+ "app": {
+ "title": {
+ "label": "實例名稱",
+ "description": "實例的標題"
+ },
+ "slogan": {
+ "label": "標語",
+ "description": "實例的標語",
+ "help": "標語顯示在首頁的標題下方"
+ },
+ "author": {
+ "label": "所有者",
+ "description": "實例的所有者名稱"
+ },
+ "avatarUrl": {
+ "label": "頭像 URL",
+ "description": "所有者頭像的圖片連結",
+ "help": "頭像顯示加載頁面和首頁頭像中"
+ },
+ "appearance": {
+ "theme": {
+ "label": "主題",
+ "description": "選擇應用主題",
+ "help": "使用者可以在自己的瀏覽器中覆蓋此項",
+ "light": "淺色",
+ "dark": "深色",
+ "system": "系統"
+ }
+ }
+ },
+ "map": {
+ "provider": {
+ "label": "地圖服務商",
+ "description": "選擇地圖服務商提供者"
+ },
+ "mapbox": {
+ "token": {
+ "label": "Mapbox Token",
+ "description": "Mapbox API 訪問令牌",
+ "help": "應當使用沒有域名限制的令牌"
+ },
+ "style": {
+ "label": "Mapbox 樣式",
+ "description": "Mapbox 地圖樣式 URL"
+ }
+ },
+ "maplibre": {
+ "token": {
+ "label": "MapTiler Token",
+ "description": "MapTiler API 訪問令牌",
+ "help": "MapLibre 預設使用免費地圖服務商 MapTiler"
+ },
+ "style": {
+ "label": "MapLibre 樣式",
+ "description": "MapLibre 地圖樣式 URL"
+ }
+ }
+ },
+ "location": {
+ "mapbox": {
+ "token": {
+ "label": "Mapbox Token",
+ "description": "Mapbox API 訪問令牌",
+ "help": "配置後將取代 Nominatim 作為位置信息服務"
+ }
+ },
+ "nominatim": {
+ "baseUrl": {
+ "label": "Nominatim 基礎 URL",
+ "description": "Nominatim 反向地理編碼 API 的基礎 URL",
+ "help": "留空則預設使用公開 Nominatim 服務"
+ }
+ }
+ },
+ "storage": {
+ "s3": {
+ "bucket": {
+ "label": "儲存桶名稱",
+ "description": "S3 儲存桶的名稱"
+ },
+ "region": {
+ "label": "區域",
+ "description": "S3 儲存桶所在的 AWS 區域"
+ },
+ "endpoint": {
+ "label": "端點",
+ "description": "S3 服務的端點 URL"
+ },
+ "prefix": {
+ "label": "前綴",
+ "description": "儲存在桶中的檔案前綴路徑"
+ },
+ "cdnUrl": {
+ "label": "CDN URL",
+ "description": "用於訪問檔案的 CDN 地址"
+ },
+ "accessKeyId": {
+ "label": "存取金鑰 ID",
+ "description": "AWS IAM 存取金鑰 ID"
+ },
+ "secretAccessKey": {
+ "label": "祕密存取金鑰",
+ "description": "AWS IAM 祕密存取金鑰"
+ },
+ "forcePathStyle": {
+ "label": "強制路徑方式",
+ "description": "使用路徑方式 URL 而不是虛擬主機方式"
+ },
+ "maxKeys": {
+ "label": "最大金鑰數",
+ "description": "列舉物件時返回的最大數量"
+ }
+ },
+ "local": {
+ "basePath": {
+ "label": "基本路徑",
+ "description": "本地儲存的基本目錄路徑"
+ },
+ "baseUrl": {
+ "label": "基本 URL",
+ "description": "用於訪問本地檔案的基本 URL"
+ },
+ "prefix": {
+ "label": "前綴",
+ "description": "本地儲存中所有檔案的路徑前綴"
+ }
+ },
+ "openlist": {
+ "baseUrl": {
+ "label": "OpenList 基本 URL",
+ "description": "OpenList 伺服器的基本 URL"
+ },
+ "rootPath": {
+ "label": "根路徑",
+ "description": "在 OpenList 中儲存相片的根路徑"
+ },
+ "token": {
+ "label": "身份驗證令牌",
+ "description": "OpenList API 身份驗證令牌"
+ },
+ "uploadEndpoint": {
+ "label": "上傳端點",
+ "description": "用於上傳檔案的 API 端點(預設:/api/fs/put)"
+ },
+ "downloadEndpoint": {
+ "label": "下載端點",
+ "description": "用於下載檔案的 API 端點(選擇性)"
+ },
+ "listEndpoint": {
+ "label": "列表端點",
+ "description": "用於列出檔案的 API 端點(選擇性)"
+ },
+ "deleteEndpoint": {
+ "label": "刪除端點",
+ "description": "用於刪除檔案的 API 端點(預設:/api/fs/remove)"
+ },
+ "metaEndpoint": {
+ "label": "中繼資料端點",
+ "description": "用於取得檔案中繼資料的 API 端點(預設:/api/fs/get)"
+ },
+ "pathField": {
+ "label": "路徑欄位名稱",
+ "description": "API 請求中檔案路徑的參數名稱(預設:path)"
+ },
+ "cdnUrl": {
+ "label": "CDN URL",
+ "description": "用於訪問圖像的自訂 CDN URL"
+ }
+ }
+ }
}
}
diff --git a/nuxt.config.ts b/nuxt.config.ts
index 735b9471..24ca77e4 100644
--- a/nuxt.config.ts
+++ b/nuxt.config.ts
@@ -191,7 +191,7 @@ export default defineNuxtConfig({
},
colorMode: {
- preference: process.env.NUXT_PUBLIC_COLOR_MODE_PREFERENCE || 'dark',
+ // preference: process.env.NUXT_PUBLIC_COLOR_MODE_PREFERENCE || 'dark',
storageKey: 'cframe-color-mode',
},
diff --git a/server/api/photos/livephoto/manage.post.ts b/server/api/photos/livephoto/manage.post.ts
index faea2849..17b9f0f1 100644
--- a/server/api/photos/livephoto/manage.post.ts
+++ b/server/api/photos/livephoto/manage.post.ts
@@ -4,7 +4,7 @@ import {
} from '~~/server/services/video/scanner'
import { eq } from 'drizzle-orm'
import { findLivePhotoVideoForImage } from '~~/server/services/video/livephoto'
-import { getStorageManager } from '~~/server/plugins/storage'
+import { getStorageManager } from '~~/server/plugins/3.storage'
import { batchTestLivePhotoDetection } from '~~/server/services/video/test-utils'
export default eventHandler(async (event) => {
diff --git a/server/api/system/settings/[namespace].get.ts b/server/api/system/settings/[namespace].get.ts
new file mode 100644
index 00000000..8f2e4e8e
--- /dev/null
+++ b/server/api/system/settings/[namespace].get.ts
@@ -0,0 +1,30 @@
+import { z } from 'zod'
+import { settingNamespaces } from '~~/server/services/settings/contants'
+import { settingsManager } from '~~/server/services/settings/settingsManager'
+
+export default eventHandler(async (event) => {
+ const { namespace } = await getValidatedRouterParams(
+ event,
+ z.object({
+ namespace: z.enum([...settingNamespaces]),
+ }).parse,
+ )
+
+ const session = await requireUserSession(event)
+ if (!session || !session.user.isAdmin) {
+ throw createError({
+ statusCode: 403,
+ statusMessage: 'Admin privileges required',
+ })
+ }
+
+ try {
+ const settings = await settingsManager.getNamespace(namespace)
+ return { namespace, settings }
+ } catch {
+ throw createError({
+ statusCode: 404,
+ statusMessage: `Namespace ${namespace} not found or empty`,
+ })
+ }
+})
diff --git a/server/api/system/settings/[namespace]/[key].ts b/server/api/system/settings/[namespace]/[key].ts
new file mode 100644
index 00000000..dd93a942
--- /dev/null
+++ b/server/api/system/settings/[namespace]/[key].ts
@@ -0,0 +1,57 @@
+import { z } from 'zod'
+import {
+ settingKeys,
+ settingNamespaces,
+} from '~~/server/services/settings/contants'
+import { settingsManager } from '~~/server/services/settings/settingsManager'
+
+export default eventHandler(async (event) => {
+ const { namespace, key } = await getValidatedRouterParams(
+ event,
+ z.object({
+ namespace: z.enum([...settingNamespaces]),
+ key: z.enum([...settingKeys]),
+ }).parse,
+ )
+
+ if (event.method === 'GET') {
+ try {
+ const value = await settingsManager.get(namespace, key)
+ return { namespace, key, value }
+ } catch {
+ throw createError({
+ statusCode: 404,
+ statusMessage: `Setting ${namespace}:${key} not found`,
+ })
+ }
+ }
+
+ if (event.method === 'PUT') {
+ const session = await requireUserSession(event)
+ if (!session || !session.user.isAdmin) {
+ throw createError({
+ statusCode: 403,
+ statusMessage: 'Admin privileges required',
+ })
+ }
+
+ const { value } = await readValidatedBody(
+ event,
+ z.object({
+ value: z.any(),
+ }).parse,
+ )
+
+ try {
+ await settingsManager.set(namespace, key, value, session.user.id)
+ return { namespace, key, value }
+ } catch (err) {
+ throw createError({
+ statusCode: 400,
+ statusMessage: (err as Error).message || 'Failed to update setting',
+ })
+ }
+ }
+
+ throw createError({ statusCode: 405 })
+})
diff --git a/server/api/system/settings/all.get.ts b/server/api/system/settings/all.get.ts
new file mode 100644
index 00000000..9acc5dd6
--- /dev/null
+++ b/server/api/system/settings/all.get.ts
@@ -0,0 +1,46 @@
+import { useDB, tables, eq } from '~~/server/utils/db'
+
+/**
+ * 获取所有公开设置
+ * 仅返回 isPublic=true 的设置,按命名空间分组
+ */
+export default eventHandler(async () => {
+ const db = useDB()
+
+ // 查询所有公开设置
+ const allSettings = db
+ .select()
+ .from(tables.settings)
+ .where(eq(tables.settings.isPublic, true))
+ .all()
+
+ // 按命名空间分组
+ const grouped: Record<string, Record<string, any>> = {}
+
+ for (const setting of allSettings) {
+ if (!grouped[setting.namespace]) {
+ grouped[setting.namespace] = {}
+ }
+
+ // 解析值
+ let value: any = setting.value
+ try {
+ if (setting.type === 'json') {
+ value = setting.value ? JSON.parse(setting.value) : null
+ } else if (setting.type === 'number') {
+ value = setting.value ? Number(setting.value) : null
+ } else if (setting.type === 'boolean') {
+ value = setting.value === 'true' || setting.value === '1'
+ }
+ } catch {
+ // 保持原始值
+ }
+
+ grouped[setting.namespace][setting.key] = value
+ }
+
+ return {
+ timestamp: Date.now(),
+ data: grouped,
+ }
+})
diff --git a/server/api/system/settings/batch.put.ts b/server/api/system/settings/batch.put.ts
new file mode 100644
index 00000000..1c6434c8
--- /dev/null
+++ b/server/api/system/settings/batch.put.ts
@@ -0,0 +1,92 @@
+import { z } from 'zod'
+import {
+ settingKeys,
+ settingNamespaces,
+} from '~~/server/services/settings/contants'
+import { settingsManager } from '~~/server/services/settings/settingsManager'
+
+/**
+ * PUT /api/system/settings/batch
+ *
+ * 批量更新设置
+ * 避免逐个更新产生多个 HTTP 请求
+ *
+ * @body {updates} 要更新的设置数组
+ * @returns {success, updated} 成功标志和更新数量
+ *
+ * @example
+ * PUT /api/system/settings/batch
+ * {
+ * updates: [
+ * { namespace: 'app', key: 'title', value: 'ChronoFrame' },
+ * { namespace: 'app', key: 'slogan', value: 'A photo gallery' },
+ * ]
+ * }
+ */
+export default eventHandler(async (event) => {
+ const session = await requireUserSession(event)
+ if (!session || !session.user.isAdmin) {
+ throw createError({
+ statusCode: 403,
+ statusMessage: 'Admin privileges required',
+ })
+ }
+
+ const body = await readValidatedBody(
+ event,
+ z
+ .object({
+ updates: z.array(
+ z.object({
+ namespace: z.enum([...settingNamespaces]),
+ key: z.enum([...settingKeys]),
+ value: z.any(),
+ }),
+ ),
+ })
+ .parse,
+ )
+
+ try {
+ let successCount = 0
+ const errors: Array<{ namespace: string; key: string; error: string }> = []
+
+ // 逐个更新设置
+ for (const update of body.updates) {
+ try {
+ await settingsManager.set(
+ update.namespace,
+ update.key,
+ update.value,
+ session.user.id,
+ )
+ successCount++
+ } catch (err) {
+ errors.push({
+ namespace: update.namespace,
+ key: update.key,
+ error: (err as Error).message,
+ })
+ }
+ }
+
+ // 如果有错误,返回部分成功的响应
+ if (errors.length > 0) {
+ return {
+ success: false,
+ updated: successCount,
+ errors,
+ }
+ }
+
+ return {
+ success: true,
+ updated: successCount,
+ }
+ } catch (error) {
+ throw createError({
+ statusCode: 400,
+ statusMessage: (error as Error).message || 'Failed to update settings',
+ })
+ }
+})
diff --git a/server/api/system/settings/fields.get.ts b/server/api/system/settings/fields.get.ts
new file mode 100644
index 00000000..fff19cf7
--- /dev/null
+++ b/server/api/system/settings/fields.get.ts
@@ -0,0 +1,75 @@
+import { z } from 'zod'
+import { settingsManager } from '~~/server/services/settings/settingsManager'
+import { getSettingUIConfig } from '~~/server/services/settings/ui-config'
+import type { SettingsFieldsResponse } from '~~/shared/types/settings'
+
+/**
+ * GET /api/system/settings/fields?namespace=app
+ *
+ * 获取指定命名空间的字段描述
+ * 每个字段都包含当前值、默认值、UI 配置等完整信息
+ * 前端可直接用来渲染表单
+ *
+ * @query namespace 设置命名空间(app, map, location, storage 等)
+ * @returns SettingsFieldsResponse
+ */
+export default eventHandler(async (event) => {
+ const query = await getValidatedQuery(
+ event,
+ z
+ .object({
+ namespace: z.string().min(1),
+ })
+ .parse,
+ )
+
+ const session = await requireUserSession(event)
+ if (!session || !session.user.isAdmin) {
+ throw createError({
+ statusCode: 403,
+ statusMessage: 'Admin privileges required',
+ })
+ }
+
+ try {
+ // 获取该命名空间的所有设置
+ const schema = await settingsManager.getSchema()
+ const namespaceSettings = schema.filter(
+ (s) => s.namespace === query.namespace,
+ )
+
+ if (namespaceSettings.length === 0) {
+ throw createError({
+ statusCode: 404,
+ statusMessage: `Namespace ${query.namespace} not found`,
+ })
+ }
+
+ // 为每个设置添加 UI 配置
+ const fields = namespaceSettings.map((setting) => {
+ const uiConfig = getSettingUIConfig(query.namespace, setting.key)
+ return {
+ ...setting,
+ ui: uiConfig || {
+ type: 'input' as const,
+ required: false,
+ },
+ }
+ })
+
+ const response: SettingsFieldsResponse = {
+ namespace: query.namespace,
+ fields,
+ }
+
+ return response
+ } catch (error) {
+ if ((error as any).statusCode) {
+ throw error
+ }
+ throw createError({
+ statusCode: 500,
+ statusMessage: (error as Error).message || 'Failed to fetch settings fields',
+ })
+ }
+})
diff --git a/server/api/system/settings/schema.get.ts b/server/api/system/settings/schema.get.ts
new file mode 100644
index 00000000..5f1148a6
--- /dev/null
+++ b/server/api/system/settings/schema.get.ts
@@ -0,0 +1,14 @@
+import { settingsManager } from '~~/server/services/settings/settingsManager'
+
+export default eventHandler(async (event) => {
+ const session = await requireUserSession(event)
+ if (!session || !session.user.isAdmin) {
+ throw createError({
+ statusCode: 403,
+ statusMessage: 'Admin privileges required',
+ })
+ }
+
+ const settingsSchema = settingsManager.getSchema()
+ return settingsSchema
+})
diff --git a/server/api/system/settings/storage-config/[id].ts b/server/api/system/settings/storage-config/[id].ts
new file mode 100644
index 00000000..cad304ed
--- /dev/null
+++ b/server/api/system/settings/storage-config/[id].ts
@@ -0,0 +1,78 @@
+import { z } from 'zod'
+import { settingsManager } from '~~/server/services/settings/settingsManager'
+import {
+ localStorageConfigSchema,
+ openListStorageConfigSchema,
+ s3StorageConfigSchema,
+} from '~~/server/services/storage'
+
+export default eventHandler(async (event) => {
+ const session = await requireUserSession(event)
+ if (!session.user.isAdmin) {
+ throw createError({
+ statusCode: 403,
+ statusMessage: 'Forbidden',
+ })
+ }
+
+ const { id: storageConfigId } = await getValidatedRouterParams(
+ event,
+ z.object({
+ id: z.string().transform((val) => parseInt(val, 10)),
+ }).parse,
+ )
+
+ const storageConfig =
+ await settingsManager.storage.getProviderById(storageConfigId)
+
+ if (!storageConfig) {
+ throw createError({
+ statusCode: 404,
+ statusMessage: 'Storage configuration not found',
+ })
+ }
+
+ switch (event.method) {
+ case 'GET':
+ return storageConfig
+ case 'PUT': {
+ const updatedStorageConfig = await readValidatedBody(
+ event,
+ z.discriminatedUnion('provider', [
+ z.object({
+ name: z.string().optional(),
+ provider: z.literal('s3'),
+ config: s3StorageConfigSchema.partial(),
+ }),
+ z.object({
+ name: z.string().optional(),
+ provider: z.literal('local'),
+ config: localStorageConfigSchema.partial(),
+ }),
+ z.object({
+ name: z.string().optional(),
+ provider: z.literal('openlist'),
+ config: openListStorageConfigSchema.partial(),
+ }),
+ ]).parse,
+ )
+
+ await settingsManager.storage.updateProvider(
+ storageConfigId,
+ updatedStorageConfig,
+ )
+
+ return { success: true }
+ }
+ case 'DELETE': {
+ await settingsManager.storage.deleteProvider(storageConfigId)
+ return { success: true }
+ }
+ default: {
+ throw createError({
+ statusCode: 405,
+ statusMessage: 'Method Not Allowed',
+ })
+ }
+ }
+})
diff --git a/server/api/system/settings/storage-config/index.ts b/server/api/system/settings/storage-config/index.ts
new file mode 100644
index 00000000..1fb9d17a
--- /dev/null
+++ b/server/api/system/settings/storage-config/index.ts
@@ -0,0 +1,54 @@
+import { z } from 'zod'
+import { settingsManager } from '~~/server/services/settings/settingsManager'
+import {
+ localStorageConfigSchema,
+ openListStorageConfigSchema,
+ s3StorageConfigSchema,
+} from '~~/server/services/storage'
+
+export default eventHandler(async (event) => {
+ const session = await requireUserSession(event)
+ if (!session.user.isAdmin) {
+ throw createError({
+ statusCode: 403,
+ statusMessage: 'Forbidden',
+ })
+ }
+
+ switch (event.method) {
+ case 'GET': {
+ return await settingsManager.storage.getProviders()
+ }
+ case 'POST': {
+ const newStorageConfig = await readValidatedBody(
+ event,
+ z.discriminatedUnion('provider', [
+ z.object({
+ name: z.string(),
+ provider: z.literal('s3'),
+ config: s3StorageConfigSchema,
+ }),
+ z.object({
+ name: z.string(),
+ provider: z.literal('local'),
+ config: localStorageConfigSchema,
+ }),
+ z.object({
+ name: z.string(),
+ provider: z.literal('openlist'),
+ config: openListStorageConfigSchema,
+ }),
+ ]).parse,
+ )
+
+ const newId = await settingsManager.storage.addProvider(newStorageConfig)
+ return { id: newId }
+ }
+ default: {
+ throw createError({
+ statusCode: 405,
+ statusMessage: 'Method Not Allowed',
+ })
+ }
+ }
+})
diff --git a/server/database/schema.ts b/server/database/schema.ts
index 700478a1..41c39590 100644
--- a/server/database/schema.ts
+++ b/server/database/schema.ts
@@ -1,6 +1,13 @@
import { sql } from 'drizzle-orm'
-import { sqliteTable, text, integer, real } from 'drizzle-orm/sqlite-core'
+import {
+ sqliteTable,
+ text,
+ integer,
+ real,
+ uniqueIndex,
+} from 'drizzle-orm/sqlite-core'
import type { NeededExif } from '~~/shared/types/photo'
+import type { StorageConfig } from '../services/storage'
type PipelineQueuePayload =
| {
@@ -148,3 +155,54 @@ export const albumPhotos = sqliteTable('album_photos', {
.notNull()
.default(sql`(unixepoch())`),
})
+
+export const settings = sqliteTable(
+ 'settings',
+ {
+ id: integer('id').primaryKey({ autoIncrement: true }),
+ namespace: text('namespace').notNull().default('common'),
+ key: text('key').notNull(),
+ type: text('type', {
+ enum: ['string', 'number', 'boolean', 'json'],
+ }).notNull(),
+ value: text('value'),
+ defaultValue: text('default_value'),
+ label: text('label'),
+ description: text('description'),
+ isPublic: integer('is_public', { mode: 'boolean' })
+ .default(false)
+ .notNull(),
+ isReadonly: integer('is_readonly', { mode: 'boolean' })
+ .default(false)
+ .notNull(),
+ isSecret: integer('is_secret', { mode: 'boolean' })
+ .default(false)
+ .notNull(),
+ enum: text('enum', { mode: 'json' }).$type<string[] | null>(),
+ updatedAt: integer('updated_at', { mode: 'timestamp' })
+ .notNull()
+ .default(sql`(unixepoch())`),
+ updatedBy: integer('updated_by').references(() => users.id, {
+ onDelete: 'set null',
+ }),
+ },
+ (t) => [uniqueIndex('idx_namespace_key').on(t.namespace, t.key)],
+)
+
+export const settings_storage_providers = sqliteTable(
+ 'settings_storage_providers',
+ {
+ id: integer('id').primaryKey({ autoIncrement: true }),
+ name: text('name').notNull(),
+ provider: text('provider', {
+ enum: ['s3', 'local', 'openlist'],
+ }).notNull(),
+ config: text('config', { mode: 'json' }).$type<StorageConfig>().notNull(),
+ createdAt: integer('created_at', { mode: 'timestamp' })
+ .notNull()
+ .default(sql`(unixepoch())`),
+ updatedAt: integer('updated_at', { mode: 'timestamp' })
+ .notNull()
+ .default(sql`(unixepoch())`),
+ },
+)
diff --git a/server/plugins/seed.ts b/server/plugins/1.seed.ts
similarity index 100%
rename from server/plugins/seed.ts
rename to server/plugins/1.seed.ts
diff --git a/server/plugins/2.settings-manager.ts b/server/plugins/2.settings-manager.ts
new file mode 100644
index 00000000..ada7d23f
--- /dev/null
+++ b/server/plugins/2.settings-manager.ts
@@ -0,0 +1,173 @@
+import { DEFAULT_SETTINGS } from '../services/settings/contants'
+import { settingsManager } from '../services/settings/settingsManager'
+
+export default defineNitroPlugin(async (_nitroApp) => {
+ const _settingsManager = settingsManager
+
+ // Mark initialization phase to prevent storage provider switch triggers
+ // until storage manager is properly initialized in plugin 2_storage.ts
+ _settingsManager.setInitializingFlag(true)
+
+ try {
+ // Initialize default settings first
+ await _settingsManager.init(DEFAULT_SETTINGS)
+
+ // Migrate existing configurations from runtimeConfig
+ // Note: Storage manager will be initialized in the next plugin (2_storage.ts)
+ await migrateRuntimeConfigToSettings()
+ } finally {
+ _settingsManager.setInitializingFlag(false)
+ }
+})
+
+/**
+ * Migrate existing configurations from runtimeConfig to the settings system
+ */
+async function migrateRuntimeConfigToSettings() {
+ const config = useRuntimeConfig()
+ const _logger = logger.dynamic('settings-migration')
+
+ try {
+ // Migrate app settings
+ if (config.public.app) {
+ _logger.info('Migrating app settings')
+ const appSettings = {
+ title: config.public.app.title,
+ slogan: config.public.app.slogan,
+ author: config.public.app.author,
+ avatarUrl: config.public.app.avatarUrl,
+ }
+
+ for (const [key, value] of Object.entries(appSettings)) {
+ if (value) {
+ try {
+ await settingsManager.set('app', key as any, value, undefined, true)
+ _logger.debug(`Migrated app.${key}`)
+ } catch (error) {
+ _logger.warn(`Failed to migrate app.${key}:`, error)
+ }
+ }
+ }
+ }
+
+ // Migrate map settings
+ if (config.public.map) {
+ _logger.info('Migrating map settings')
+ const mapSettings = {
+ provider: config.public.map.provider,
+ 'mapbox.token': config.mapbox?.accessToken || '',
+ 'mapbox.style': config.public.map.mapbox?.style || '',
+ 'maplibre.token': config.public.map.maplibre?.token || '',
+ 'maplibre.style': config.public.map.maplibre?.style || '',
+ }
+
+ for (const [key, value] of Object.entries(mapSettings)) {
+ if (value) {
+ try {
+ await settingsManager.set('map', key as any, value, undefined, true)
+ _logger.debug(`Migrated map.${key}`)
+ } catch (error) {
+ _logger.warn(`Failed to migrate map.${key}:`, error)
+ }
+ }
+ }
+ }
+
+ // Migrate storage configuration and set as active provider
+ if (config.STORAGE_PROVIDER || config.provider) {
+ _logger.info('Migrating storage configuration')
+
+ const storageProvider = config.STORAGE_PROVIDER || 's3'
+ const providerConfig = config.provider?.[storageProvider as keyof typeof config.provider]
+
+ if (providerConfig) {
+ try {
+ // Check if a provider of the same type already exists
+ const existingProviders = await settingsManager.storage.getProviders()
+ const sameTypeProviderExists = existingProviders.some(
+ (provider) => provider.provider === storageProvider,
+ )
+
+ if (sameTypeProviderExists) {
+ _logger.info(
+ `Storage provider of type ${storageProvider} already exists, skipping creation`,
+ )
+ } else {
+ // Create a storage provider from the current configuration
+ const providerName = `Migrated ${storageProvider} Provider`
+
+ const providerId = await settingsManager.storage.addProvider({
+ name: providerName,
+ provider: storageProvider as 's3' | 'local' | 'openlist',
+ config: normalizeProviderConfig(storageProvider, providerConfig),
+ })
+
+ // Set this as the active provider
+ await settingsManager.set('storage', 'provider', providerId, undefined, true)
+ _logger.info(
+ `Storage provider migrated and set as active. Provider ID: ${providerId}`,
+ )
+ }
+ } catch (error) {
+ _logger.error('Failed to migrate storage provider:', error)
+ }
+ }
+ }
+
+ _logger.info('Configuration migration completed')
+ } catch (error) {
+ _logger.error('Failed to migrate configurations:', error)
+ }
+}
+
+/**
+ * Normalize provider configuration based on provider type
+ */
+function normalizeProviderConfig(
+ provider: string,
+ config: any,
+): any {
+ switch (provider) {
+ case 's3':
+ return {
+ provider: 's3',
+ endpoint: config.endpoint || '',
+ bucket: config.bucket || '',
+ region: config.region || 'auto',
+ accessKeyId: config.accessKeyId || '',
+ secretAccessKey: config.secretAccessKey || '',
+ prefix: config.prefix || '/photos',
+ cdnUrl: config.cdnUrl || '',
+ forcePathStyle: config.forcePathStyle ?? false,
+ }
+
+ case 'local':
+ return {
+ provider: 'local',
+ basePath: config.localPath || './data/storage',
+ baseUrl: config.baseUrl || '/storage',
+ prefix: config.prefix || 'photos/',
+ }
+
+ case 'openlist': {
+ // Support both old nested and new flat endpoint formats
+ const oldEndpoints = config.endpoints || {}
+ return {
+ provider: 'openlist',
+ baseUrl: config.baseUrl || '',
+ rootPath: config.rootPath || '',
+ token: config.token || '',
+ uploadEndpoint: config.uploadEndpoint ?? oldEndpoints.upload ?? '/api/fs/put',
+ downloadEndpoint: config.downloadEndpoint ?? oldEndpoints.download,
+ listEndpoint: config.listEndpoint ?? oldEndpoints.list,
+ deleteEndpoint: config.deleteEndpoint ?? oldEndpoints.delete ?? '/api/fs/remove',
+ metaEndpoint: config.metaEndpoint ?? oldEndpoints.meta ?? '/api/fs/get',
+ pathField: config.pathField ?? 'path',
+ cdnUrl: config.cdnUrl || '',
+ }
+ }
+
+ default:
+ return config
+ }
+}
diff --git a/server/plugins/3.storage.ts b/server/plugins/3.storage.ts
new file mode 100644
index 00000000..92eeddf3
--- /dev/null
+++ b/server/plugins/3.storage.ts
@@ -0,0 +1,116 @@
+import path from 'node:path'
+import type { LocalStorageConfig, StorageConfig } from '../services/storage'
+import { StorageManager, getGlobalStorageManager } from '../services/storage'
+import { setGlobalStorageManager } from '../services/storage/events'
+import { logger } from '../utils/logger'
+import { settingsManager } from '../services/settings/settingsManager'
+
+/**
+ * Get the global storage manager instance
+ * Used in non-request context (e.g., background tasks, event handlers)
+ */
+export function getStorageManager() {
+ const storageManager = getGlobalStorageManager()
+ if (!storageManager) {
+ throw new Error('Storage manager not initialized')
+ }
+ return storageManager
+}
+
+export default nitroPlugin(async (nitroApp) => {
+ // const config = useRuntimeConfig()
+
+ // Wait for settings migration to complete if still initializing
+ // This ensures we get the active provider after config migration
+ let activeProvider = await settingsManager.storage.getActiveProvider()
+
+ if (!activeProvider) {
+ // Retry while settings manager is still initializing
+ let attempts = 0
+ const maxAttempts = 100 // 5 seconds max with 50ms intervals
+
+ while (!activeProvider && attempts < maxAttempts && settingsManager.isInitializing_()) {
+ await new Promise(resolve => setTimeout(resolve, 50))
+ activeProvider = await settingsManager.storage.getActiveProvider()
+ attempts++
+ }
+ }
+
+ if (!activeProvider) {
+ logger.storage.error('No active storage provider configured.')
+ return
+ }
+
+ const storageConfiguration = activeProvider.config
+
+ const storageManager = new StorageManager(
+ storageConfiguration,
+ logger.storage,
+ )
+
+ // 设置全局实例
+ setGlobalStorageManager(storageManager)
+
+ // Set storage manager in context for each request
+ nitroApp.hooks.hook('request', (event) => {
+ event.context.storage = storageManager
+ })
+
+ // Initialize local storage directory if needed
+ const isLocalStorageProvider = (
+ provider: StorageConfig,
+ ): provider is LocalStorageConfig => {
+ return provider?.provider === 'local'
+ }
+
+ if (isLocalStorageProvider(storageConfiguration)) {
+ const localBase = storageConfiguration.basePath
+ try {
+ if (!path.isAbsolute(localBase)) {
+ logger.storage.warn(`LOCAL basePath is not absolute: ${localBase}`)
+ }
+ await import('node:fs').then(async (m) => {
+ const fs = m.promises as typeof import('node:fs').promises
+ await fs.mkdir(localBase, { recursive: true })
+ })
+ logger.storage.success(`Local storage ready at: ${localBase}`)
+ } catch (err) {
+ logger.storage.error('Failed to prepare local storage directory', err)
+ }
+ }
+
+ // Setup event listeners for storage manager
+ storageManager.on('provider-changed', async (event) => {
+ logger.storage.info(
+ `Storage provider changed from ${event.oldProvider} to ${event.provider}`,
+ )
+
+ // Re-initialize local storage if switching to local provider
+ if (event.provider === 'local') {
+ try {
+ const newProvider = await settingsManager.storage.getActiveProvider()
+ if (
+ newProvider &&
+ isLocalStorageProvider(newProvider.config)
+ ) {
+ const localBase = newProvider.config.basePath
+ await import('node:fs').then(async (m) => {
+ const fs = m.promises as typeof import('node:fs').promises
+ await fs.mkdir(localBase, { recursive: true })
+ })
+ logger.storage.success(`Local storage ready at: ${localBase}`)
+ }
+ } catch (error) {
+ logger.storage.error('Failed to initialize local storage:', error)
+ }
+ }
+ })
+
+ storageManager.on('provider-error', (event) => {
+ logger.storage.error(
+ `Storage provider error for ${event.provider}: ${event.error?.message}`,
+ )
+ })
+
+ logger.storage.success('Storage plugin initialized successfully')
+})
diff --git a/server/plugins/pipeline-queue.ts b/server/plugins/4.pipeline-queue.ts
similarity index 100%
rename from server/plugins/pipeline-queue.ts
rename to server/plugins/4.pipeline-queue.ts
diff --git a/server/plugins/storage.ts b/server/plugins/storage.ts
deleted file mode 100644
index 65c03338..00000000
--- a/server/plugins/storage.ts
+++ /dev/null
@@ -1,103 +0,0 @@
-import path from 'node:path'
-import type { StorageConfig } from '../services/storage'
-import { StorageManager } from '../services/storage'
-import { logger } from '../utils/logger'
-
-// 全局 storageManager 实例,可以在非请求上下文中使用
-let globalStorageManager: StorageManager
-
-export function getStorageManager(): StorageManager {
- if (!globalStorageManager) {
- throw new Error('Storage manager not initialized')
- }
- return globalStorageManager
-}
-
-export default nitroPlugin(async (nitroApp) => {
- const config = useRuntimeConfig()
-
- const storageConfiguration: Record<'s3' | 'local' | 'openlist', 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.cdnUrl,
- accessKeyId: config.provider.s3.accessKeyId,
- secretAccessKey: config.provider.s3.secretAccessKey,
- forcePathStyle: config.provider.s3.forcePathStyle,
- },
- local: {
- provider: 'local',
- basePath:
- config.provider.local.localPath ||
- path.resolve(process.cwd(), 'data', 'storage'),
- baseUrl: config.provider.local.baseUrl || '/storage',
- prefix: config.provider.local.prefix || 'photos/',
- },
- openlist: {
- provider: 'openlist',
- baseUrl: config.provider.openlist?.baseUrl || '',
- rootPath: config.provider.openlist?.rootPath || '',
- token: config.provider.openlist?.token || '',
- endpoints: {
- upload: config.provider.openlist?.endpoints?.upload ?? '/api/fs/put',
- download: config.provider.openlist?.endpoints?.download ?? '',
- list: config.provider.openlist?.endpoints?.list ?? '',
- delete: config.provider.openlist?.endpoints?.delete ?? '/api/fs/remove',
- meta: config.provider.openlist?.endpoints?.meta ?? '/api/fs/get',
- },
- pathField: config.provider.openlist?.pathField || 'path',
- cdnUrl:
- config.provider.openlist?.cdnUrl ||
- (config.provider.openlist?.baseUrl
- ? `${config.provider.openlist.baseUrl.replace(/\/$/, '')}/d`
- : undefined),
- },
- }
-
- const selectedProvider =
- (config.STORAGE_PROVIDER as 's3' | 'local' | 'openlist') || 'local'
- const storageManager = new StorageManager(
- storageConfiguration[selectedProvider],
- logger.storage,
- )
-
- if (selectedProvider === 'openlist') {
- const openlistConfig = storageConfiguration.openlist as any
- if (!openlistConfig.baseUrl) {
- logger.storage.error('OpenList baseUrl is not configured. Please set provider.openlist.baseUrl in runtimeConfig or corresponding .env variables.')
- }
- if (!openlistConfig.rootPath) {
- logger.storage.error('OpenList rootPath is not configured. Please set provider.openlist.rootPath in runtimeConfig or corresponding .env variables.')
- }
- if (!openlistConfig.token) {
- logger.storage.error('OpenList token is not configured. Please set provider.openlist.token in runtimeConfig or NUXT_PROVIDER_OPENLIST_TOKEN in .env file.')
- }
- }
-
- // 设置全局实例
- globalStorageManager = storageManager
-
- nitroApp.hooks.hook('request', (event) => {
- event.context.storage = storageManager
- })
-
- // 本地存储路径校验与创建
- if (selectedProvider === 'local') {
- const localBase = (storageConfiguration.local as any).basePath as string
- try {
- if (!path.isAbsolute(localBase)) {
- logger.storage.warn(`LOCAL basePath is not absolute: ${localBase}`)
- }
- await import('node:fs').then(async (m) => {
- const fs = m.promises as typeof import('node:fs').promises
- await fs.mkdir(localBase, { recursive: true })
- })
- logger.storage.success(`Local storage ready at: ${localBase}`)
- } catch (err) {
- logger.storage.error('Failed to prepare local storage directory', err)
- }
- }
-})
diff --git a/server/routes/storage/[...path].ts b/server/routes/storage/[...path].ts
index 60c94cd7..acca0b67 100644
--- a/server/routes/storage/[...path].ts
+++ b/server/routes/storage/[...path].ts
@@ -1,6 +1,6 @@
import path from 'node:path'
import { createReadStream, promises as fs } from 'node:fs'
-import { getStorageManager } from '../../plugins/storage'
+import { getStorageManager } from '../../plugins/3.storage'
// lightweight: avoid TS type dep; fallback when not resolvable
const guessContentType = (filePath: string): string => {
const ext = (filePath.split('.').pop() || '').toLowerCase()
diff --git a/server/services/image/processor.ts b/server/services/image/processor.ts
index 177abe7d..cbb24559 100644
--- a/server/services/image/processor.ts
+++ b/server/services/image/processor.ts
@@ -1,7 +1,7 @@
import path from 'path'
import bmp from '@vingle/bmp-js'
import heicConvert from 'heic-convert'
-import { getStorageManager } from '~~/server/plugins/storage'
+import { getStorageManager } from '~~/server/plugins/3.storage'
import sharp from 'sharp'
import { withRetry, RetryPresets, RetryConditions } from '../../utils/retry'
diff --git a/server/services/location/geocoding.ts b/server/services/location/geocoding.ts
index 4de5c1bf..73502d8c 100644
--- a/server/services/location/geocoding.ts
+++ b/server/services/location/geocoding.ts
@@ -1,4 +1,5 @@
import { withRetry, RetryPresets } from '../../utils/retry'
+import { settingsManager } from '../settings/settingsManager'
export interface LocationInfo {
latitude: number
@@ -28,66 +29,77 @@ export class MapboxGeocodingProvider implements GeocodingProvider {
async reverseGeocode(lat: number, lon: number): Promise<LocationInfo | null> {
try {
- return await withRetry(async () => {
- // 应用速率限制
- await this.applyRateLimit()
-
- const url = new URL('/search/geocode/v6/reverse', this.baseUrl)
- url.searchParams.set('access_token', this.accessToken)
- url.searchParams.set('longitude', lon.toString())
- url.searchParams.set('latitude', lat.toString())
- url.searchParams.set('types', 'address,place,district,region,country')
- url.searchParams.set('language', 'zh-Hants')
-
- logger.location.info(`Mapbox API URL: ${url.toString()}`)
-
- const response = await fetch(url.toString())
-
- if (!response.ok) {
- throw new Error(`Mapbox API error: ${response.status} ${response.statusText}`)
- }
-
- const data = await response.json()
-
- if (!data || !data.features || data.features.length === 0) {
- logger.location.warn('Mapbox API returned no features')
- return null
- }
-
- // 取第一个最相关的结果
- const feature = data.features[0]
- const properties = feature.properties || {}
- const context = properties.context || {}
-
- // 提取国家信息
- const country = context.country?.name
-
- // 提取城市信息(优先级:locality > place > locality > district > region)
- const city =
- context.locality?.name ||
- context.place?.name ||
- context.locality?.name ||
- context.district?.name ||
- context.region?.name
-
- // 构建位置名称
- const locationName = properties.place_formatted || properties.name
-
- logger.location.success(`Successfully geocoded location: ${city}, ${country}`)
- return {
- latitude: lat,
- longitude: lon,
- country,
- city,
- locationName,
- }
- }, {
- ...RetryPresets.network,
- timeout: 10000,
- delayStrategy: 'exponential'
- }, logger.location)
+ return await withRetry(
+ async () => {
+ // 应用速率限制
+ await this.applyRateLimit()
+
+ const url = new URL('/search/geocode/v6/reverse', this.baseUrl)
+ url.searchParams.set('access_token', this.accessToken)
+ url.searchParams.set('longitude', lon.toString())
+ url.searchParams.set('latitude', lat.toString())
+ url.searchParams.set('types', 'address,place,district,region,country')
+ url.searchParams.set('language', 'zh-Hants')
+
+ logger.location.info(`Mapbox API URL: ${url.toString()}`)
+
+ const response = await fetch(url.toString())
+
+ if (!response.ok) {
+ throw new Error(
+ `Mapbox API error: ${response.status} ${response.statusText}`,
+ )
+ }
+
+ const data = await response.json()
+
+ if (!data || !data.features || data.features.length === 0) {
+ logger.location.warn('Mapbox API returned no features')
+ return null
+ }
+
+ // 取第一个最相关的结果
+ const feature = data.features[0]
+ const properties = feature.properties || {}
+ const context = properties.context || {}
+
+ // 提取国家信息
+ const country = context.country?.name
+
+ // 提取城市信息(优先级:locality > place > locality > district > region)
+ const city =
+ context.locality?.name ||
+ context.place?.name ||
+ context.locality?.name ||
+ context.district?.name ||
+ context.region?.name
+
+ // 构建位置名称
+ const locationName = properties.place_formatted || properties.name
+
+ logger.location.success(
+ `Successfully geocoded location: ${city}, ${country}`,
+ )
+ return {
+ latitude: lat,
+ longitude: lon,
+ country,
+ city,
+ locationName,
+ }
+ },
+ {
+ ...RetryPresets.network,
+ timeout: 10000,
+ delayStrategy: 'exponential',
+ },
+ logger.location,
+ )
} catch (error) {
- logger.location.error('Mapbox reverse geocoding failed after all retries:', error)
+ logger.location.error(
+ 'Mapbox reverse geocoding failed after all retries:',
+ error,
+ )
return null
}
}
@@ -116,71 +128,80 @@ export class NominatimGeocodingProvider implements GeocodingProvider {
private readonly rateLimitMs = 1000 // Nominatim 要求至少1秒间隔
constructor(baseUrl?: string) {
- this.baseUrl = baseUrl || useRuntimeConfig().nominatim?.baseUrl || 'https://nominatim.openstreetmap.org'
+ this.baseUrl = baseUrl || 'https://nominatim.openstreetmap.org'
}
async reverseGeocode(lat: number, lon: number): Promise<LocationInfo | null> {
try {
- return await withRetry(async () => {
- // 应用速率限制
- await this.applyRateLimit()
-
- const url = new URL('/reverse', this.baseUrl)
- url.searchParams.set('lat', lat.toString())
- url.searchParams.set('lon', lon.toString())
- url.searchParams.set('format', 'json')
- url.searchParams.set('addressdetails', '1')
- url.searchParams.set('accept-language', 'zh-CN,zh,en')
-
- const response = await fetch(url.toString(), {
- headers: {
- 'User-Agent': this.userAgent,
- },
- })
-
- if (!response.ok) {
- throw new Error(`Nominatim API error: ${response.status} ${response.statusText}`)
- }
-
- const data = await response.json()
-
- if (!data || data.error) {
- throw new Error(`Nominatim API returned error: ${data?.error}`)
- }
-
- const address = data.address || {}
-
- // 提取国家信息
- const country = address.country || address.country_code?.toUpperCase()
-
- // 提取城市信息(优先级:district > city > town > county > state > village > hamlet)
- // 适配中国行政区划
- const city =
- address.district ||
- address.city ||
- address.town ||
- address.county ||
- address.state ||
- address.village ||
- address.hamlet
-
- // 构建位置名称
- const locationName = data.display_name
-
- return {
- latitude: lat,
- longitude: lon,
- country,
- city,
- locationName,
- }
- }, {
- ...RetryPresets.network,
- timeout: 15000, // Nominatim 可能比较慢
- delayStrategy: 'linear' // 线性退避,避免过快重试
- }, logger.location)
+ return await withRetry(
+ async () => {
+ // 应用速率限制
+ await this.applyRateLimit()
+
+ const url = new URL('/reverse', this.baseUrl)
+ url.searchParams.set('lat', lat.toString())
+ url.searchParams.set('lon', lon.toString())
+ url.searchParams.set('format', 'json')
+ url.searchParams.set('addressdetails', '1')
+ url.searchParams.set('accept-language', 'zh-CN,zh,en')
+
+ const response = await fetch(url.toString(), {
+ headers: {
+ 'User-Agent': this.userAgent,
+ },
+ })
+
+ if (!response.ok) {
+ throw new Error(
+ `Nominatim API error: ${response.status} ${response.statusText}`,
+ )
+ }
+
+ const data = await response.json()
+
+ if (!data || data.error) {
+ throw new Error(`Nominatim API returned error: ${data?.error}`)
+ }
+
+ const address = data.address || {}
+
+ // 提取国家信息
+ const country = address.country || address.country_code?.toUpperCase()
+
+ // 提取城市信息(优先级:district > city > town > county > state > village > hamlet)
+ // 适配中国行政区划
+ const city =
+ address.district ||
+ address.city ||
+ address.town ||
+ address.county ||
+ address.state ||
+ address.village ||
+ address.hamlet
+
+ // 构建位置名称
+ const locationName = data.display_name
+
+ return {
+ latitude: lat,
+ longitude: lon,
+ country,
+ city,
+ locationName,
+ }
+ },
+ {
+ ...RetryPresets.network,
+ timeout: 15000, // Nominatim 可能比较慢
+ delayStrategy: 'linear', // 线性退避,避免过快重试
+ },
+ logger.location,
+ )
} catch (error) {
- logger.location.error('Nominatim reverse geocoding failed after all retries:', error)
+ logger.location.error(
+ 'Nominatim reverse geocoding failed after all retries:',
+ error,
+ )
return null
}
}
@@ -202,15 +223,22 @@ export class NominatimGeocodingProvider implements GeocodingProvider {
* 创建地理编码提供者实例
* @description 优先使用 Mapbox,如果没有配置则回退到 Nominatim
*/
-function createGeocodingProvider(): GeocodingProvider {
- const mapboxToken = useRuntimeConfig().mapbox?.accessToken
+async function createGeocodingProvider(): Promise<GeocodingProvider> {
+ // const mapboxToken = useRuntimeConfig().mapbox?.accessToken
+ const mapboxToken = await settingsManager.get<string>(
+ 'location',
+ 'mapbox.token',
+ )
if (mapboxToken) {
return new MapboxGeocodingProvider(mapboxToken)
}
// 回退到 Nominatim 提供者
- return new NominatimGeocodingProvider()
+ return new NominatimGeocodingProvider(
+ (await settingsManager.get<string>('location', 'nominatim.baseUrl')) ||
+ undefined,
+ )
}
export async function extractLocationFromGPS(
@@ -235,7 +263,7 @@ export async function extractLocationFromGPS(
)
// 如果没有指定提供者,使用默认提供者
- const geocodingProvider = provider || createGeocodingProvider()
+ const geocodingProvider = provider || (await createGeocodingProvider())
try {
const locationInfo = await geocodingProvider.reverseGeocode(
diff --git a/server/services/pipeline-queue/manager.ts b/server/services/pipeline-queue/manager.ts
index 22559cc2..674578a0 100644
--- a/server/services/pipeline-queue/manager.ts
+++ b/server/services/pipeline-queue/manager.ts
@@ -19,7 +19,7 @@ import {
} from '../location/geocoding'
import { findLivePhotoVideoForImage } from '../video/livephoto'
import { processMotionPhotoFromXmp } from '../video/motion-photo'
-import { getStorageManager } from '~~/server/plugins/storage'
+import { getStorageManager } from '~~/server/plugins/3.storage'
export class QueueManager {
private static instances: Map<string, QueueManager> = new Map()
diff --git a/server/services/settings/contants.ts b/server/services/settings/contants.ts
new file mode 100644
index 00000000..729e9db0
--- /dev/null
+++ b/server/services/settings/contants.ts
@@ -0,0 +1,154 @@
+import type { SettingConfig } from '~~/shared/types/settings'
+
+// 存储提供商的枚举值
+export const STORAGE_PROVIDERS = ['local', 's3', 'openlist'] as const
+export type StorageProvider = (typeof STORAGE_PROVIDERS)[number]
+
+export const DEFAULT_SETTINGS = [
+ // NAMESPACE: system
+ {
+ namespace: 'system',
+ key: 'firstLaunch',
+ type: 'boolean',
+ value: true,
+ defaultValue: true,
+ label: 'settings.system.firstLaunch.label',
+ description: 'settings.system.firstLaunch.description',
+ isReadonly: true,
+ },
+ // NAMESPACE: app
+ {
+ namespace: 'app',
+ key: 'title',
+ type: 'string',
+ defaultValue: 'ChronoFrame',
+ label: 'settings.app.title.label',
+ description: 'settings.app.title.description',
+ isPublic: true,
+ },
+ {
+ namespace: 'app',
+ key: 'slogan',
+ type: 'string',
+ defaultValue: '',
+ label: 'settings.app.slogan.label',
+ description: 'settings.app.slogan.description',
+ isPublic: true,
+ },
+ {
+ namespace: 'app',
+ key: 'author',
+ type: 'string',
+ defaultValue: '',
+ label: 'settings.app.author.label',
+ description: 'settings.app.author.description',
+ isPublic: true,
+ },
+ {
+ namespace: 'app',
+ key: 'avatarUrl',
+ type: 'string',
+ defaultValue: '',
+ label: 'settings.app.avatarUrl.label',
+ description: 'settings.app.avatarUrl.description',
+ isPublic: true,
+ },
+ {
+ namespace: 'app',
+ key: 'appearance.theme',
+ type: 'string',
+ defaultValue: 'system',
+ enum: ['light', 'dark', 'system'],
+ label: 'settings.app.avatarUrl.label',
+ description: 'settings.app.avatarUrl.description',
+ isPublic: true,
+ },
+ // NAMESPACE: map
+ {
+ namespace: 'map',
+ key: 'provider',
+ type: 'string',
+ defaultValue: 'maplibre',
+ enum: ['mapbox', 'maplibre'],
+ label: 'settings.map.provider.label',
+ description: 'settings.map.provider.description',
+ isPublic: true,
+ },
+ {
+ namespace: 'map',
+ key: 'mapbox.token',
+ type: 'string',
+ defaultValue: '',
+ label: 'settings.map.mapbox.token.label',
+ description: 'settings.map.mapbox.token.description',
+ isPublic: true,
+ },
+ {
+ namespace: 'map',
+ key: 'mapbox.style',
+ type: 'string',
+ defaultValue: '',
+ label: 'settings.map.mapbox.style.label',
+ description: 'settings.map.mapbox.style.description',
+ isPublic: true,
+ },
+ {
+ namespace: 'map',
+ key: 'maplibre.token',
+ type: 'string',
+ defaultValue: '',
+ label: 'settings.map.maplibre.token.label',
+ description: 'settings.map.maplibre.token.description',
+ isPublic: true,
+ },
+ {
+ namespace: 'map',
+ key: 'maplibre.style',
+ type: 'string',
+ defaultValue: '',
+ label: 'settings.map.maplibre.style.label',
+ description: 'settings.map.maplibre.style.description',
+ isPublic: true,
+ },
+ // NAMESPACE: location
+ {
+ namespace: 'location',
+ key: 'mapbox.token',
+ type: 'string',
+ defaultValue: '',
+ label: 'settings.location.mapbox.token.label',
+ description: 'settings.location.mapbox.token.description',
+ isPublic: true,
+ },
+ {
+ namespace: 'location',
+ key: 'nominatim.baseUrl',
+ type: 'string',
+ defaultValue: '',
+ label: 'settings.location.nominatim.baseUrl.label',
+ description: 'settings.location.nominatim.baseUrl.description',
+ isPublic: true,
+ },
+ // NAMESPACE: storage
+ {
+ namespace: 'storage',
+ key: 'provider',
+ type: 'number',
+ defaultValue: null,
+ label: 'settings.storage_provider.provider.label',
+ description: 'settings.storage_provider.provider.description',
+ },
+] as const satisfies SettingConfig[]
+
+export const settingNamespaces = [
+ ...new Set(DEFAULT_SETTINGS.map((s) => s.namespace)),
+] as const
+export const settingKeys = [
+ ...new Set(DEFAULT_SETTINGS.map((s) => s.key)),
+] as const
+
+export type SettingNamespace = (typeof settingNamespaces)[number]
+export type SettingKey<N extends SettingNamespace> = Extract<
+ (typeof DEFAULT_SETTINGS)[number],
+ { namespace: N }
+>['key']
diff --git a/server/services/settings/settingsManager.ts b/server/services/settings/settingsManager.ts
new file mode 100644
index 00000000..675b67c1
--- /dev/null
+++ b/server/services/settings/settingsManager.ts
@@ -0,0 +1,443 @@
+import type {
+ NewSettingStorageProvider,
+ SettingConfig,
+ SettingStorageProvider,
+ SettingType,
+ SettingValue,
+} from '~~/shared/types/settings'
+import type { SettingKey, SettingNamespace } from './contants'
+
+export class SettingsManager {
+ private static instance: SettingsManager
+ protected settingsCache: Map<string, SettingValue> = new Map()
+ protected _logger = logger.dynamic('settings-mgr')
+ protected isInitializing = false
+
+ private constructor() {}
+
+ static getInstance(): SettingsManager {
+ if (!SettingsManager.instance) {
+ SettingsManager.instance = new SettingsManager()
+ }
+ return SettingsManager.instance
+ }
+
+ /**
+ * Set the initializing flag externally
+ * Used during plugin initialization to prevent storage provider switch triggers
+ * @param flag Boolean flag to set
+ */
+ setInitializingFlag(flag: boolean): void {
+ this.isInitializing = flag
+ }
+
+ /**
+ * Check if currently initializing
+ * @returns true if initializing, false otherwise
+ */
+ isInitializing_(): boolean {
+ return this.isInitializing
+ }
+
+ /**
+ * Validate setting value against enum if defined
+ * @param value Setting value
+ * @param enumValues Enum values if defined
+ * @returns true if valid, false if not valid
+ */
+ private validateEnum(
+ value: SettingValue,
+ enumValues: string[] | null,
+ ): boolean {
+ // Allow null values if no enum is defined
+ if (value === null) {
+ return !enumValues || enumValues.length === 0
+ }
+
+ if (!enumValues || enumValues.length === 0) {
+ return true
+ }
+ return enumValues.includes(String(value))
+ }
+
+ /**
+ * Generate cache key for a setting
+ * @param namespace
+ * @param key
+ * @returns Cache key string
+ * @example
+ * getCacheKey('app', 'theme') => 'app:theme'
+ */
+ private getCacheKey(
+ namespace: SettingNamespace,
+ key: SettingKey<typeof namespace>,
+ ): string {
+ return `${namespace}:${key}`
+ }
+
+ /**
+ * Serialize setting value to string for storage
+ * @param value Setting value
+ * @returns Serialized string
+ * @example
+ * serialize(true) => 'true'
+ * serialize({ theme: 'dark' }) => '{"theme":"dark"}'
+ * serialize(null) => 'null'
+ */
+ private serialize(value: SettingValue): string | null {
+ if (value === null) return null
+ if (typeof value === 'string') return value
+ return JSON.stringify(value)
+ }
+
+ /**
+ * Deserialize setting value from string
+ * @param value Serialized string or null
+ * @param type Setting type
+ * @returns Deserialized setting value
+ * @example
+ * deserialize('true', 'boolean') => true
+ * deserialize('{"theme":"dark"}', 'json') => { theme: 'dark' }
+ * deserialize('null', 'string') => null
+ * deserialize(null, 'string') => null
+ */
+ private deserialize(value: string | null, type: SettingType): SettingValue {
+ // Handle null or 'null' string value
+ if (value === null || value === 'null') {
+ return null
+ }
+
+ switch (type) {
+ case 'string':
+ return value
+ case 'number':
+ return Number(value)
+ case 'boolean':
+ return value === 'true'
+ default:
+ return JSON.parse(value)
+ }
+ }
+
+ /**
+ * Initialize settings manager with default settings
+ * @param configs Array of setting configurations
+ */
+ async init(configs: SettingConfig[]): Promise<void> {
+ const db = useDB()
+
+ this._logger.info('Initializing settings manager with default settings')
+
+ for (const config of configs) {
+ // Skip if namespace or key is missing
+ if (!config.namespace || !config.key) {
+ this._logger.warn('Skipping config with missing namespace or key')
+ continue
+ }
+
+ // Check if setting exists
+ const existing = db
+ .select()
+ .from(tables.settings)
+ .where(
+ and(
+ eq(tables.settings.namespace, config.namespace),
+ eq(tables.settings.key, config.key),
+ ),
+ )
+ .get()
+
+ // If not exists and has default value, insert it
+ if (!existing) {
+ db.insert(tables.settings)
+ .values({
+ namespace: config.namespace,
+ key: config.key,
+ type: config.type,
+ value: this.serialize(config.defaultValue),
+ defaultValue: this.serialize(config.defaultValue),
+ label: config.label,
+ description: config.description,
+ isPublic: config.isPublic,
+ isReadonly: config.isReadonly,
+ isSecret: config.isSecret,
+ enum: config.enum ? config.enum : null,
+ })
+ .run()
+ }
+ }
+ }
+
+ async get<T = SettingValue>(
+ namespace: SettingNamespace,
+ key: SettingKey<typeof namespace>,
+ defaultValue?: T,
+ ): Promise<T | null> {
+ const cacheKey = this.getCacheKey(namespace, key)
+
+ // Check cache first
+ if (this.settingsCache.has(cacheKey)) {
+ this._logger.debug(`Cache hit for setting ${cacheKey}`)
+ return this.settingsCache.get(cacheKey) as T
+ }
+
+ // If not in cache, fetch from database
+ const db = useDB()
+ const setting = db
+ .select()
+ .from(tables.settings)
+ .where(
+ and(
+ eq(tables.settings.namespace, namespace),
+ eq(tables.settings.key, key),
+ ),
+ )
+ .get()
+
+ // If not found, return default value
+ if (!setting) {
+ this._logger.debug(
+ `Setting ${cacheKey} not found, returning default value`,
+ )
+ return defaultValue ?? null
+ }
+
+ this._logger.debug(`Setting ${cacheKey} fetched from database`)
+ const value = this.deserialize(setting.value, setting.type)
+ this.settingsCache.set(cacheKey, value)
+
+ return value as T
+ }
+
+ async set(
+ namespace: SettingNamespace,
+ key: SettingKey<typeof namespace>,
+ value: SettingValue,
+ updatedBy?: number,
+ sudo = false,
+ ): Promise<void> {
+ const db = useDB()
+ const cacheKey = this.getCacheKey(namespace, key)
+
+ const existing = db
+ .select()
+ .from(tables.settings)
+ .where(
+ and(
+ eq(tables.settings.namespace, namespace),
+ eq(tables.settings.key, key),
+ ),
+ )
+ .get()
+
+ if (!existing) {
+ this._logger.warn(`Setting ${namespace}:${key} does not exist`)
+ throw new Error(`Setting ${namespace}:${key} does not exist`)
+ }
+
+ if (existing.isReadonly && !sudo) {
+ this._logger.warn(
+ `Attempt to modify readonly setting ${namespace}:${key}`,
+ )
+ throw new Error(`Setting ${namespace}:${key} is readonly`)
+ }
+
+ if (!this.validateEnum(value, existing.enum)) {
+ this._logger.warn(
+ `Invalid value for enum setting ${namespace}:${key}. Value: ${value}, allowed: ${existing.enum?.join(', ')}`,
+ )
+ throw new Error(
+ `Invalid value for setting ${namespace}:${key}. Allowed values: ${existing.enum?.join(', ')}`,
+ )
+ }
+
+ const serializedValue = this.serialize(value)
+
+ db.update(tables.settings)
+ .set({
+ value: serializedValue,
+ updatedAt: new Date(),
+ updatedBy: updatedBy ?? null,
+ })
+ .where(
+ and(
+ eq(tables.settings.namespace, namespace),
+ eq(tables.settings.key, key),
+ ),
+ )
+ .run()
+
+ this._logger.info(`Setting ${namespace}:${key} updated`)
+ this.settingsCache.set(cacheKey, value)
+
+ // Trigger storage provider switch if storage:provider is being changed
+ // Skip during initialization as storage manager is not yet initialized
+ if (namespace === 'storage' && key === 'provider' && !this.isInitializing) {
+ // Use setImmediate to avoid blocking and handle async operation
+ setImmediate(() => {
+ this.triggerStorageProviderSwitch(value as number).catch((error) => {
+ this._logger.error('Failed to trigger storage provider switch:', error)
+ })
+ })
+ }
+ }
+
+ /**
+ * Trigger storage provider switch
+ * @param providerId Provider ID to switch to
+ */
+ private async triggerStorageProviderSwitch(providerId: number): Promise<void> {
+ try {
+ // Dynamically import to avoid circular dependency issues
+ const { getGlobalStorageManager } = await import('~~/server/services/storage/events')
+ const loggerModule = await import('~~/server/utils/logger')
+
+ const storageManager = getGlobalStorageManager()
+ if (!storageManager) {
+ this._logger.warn(
+ 'Storage manager not initialized, cannot switch provider',
+ )
+ return
+ }
+
+ const newProvider = await this.storage.getProviderById(providerId)
+ if (!newProvider) {
+ this._logger.error(`Provider with ID ${providerId} not found`)
+ return
+ }
+
+ this._logger.info(
+ `Triggering storage provider switch to: ${newProvider.name} (ID: ${providerId})`,
+ )
+
+ await storageManager.registerProvider(
+ newProvider.config,
+ loggerModule.logger.dynamic('storage'),
+ )
+ } catch (error) {
+ this._logger.error('Failed to switch storage provider:', error)
+ }
+ }
+
+ async getNamespace(
+ namespace: SettingNamespace,
+ ): Promise<Record<string, SettingValue>> {
+ const db = useDB()
+ const settings = db
+ .select()
+ .from(tables.settings)
+ .where(eq(tables.settings.namespace, namespace))
+ .all()
+
+ const result: Record<string, SettingValue> = {}
+
+ for (const setting of settings) {
+ result[setting.key] = this.deserialize(setting.value, setting.type)
+ }
+ return result
+ }
+
+ async getSchema(): Promise<SettingConfig[]> {
+ const db = useDB()
+ const settings = db.select().from(tables.settings).all()
+
+ return settings.map((setting) => ({
+ namespace: setting.namespace,
+ key: setting.key,
+ type: setting.type,
+ value: this.deserialize(setting.value, setting.type),
+ defaultValue:
+ setting.defaultValue &&
+ this.deserialize(setting.defaultValue, setting.type),
+ label: setting.label,
+ description: setting.description,
+ isReadonly: setting.isReadonly,
+ isSecret: setting.isSecret,
+ // 包含枚举值,过滤掉 null
+ ...(setting.enum ? { enum: setting.enum } : {}),
+ }))
+ }
+
+ // Storage Providers Management
+ public storage = {
+ async getProviders(): Promise<SettingStorageProvider[]> {
+ const db = useDB()
+ const providers = db
+ .select()
+ .from(tables.settings_storage_providers)
+ .all()
+ return providers
+ },
+
+ async getProviderById(id: number): Promise<SettingStorageProvider | null> {
+ const db = useDB()
+ const provider = db
+ .select()
+ .from(tables.settings_storage_providers)
+ .where(eq(tables.settings_storage_providers.id, id))
+ .get()
+ return provider || null
+ },
+
+ async getActiveProvider(): Promise<SettingStorageProvider | null> {
+ const providerId = await settingsManager.get<number>(
+ 'storage',
+ 'provider',
+ )
+ if (!providerId) {
+ return null
+ }
+ return this.getProviderById(providerId)
+ },
+
+ async addProvider(
+ providerConfig: NewSettingStorageProvider,
+ ): Promise<number> {
+ const db = useDB()
+ const result = db
+ .insert(tables.settings_storage_providers)
+ .values({
+ name: providerConfig.name,
+ provider: providerConfig.provider,
+ config: providerConfig.config,
+ })
+ .run()
+
+ // If no active provider and this is the only provider, set this as active
+ const currentActiveProvider = await settingsManager.get<number>(
+ 'storage',
+ 'provider',
+ )
+ if (!currentActiveProvider && (await this.getProviders()).length === 1) {
+ await settingsManager.set(
+ 'storage',
+ 'provider',
+ result.lastInsertRowid as number,
+ )
+ }
+ return result.lastInsertRowid as number
+ },
+
+ async updateProvider(
+ id: number,
+ providerConfig: Partial<NewSettingStorageProvider['config']>,
+ ): Promise<void> {
+ const db = useDB()
+ db.update(tables.settings_storage_providers)
+ .set({
+ ...providerConfig,
+ })
+ .where(eq(tables.settings_storage_providers.id, id))
+ .run()
+ },
+
+ async deleteProvider(id: number): Promise<void> {
+ const db = useDB()
+ db.delete(tables.settings_storage_providers)
+ .where(eq(tables.settings_storage_providers.id, id))
+ .run()
+ },
+ }
+}
+
+export const settingsManager = SettingsManager.getInstance()
diff --git a/server/services/settings/ui-config.ts b/server/services/settings/ui-config.ts
new file mode 100644
index 00000000..6a22fd24
--- /dev/null
+++ b/server/services/settings/ui-config.ts
@@ -0,0 +1,125 @@
+import type { FieldUIConfig } from '~~/shared/types/settings'
+
+/**
+ * Extended settings configuration with UI descriptions
+ * This defines how the frontend displays and interacts with each settings field
+ *
+ * Note:
+ * - This is only used on the Server side
+ * - UI configuration information is returned to the frontend via API
+ * - Avoid duplicating these configurations on the frontend
+ */
+export const APP_SETTINGS_UI: Record<string, FieldUIConfig> = {
+ title: {
+ type: 'input',
+ placeholder: 'ChronoFrame',
+ required: true,
+ },
+ slogan: {
+ type: 'input',
+ placeholder: 'Your gallery slogan',
+ help: 'settings.app.slogan.help',
+ },
+ author: {
+ type: 'input',
+ placeholder: 'Your name',
+ },
+ avatarUrl: {
+ type: 'url',
+ placeholder: 'https://example.com/avatar.jpg',
+ help: 'settings.app.avatarUrl.help',
+ },
+ 'appearance.theme': {
+ type: 'tabs',
+ options: [
+ {
+ label: 'settings.app.appearance.theme.light',
+ value: 'light',
+ icon: 'tabler:sun',
+ },
+ {
+ label: 'settings.app.appearance.theme.dark',
+ value: 'dark',
+ icon: 'tabler:moon',
+ },
+ {
+ label: 'settings.app.appearance.theme.system',
+ value: 'system',
+ icon: 'tabler:device-desktop',
+ },
+ ],
+ help: 'settings.app.appearance.theme.help',
+ },
+}
+
+export const MAP_SETTINGS_UI: Record<string, FieldUIConfig> = {
+ provider: {
+ type: 'tabs',
+ options: [
+ { label: 'MapBox', value: 'mapbox' },
+ { label: 'MapLibre', value: 'maplibre' },
+ ],
+ },
+ 'mapbox.token': {
+ type: 'password',
+ placeholder: 'pk.xxxxxx',
+ required: true,
+ visibleIf: { fieldKey: 'provider', value: 'mapbox' },
+ help: 'settings.map.mapbox.token.help',
+ },
+ 'mapbox.style': {
+ type: 'input',
+ placeholder: 'mapbox://styles/mapbox/light-v11',
+ visibleIf: { fieldKey: 'provider', value: 'mapbox' },
+ },
+ 'maplibre.token': {
+ type: 'password',
+ placeholder: 'pk.xxxxxx',
+ required: true,
+ visibleIf: { fieldKey: 'provider', value: 'maplibre' },
+ help: 'settings.map.maplibre.token.help',
+ },
+ 'maplibre.style': {
+ type: 'input',
+ placeholder: 'https://example.com/style.json',
+ visibleIf: { fieldKey: 'provider', value: 'maplibre' },
+ },
+}
+
+export const LOCATION_SETTINGS_UI: Record<string, FieldUIConfig> = {
+ 'mapbox.token': {
+ type: 'password',
+ placeholder: 'pk.xxxxxx',
+ help: 'settings.location.mapbox.token.help',
+ },
+ 'nominatim.baseUrl': {
+ type: 'url',
+ placeholder: 'https://nominatim.openstreetmap.org',
+ help: 'settings.location.nominatim.baseUrl.help',
+ },
+}
+
+export const STORAGE_SETTINGS_UI: Record<string, FieldUIConfig> = {
+ provider: {
+ type: 'select',
+ help: 'settings.storage.provider.help',
+ },
+}
+
+/**
+ * Get UI configuration for a specific setting
+ * Used to return complete field descriptions in the fields.get.ts API
+ */
+export function getSettingUIConfig(
+ namespace: string,
+ key: string,
+): FieldUIConfig | undefined {
+ const uiConfigMap: Record<string, Record<string, FieldUIConfig>> = {
+ app: APP_SETTINGS_UI,
+ map: MAP_SETTINGS_UI,
+ location: LOCATION_SETTINGS_UI,
+ storage: STORAGE_SETTINGS_UI,
+ }
+
+ return uiConfigMap[namespace]?.[key]
+}
diff --git a/server/services/storage/events.ts b/server/services/storage/events.ts
new file mode 100644
index 00000000..d8eb5351
--- /dev/null
+++ b/server/services/storage/events.ts
@@ -0,0 +1,30 @@
+import type { StorageManager } from './manager'
+
+/**
+ * Global storage manager for non-request context
+ */
+let globalStorageManager: StorageManager | null = null
+
+/**
+ * Set the global storage manager instance
+ * @param storageManager StorageManager instance
+ */
+export function setGlobalStorageManager(storageManager: StorageManager): void {
+ globalStorageManager = storageManager
+}
+
+/**
+ * Get the global storage manager instance
+ * @returns StorageManager instance or null if not initialized
+ */
+export function getGlobalStorageManager(): StorageManager | null {
+ return globalStorageManager
+}
+
+/**
+ * Check if storage manager is initialized
+ * @returns true if storage manager is initialized
+ */
+export function isStorageManagerInitialized(): boolean {
+ return globalStorageManager !== null
+}
diff --git a/server/services/storage/index.ts b/server/services/storage/index.ts
index ed1607f6..082f53ea 100644
--- a/server/services/storage/index.ts
+++ b/server/services/storage/index.ts
@@ -1,9 +1,30 @@
-export { StorageProvider, StorageConfig, StorageObject } from './interfaces'
+export { StorageProvider, StorageObject } from './interfaces'
+
+export {
+ s3StorageConfigSchema,
+ localStorageConfigSchema,
+ openListStorageConfigSchema,
+ storageConfigSchema,
+} from '~~/shared/types/storage'
+
+export {
+ S3StorageConfig,
+ LocalStorageConfig,
+ OpenListStorageConfig,
+ StorageConfig,
+} from '~~/shared/types/storage'
export { StorageProviderFactory, StorageManager } from './manager'
+export type { StorageManagerEventType, StorageManagerEventListener, StorageManagerEvent } from './manager'
+
export { S3StorageProvider } from './providers/s3'
-export { HubR2StorageProvider } from './providers/hub-r2'
-export { GitHubStorageProvider } from './providers/github'
export { LocalStorageProvider } from './providers/local'
export { OpenListStorageProvider } from './providers/openlist'
+
+export {
+ setGlobalStorageManager,
+ getGlobalStorageManager,
+ isStorageManagerInitialized,
+} from './events'
+
diff --git a/server/services/storage/interfaces.ts b/server/services/storage/interfaces.ts
index fe9bc867..2d61ce11 100644
--- a/server/services/storage/interfaces.ts
+++ b/server/services/storage/interfaces.ts
@@ -1,3 +1,5 @@
+import type { StorageConfig } from '.'
+
export interface StorageObject {
key: string
size?: number
@@ -5,69 +7,6 @@ export interface StorageObject {
lastModified?: Date
}
-export type S3StorageConfig = {
- provider: 's3'
- bucket?: string
- region?: string
- endpoint?: string
- prefix?: string
- cdnUrl?: string
- accessKeyId?: string
- secretAccessKey?: string
- forcePathStyle?: boolean
- maxKeys?: number
-}
-
-export type HubR2StorageConfig = {
- provider: 'hub-r2'
- prefix?: string
- maxKeys?: number
- cdnUrl?: string
-}
-
-export type GitHubStorageConfig = {
- provider: 'github'
- owner?: string
- repository?: string
- branch?: string
- path?: string
- prefix?: string
- token?: string
-}
-
-export type LocalStorageConfig = {
- provider: 'local'
- /** Absolute directory where files are stored */
- basePath: string
- /** Public base URL to serve files, e.g. /storage or https://domain.com/storage */
- baseUrl?: string
- /** Optional prefix for logical keys within basePath */
- prefix?: string
-}
-
-export type OpenListStorageConfig = {
- provider: 'openlist'
- baseUrl: string
- rootPath: string
- token: string
- endpoints: {
- upload: string
- download: string
- list: string
- delete: string
- meta: string
- }
- pathField?: string
- cdnUrl?: string
-}
-
-export type StorageConfig =
- | S3StorageConfig
- | HubR2StorageConfig
- | GitHubStorageConfig
- | LocalStorageConfig
- | OpenListStorageConfig
-
export interface UploadOptions {
contentType?: string
metadata?: Record<string, string>
diff --git a/server/services/storage/manager.ts b/server/services/storage/manager.ts
index 3b54737d..9d432cac 100644
--- a/server/services/storage/manager.ts
+++ b/server/services/storage/manager.ts
@@ -1,10 +1,23 @@
import type { StorageConfig, StorageProvider } from '.';
import { S3StorageProvider } from '.'
import type { Logger } from '../../utils/logger'
-import { HubR2StorageProvider } from './providers/hub-r2'
import { LocalStorageProvider } from './providers/local'
import { OpenListStorageProvider } from './providers/openlist'
+export type StorageManagerEventType = 'provider-changed' | 'provider-error'
+
+export interface StorageManagerEventListener {
+ (event: StorageManagerEvent): void | Promise<void>
+}
+
+export interface StorageManagerEvent {
+ type: StorageManagerEventType
+ provider?: string
+ oldProvider?: string
+ error?: Error
+ timestamp: number
+}
+
// eslint-disable-next-line @typescript-eslint/no-extraneous-class
export class StorageProviderFactory {
static createProvider(
@@ -14,15 +27,10 @@ export class StorageProviderFactory {
switch (config.provider) {
case 's3':
return new S3StorageProvider(config, logger)
- case 'hub-r2':
- return new HubR2StorageProvider(config, logger)
case 'local':
return new LocalStorageProvider(config, logger)
case 'openlist':
return new OpenListStorageProvider(config as any, logger)
- case 'github':
- // TODO: Implement GitHub storage provider
- throw new Error('GitHub storage provider not implemented yet')
default:
throw new Error(`Unknown storage provider`)
}
@@ -31,22 +39,121 @@ export class StorageProviderFactory {
export class StorageManager {
private provider: StorageProvider
+ private logger?: Logger['storage']
+ private eventListeners: Map<StorageManagerEventType, StorageManagerEventListener[]> = new Map()
+ private currentProviderName?: string
constructor(config: StorageConfig, logger?: Logger['storage']) {
- logger?.info(`Creating storage provider: ${config.provider}`)
+ this.logger = logger
+ this.logger?.info(`Creating storage provider: ${config.provider}`)
+ this.currentProviderName = config.provider
this.provider = StorageProviderFactory.createProvider(config, logger)
}
- registerProvider(config: StorageConfig, logger?: Logger['storage']) {
- logger?.info(`Registering storage provider: ${config.provider}`)
- this.provider = StorageProviderFactory.createProvider(config, logger)
+ /**
+ * Register event listener for storage manager events
+ * @param eventType Type of event to listen for
+ * @param listener Event listener callback
+ */
+ public on(
+ eventType: StorageManagerEventType,
+ listener: StorageManagerEventListener,
+ ): void {
+ if (!this.eventListeners.has(eventType)) {
+ this.eventListeners.set(eventType, [])
+ }
+ this.eventListeners.get(eventType)!.push(listener)
+ this.logger?.debug(`Event listener registered for: ${eventType}`)
+ }
+
+ /**
+ * Unregister event listener
+ * @param eventType Type of event
+ * @param listener Event listener callback
+ */
+ public off(
+ eventType: StorageManagerEventType,
+ listener: StorageManagerEventListener,
+ ): void {
+ const listeners = this.eventListeners.get(eventType)
+ if (listeners) {
+ const index = listeners.indexOf(listener)
+ if (index > -1) {
+ listeners.splice(index, 1)
+ this.logger?.debug(`Event listener unregistered for: ${eventType}`)
+ }
+ }
}
- getProvider<T extends StorageProvider>() {
+ /**
+ * Emit event to all registered listeners
+ * @param event Event to emit
+ */
+ private async emitEvent(event: StorageManagerEvent): Promise<void> {
+ const listeners = this.eventListeners.get(event.type) || []
+ for (const listener of listeners) {
+ try {
+ await listener(event)
+ } catch (error) {
+ this.logger?.error(`Error in event listener for ${event.type}:`, error)
+ }
+ }
+ }
+
+ /**
+ * Register/switch storage provider
+ * @param config New storage configuration
+ * @param logger Optional logger instance
+ */
+ async registerProvider(config: StorageConfig, logger?: Logger['storage']): Promise<void> {
+ try {
+ const oldProviderName = this.currentProviderName
+ this.logger = logger || this.logger
+
+ this.logger?.info(`Switching storage provider from ${oldProviderName} to ${config.provider}`)
+
+ const newProvider = StorageProviderFactory.createProvider(config, this.logger)
+ this.provider = newProvider
+ this.currentProviderName = config.provider
+
+ this.logger?.success(`Storage provider switched to: ${config.provider}`)
+
+ // Emit provider-changed event
+ await this.emitEvent({
+ type: 'provider-changed',
+ provider: config.provider,
+ oldProvider: oldProviderName,
+ timestamp: Date.now(),
+ })
+ } catch (error) {
+ this.logger?.error(`Failed to register storage provider: ${config.provider}`, error)
+
+ // Emit provider-error event
+ await this.emitEvent({
+ type: 'provider-error',
+ provider: config.provider,
+ error: error as Error,
+ timestamp: Date.now(),
+ })
+
+ throw error
+ }
+ }
+
+ /**
+ * Get current storage provider
+ */
+ getProvider<T extends StorageProvider>(): T {
if (!this.provider) {
throw new Error(`Storage provider not registered`)
}
-
return this.provider as T
}
+
+ /**
+ * Get current provider name
+ */
+ getCurrentProviderName(): string | undefined {
+ return this.currentProviderName
+ }
}
diff --git a/server/services/storage/providers/github.ts b/server/services/storage/providers/github.ts
deleted file mode 100644
index 1f81174c..00000000
--- a/server/services/storage/providers/github.ts
+++ /dev/null
@@ -1,24 +0,0 @@
-// TODO: Implement GitHub storage provider and remove below line
-/* eslint-disable @typescript-eslint/no-unused-vars */
-import type { StorageObject, StorageProvider } from '../interfaces'
-
-export class GitHubStorageProvider implements StorageProvider {
- create(key: string, data: Buffer): Promise<StorageObject> {
- throw new Error('Method not implemented.')
- }
- delete(key: string): Promise<void> {
- throw new Error('Method not implemented.')
- }
- get(key: string): Promise<Buffer | null> {
- throw new Error('Method not implemented.')
- }
- getPublicUrl(key: string): string {
- throw new Error('Method not implemented.')
- }
- listAll(): Promise<StorageObject[]> {
- throw new Error('Method not implemented.')
- }
- listImages(): Promise<StorageObject[]> {
- throw new Error('Method not implemented.')
- }
-}
diff --git a/server/services/storage/providers/hub-r2.ts b/server/services/storage/providers/hub-r2.ts
deleted file mode 100644
index 5627f41a..00000000
--- a/server/services/storage/providers/hub-r2.ts
+++ /dev/null
@@ -1,59 +0,0 @@
-import type {
- HubR2StorageConfig,
- StorageObject,
- StorageProvider,
- UploadOptions,
-} from '../interfaces'
-
-/**
- * @deprecated DO NOT use HubR2StorageProvider anymore, use S3StorageProvider instead
- */
-export class HubR2StorageProvider implements StorageProvider {
- config: HubR2StorageConfig
- private logger?: Logger['storage']
-
- constructor(config: HubR2StorageConfig, logger?: Logger['storage']) {
- 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,
- _contentType?: string,
- ): Promise<StorageObject> {
- throw new Error('Method not implemented.')
- }
-
- async delete(_key: string): Promise<void> {
- throw new Error('Method not implemented.')
- }
-
- async get(_key: string): Promise<Buffer | null> {
- throw new Error('Method not implemented.')
- }
-
- getPublicUrl(key: string): string {
- const { cdnUrl } = this.config
-
- if (cdnUrl) {
- return `${cdnUrl.replace(/\/+$/, '')}/${key.replace(/^\/+/, '')}`
- }
-
- return key
- }
-
- async listAll(): Promise<StorageObject[]> {
- throw new Error('Method not implemented.')
- }
-
- listImages(): Promise<StorageObject[]> {
- throw new Error('Method not implemented.')
- }
-}
diff --git a/server/services/storage/providers/openlist.ts b/server/services/storage/providers/openlist.ts
index b8459487..1064fd85 100644
--- a/server/services/storage/providers/openlist.ts
+++ b/server/services/storage/providers/openlist.ts
@@ -1,5 +1,5 @@
import type { Logger } from '../../../utils/logger'
-import type { StorageProvider, StorageObject, OpenListStorageConfig } from '../interfaces'
+import type { StorageProvider, StorageObject } from '../interfaces'
/**
* OpenListStorageProvider implements StorageProvider for OpenList API.
@@ -69,7 +69,7 @@ export class OpenListStorageProvider implements StorageProvider {
async create(key: string, fileBuffer: Buffer, contentType?: string): Promise<StorageObject> {
const rootedKey = this.withRoot(key)
const absoluteKey = this.toAbsolutePath(rootedKey)
- const uploadPath = this.config.endpoints.upload
+ const uploadPath = this.config.uploadEndpoint || '/api/fs/put'
const resp = await this.request(uploadPath, {
method: 'PUT',
@@ -106,7 +106,7 @@ export class OpenListStorageProvider implements StorageProvider {
}
async delete(key: string): Promise<void> {
- const deletePath = this.config.endpoints.delete
+ const deletePath = this.config.deleteEndpoint || '/api/fs/remove'
const urlPath = `${deletePath}`
const rootedKey = this.withRoot(key)
const normalized = rootedKey.replace(/^\/+/, '')
@@ -129,8 +129,9 @@ export class OpenListStorageProvider implements StorageProvider {
}
async get(key: string): Promise<Buffer | null> {
- // If download endpoint is empty string, try to resolve raw_url via meta and fetch it
- if (!this.config.endpoints.download || this.config.endpoints.download === '') {
+ // If download endpoint is not provided, try to resolve raw_url via meta and fetch it
+ const downloadPath = this.config.downloadEndpoint
+ if (!downloadPath) {
const info = await this.getFileMeta(this.withRoot(key))
const rawUrl = (info as any)?.raw_url || undefined
if (!rawUrl) return null
@@ -141,7 +142,6 @@ export class OpenListStorageProvider implements StorageProvider {
return Buffer.from(arrayBuffer)
}
- const downloadPath = this.config.endpoints.download
const rootedKey = this.withRoot(key)
const urlPath = `${downloadPath}?${encodeURIComponent(this.pathField)}=${encodeURIComponent(rootedKey)}`
const resp = await this.request(urlPath, { method: 'GET' })
@@ -162,7 +162,7 @@ export class OpenListStorageProvider implements StorageProvider {
}
async getFileMeta(key: string): Promise<StorageObject | null> {
- const metaPath = this.config.endpoints.meta || this.config.endpoints.download
+ const metaPath = this.config.metaEndpoint || this.config.downloadEndpoint || '/api/fs/get'
const rootedKey = this.withRoot(key)
const urlPath = metaPath
const payload: Record<string, any> = {
@@ -200,8 +200,9 @@ export class OpenListStorageProvider implements StorageProvider {
async listAll(): Promise<StorageObject[]> {
// Listing API not provided explicitly; return empty array by default.
// You can configure custom list endpoint and parsing later.
- if (!this.config.endpoints.list || this.config.endpoints.list === '') return []
- const listPath = this.config.endpoints.list
+ const listPath = this.config.listEndpoint
+ if (!listPath) return []
+
const payload: Record<string, any> = {
[this.pathField]: this.toAbsolutePath(this.normalizedRoot()),
password: '',
diff --git a/server/services/storage/providers/s3.ts b/server/services/storage/providers/s3.ts
index 756d6954..3c1ea947 100644
--- a/server/services/storage/providers/s3.ts
+++ b/server/services/storage/providers/s3.ts
@@ -8,7 +8,6 @@ import {
} from '@aws-sdk/client-s3'
import { getSignedUrl } from '@aws-sdk/s3-request-presigner'
import type {
- S3StorageConfig,
StorageObject,
StorageProvider,
UploadOptions,
diff --git a/server/services/video/livephoto.ts b/server/services/video/livephoto.ts
index 8504b0a7..bd5aa9f4 100644
--- a/server/services/video/livephoto.ts
+++ b/server/services/video/livephoto.ts
@@ -1,6 +1,6 @@
import path from 'path'
import { eq } from 'drizzle-orm'
-import { getStorageManager } from '~~/server/plugins/storage'
+import { getStorageManager } from '~~/server/plugins/3.storage'
/**
* 处理 LivePhoto MOV 文件,匹配相同文件名的照片并更新 LivePhoto 信息
diff --git a/server/services/video/scanner.ts b/server/services/video/scanner.ts
index 0feab056..349ce0c2 100644
--- a/server/services/video/scanner.ts
+++ b/server/services/video/scanner.ts
@@ -1,4 +1,4 @@
-import { getStorageManager } from '~~/server/plugins/storage'
+import { getStorageManager } from '~~/server/plugins/3.storage'
import { processLivePhotoVideo, isLivePhotoVideo } from '../video/livephoto'
/**
diff --git a/shared/types/settings.ts b/shared/types/settings.ts
new file mode 100644
index 00000000..afa27fe0
--- /dev/null
+++ b/shared/types/settings.ts
@@ -0,0 +1,97 @@
+import type * as schema from '../../server/database/schema'
+
+export type SettingType = typeof schema.settings.$inferSelect.type
+export type SettingValue = string | number | boolean | Record<string, any> | null
+
+export type SettingConfig = Omit<
+ typeof schema.settings.$inferInsert,
+ 'value' | 'defaultValue' | 'id' | 'updatedAt' | 'updatedBy' | 'enum'
+> & {
+ value?: SettingValue
+ defaultValue: SettingValue
+ enum?: ReadonlyArray<string>
+}
+
+export type SettingStorageProvider = typeof schema.settings_storage_providers.$inferSelect
+export type NewSettingStorageProvider = typeof schema.settings_storage_providers.$inferInsert
+
+/**
+ * UI 字段类型枚举
+ * 定义在 shared 中以便前端使用
+ */
+export type FieldUIType =
+ | 'input' // 文本输入
+ | 'password' // 密码输入
+ | 'url' // URL 输入
+ | 'textarea' // 文本域
+ | 'select' // 下拉选择
+ | 'radio' // 单选按钮
+ | 'tabs' // 标签页选择
+ | 'toggle' // 开关
+ | 'number' // 数字输入
+ | 'custom' // 自定义组件
+
+/**
+ * 字段 UI 配置
+ * 定义前端如何展示和交互一个设置字段
+ */
+export interface FieldUIConfig {
+ // 基础 UI 类型
+ type: FieldUIType
+
+ // 输入相关
+ placeholder?: string
+ help?: string
+
+ // 条件展示 - 根据其他字段的值来决定是否显示这个字段
+ visibleIf?: {
+ fieldKey: string
+ value: SettingValue
+ }
+
+ // 可选项(用于 select/radio/tabs)
+ options?: ReadonlyArray<{
+ label: string
+ value: SettingValue
+ icon?: string
+ }>
+
+ // 验证规则(前端 UX 提示)
+ required?: boolean
+ minLength?: number
+ maxLength?: number
+ pattern?: string // 正则表达式
+
+ // 样式和尺寸
+ size?: 'sm' | 'md' | 'lg'
+ variant?: 'soft' | 'outline'
+ icon?: string
+}
+
+/**
+ * 完整的字段描述符
+ * 包含后端配置和前端 UI 信息
+ * 由 API 返回给前端,前端可直接渲染
+ */
+export interface FieldDescriptor extends SettingConfig {
+ ui: FieldUIConfig
+}
+
+/**
+ * Settings 字段获取响应
+ */
+export interface SettingsFieldsResponse {
+ namespace: string
+ fields: FieldDescriptor[]
+}
+
+/**
+ * Settings 批量更新请求
+ */
+export interface SettingsBatchUpdateRequest {
+ updates: Array<{
+ namespace: string
+ key: string
+ value: SettingValue
+ }>
+}
diff --git a/shared/types/storage.ts b/shared/types/storage.ts
new file mode 100644
index 00000000..806c202f
--- /dev/null
+++ b/shared/types/storage.ts
@@ -0,0 +1,47 @@
+import { z } from 'zod'
+
+export const s3StorageConfigSchema = z.object({
+ provider: z.literal('s3'),
+ bucket: z.string(),
+ region: z.string().default('auto'),
+ endpoint: z.string(),
+ prefix: z.string().default('/photos').optional(),
+ cdnUrl: z.string().optional(),
+ accessKeyId: z.string(),
+ secretAccessKey: z.string(),
+ forcePathStyle: z.boolean().optional(),
+ maxKeys: z.number().optional(),
+})
+
+export const localStorageConfigSchema = z.object({
+ provider: z.literal('local'),
+ basePath: z.string().min(1),
+ baseUrl: z.string().optional(),
+ prefix: z.string().optional(),
+})
+
+export const openListStorageConfigSchema = z.object({
+ provider: z.literal('openlist'),
+ baseUrl: z.string().min(1),
+ rootPath: z.string().min(1),
+ token: z.string().min(1),
+ uploadEndpoint: z.string().default('/api/fs/put').optional(),
+ downloadEndpoint: z.string().optional(),
+ listEndpoint: z.string().optional(),
+ deleteEndpoint: z.string().default('/api/fs/remove').optional(),
+ metaEndpoint: z.string().default('/api/fs/get').optional(),
+ pathField: z.string().default('path').optional(),
+ cdnUrl: z.string().optional(),
+})
+
+export const storageConfigSchema = z.discriminatedUnion('provider', [
+ s3StorageConfigSchema,
+ localStorageConfigSchema,
+ openListStorageConfigSchema,
+])
+
+export type StorageConfig = z.infer<typeof storageConfigSchema>
+
+export type S3StorageConfig = z.infer<typeof s3StorageConfigSchema>
+export type LocalStorageConfig = z.infer<typeof localStorageConfigSchema>
+export type OpenListStorageConfig = z.infer<typeof openListStorageConfigSchema>