From ff2f1478a7e5a25b53c19605fddcc7e3f16aa5ff Mon Sep 17 00:00:00 2001 From: yibaiba <946100224@qq.com> Date: Tue, 11 Aug 2026 13:19:24 +0800 Subject: [PATCH] [fix-nine-regressions-02] render timestamps in device timezone --- internal/api/openapi.vohive.yaml | 33 +++++ internal/api/openapi_test.go | 4 + internal/api/server.go | 3 + internal/api/system_time.go | 127 ++++++++++++++++++ internal/api/system_time_test.go | 115 ++++++++++++++++ web/src/App.vue | 60 ++++++++- web/src/components/DebugPanel.vue | 6 +- web/src/components/DeviceAtTab.vue | 5 +- web/src/components/DeviceUssdTab.vue | 5 +- web/src/components/ErrorState.vue | 5 +- web/src/components/TrafficAnalysisPanel.vue | 46 ++----- web/src/services/system.ts | 7 + web/src/utils/deviceTime.ts | 141 ++++++++++++++++++++ web/src/views/Dashboard.vue | 3 +- web/src/views/Logs.vue | 18 +-- web/src/views/Settings.vue | 7 +- web/src/views/Sms.vue | 13 +- web/tests/deviceTime.test.ts | 65 +++++++++ 18 files changed, 593 insertions(+), 70 deletions(-) create mode 100644 internal/api/system_time.go create mode 100644 internal/api/system_time_test.go create mode 100644 web/src/utils/deviceTime.ts create mode 100644 web/tests/deviceTime.test.ts diff --git a/internal/api/openapi.vohive.yaml b/internal/api/openapi.vohive.yaml index 86cc434d..3eedf4c0 100644 --- a/internal/api/openapi.vohive.yaml +++ b/internal/api/openapi.vohive.yaml @@ -593,6 +593,20 @@ paths: '401': $ref: '#/components/responses/Unauthorized' + /system/time: + get: + tags: [settings] + summary: 获取设备当前时间和时区 + responses: + '200': + description: 设备时间快照 + content: + application/json: + schema: + $ref: '#/components/schemas/SystemTimeResponse' + '401': + $ref: '#/components/responses/Unauthorized' + /devices: get: tags: [devices] @@ -1765,6 +1779,25 @@ components: docs: $ref: '#/components/schemas/DocsLinks' + SystemTimeResponse: + type: object + required: [now, timezone, offset_seconds, source] + properties: + now: + type: string + format: date-time + timezone: + type: string + description: 可解析时为 IANA 时区名;仅能确定固定偏移时为空 + example: Asia/Shanghai + offset_seconds: + type: integer + description: 当前时刻相对 UTC 的秒偏移 + example: 28800 + source: + type: string + enum: [runtime_location, env_tz, etc_timezone, etc_localtime, fixed_offset] + LoginRequest: type: object required: [username, password] diff --git a/internal/api/openapi_test.go b/internal/api/openapi_test.go index 429944b5..62252302 100644 --- a/internal/api/openapi_test.go +++ b/internal/api/openapi_test.go @@ -19,4 +19,8 @@ func TestOpenAPIVoHiveYAMLValid(t *testing.T) { if doc["openapi"] == "" { t.Fatalf("openapi.vohive.yaml missing openapi version") } + paths, ok := doc["paths"].(map[string]any) + if !ok || paths["/system/time"] == nil { + t.Fatal("openapi.vohive.yaml missing /system/time") + } } diff --git a/internal/api/server.go b/internal/api/server.go index ab8c34a4..950c9f73 100644 --- a/internal/api/server.go +++ b/internal/api/server.go @@ -80,6 +80,7 @@ type Server struct { notifyMgr *notify.Manager websheets *vwebsheet.Broker cardPolicies cardPolicyStore + systemTime systemTimeProvider httpSrvMu sync.Mutex httpSrv *http.Server @@ -118,6 +119,7 @@ func New(cfg *config.Config, pool *device.Pool, fs http.FileSystem, proxyMgr *se notifyMgr: notifyMgr, proxyRepo: repo.NewDBRepo(), cardPolicies: databaseCardPolicyStore{}, + systemTime: newOSSystemTimeProvider(), websheets: vwebsheet.New(vwebsheet.Config{BasePath: "/api/websheets"}), loginAttempts: make(map[string]loginAttempt), smsLimiter: newSMSRateLimiterWithConfig( @@ -286,6 +288,7 @@ func (s *Server) newRouter() *gin.Engine { api.POST("/settings/notifications/email/test", s.handleTestEmailNotification) api.POST("/settings/password", s.handleChangePassword) // 修改登录密码 api.GET("/system/info", s.handleSystemInfo) // 获取系统运行与版本信息 + api.GET("/system/time", s.handleSystemTime) // 获取设备时间和时区 api.GET("/system/update/check", s.handleCheckUpdate) // 检查系统更新 api.POST("/system/update/apply", s.handleApplyUpdate) // 应用系统更新 diff --git a/internal/api/system_time.go b/internal/api/system_time.go new file mode 100644 index 00000000..baf42bee --- /dev/null +++ b/internal/api/system_time.go @@ -0,0 +1,127 @@ +package api + +import ( + "net/http" + "os" + "path/filepath" + "strings" + "time" + + "github.com/gin-gonic/gin" +) + +type systemTimeInfo struct { + Now string `json:"now"` + Timezone string `json:"timezone"` + OffsetSeconds int `json:"offset_seconds"` + Source string `json:"source"` +} + +type systemTimeProvider interface { + Snapshot() systemTimeInfo +} + +type systemTimeDependencies struct { + now func() time.Time + getenv func(string) string + readFile func(string) ([]byte, error) + readlink func(string) (string, error) +} + +type osSystemTimeProvider struct { + deps systemTimeDependencies +} + +func newOSSystemTimeProvider() osSystemTimeProvider { + return osSystemTimeProvider{deps: systemTimeDependencies{ + now: time.Now, + getenv: os.Getenv, + readFile: os.ReadFile, + readlink: os.Readlink, + }} +} + +func (p osSystemTimeProvider) Snapshot() systemTimeInfo { + now := p.deps.now() + zoneName, source, location := resolveSystemLocation(now, p.deps) + if location == nil { + _, offset := now.Zone() + location = time.FixedZone("device", offset) + } + deviceNow := now.In(location) + _, offset := deviceNow.Zone() + return systemTimeInfo{ + Now: deviceNow.Format(time.RFC3339Nano), + Timezone: zoneName, + OffsetSeconds: offset, + Source: source, + } +} + +func resolveSystemLocation(now time.Time, deps systemTimeDependencies) (string, string, *time.Location) { + candidates := []struct { + name string + source string + }{ + {name: now.Location().String(), source: "runtime_location"}, + {name: strings.TrimPrefix(strings.TrimSpace(deps.getenv("TZ")), ":"), source: "env_tz"}, + {name: readTimezoneFile(deps.readFile), source: "etc_timezone"}, + {name: readLocaltimeZone(deps.readlink), source: "etc_localtime"}, + } + for _, candidate := range candidates { + if location := loadNamedLocation(candidate.name); location != nil { + return candidate.name, candidate.source, location + } + } + return "", "fixed_offset", nil +} + +func loadNamedLocation(name string) *time.Location { + name = strings.TrimSpace(name) + if name == "" || name == "Local" { + return nil + } + location, err := time.LoadLocation(name) + if err != nil { + return nil + } + return location +} + +func readTimezoneFile(readFile func(string) ([]byte, error)) string { + content, err := readFile("/etc/timezone") + if err != nil { + return "" + } + return strings.TrimSpace(string(content)) +} + +func readLocaltimeZone(readlink func(string) (string, error)) string { + target, err := readlink("/etc/localtime") + if err != nil { + return "" + } + if !filepath.IsAbs(target) { + target = filepath.Join("/etc", target) + } + cleaned := filepath.Clean(target) + marker := string(filepath.Separator) + "zoneinfo" + string(filepath.Separator) + index := strings.LastIndex(cleaned, marker) + if index < 0 { + return "" + } + name := strings.TrimPrefix(cleaned[index+len(marker):], "posix/") + return strings.TrimPrefix(name, "right/") +} + +func (s *Server) currentSystemTimeProvider() systemTimeProvider { + if s.systemTime != nil { + return s.systemTime + } + provider := newOSSystemTimeProvider() + return provider +} + +func (s *Server) handleSystemTime(c *gin.Context) { + c.JSON(http.StatusOK, s.currentSystemTimeProvider().Snapshot()) +} diff --git a/internal/api/system_time_test.go b/internal/api/system_time_test.go new file mode 100644 index 00000000..1f2daa6e --- /dev/null +++ b/internal/api/system_time_test.go @@ -0,0 +1,115 @@ +package api + +import ( + "encoding/json" + "errors" + "net/http" + "net/http/httptest" + "testing" + "time" + + "github.com/gin-gonic/gin" + "github.com/iniwex5/vohive/internal/config" +) + +type systemTimeProviderStub struct { + info systemTimeInfo +} + +func (s systemTimeProviderStub) Snapshot() systemTimeInfo { return s.info } + +func unavailableFile(string) ([]byte, error) { return nil, errors.New("unavailable") } + +func unavailableLink(string) (string, error) { return "", errors.New("unavailable") } + +func TestSystemTimeProviderUsesEtcTimezone(t *testing.T) { + localOnly := time.FixedZone("Local", 0) + instant := time.Date(2026, 8, 11, 4, 30, 0, 0, localOnly) + provider := osSystemTimeProvider{deps: systemTimeDependencies{ + now: func() time.Time { return instant }, + getenv: func(string) string { return "" }, + readFile: func(string) ([]byte, error) { return []byte("Asia/Shanghai\n"), nil }, + readlink: unavailableLink, + }} + + got := provider.Snapshot() + if got.Timezone != "Asia/Shanghai" || got.Source != "etc_timezone" || got.OffsetSeconds != 8*60*60 { + t.Fatalf("snapshot=%+v", got) + } + if got.Now != "2026-08-11T12:30:00+08:00" { + t.Fatalf("now=%q", got.Now) + } +} + +func TestSystemTimeProviderPrefersExplicitRuntimeLocation(t *testing.T) { + london, err := time.LoadLocation("Europe/London") + if err != nil { + t.Fatal(err) + } + provider := osSystemTimeProvider{deps: systemTimeDependencies{ + now: func() time.Time { return time.Date(2026, 8, 11, 5, 30, 0, 0, london) }, + getenv: func(string) string { return "Asia/Shanghai" }, + readFile: func(string) ([]byte, error) { return []byte("Asia/Tokyo"), nil }, + readlink: unavailableLink, + }} + + got := provider.Snapshot() + if got.Timezone != "Europe/London" || got.Source != "runtime_location" || got.OffsetSeconds != 3600 { + t.Fatalf("snapshot=%+v", got) + } +} + +func TestSystemTimeProviderExposesFixedOffsetFallback(t *testing.T) { + location := time.FixedZone("unknown-device-zone", 5*60*60+30*60) + provider := osSystemTimeProvider{deps: systemTimeDependencies{ + now: func() time.Time { return time.Date(2026, 8, 11, 9, 0, 0, 0, location) }, + getenv: func(string) string { return "invalid-zone" }, + readFile: unavailableFile, + readlink: unavailableLink, + }} + + got := provider.Snapshot() + if got.Timezone != "" || got.Source != "fixed_offset" || got.OffsetSeconds != 19800 { + t.Fatalf("snapshot=%+v", got) + } + if _, err := time.Parse(time.RFC3339Nano, got.Now); err != nil { + t.Fatalf("now is not RFC3339: %v", err) + } +} + +func TestReadLocaltimeZoneExtractsIANAName(t *testing.T) { + got := readLocaltimeZone(func(string) (string, error) { + return "../usr/share/zoneinfo/posix/Europe/London", nil + }) + if got != "Europe/London" { + t.Fatalf("zone=%q", got) + } +} + +func TestSystemTimeEndpointReturnsInjectedSnapshot(t *testing.T) { + gin.SetMode(gin.TestMode) + want := systemTimeInfo{ + Now: "2026-08-11T12:30:00+08:00", Timezone: "Asia/Shanghai", + OffsetSeconds: 28800, Source: "runtime_location", + } + s := &Server{ + auth: config.WebConfig{Username: "admin", Password: "secret"}, + systemTime: systemTimeProviderStub{info: want}, + } + router := s.newRouter() + recorder := httptest.NewRecorder() + request := httptest.NewRequest(http.MethodGet, "/api/system/time", nil) + request.Header.Set("Authorization", "Bearer "+testSessionToken(t, "secret", time.Now().Add(time.Hour))) + router.ServeHTTP(recorder, request) + + if recorder.Code != http.StatusOK { + t.Fatalf("code=%d body=%s", recorder.Code, recorder.Body.String()) + } + var got systemTimeInfo + if err := json.Unmarshal(recorder.Body.Bytes(), &got); err != nil { + t.Fatal(err) + } + if got != want { + t.Fatalf("got=%+v want=%+v", got, want) + } +} diff --git a/web/src/App.vue b/web/src/App.vue index 2ba71535..ba5ba625 100644 --- a/web/src/App.vue +++ b/web/src/App.vue @@ -3,8 +3,11 @@ import { computed, defineAsyncComponent, ref, onMounted, watch } from 'vue' import { useRoute } from 'vue-router' import { useAuthStore } from './stores/auth' import LoadingScreen from './components/LoadingScreen.vue' +import ErrorState from './components/ErrorState.vue' import { ElMessage } from 'element-plus' import { shouldShowDisclaimer } from './disclaimer' +import { systemService } from './services/system' +import { configureDeviceTime, deviceNow, resetDeviceTime } from './utils/deviceTime' const DISCLAIMER_AGREED_AT_KEY = 'vohive_disclaimer_agreed_at' @@ -16,6 +19,9 @@ const showDisclaimer = ref(false) const confirmText = ref('') const expectedConfirmText = '我同意并确认' const canAccept = computed(() => confirmText.value === expectedConfirmText) +const deviceTimeState = ref<'idle' | 'loading' | 'ready' | 'error'>(auth.isAuthenticated ? 'loading' : 'idle') +const deviceTimeError = ref('') +let deviceTimeGeneration = 0 function toggleTheme() { isDark.value = !isDark.value @@ -40,11 +46,11 @@ onMounted(() => { // 监听登录状态,每周首次登录弹一次(同意状态持久化在 localStorage, // 跨会话/跨标签页生效,距上次同意满一周后再次登录才会重新弹出) -watch(() => auth.isAuthenticated, (isAuthenticated) => { - if (isAuthenticated) { +watch([() => auth.isAuthenticated, deviceTimeState], ([isAuthenticated, timeState]) => { + if (isAuthenticated && timeState === 'ready') { const agreedAtRaw = localStorage.getItem(DISCLAIMER_AGREED_AT_KEY) const agreedAt = agreedAtRaw === null ? null : Number(agreedAtRaw) - if (shouldShowDisclaimer(agreedAt, Date.now())) { + if (shouldShowDisclaimer(agreedAt, deviceNow())) { confirmText.value = '' showDisclaimer.value = true } @@ -53,9 +59,42 @@ watch(() => auth.isAuthenticated, (isAuthenticated) => { } }, { immediate: true }) +async function syncDeviceTime() { + const generation = ++deviceTimeGeneration + deviceTimeState.value = 'loading' + deviceTimeError.value = '' + const requestStartedAt = Date.now() + const result = await systemService.getTime() + const responseReceivedAt = Date.now() + if (generation !== deviceTimeGeneration || !auth.isAuthenticated) return + if (!result.ok) { + deviceTimeState.value = 'error' + deviceTimeError.value = result.error.message + return + } + try { + configureDeviceTime(result.data, requestStartedAt, responseReceivedAt) + deviceTimeState.value = 'ready' + } catch (error) { + deviceTimeState.value = 'error' + deviceTimeError.value = error instanceof Error ? error.message : '设备时间同步失败' + } +} + +watch(() => auth.isAuthenticated, (isAuthenticated) => { + if (isAuthenticated) { + void syncDeviceTime() + return + } + deviceTimeGeneration++ + resetDeviceTime() + deviceTimeState.value = 'idle' + deviceTimeError.value = '' +}, { immediate: true }) + function acceptDisclaimer() { if (!canAccept.value) return - localStorage.setItem(DISCLAIMER_AGREED_AT_KEY, String(Date.now())) + localStorage.setItem(DISCLAIMER_AGREED_AT_KEY, String(deviceNow())) showDisclaimer.value = false } @@ -76,11 +115,12 @@ const UnauthenticatedShell = defineAsyncComponent(() => import('./layouts/Unauth const shell = computed(() => auth.isAuthenticated && route.name !== 'Login' ? AuthenticatedShell : UnauthenticatedShell ) +const canRenderShell = computed(() => !auth.isAuthenticated || deviceTimeState.value === 'ready') + +
+ +
diff --git a/web/src/components/DebugPanel.vue b/web/src/components/DebugPanel.vue index f8fe9c24..37ce69ee 100644 --- a/web/src/components/DebugPanel.vue +++ b/web/src/components/DebugPanel.vue @@ -3,6 +3,7 @@ import { computed, onMounted, ref, watch } from 'vue' import { ElMessage } from 'element-plus' import { debugCollector } from '../debug/collector' import { copyToClipboard } from '../utils/clipboard' +import { deviceNow, formatDeviceDateTime } from '../utils/deviceTime' const props = defineProps<{ modelValue: boolean @@ -35,7 +36,7 @@ watch( ) function fmtTs(ts: number) { - return new Date(ts).toLocaleString() + return formatDeviceDateTime(ts, { clientClock: true }) } async function copySnapshot() { @@ -44,8 +45,7 @@ async function copySnapshot() { function downloadSnapshot() { try { - const now = new Date() - const stamp = `${now.getFullYear()}${String(now.getMonth() + 1).padStart(2, '0')}${String(now.getDate()).padStart(2, '0')}-${String(now.getHours()).padStart(2, '0')}${String(now.getMinutes()).padStart(2, '0')}${String(now.getSeconds()).padStart(2, '0')}` + const stamp = formatDeviceDateTime(deviceNow()).replaceAll('-', '').replace(' ', '-').replaceAll(':', '') const blob = new Blob([JSON.stringify(debugCollector.sanitizedSnapshot(), null, 2)], { type: 'application/json;charset=utf-8' }) const url = URL.createObjectURL(blob) const a = document.createElement('a') diff --git a/web/src/components/DeviceAtTab.vue b/web/src/components/DeviceAtTab.vue index 54e63c6c..0a6cc8f9 100644 --- a/web/src/components/DeviceAtTab.vue +++ b/web/src/components/DeviceAtTab.vue @@ -3,6 +3,7 @@ import { computed, ref, watch } from 'vue' import { Code24Regular, Warning24Regular } from '@vicons/fluent' import { AT_TEMPLATES } from '../constants/atTemplates' import { devicesService } from '../services/devices' +import { formatDeviceTime } from '../utils/deviceTime' const props = defineProps<{ deviceId: string @@ -114,7 +115,7 @@ function clearATHistory() {
{{ h.cmd }}
-
{{ new Date(h.ts).toLocaleTimeString() }}
+
{{ formatDeviceTime(h.ts, { clientClock: true }) }}
@@ -123,7 +124,7 @@ function clearATHistory() {
{{ h.response }}
- {{ new Date(h.ts).toLocaleTimeString() }} + {{ formatDeviceTime(h.ts, { clientClock: true }) }}
diff --git a/web/src/components/DeviceUssdTab.vue b/web/src/components/DeviceUssdTab.vue index f5323f0f..73472da9 100644 --- a/web/src/components/DeviceUssdTab.vue +++ b/web/src/components/DeviceUssdTab.vue @@ -2,6 +2,7 @@ import { ref, computed } from 'vue' import { Phone24Regular } from '@vicons/fluent' import { devicesService } from '../services/devices' +import { formatDeviceTime } from '../utils/deviceTime' const props = defineProps<{ deviceId: string @@ -151,7 +152,7 @@ function clearHistory() {
{{ msg.content }}
-
{{ new Date(msg.ts).toLocaleTimeString() }}
+
{{ formatDeviceTime(msg.ts, { clientClock: true }) }}
@@ -163,7 +164,7 @@ function clearHistory() {
{{ msg.content }}
- {{ new Date(msg.ts).toLocaleTimeString() }} + {{ formatDeviceTime(msg.ts, { clientClock: true }) }} DCS: {{ msg.dcs }} {{ msg.channel === 'vowifi' ? 'VoWiFi' : 'CS' }}
diff --git a/web/src/components/ErrorState.vue b/web/src/components/ErrorState.vue index b0c940e6..82e896f3 100644 --- a/web/src/components/ErrorState.vue +++ b/web/src/components/ErrorState.vue @@ -1,5 +1,6 @@ diff --git a/web/src/components/TrafficAnalysisPanel.vue b/web/src/components/TrafficAnalysisPanel.vue index 399307c2..a01a3175 100644 --- a/web/src/components/TrafficAnalysisPanel.vue +++ b/web/src/components/TrafficAnalysisPanel.vue @@ -4,6 +4,7 @@ import ErrorState from './ErrorState.vue' import RefreshButton from './RefreshButton.vue' import type { AppError } from '../types/domain' import type { TrafficAnalysis, TrafficRange } from '../services/traffic' +import { formatDeviceDate, formatDeviceDateTime, formatDeviceMonthDay, formatDeviceTime } from '../utils/deviceTime' type TrafficAnalysisMode = 'global' | 'device' type TooltipParam = { @@ -150,47 +151,24 @@ function formatBytes(bytes: unknown) { return `${val.toFixed(i === 0 ? 0 : 2)} ${units[i]}` } -function parsePeriodStart(value: unknown): Date | null { - if (typeof value !== 'string' || !value.trim()) return null - const date = new Date(value) - return Number.isFinite(date.getTime()) ? date : null -} - -function pad2(value: number) { - return String(value).padStart(2, '0') -} - -function formatLocalDate(date: Date) { - return `${date.getFullYear()}-${pad2(date.getMonth() + 1)}-${pad2(date.getDate())}` -} - -function formatLocalHour(date: Date) { - return `${pad2(date.getHours())}:00` -} - -function formatLocalDateHour(date: Date) { - return `${formatLocalDate(date)} ${formatLocalHour(date)}` -} - function formatTrafficAxisTime(periodStart: unknown, fallback: string) { - const date = parsePeriodStart(periodStart) - if (!date) return fallback - if (props.range === 'day') return formatLocalHour(date) - return `${pad2(date.getMonth() + 1)}-${pad2(date.getDate())}` + if (typeof periodStart !== 'string') return fallback + if (props.range === 'day') return formatDeviceTime(periodStart, { fallback }).slice(0, 5) + return formatDeviceMonthDay(periodStart, { fallback }) } function formatTrafficTooltipTime(periodStart: unknown, fallback: string | number | undefined) { - const date = parsePeriodStart(periodStart) - if (!date) return fallback ?? '' - if (props.range === 'day') return formatLocalDateHour(date) - return formatLocalDate(date) + const fallbackText = String(fallback ?? '') + if (typeof periodStart !== 'string') return fallbackText + if (props.range === 'day') return formatDeviceDateTime(periodStart, { fallback: fallbackText }).slice(0, 16) + return formatDeviceDate(periodStart, { fallback: fallbackText }) } function formatTrafficBucketTime(bucket: { period_start?: string; bucket?: string }) { - const date = parsePeriodStart(bucket?.period_start) - if (!date) return bucket?.bucket || '' - if (props.range === 'day') return formatLocalDateHour(date) - return formatLocalDate(date) + const fallback = bucket?.bucket || '' + if (!bucket?.period_start) return fallback + if (props.range === 'day') return formatDeviceDateTime(bucket.period_start, { fallback }).slice(0, 16) + return formatDeviceDate(bucket.period_start, { fallback }) } const analysisTotal = computed(() => { diff --git a/web/src/services/system.ts b/web/src/services/system.ts index da290b6d..104a634e 100644 --- a/web/src/services/system.ts +++ b/web/src/services/system.ts @@ -1,5 +1,6 @@ import { api } from '../stores/auth' import { callService } from './http' +import type { DeviceTimeInfo } from '../utils/deviceTime' export type DocsLinks = { swagger_ui: string @@ -200,6 +201,12 @@ export type TestEmailResponse = { } export const systemService = { + getTime() { + return callService(async () => { + const res = await api.get('/system/time') + return res.data as DeviceTimeInfo + }) + }, getInfo() { return callService(async () => { const res = await api.get('/system/info') diff --git a/web/src/utils/deviceTime.ts b/web/src/utils/deviceTime.ts new file mode 100644 index 00000000..a48282b9 --- /dev/null +++ b/web/src/utils/deviceTime.ts @@ -0,0 +1,141 @@ +export type DeviceTimeInfo = { + now: string + timezone: string + offset_seconds: number + source: string +} + +export type DeviceTimeFormatOptions = { + clientClock?: boolean + fallback?: string +} + +type DeviceClock = { + timezone: string + offsetSeconds: number + clientDeltaMs: number +} + +type DateParts = { + year: string + month: string + day: string + hour: string + minute: string + second: string +} + +const naiveDateTimePattern = /^(\d{4})[-/](\d{2})[-/](\d{2})[ T](\d{2}):(\d{2}):(\d{2})(?:\.\d+)?$/ +let deviceClock: DeviceClock | null = null +let datePartsFormatter: Intl.DateTimeFormat | null = null + +export function configureDeviceTime(info: DeviceTimeInfo, requestStartedAt: number, responseReceivedAt: number) { + const serverEpoch = Date.parse(info.now) + if (!Number.isFinite(serverEpoch)) throw new Error('设备时间 API 返回了无效 now') + if (!Number.isInteger(info.offset_seconds) || Math.abs(info.offset_seconds) > 24 * 60 * 60) { + throw new Error('设备时间 API 返回了无效 offset_seconds') + } + const timezone = String(info.timezone || '').trim() + if (timezone) validateTimezone(timezone) + const source = String(info.source || '').trim() + if (!source) throw new Error('设备时间 API 未返回检测来源') + + const midpoint = requestStartedAt + (responseReceivedAt - requestStartedAt) / 2 + deviceClock = { + timezone, + offsetSeconds: info.offset_seconds, + clientDeltaMs: serverEpoch - midpoint + } + datePartsFormatter = null +} + +export function resetDeviceTime() { + deviceClock = null + datePartsFormatter = null +} + +export function deviceNow(clientNow = Date.now()) { + if (!deviceClock) throw new Error('设备时间尚未同步') + return clientNow + deviceClock.clientDeltaMs +} + +export function formatDeviceDateTime(value: string | number | Date, options: DeviceTimeFormatOptions = {}) { + const naive = parseNaiveDateTime(value) + if (naive) return `${naive.year}-${naive.month}-${naive.day} ${naive.hour}:${naive.minute}:${naive.second}` + const parts = resolveDateParts(value, options) + if (!parts) return invalidTimeText(value, options) + return `${parts.year}-${parts.month}-${parts.day} ${parts.hour}:${parts.minute}:${parts.second}` +} + +export function formatDeviceDate(value: string | number | Date, options: DeviceTimeFormatOptions = {}) { + const naive = parseNaiveDateTime(value) + if (naive) return `${naive.year}-${naive.month}-${naive.day}` + const parts = resolveDateParts(value, options) + if (!parts) return invalidTimeText(value, options) + return `${parts.year}-${parts.month}-${parts.day}` +} + +export function formatDeviceTime(value: string | number | Date, options: DeviceTimeFormatOptions = {}) { + const naive = parseNaiveDateTime(value) + if (naive) return `${naive.hour}:${naive.minute}:${naive.second}` + const parts = resolveDateParts(value, options) + if (!parts) return invalidTimeText(value, options) + return `${parts.hour}:${parts.minute}:${parts.second}` +} + +export function formatDeviceMonthDay(value: string | number | Date, options: DeviceTimeFormatOptions = {}) { + const naive = parseNaiveDateTime(value) + if (naive) return `${naive.month}-${naive.day}` + const parts = resolveDateParts(value, options) + if (!parts) return invalidTimeText(value, options) + return `${parts.month}-${parts.day}` +} + +function validateTimezone(timezone: string) { + try { + new Intl.DateTimeFormat('en-CA', { timeZone: timezone }).format(0) + } catch { + throw new Error(`设备时间 API 返回了无效 IANA 时区: ${timezone}`) + } +} + +function parseNaiveDateTime(value: string | number | Date): DateParts | null { + if (typeof value !== 'string') return null + const match = value.trim().match(naiveDateTimePattern) + if (!match) return null + return { + year: match[1], month: match[2], day: match[3], + hour: match[4], minute: match[5], second: match[6] + } +} + +function resolveDateParts(value: string | number | Date, options: DeviceTimeFormatOptions): DateParts | null { + if (!deviceClock) return null + let epoch = value instanceof Date ? value.getTime() : typeof value === 'number' ? value : Date.parse(value) + if (!Number.isFinite(epoch)) return null + if (options.clientClock && (typeof value === 'number' || value instanceof Date)) { + epoch += deviceClock.clientDeltaMs + } + if (!deviceClock.timezone) epoch += deviceClock.offsetSeconds * 1000 + const formatter = currentDatePartsFormatter() + const fields = Object.fromEntries(formatter.formatToParts(epoch).map(part => [part.type, part.value])) + return { + year: fields.year, month: fields.month, day: fields.day, + hour: fields.hour, minute: fields.minute, second: fields.second + } +} + +function currentDatePartsFormatter() { + if (datePartsFormatter) return datePartsFormatter + const timeZone = deviceClock?.timezone || 'UTC' + datePartsFormatter = new Intl.DateTimeFormat('en-CA', { + timeZone, hourCycle: 'h23', year: 'numeric', month: '2-digit', day: '2-digit', + hour: '2-digit', minute: '2-digit', second: '2-digit' + }) + return datePartsFormatter +} + +function invalidTimeText(value: string | number | Date, options: DeviceTimeFormatOptions) { + if (!deviceClock) return '设备时间未同步' + return options.fallback ?? (typeof value === 'string' ? value : '') +} diff --git a/web/src/views/Dashboard.vue b/web/src/views/Dashboard.vue index 684cb442..0714fe6f 100644 --- a/web/src/views/Dashboard.vue +++ b/web/src/views/Dashboard.vue @@ -12,6 +12,7 @@ import TrafficAnalysisPanel from '../components/TrafficAnalysisPanel.vue' import { usePollingScheduler } from '../composables/usePollingScheduler' import { useDashboardStore } from '../stores/dashboard' import type { TrafficRange } from '../services/traffic' +import { formatDeviceTime } from '../utils/deviceTime' const dashboard = useDashboardStore() const router = useRouter() @@ -108,7 +109,7 @@ onMounted(() => {
最近刷新
- {{ lastUpdatedAt ? new Date(lastUpdatedAt).toLocaleTimeString() : '--:--:--' }} + {{ lastUpdatedAt ? formatDeviceTime(lastUpdatedAt, { clientClock: true }) : '--:--:--' }}
diff --git a/web/src/views/Logs.vue b/web/src/views/Logs.vue index e2ea917d..13829615 100644 --- a/web/src/views/Logs.vue +++ b/web/src/views/Logs.vue @@ -6,6 +6,7 @@ import PageHeader from '../components/PageHeader.vue' import { ArrowDownload24Regular, Delete24Regular, Pause24Regular, Play24Regular } from '@vicons/fluent' import { useLogsStore } from '../stores/logs' import { useEventStream } from '../composables/useEventStream' +import { deviceNow, formatDeviceDate, formatDeviceDateTime } from '../utils/deviceTime' // 日志条目类型 interface LogEntry { @@ -98,7 +99,7 @@ function clearLogs() { // 导出日志 function exportLogs() { const content = filteredLogs.value.map(log => { - const time = new Date(log.time).toLocaleString() + const time = formatDeviceDateTime(log.time, { fallback: log.time }) const fields = log.fields ? ` ${log.fields}` : '' return `[${time}] ${log.level.toUpperCase().padEnd(5)} ${log.caller} ${log.message}${fields}` }).join('\n') @@ -107,7 +108,7 @@ function exportLogs() { const url = URL.createObjectURL(blob) const a = document.createElement('a') a.href = url - a.download = `logs-${new Date().toISOString().slice(0, 10)}.txt` + a.download = `logs-${formatDeviceDate(deviceNow())}.txt` a.click() URL.revokeObjectURL(url) ElMessage.success('已导出日志') @@ -127,18 +128,7 @@ function getLevelClass(level: string): string { // 格式化日期时间 function formatDateTime(isoTime: string): string { - try { - const d = new Date(isoTime) - const yyyy = d.getFullYear() - const MM = String(d.getMonth() + 1).padStart(2, '0') - const dd = String(d.getDate()).padStart(2, '0') - const HH = String(d.getHours()).padStart(2, '0') - const mm = String(d.getMinutes()).padStart(2, '0') - const ss = String(d.getSeconds()).padStart(2, '0') - return `${yyyy}-${MM}-${dd} ${HH}:${mm}:${ss}` - } catch { - return isoTime - } + return formatDeviceDateTime(isoTime, { fallback: isoTime }) } // 加载历史日志 diff --git a/web/src/views/Settings.vue b/web/src/views/Settings.vue index d563c29c..32edeb54 100644 --- a/web/src/views/Settings.vue +++ b/web/src/views/Settings.vue @@ -14,6 +14,7 @@ import { Delete20Regular, DocumentText24Regular } from '@vicons/fluent' +import { formatDeviceDateTime } from '../utils/deviceTime' const settingsStore = useSettingsStore() const { systemInfo, loadingNotifications, savingNotifications, testingWebhook, testingBark, testingEmail, changingPassword, passwordForm, telegramForm, feishuForm, qqForm, webhookSettings, barkSettings, emailForm, pushplusForm } = storeToRefs(settingsStore) @@ -393,7 +394,11 @@ onBeforeUnmount(() => {
- +
diff --git a/web/src/views/Sms.vue b/web/src/views/Sms.vue index 1ffe7120..091f8119 100644 --- a/web/src/views/Sms.vue +++ b/web/src/views/Sms.vue @@ -16,6 +16,7 @@ import type { DeviceMgmtListItem, SMSMessage } from '../types/api' import { Delete24Regular, Mail24Regular, Send24Regular } from '@vicons/fluent' import { RecycleScroller } from 'vue-virtual-scroller' import 'vue-virtual-scroller/dist/vue-virtual-scroller.css' +import { formatDeviceDate, formatDeviceDateTime, formatDeviceTime } from '../utils/deviceTime' type SmsThread = { key: string @@ -63,13 +64,11 @@ function parseTs(s: string) { } function formatClock(ms: number) { - return ms ? new Date(ms).toLocaleTimeString() : '' + return ms ? formatDeviceTime(ms) : '' } -function dateKey(ms: number) { - const t = new Date(ms) - if (!Number.isFinite(t.getTime())) return '未知日期' - return `${t.getFullYear()}-${String(t.getMonth() + 1).padStart(2, '0')}-${String(t.getDate()).padStart(2, '0')}` +function dateKey(timestamp: string) { + return formatDeviceDate(timestamp, { fallback: '未知日期' }) } function lastSeenKey(threadKey: string) { @@ -120,7 +119,7 @@ const selectedThreadGroups = computed(() => { const out: Array<{ date: string; items: SMSMessage[] }> = [] let last = '' for (const m of threadMessages.value) { - const key = dateKey(parseTs(m.timestamp)) + const key = dateKey(m.timestamp) if (!out.length || key !== last) { out.push({ date: key, items: [m] }) last = key @@ -927,7 +926,7 @@ async function confirmDeleteThread(thread: SmsThread) { {{ m.device_name }} - {{ new Date(m.timestamp).toLocaleString() }} + {{ formatDeviceDateTime(m.timestamp) }} ✓ ✗ resetDeviceTime()) + +test('formats absolute timestamps in the device IANA timezone', () => { + configureDeviceTime({ + now: '2026-08-11T12:00:00+08:00', + timezone: 'Asia/Shanghai', + offset_seconds: 28800, + source: 'etc_timezone' + }, 0, 0) + + assert.equal(formatDeviceDateTime('2026-08-11T04:30:15Z'), '2026-08-11 12:30:15') +}) + +test('preserves historical device-local log timestamps without a zone', () => { + configureDeviceTime({ + now: '2026-08-11T12:00:00+08:00', + timezone: 'Asia/Shanghai', + offset_seconds: 28800, + source: 'runtime_location' + }, 0, 0) + + assert.equal(formatDeviceDateTime('2026-08-11 04:11:14'), '2026-08-11 04:11:14') +}) + +test('uses the explicit fixed offset when no IANA zone is available', () => { + configureDeviceTime({ + now: '2026-08-11T09:30:00+05:30', + timezone: '', + offset_seconds: 19800, + source: 'fixed_offset' + }, 0, 0) + + assert.equal(formatDeviceTime('2026-08-11T04:00:00Z'), '09:30:00') +}) + +test('calibrates browser-generated timestamps against the device clock', () => { + configureDeviceTime({ + now: '1970-01-01T00:00:10Z', + timezone: 'UTC', + offset_seconds: 0, + source: 'runtime_location' + }, 1000, 3000) + + assert.equal(deviceNow(4000), 12000) + assert.equal(formatDeviceTime(4000, { clientClock: true }), '00:00:12') +}) + +test('rejects an invalid named timezone instead of using the browser timezone', () => { + assert.throws(() => configureDeviceTime({ + now: '2026-08-11T12:00:00+08:00', + timezone: 'not/a-zone', + offset_seconds: 28800, + source: 'env_tz' + }, 0, 0), /无效 IANA 时区/) +})