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: 重构仪表盘首页,重写系统状态报告 API

Timothy Yin0bf4e9bc41d7
diff --git a/app/pages/dashboard/index.vue b/app/pages/dashboard/index.vue
index 83902b53..afde793d 100644
--- a/app/pages/dashboard/index.vue
+++ b/app/pages/dashboard/index.vue
@@ -7,165 +7,151 @@ useHead({
title: $t('title.dashboard'),
})
-interface SystemHealth {
- uptime: number
- memory: {
- used: number
- total: number
- }
- processing: {
- active: boolean
- queued: number
- }
-}
-
-const { data: photos, refresh: refreshPhotos } = await useFetch('/api/photos', {
- server: false,
-})
+const dayjs = useDayjs()
-const { data: healthStatus, refresh: refreshHealth } =
- await useFetch<SystemHealth>('/api/health/system', {
- server: false,
- })
+const { data: dashboardStats, refresh: refreshStats } =
+ await useFetch('/api/system/stats')
const isLoading = ref(false)
const refreshData = async () => {
isLoading.value = true
try {
- await Promise.all([refreshPhotos(), refreshHealth()])
+ await Promise.all([refreshStats()])
} finally {
isLoading.value = false
}
}
-// 定期刷新状态
-const refreshInterval = setInterval(refreshData, 30000)
+const refreshInterval = setInterval(refreshData, 1500)
onBeforeUnmount(() => {
clearInterval(refreshInterval)
})
+
+const systemStatus = computed(() => {
+ if (!dashboardStats.value) return 'unknown'
+
+ const memoryUsage = dashboardStats.value.memory
+ ? (dashboardStats.value.memory.used / dashboardStats.value.memory.total) *
+ 100
+ : 0
+
+ if (memoryUsage > 90) return 'critical'
+ if (memoryUsage > 70) return 'warning'
+ return 'healthy'
+})
+
+// 趋势图表
+const chartData = computed(() => {
+ if (!dashboardStats.value?.trends) return { labels: [], data: [] }
+
+ return {
+ labels: dashboardStats.value.trends.map((item) => {
+ const date = new Date(item.date || '')
+ return dayjs(date).format("MM-DD")
+ }),
+ data: dashboardStats.value.trends.map((item) => item.count),
+ }
+})
</script>
<template>
<div class="flex flex-col gap-6 h-full p-4">
<div class="flex items-center justify-between">
<h1 class="text-2xl font-bold">仪表板概览</h1>
- <UButton
- icon="i-tabler-refresh"
- variant="outline"
- :loading="isLoading"
- @click="refreshData"
- >
- 刷新
- </UButton>
</div>
- <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
- <!-- 总照片数量 -->
- <UCard>
+ <!-- 核心指标条 - 横向布局 -->
+ <div class="grid grid-cols-2 lg:grid-cols-4 gap-4">
+ <!-- 照片总数 -->
+ <div
+ class="border bg-gradient-to-r from-blue-50 to-cyan-50 border-cyan-100 dark:from-blue-950 dark:to-cyan-950 dark:border-cyan-900 rounded-lg p-4 text-blue-400 dark:text-white"
+ >
<div class="flex items-center justify-between">
<div>
- <p class="text-sm text-neutral-500 dark:text-neutral-400">
- 总照片数量
+ <p class="text-sm opacity-90 font-medium">照片总数</p>
+ <p class="text-lg font-bold">
+ {{ dashboardStats?.photos?.total || 0 }}
</p>
- <p class="text-2xl font-bold">{{ photos?.length || 0 }}</p>
</div>
<UIcon
name="i-tabler-photo"
- class="w-8 h-8 text-info"
+ class="size-8 opacity-80"
/>
</div>
- </UCard>
+ </div>
- <!-- 系统内存使用 -->
- <UCard>
+ <!-- 本月新增 -->
+ <div
+ class="border bg-gradient-to-r from-green-50 to-emerald-50 border-emerald-100 dark:from-green-950 dark:to-emerald-950 dark:border-emerald-900 rounded-lg p-4 text-green-400 dark:text-white"
+ >
<div class="flex items-center justify-between">
<div>
- <p class="text-sm text-neutral-500 dark:text-neutral-400">
- 内存使用率
- </p>
- <p class="text-2xl font-bold">
- {{
- healthStatus?.memory
- ? Math.round(
- (healthStatus.memory.used / healthStatus.memory.total) *
- 100,
- )
- : 0
- }}%
+ <p class="text-sm opacity-90">本月新增</p>
+ <p class="text-lg font-bold">
+ {{ dashboardStats?.photos?.thisMonth || 0 }}
</p>
</div>
<UIcon
- name="i-tabler-cpu"
- class="w-8 h-8 text-success"
+ name="i-tabler-plus"
+ class="w-8 h-8 opacity-80"
/>
</div>
- </UCard>
+ </div>
- <!-- 系统运行时间 -->
- <UCard>
+ <!-- 处理中 -->
+ <div
+ class="border bg-gradient-to-r from-purple-50 to-violet-50 border-violet-100 dark:from-purple-950 dark:to-violet-950 dark:border-violet-900 rounded-lg p-4 text-purple-400 dark:text-white"
+ >
<div class="flex items-center justify-between">
<div>
- <p class="text-sm text-neutral-500 dark:text-neutral-400">
- 运行时间
- </p>
- <p class="text-2xl font-bold">
+ <p class="text-sm opacity-90">队列状态</p>
+ <p class="text-lg font-bold">
{{
- healthStatus?.uptime
- ? Math.round(healthStatus.uptime / 3600)
- : 0
- }}h
+ (dashboardStats?.workerPool?.activeWorkers || 0) > 0
+ ? '处理中'
+ : '空闲'
+ }}
</p>
</div>
<UIcon
- name="i-tabler-clock"
- class="w-8 h-8 text-warning-500"
+ name="i-tabler-loader"
+ class="w-8 h-8 opacity-80"
/>
</div>
- </UCard>
+ </div>
- <!-- 系统状态 -->
- <UCard>
+ <!-- 存储使用量 -->
+ <div
+ class="border bg-gradient-to-r from-indigo-50 to-blue-50 border-blue-100 dark:from-indigo-950 dark:to-blue-950 dark:border-blue-900 rounded-lg p-4 text-indigo-400 dark:text-white"
+ >
<div class="flex items-center justify-between">
<div>
- <p class="text-sm text-neutral-500 dark:text-neutral-400">
- 系统状态
- </p>
- <p class="text-2xl font-bold">
- <UBadge
- :color="
- healthStatus?.processing?.active !== false
- ? 'success'
- : 'warning'
- "
- variant="solid"
- >
- {{
- healthStatus?.processing?.active !== false ? '正常' : '待机'
- }}
- </UBadge>
+ <p class="text-sm opacity-90">存储使用</p>
+ <p class="text-lg font-bold">
+ {{ formatBytes(dashboardStats?.storage?.totalSize || 0) }}
</p>
</div>
<UIcon
- name="i-tabler-heart"
- class="w-8 h-8 text-error"
+ name="i-tabler-database"
+ class="w-8 h-8 opacity-80"
/>
</div>
- </UCard>
+ </div>
</div>
- <!-- 系统信息 -->
+ <!-- 运行信息 -->
<UCard>
<template #header>
- <h2 class="text-lg font-semibold">系统信息</h2>
+ <h2 class="text-lg font-semibold pb-1.5">运行信息</h2>
</template>
- <div class="grid grid-cols-2 gap-4">
+ <div class="grid grid-cols-2 md:grid-cols-4 gap-4">
<div>
<p class="text-sm text-neutral-500 dark:text-neutral-400">应用版本</p>
<NuxtLink
- class="text-lg font-bold"
+ class="text-lg font-bold hover:text-primary"
target="_blank"
external
:to="`https://github.com/HoshinoSuzumi/chronoframe/releases/tag/v${$config.public.VERSION}`"
@@ -173,6 +159,25 @@ onBeforeUnmount(() => {
v{{ $config.public.VERSION }}
</NuxtLink>
</div>
+ <div>
+ <p class="text-sm text-neutral-500 dark:text-neutral-400">运行时间</p>
+ <p class="text-lg font-bold">
+ {{
+ dashboardStats?.uptime
+ ? $dayjs.duration(dashboardStats.uptime, 'seconds').humanize()
+ : '-'
+ }}
+ </p>
+ </div>
+ <div>
+ <p class="text-sm text-neutral-500 dark:text-neutral-400">运行环境</p>
+ <UBadge
+ :color="dashboardStats?.runningOn === 'docker' ? 'info' : 'success'"
+ variant="soft"
+ >
+ {{ dashboardStats?.runningOn || 'unknown' }}
+ </UBadge>
+ </div>
<div>
<p class="text-sm text-neutral-500 dark:text-neutral-400">最后更新</p>
<p class="text-lg font-bold">
@@ -182,49 +187,166 @@ onBeforeUnmount(() => {
</div>
</UCard>
- <!-- 最近照片 -->
- <UCard v-if="photos?.length">
- <template #header>
- <h2 class="text-lg font-semibold">最近照片</h2>
- </template>
+ <!-- 详细统计区域 -->
+ <div class="grid grid-cols-1 lg:grid-cols-3 gap-4">
+ <!-- 左侧:照片统计图表 -->
+ <div class="lg:col-span-2">
+ <UCard>
+ <template #header>
+ <div class="flex items-center justify-between pb-1.5">
+ <h2 class="text-lg font-semibold">新增照片趋势</h2>
+ <div class="flex gap-2">
+ <UBadge
+ color="info"
+ variant="soft"
+ >
+ 本周 {{ dashboardStats?.photos?.thisWeek || 0 }}
+ </UBadge>
+ <UBadge
+ color="success"
+ variant="soft"
+ >
+ 本月 {{ dashboardStats?.photos?.thisMonth || 0 }}
+ </UBadge>
+ </div>
+ </div>
+ </template>
- <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
- <div
- v-for="photo in photos.slice(0, 12)"
- :key="photo.id"
- class="flex items-center gap-3 p-3 bg-neutral-50 dark:bg-neutral-800 rounded-lg"
- >
- <div
- class="w-12 h-12 bg-neutral-200 dark:bg-neutral-700 rounded flex items-center justify-center relative"
- >
- <!-- <img
- :src="photo.thumbnailUrl || ''"
- alt="Photo thumbnail"
- class="w-full h-full rounded object-cover"
- /> -->
- <ThumbImage
- :src="photo.thumbnailUrl || ''"
- :alt="photo.title || 'Photo thumbnail'"
- :thumbhash="photo.thumbnailHash || ''"
- class="w-full h-full rounded object-cover"
- />
+ <!-- 简单的趋势展示 -->
+ <div class="space-y-2">
+ <div
+ v-for="(trend, index) in dashboardStats?.trends || []"
+ :key="trend.date"
+ class="flex items-center gap-3"
+ >
+ <div class="text-sm text-neutral-500 dark:text-neutral-400 w-12">
+ {{ chartData.labels[index] }}
+ </div>
+ <UProgress
+ :model-value="
+ chartData.data[index] && chartData.data.length
+ ? (chartData.data[index] / Math.max(...chartData.data) ||
+ 0) * 100
+ : 1
+ "
+ color="info"
+ class="flex-1"
+ />
+ <div class="text-sm font-medium w-8 text-right">
+ {{ trend.count }}
+ </div>
+ </div>
</div>
- <div class="flex-1 min-w-0">
- <p class="font-medium truncate">{{ photo.title || photo.id }}</p>
- <p class="text-sm text-neutral-500 inline-flex gap-2">
- <span>
+ </UCard>
+ </div>
+
+ <!-- 右侧:系统资源监控 -->
+ <div class="space-y-4">
+ <!-- 内存使用 -->
+ <UCard>
+ <template #header>
+ <h3 class="font-semibold pb-1.5">内存使用率</h3>
+ </template>
+
+ <div class="space-y-2">
+ <UProgress
+ :model-value="
+ dashboardStats?.memory
+ ? Math.round(
+ (dashboardStats.memory.used /
+ dashboardStats.memory.total) *
+ 100,
+ )
+ : 0
+ "
+ :color="
+ systemStatus === 'healthy'
+ ? 'success'
+ : systemStatus === 'warning'
+ ? 'warning'
+ : systemStatus === 'critical'
+ ? 'error'
+ : 'neutral'
+ "
+ class="w-full"
+ />
+ <div class="flex justify-between text-sm">
+ <div class="text-xs text-neutral-500 dark:text-neutral-400">
{{
- photo.dateTaken
- ? $dayjs(photo.dateTaken).format('YYYY-MM-DD')
- : '未知日期'
+ dashboardStats?.memory
+ ? `${Math.round((dashboardStats.memory.used / 1024 / 1024 / 1024) * 100) / 100}GB / ${Math.round((dashboardStats.memory.total / 1024 / 1024 / 1024) * 100) / 100}GB`
+ : '系统内存'
}}
+ </div>
+ <span>
+ {{
+ dashboardStats?.memory
+ ? Math.round(
+ (dashboardStats.memory.used /
+ dashboardStats.memory.total) *
+ 100,
+ )
+ : 0
+ }}%
</span>
- <span>{{ formatBytes(photo.fileSize || 0) }}</span>
- </p>
+ </div>
</div>
- </div>
+ </UCard>
+
+ <!-- 队列详情 -->
+ <UCard>
+ <template #header>
+ <h3 class="font-semibold pb-1.5">处理队列</h3>
+ </template>
+
+ <div class="space-y-1">
+ <div class="flex justify-between items-center text-sm">
+ <span>活跃 Workers</span>
+ <UBadge variant="soft">
+ {{ dashboardStats?.workerPool?.activeWorkers || 0 }}
+ </UBadge>
+ </div>
+ <div class="flex justify-between items-center text-sm">
+ <span>总 Workers</span>
+ <UBadge variant="soft">
+ {{ dashboardStats?.workerPool?.totalWorkers || 0 }}
+ </UBadge>
+ </div>
+ <div class="flex justify-between items-center text-sm">
+ <span>已处理</span>
+ <UBadge variant="soft">
+ {{ dashboardStats?.workerPool?.totalProcessed || 0 }}
+ </UBadge>
+ </div>
+ <div class="flex justify-between items-center text-sm">
+ <span>出错数</span>
+ <UBadge variant="soft">
+ {{ dashboardStats?.workerPool?.totalErrors || 0 }}
+ </UBadge>
+ </div>
+ <div class="flex justify-between items-center text-sm">
+ <span>成功率</span>
+ <UBadge
+ :color="
+ (dashboardStats?.workerPool?.averageSuccessRate || 0) > 90
+ ? 'success'
+ : (dashboardStats?.workerPool?.averageSuccessRate || 0) > 70
+ ? 'warning'
+ : 'error'
+ "
+ variant="soft"
+ >
+ {{
+ Math.round(
+ dashboardStats?.workerPool?.averageSuccessRate || 0,
+ )
+ }}%
+ </UBadge>
+ </div>
+ </div>
+ </UCard>
</div>
- </UCard>
+ </div>
</div>
</template>
diff --git a/server/api/health/processor.ts b/server/api/health/processor.ts
deleted file mode 100644
index 5735979e..00000000
--- a/server/api/health/processor.ts
+++ /dev/null
@@ -1,15 +0,0 @@
-export default eventHandler(async (_event) => {
- // 简单的处理器状态检查
- const status = {
- mode: 'background-processing',
- active: true,
- type: 'async-setImmediate',
- blocking: false
- }
-
- return {
- processor: status,
- timestamp: new Date().toISOString(),
- message: 'Background photo processing status'
- }
-})
diff --git a/server/api/health/system.ts b/server/api/health/system.ts
deleted file mode 100644
index 42c89421..00000000
--- a/server/api/health/system.ts
+++ /dev/null
@@ -1,26 +0,0 @@
-export default eventHandler(async (event) => {
- const method = getMethod(event)
-
- if (method === 'GET') {
- const memUsage = process.memoryUsage()
- const uptime = process.uptime()
-
- return {
- uptime: uptime,
- memory: {
- used: memUsage.heapUsed,
- total: memUsage.heapTotal
- },
- processing: {
- active: true,
- queued: 0 // 后台处理不维护队列
- },
- timestamp: new Date().toISOString()
- }
- }
-
- throw createError({
- statusCode: 405,
- statusMessage: 'Method not allowed'
- })
-})
diff --git a/server/api/system/stats.get.ts b/server/api/system/stats.get.ts
new file mode 100644
index 00000000..6de15e41
--- /dev/null
+++ b/server/api/system/stats.get.ts
@@ -0,0 +1,193 @@
+import { sql, and, gte } from 'drizzle-orm'
+import * as si from 'systeminformation'
+import { readFileSync } from 'node:fs'
+
+async function getQueueStats() {
+ const workerPool = globalThis.__workerPool
+ return workerPool ? workerPool.getPoolStats() : null
+}
+
+async function checkIfDocker(): Promise<boolean> {
+ try {
+ // 检查是否存在Docker特有的文件
+ const fs = await import('fs')
+ return fs.existsSync('/.dockerenv') || fs.existsSync('/proc/1/cgroup')
+ } catch {
+ return false
+ }
+}
+
+// 在Docker容器中获取内存信息
+async function getDockerMemoryInfo(): Promise<{
+ used: number
+ total: number
+} | null> {
+ try {
+ // 尝试从/proc/meminfo读取内存信息
+ const meminfo = readFileSync('/proc/meminfo', 'utf8')
+ const lines = meminfo.split('\n')
+
+ let totalMem = 0
+ let availableMem = 0
+
+ for (const line of lines) {
+ if (line.startsWith('MemTotal:')) {
+ totalMem = parseInt(line.split(/\s+/)[1]) * 1024 // 转换为字节
+ } else if (line.startsWith('MemAvailable:')) {
+ availableMem = parseInt(line.split(/\s+/)[1]) * 1024 // 转换为字节
+ }
+ }
+
+ if (totalMem > 0) {
+ return {
+ total: totalMem,
+ used: totalMem - availableMem,
+ }
+ }
+
+ return null
+ } catch (error) {
+ console.warn('Failed to read /proc/meminfo:', error)
+ return null
+ }
+}
+
+async function getMemoryStats() {
+ let memoryInfo: {
+ used: number
+ total: number
+ } | null = null
+ try {
+ const isDocker = await checkIfDocker()
+
+ if (isDocker) {
+ memoryInfo = await getDockerMemoryInfo()
+ }
+
+ if (!memoryInfo) {
+ const sysMemInfo = await si.mem()
+ memoryInfo = {
+ used: sysMemInfo.used,
+ total: sysMemInfo.total,
+ }
+ }
+ } catch (error) {
+ console.warn(
+ 'Failed to get system memory info, falling back to process info:',
+ error,
+ )
+ const memUsage = process.memoryUsage()
+ memoryInfo = {
+ used: memUsage.heapUsed,
+ total: memUsage.heapTotal,
+ }
+ }
+
+ return memoryInfo
+}
+
+export default eventHandler(async (event) => {
+ await requireUserSession(event)
+
+ // 获取基础统计
+ const totalPhotos = await useDB()
+ .select({ count: sql<number>`count(*)` })
+ .from(tables.photos)
+ .get()
+
+ // 获取今日新增照片数量
+ const today = new Date()
+ today.setHours(0, 0, 0, 0)
+ const todayISO = today.toISOString()
+
+ const todayPhotos = await useDB()
+ .select({ count: sql<number>`count(*)` })
+ .from(tables.photos)
+ .where(gte(tables.photos.dateTaken, todayISO))
+ .get()
+
+ // 获取本周新增照片数量
+ const weekAgo = new Date()
+ weekAgo.setDate(weekAgo.getDate() - 7)
+ weekAgo.setHours(0, 0, 0, 0)
+ const weekAgoISO = weekAgo.toISOString()
+
+ const weekPhotos = await useDB()
+ .select({ count: sql<number>`count(*)` })
+ .from(tables.photos)
+ .where(gte(tables.photos.dateTaken, weekAgoISO))
+ .get()
+
+ // 获取本月新增照片数量
+ const monthStart = new Date()
+ monthStart.setDate(1)
+ monthStart.setHours(0, 0, 0, 0)
+ const monthStartISO = monthStart.toISOString()
+
+ const monthPhotos = await useDB()
+ .select({ count: sql<number>`count(*)` })
+ .from(tables.photos)
+ .where(gte(tables.photos.dateTaken, monthStartISO))
+ .get()
+
+ // 获取存储统计(估算)
+ const storageStats = await useDB()
+ .select({
+ totalSize: sql<number>`COALESCE(sum(file_size), 0)`,
+ avgSize: sql<number>`COALESCE(avg(file_size), 0)`,
+ maxSize: sql<number>`COALESCE(max(file_size), 0)`,
+ })
+ .from(tables.photos)
+ .get()
+
+ // 获取最近7天的上传趋势
+ const trendData = []
+ for (let i = 6; i >= 0; i--) {
+ const date = new Date()
+ date.setDate(date.getDate() - i)
+ date.setHours(0, 0, 0, 0)
+ const dateISO = date.toISOString()
+
+ const nextDate = new Date(date)
+ nextDate.setDate(nextDate.getDate() + 1)
+ const nextDateISO = nextDate.toISOString()
+
+ const dayCount = await useDB()
+ .select({ count: sql<number>`count(*)` })
+ .from(tables.photos)
+ .where(
+ and(
+ gte(tables.photos.dateTaken, dateISO),
+ sql`${tables.photos.dateTaken} < ${nextDateISO}`,
+ ),
+ )
+ .get()
+
+ trendData.push({
+ date: date.toISOString().split('T')[0],
+ count: dayCount?.count || 0,
+ })
+ }
+
+ return {
+ uptime: process.uptime() || 0,
+ runningOn: (await checkIfDocker())
+ ? 'docker'
+ : (await si.osInfo().then((info) => info.distro)) || 'unknown',
+ memory: (await getMemoryStats()) || { used: 0, total: 0 },
+ photos: {
+ total: totalPhotos?.count || 0,
+ today: todayPhotos?.count || 0,
+ thisWeek: weekPhotos?.count || 0,
+ thisMonth: monthPhotos?.count || 0,
+ },
+ workerPool: (await getQueueStats()) || null,
+ storage: {
+ totalSize: storageStats?.totalSize || 0,
+ averageSize: storageStats?.avgSize || 0,
+ maxSize: storageStats?.maxSize || 0,
+ },
+ trends: trendData.toReversed(),
+ timestamp: new Date().toISOString(),
+ }
+})