[fix-nine-regressions-02] render timestamps in device timezone

This commit is contained in:
yibaiba committed 2026-08-11 13:19:24 +08:00
1 parent 36fea12adb
commit ff2f1478a7
18 files changed
+593 -70

No files matched your search

+33
View File
@@ -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]
+4
View File
@@ -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")
}
}
+3
View File
@@ -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) // 应用系统更新
+127
View File
@@ -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())
}
+115
View File
@@ -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)
}
}
+55 -5
View File
@@ -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')
</script>
<template>
<div class="h-screen w-screen overflow-hidden bg-gray-50 dark:bg-[#101014] text-gray-900 dark:text-gray-100 font-sans selection:bg-indigo-500 selection:text-white transition-colors duration-300">
<Suspense>
<Suspense v-if="canRenderShell">
<template #default>
<component :is="shell" :is-dark="isDark" @toggle-theme="toggleTheme" />
</template>
@@ -88,6 +128,16 @@ const shell = computed(() =>
<LoadingScreen />
</template>
</Suspense>
<LoadingScreen v-else-if="deviceTimeState === 'loading'" />
<div v-else class="h-full flex items-center justify-center p-6">
<ErrorState
class="w-full max-w-xl"
title="设备时间同步失败"
:message="deviceTimeError"
retry-text="重试"
@retry="syncDeviceTime"
/>
</div>
<!-- 高级感全屏免责声明弹窗 -->
<Transition name="fade-slide">
+3 -3
View File
@@ -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')
+3 -2
View File
@@ -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() {
<div class="flex w-full justify-end">
<div class="max-w-[80%] bg-indigo-500 text-white rounded-2xl rounded-tr-sm px-4 py-2.5 shadow-sm">
<div class="text-sm font-mono break-words">{{ h.cmd }}</div>
<div class="text-[10px] text-indigo-100 mt-1 text-right">{{ new Date(h.ts).toLocaleTimeString() }}</div>
<div class="text-[10px] text-indigo-100 mt-1 text-right">{{ formatDeviceTime(h.ts, { clientClock: true }) }}</div>
</div>
</div>
@@ -123,7 +124,7 @@ function clearATHistory() {
<div class="max-w-[80%] rounded-2xl rounded-tl-sm px-4 py-2.5 shadow-sm" :class="!h.ok ? 'bg-red-50 dark:bg-red-900/30 text-red-700 dark:text-red-300 border border-red-100 dark:border-red-900/50' : 'bg-white dark:bg-gray-800 text-gray-800 dark:text-gray-200 border border-gray-100 dark:border-white/5'">
<div class="text-sm whitespace-pre-wrap break-words font-mono">{{ h.response }}</div>
<div class="text-[10px] mt-1 text-gray-400 flex items-center gap-2">
<span>{{ new Date(h.ts).toLocaleTimeString() }}</span>
<span>{{ formatDeviceTime(h.ts, { clientClock: true }) }}</span>
</div>
</div>
</div>
+3 -2
View File
@@ -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() {
<!-- 请求记录(右侧气泡) -->
<div v-if="msg.type === 'req'" class="max-w-[80%] bg-indigo-500 text-white rounded-2xl rounded-tr-sm px-4 py-2.5 shadow-sm">
<div class="text-sm break-words">{{ msg.content }}</div>
<div class="text-[10px] text-indigo-100 mt-1 text-right">{{ new Date(msg.ts).toLocaleTimeString() }}</div>
<div class="text-[10px] text-indigo-100 mt-1 text-right">{{ formatDeviceTime(msg.ts, { clientClock: true }) }}</div>
</div>
<!-- 系统消息(居中) -->
@@ -163,7 +164,7 @@ function clearHistory() {
<div v-else class="max-w-[80%] rounded-2xl rounded-tl-sm px-4 py-2.5 shadow-sm" :class="msg.type === 'err' ? 'bg-red-50 dark:bg-red-900/30 text-red-700 dark:text-red-300 border border-red-100 dark:border-red-900/50' : 'bg-white dark:bg-gray-800 text-gray-800 dark:text-gray-200 border border-gray-100 dark:border-white/5'">
<div class="text-sm whitespace-pre-wrap break-words font-mono">{{ msg.content }}</div>
<div class="text-[10px] mt-1 text-gray-400 flex items-center gap-2">
<span>{{ new Date(msg.ts).toLocaleTimeString() }}</span>
<span>{{ formatDeviceTime(msg.ts, { clientClock: true }) }}</span>
<span v-if="msg.dcs !== undefined" class="bg-gray-100 dark:bg-gray-700 px-1 rounded">DCS: {{ msg.dcs }}</span>
<span v-if="msg.channel" class="bg-gray-100 dark:bg-gray-700 px-1 rounded">{{ msg.channel === 'vowifi' ? 'VoWiFi' : 'CS' }}</span>
</div>
+4 -1
View File
@@ -1,5 +1,6 @@
<script setup lang="ts">
import { computed } from 'vue'
import { formatDeviceDateTime } from '../utils/deviceTime'
const props = defineProps<{
title?: string
@@ -21,7 +22,9 @@ const metaText = computed(() => {
const method = (props.requestMethod || '').toUpperCase()
if (method && props.requestUrl) parts.push(`${method} ${props.requestUrl}`)
else if (props.requestUrl) parts.push(String(props.requestUrl))
if (props.lastSuccessAt) parts.push(`最后成功:${new Date(props.lastSuccessAt).toLocaleString()}`)
if (props.lastSuccessAt) {
parts.push(`最后成功:${formatDeviceDateTime(props.lastSuccessAt, { clientClock: true })}`)
}
return parts.join(' · ')
})
</script>
+12 -34
View File
@@ -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(() => {
+7
View File
@@ -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')
+141
View File
@@ -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 : '')
}
+2 -1
View File
@@ -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(() => {
<div class="ui-panel p-4">
<div class="text-xs text-gray-400">最近刷新</div>
<div class="text-sm font-mono mt-2 text-gray-600 dark:text-gray-300">
{{ lastUpdatedAt ? new Date(lastUpdatedAt).toLocaleTimeString() : '--:--:--' }}
{{ lastUpdatedAt ? formatDeviceTime(lastUpdatedAt, { clientClock: true }) : '--:--:--' }}
</div>
</div>
</div>
+4 -14
View File
@@ -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 })
}
// 加载历史日志
+6 -1
View File
@@ -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(() => {
</el-button>
</div>
<div class="p-3 bg-gray-50 dark:bg-white/5 rounded-lg">
<FieldRow label="构建时间" :value="systemInfo.build_time" monospace />
<FieldRow
label="构建时间"
:value="formatDeviceDateTime(systemInfo.build_time, { fallback: systemInfo.build_time })"
monospace
/>
</div>
<div class="p-3 bg-gray-50 dark:bg-white/5 rounded-lg">
<FieldRow label="配置路径" :value="systemInfo.config" monospace copyable />
+6 -7
View File
@@ -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) {
<span v-if="m.device_name" class="text-[10px] font-bold text-gray-400 bg-gray-100 dark:bg-white/5 px-1.5 py-0.5 rounded">
{{ m.device_name }}
</span>
<span class="text-[11px] text-gray-400 font-mono">{{ new Date(m.timestamp).toLocaleString() }}</span>
<span class="text-[11px] text-gray-400 font-mono">{{ formatDeviceDateTime(m.timestamp) }}</span>
<span v-if="m.type === 2 && m.status === 2" class="text-green-500 text-xs" title="发送成功">✓</span>
<span v-else-if="m.type === 2 && m.status === 3" class="text-red-500 text-xs" title="发送失败">✗</span>
<el-button
+65
View File
@@ -0,0 +1,65 @@
import assert from 'node:assert/strict'
import test from 'node:test'
import {
configureDeviceTime,
deviceNow,
formatDeviceDateTime,
formatDeviceTime,
resetDeviceTime
} from '../src/utils/deviceTime.ts'
test.afterEach(() => 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 时区/)
})