release: bump version to 0.78.0
ci / backend (push) Canceled after 0s
ci / frontend (push) Canceled after 0s
ci / delivery (push) Canceled after 0s
release / images (push) Canceled after 0s
release / client_release (push) Canceled after 0s

This commit is contained in:
linkong committed 2026-11-23 22:40:11 +08:00
1 parent e6aa8c539b
commit 5fc698d738
96 files changed
+10214 -747

No files matched your search

+269 -6
View File
@@ -1,17 +1,21 @@
import type { ColumnDef } from '@tanstack/react-table'
import axios from 'axios'
import {
AlertTriangle,
ArrowLeft,
Bot,
BrushCleaning,
CheckCircle2,
CircleHelp,
Copy,
Database,
DatabaseZap,
Eye,
FileText,
Globe2,
History,
ImageUp,
Layers,
ListChecks,
Radio,
Redo2,
@@ -1021,6 +1025,7 @@ const fieldLabels: Record<string, string> = {
system_name: '系统名称',
refresh_interval: '刷新间隔(秒)',
data_retention_days: '数据保留天数',
snapshot_mode: '存储策略',
max_concurrent_tasks: '最大并发任务数',
auto_refresh: '自动刷新',
demo_mode: '演示模式',
@@ -1048,6 +1053,7 @@ const fieldLabels: Record<string, string> = {
const fieldHelp: Record<string, string> = {
demo_mode: '开启后访问智能星球会直接显示 OOBE 引导,不再要求首次采集条件,也会忽略本机“先浏览”临时跳过。',
data_retention_days: '与「采集管理 → 采集调度」中的历史保留天数保持同步;仅在开启自动清理时回收超期历史。',
}
function fieldLabel(key: string, locale?: SupportedLocale) {
@@ -1396,11 +1402,38 @@ function formatSnapshotTime(record: AnyRecord) {
})
}
const COLLECTOR_STORAGE_POLICY_KEYS = new Set([
'snapshot_mode',
'snapshot_overridden',
'supports_annual',
'high_volume_warning',
])
function snapshotModeLabel(mode: unknown) {
const normalized = text(mode, 'single').toLowerCase()
if (normalized === 'annual') return '年末对比'
if (normalized === 'history') return '历史快照'
return '单份增量'
}
function snapshotModeDescription(mode: unknown) {
const normalized = text(mode, 'single').toLowerCase()
if (normalized === 'annual') {
return '同自然年内原地增量更新;跨年首次采集自动固化上一年末里程碑快照,支撑算力跨年对比。'
}
if (normalized === 'history') {
return '每次采集均保留历史版本与时间胶囊对比,超期非当前快照受自动清理与保留天数约束。'
}
return '仅保留最新 1 份数据,按实体差异原地增量更新,未变化记录零写入,极省硬盘容量。'
}
function snapshotOptionLabel(record: AnyRecord) {
const current = record.is_current === true ? '当前 · ' : ''
const status = semanticLabel(snapshotStatus(record))
const count = typeof record.record_count === 'number' ? formatCountZh(record.record_count) : pick(record, ['record_count'], '0 条')
return `${current}${formatSnapshotTime(record)} · ${status} · ${count}`
const milestoneYear = isObjectRecord(record.summary) ? record.summary.milestone_year : null
const milestoneSuffix = milestoneYear ? ` · 年末里程碑 (${String(milestoneYear)})` : ''
return `${current}${formatSnapshotTime(record)} · ${status} · ${count}${milestoneSuffix}`
}
const emptyRows = () => []
@@ -2938,6 +2971,7 @@ function ModuleConsole({ config }: { config: ModuleConfig }) {
const [newsFilters, setNewsFilters] = useState({ status: 'all', sourceType: 'all', region: 'all', tag: 'all' })
const [collectionDraftGroup, setCollectionDraftGroup] = useState<HierarchyGroup | null>(null)
const [snapshotSelectionBySource, setSnapshotSelectionBySource] = useState<Record<string, string>>({})
const [retentionDaysDraft, setRetentionDaysDraft] = useState('30')
const [loading, setLoading] = useState(false)
const [actionLoading, setActionLoading] = useState(false)
const [rowActionLoading, setRowActionLoading] = useState<Record<string, boolean>>({})
@@ -4735,6 +4769,24 @@ function ModuleConsole({ config }: { config: ModuleConfig }) {
await requestAction(label, 'put', '/settings/integrations', buildExternalIntegrationPayload(overrides))
}
const collectorStoragePolicy = useMemo(() => {
if (config !== configs.collection) return null
const collectorsState = states.find((state) => state.section.key === 'collectors')
const rawPolicy = objectAt(collectorsState?.raw, 'storage_policy')
return Object.keys(rawPolicy).length ? rawPolicy : null
}, [config, states])
useEffect(() => {
const retention = collectorStoragePolicy?.history_retention_days
if (typeof retention === 'number' && Number.isFinite(retention)) {
setRetentionDaysDraft(String(retention))
}
}, [collectorStoragePolicy?.history_retention_days])
const updateStoragePolicy = async (payload: AnyRecord, label: string) => {
await requestAction(label, 'put', '/settings/storage-policy', payload)
}
const getActiveHierarchyGroup = (groups: HierarchyGroup[]) => {
const flat = groups.flatMap((group) => group.children?.length ? group.children : [group])
return flat.find((group) => group.key === activeGroupKey) || flat[0] || null
@@ -5300,7 +5352,9 @@ function ModuleConsole({ config }: { config: ModuleConfig }) {
let groups: HierarchyGroup[] = activeState.rows.map((row) => ({
key: row.__rowId,
label: recordTitle(row),
description: row.__module,
description: config === configs.collection && activeSection.key === 'collectors'
? `${row.__module} · ${snapshotModeLabel(row.snapshot_mode)}${row.snapshot_locked === true ? ' · 全局锁定' : row.snapshot_overridden === true ? ' · 覆盖' : ''}`
: row.__module,
status: normalizeStatusLabel(recordStatus(row)),
count: Object.keys(cleanRecord(row)).length,
record: { ...cleanRecord(row), __sourceEndpoint: row.__endpointKey, __sourceLabel: row.__endpointLabel },
@@ -5462,8 +5516,11 @@ function ModuleConsole({ config }: { config: ModuleConfig }) {
setActionLoading(false)
}
}
const hiddenCollectorStorageField = (key: string) => (
activeSection.key === 'collectors' && COLLECTOR_STORAGE_POLICY_KEYS.has(key)
)
const scalarFields = Object.entries(activeGroup?.record || {})
.filter(([key, value]) => !key.startsWith('__') && ['string', 'number', 'boolean'].includes(typeof value))
.filter(([key, value]) => !key.startsWith('__') && !hiddenCollectorStorageField(key) && ['string', 'number', 'boolean'].includes(typeof value))
.map(([key, value]): FieldConfig => ({
key,
label: fieldLabel(key),
@@ -5483,7 +5540,7 @@ function ModuleConsole({ config }: { config: ModuleConfig }) {
: undefined,
}))
const objectFields = Object.entries(activeGroup?.record || {})
.filter(([key, value]) => !key.startsWith('__') && !shouldHideDatasourceConfigObjectField(activeGroup?.record || {}, activeSourceEndpoint, key) && value !== null && typeof value === 'object')
.filter(([key, value]) => !key.startsWith('__') && !hiddenCollectorStorageField(key) && !shouldHideDatasourceConfigObjectField(activeGroup?.record || {}, activeSourceEndpoint, key) && value !== null && typeof value === 'object')
.map(([key]): FieldConfig => ({ key, label: fieldLabel(key), type: 'textarea', wide: true }))
const newsSourceFields: FieldConfig[] = config === configs.earthContent && activeSection.key === 'news_sources' ? [
{ key: 'id', label: '源 ID' },
@@ -5799,10 +5856,12 @@ function ModuleConsole({ config }: { config: ModuleConfig }) {
}
if (activeSection.key === 'collectors') {
const id = pick(activeGroup.record, ['id'], '')
const globalSingleLocked = Boolean(collectorStoragePolicy?.global_single_lock || activeGroup.record.snapshot_locked === true)
await saveHierarchySettings(`/settings/collectors/${encodeURIComponent(id)}`, {
is_active: Boolean(payload.is_active),
priority: text(payload.priority, 'P1'),
frequency_minutes: Number(payload.frequency_minutes || 60),
snapshot_mode: globalSingleLocked ? 'single' : text(payload.snapshot_mode, 'single'),
}, '保存采集器设置')
return
}
@@ -5947,10 +6006,12 @@ function ModuleConsole({ config }: { config: ModuleConfig }) {
return
}
if (activeSection.key === 'collectors' && id) {
const globalSingleLocked = Boolean(collectorStoragePolicy?.global_single_lock || activeGroup.record.snapshot_locked === true)
await saveHierarchySettings(`/settings/collectors/${encodeURIComponent(id)}`, {
is_active: Boolean(payload.is_active),
priority: text(payload.priority, 'P1'),
frequency_minutes: Number(payload.frequency_minutes || 60),
snapshot_mode: globalSingleLocked ? 'single' : text(payload.snapshot_mode, 'single'),
}, '保存采集调度')
return
}
@@ -6050,7 +6111,136 @@ function ModuleConsole({ config }: { config: ModuleConfig }) {
</TactileControlGroup>
) : null
const hierarchyHeader = config === configs.earthContent && activeSection.key === 'news_sources' ? (
const renderCollectorStorageHeader = () => {
if (!collectorStoragePolicy) return null
const masterState = text(collectorStoragePolicy.master_state, 'partial')
const totalSources = Number(collectorStoragePolicy.total_sources || groups.length || 0)
const snapshotEnabledCount = Number(collectorStoragePolicy.snapshot_enabled_count || 0)
const annualCount = Number(collectorStoragePolicy.annual_count || 0)
const historyCount = Number(collectorStoragePolicy.history_count || 0)
const currentRetentionDays = Number(collectorStoragePolicy.history_retention_days || 30)
const autoPruneEnabled = Boolean(collectorStoragePolicy.auto_prune_enabled)
const globalSingleLocked = Boolean(collectorStoragePolicy.global_single_lock)
const defaultMode = text(collectorStoragePolicy.default_mode, 'single')
const parsedRetention = Number(retentionDaysDraft)
const retentionChanged = Number.isFinite(parsedRetention)
&& parsedRetention >= 1
&& parsedRetention <= 3650
&& parsedRetention !== currentRetentionDays
const statusBadgeLabel = globalSingleLocked || masterState === 'off'
? `全部单份 (0/${totalSources})`
: masterState === 'all'
? `全部历史 (${totalSources}/${totalSources})`
: `部分开启 (${snapshotEnabledCount}/${totalSources})`
const statusToneClass = globalSingleLocked || masterState === 'off'
? 'an-badge an-badge--green'
: masterState === 'all'
? 'an-badge an-badge--amber'
: 'an-badge an-badge--cyan'
const StateIcon = globalSingleLocked || masterState === 'off' ? Database : masterState === 'all' ? History : Layers
const recommendedActive = !globalSingleLocked && defaultMode === 'single' && annualCount > 0 && historyCount === 0
const allSingleActive = globalSingleLocked || masterState === 'off'
const allHistoryActive = !globalSingleLocked && masterState === 'all' && historyCount === totalSources
return (
<div className="an-storage-policy-bar" aria-label={localizeAdminText('全局采集存储策略', locale)}>
<div className="an-storage-policy-bar__summary">
<span className={statusToneClass}>
<StateIcon size={13} aria-hidden="true" />
<span>{localizeAdminText(statusBadgeLabel, locale)}</span>
</span>
<span className="an-storage-policy-bar__meta">
{localizeAdminText(`默认${snapshotModeLabel(defaultMode)}${globalSingleLocked ? '(全局单份已锁定)' : ''} · 保留 ${currentRetentionDays} 天 · ${autoPruneEnabled ? '自动清理已开' : '自动清理已关(保留存量)'}`, locale)}
</span>
</div>
<div className="an-storage-policy-bar__controls">
<div className="an-segmented" role="group" aria-label={localizeAdminText('存储总控模式', locale)}>
<button
type="button"
className={allSingleActive ? 'is-active' : undefined}
disabled={actionLoading}
onClick={() => void updateStoragePolicy({ action: 'all_single' }, '切换为全部单份')}
>
{localizeAdminText('全部单份', locale)}
</button>
<button
type="button"
className={recommendedActive ? 'is-active' : undefined}
disabled={actionLoading}
onClick={() => void updateStoragePolicy({ action: 'recommended_default' }, '应用默认推荐策略')}
>
{localizeAdminText('默认推荐', locale)}
</button>
<button
type="button"
className={allHistoryActive ? 'is-active' : undefined}
disabled={actionLoading}
onClick={() => setConfirmAction({
title: localizeAdminText('确认开启全部历史快照', locale),
description: localizeAdminText('开启全部历史快照后,IP 前缀库(iptoasn / nro)与实时船舶 AIS 数据源将继续写入完整历史快照(估算约 66 GB/月),仅建议在需要全量审计时使用。', locale),
danger: true,
confirmLabel: localizeAdminText('确认全部开启', locale),
run: () => updateStoragePolicy({ action: 'all_history' }, '切换为全部历史快照'),
})}
>
{localizeAdminText('全部历史', locale)}
</button>
</div>
<div className="an-storage-policy-bar__retention">
<label className="an-inline-field">
<span>{localizeAdminText('保留天数', locale)}</span>
<input
className="an-input an-storage-policy-bar__days"
type="number"
min={1}
max={3650}
value={retentionDaysDraft}
onChange={(event) => setRetentionDaysDraft(event.target.value)}
/>
</label>
{retentionChanged ? (
<Button
size="sm"
variant="subtle"
loading={actionLoading}
onClick={() => void updateStoragePolicy({ history_retention_days: parsedRetention }, '更新保留天数')}
>
{localizeAdminText('应用', locale)}
</Button>
) : null}
<span className="an-storage-policy-bar__switch">
<span className="an-storage-policy-bar__switch-label">{localizeAdminText('自动清理', locale)}</span>
<AdminSwitch
checked={autoPruneEnabled}
label={localizeAdminText('自动清理', locale)}
disabled={actionLoading}
onCheckedChange={(next) => {
if (!next) {
void updateStoragePolicy({ auto_prune_enabled: false }, '关闭自动清理')
return
}
setConfirmAction({
title: localizeAdminText('确认开启超期自动清理', locale),
description: localizeAdminText(`开启后将按保留窗口(历史快照与日志 ${currentRetentionDays} 天、BGP 原始观测 7 天)分批清理过期历史,同时永久保留当前最新数据与算力年末里程碑。若这是包含历史资产的开发库,请确认不再需要 ${currentRetentionDays} 天前的旧快照。`, locale),
danger: true,
confirmLabel: localizeAdminText('确认开启', locale),
run: () => updateStoragePolicy({ auto_prune_enabled: true }, '开启自动清理'),
})
}}
/>
</span>
</div>
</div>
</div>
)
}
const hierarchyHeader = config === configs.collection && activeSection.key === 'collectors' ? (
renderCollectorStorageHeader()
) : config === configs.earthContent && activeSection.key === 'news_sources' ? (
<div className="an-news-source-filters">
<select className="an-input" value={newsFilters.status} onChange={(event) => setNewsFilters((current) => ({ ...current, status: event.target.value }))}>
<option value="all">全部状态</option>
@@ -6296,7 +6486,11 @@ function ModuleConsole({ config }: { config: ModuleConfig }) {
<section className="an-field-cluster">
<div className="an-field-cluster__heading">
<h3>Time Capsule</h3>
<p>{localizeAdminText(`${snapshotTimeline.length} 个历史快照,选择后查看该版本详情。`, locale)}</p>
<p>
{snapshotTimeline.length <= 1
? localizeAdminText(`${snapshotTimeline.length} 个快照。单份增量模式下只维护最新 1 份,可在「采集调度」按数据源开启年末对比或历史快照。`, locale)
: localizeAdminText(`${snapshotTimeline.length} 个历史快照,选择后查看该版本详情。`, locale)}
</p>
</div>
<div className="an-time-capsule__controls">
<label className="an-field an-field--wide">
@@ -6434,6 +6628,75 @@ function ModuleConsole({ config }: { config: ModuleConfig }) {
/>
</section>
</>
) : activeSection.key === 'collectors' ? (
(() => {
const globalSingleLocked = Boolean(collectorStoragePolicy?.global_single_lock || record.snapshot_locked === true)
const currentMode = globalSingleLocked ? 'single' : text(record.snapshot_mode, 'single')
return (
<>
<section className="an-field-cluster an-field-cluster--compact">
<div className="an-field-cluster__heading">
<h3>{localizeAdminText('存储与快照策略', locale)}</h3>
<p>
{localizeAdminText(
globalSingleLocked
? '已开启全局全部单份锁定,需切换为默认推荐后方可单独开启历史'
: record.snapshot_overridden === true
? '自定义覆盖(独立于全局默认)'
: '继承全局默认策略',
locale,
)}
</p>
</div>
<div className="an-storage-mode-row">
<div className="an-segmented" role="group" aria-label={localizeAdminText('单源存储策略', locale)}>
{(
[
{ value: 'single', label: '单份增量' },
...(record.supports_annual === true || currentMode === 'annual'
? [{ value: 'annual', label: '年末对比' }]
: []),
{ value: 'history', label: '历史快照' },
] as const
).map((option) => {
const optionDisabled = globalSingleLocked && option.value !== 'single'
return (
<button
key={option.value}
type="button"
disabled={optionDisabled}
title={optionDisabled ? localizeAdminText('已开启全局全部单份锁定,请先切换为默认推荐或全部历史', locale) : undefined}
className={currentMode === option.value ? 'is-active' : undefined}
onClick={() => {
if (!activeGroup || optionDisabled) return
setHierarchyDraft(setNestedDraftField(hierarchyDraft, activeGroup.record, 'snapshot_mode', option.value))
}}
>
{localizeAdminText(option.label, locale)}
</button>
)
})}
</div>
<span className="an-storage-policy-bar__meta">
{localizeAdminText(snapshotModeDescription(currentMode), locale)}
</span>
</div>
{isObjectRecord(record.high_volume_warning) && currentMode === 'history' ? (
<div className="an-storage-warning" role="alert">
<AlertTriangle size={15} aria-hidden="true" />
<span>
{localizeAdminText(
`高体积提醒(预计增量 ${text(record.high_volume_warning.estimated_monthly_growth, '')}):${text(record.high_volume_warning.note, '')}`,
locale,
)}
</span>
</div>
) : null}
</section>
<FieldGrid record={activeGroup.record} draft={hierarchyDraft} onDraftChange={setHierarchyDraft} fields={editableFields} searchGroupKey={activeGroup.key} />
</>
)
})()
) : (
<FieldGrid record={activeGroup.record} draft={hierarchyDraft} onDraftChange={setHierarchyDraft} fields={editableFields} searchGroupKey={activeGroup.key} />
)}
+86
View File
@@ -1951,10 +1951,91 @@ body:has(.admin-theme-root[data-theme='dark']) .an-toast {
overflow: hidden;
}
.an-storage-policy-bar {
display: flex;
flex-wrap: wrap;
align-items: center;
justify-content: space-between;
gap: 10px 14px;
padding: 10px 12px;
border: 1px solid var(--an-border);
border-radius: 7px;
background: var(--an-surface);
}
.an-storage-policy-bar__summary,
.an-storage-policy-bar__controls,
.an-storage-policy-bar__retention {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 8px 10px;
min-width: 0;
}
.an-storage-policy-bar__meta {
color: var(--an-muted);
font-size: 12px;
line-height: 1.4;
}
.an-storage-policy-bar__retention .an-inline-field {
height: 30px;
}
.an-storage-policy-bar__retention .an-storage-policy-bar__days {
width: 72px;
min-width: 64px;
height: 30px;
padding-inline: 8px;
}
.an-storage-policy-bar__switch {
display: inline-flex;
align-items: center;
gap: 7px;
height: 30px;
}
.an-storage-policy-bar__switch-label {
color: var(--an-muted);
font-size: 12px;
white-space: nowrap;
}
.an-storage-mode-row {
display: grid;
gap: 8px;
justify-items: start;
}
.an-storage-warning {
display: grid;
grid-template-columns: 16px minmax(0, 1fr);
align-items: start;
gap: 8px;
padding: 9px 10px;
border: 1px solid color-mix(in srgb, var(--an-warning) 55%, var(--an-border));
border-radius: 6px;
background: color-mix(in srgb, var(--an-warning) 10%, var(--an-surface));
color: var(--an-text);
font-size: 12px;
line-height: 1.45;
}
.an-storage-warning svg {
color: var(--an-warning);
margin-top: 1px;
}
@media (max-width: 900px) {
.an-news-source-filters {
grid-template-columns: repeat(2, minmax(0, 1fr));
}
.an-storage-policy-bar {
align-items: stretch;
}
}
@media (max-width: 560px) {
@@ -4311,6 +4392,11 @@ body[data-admin-theme='dark'] .an-connection-test-input > .tui-button:hover:not(
outline-offset: -2px;
}
.an-segmented button:disabled {
opacity: 0.45;
cursor: not-allowed;
}
.an-summary-kpis {
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
+27
View File
@@ -861,6 +861,33 @@ export const legacyUiTextEnUS: Record<string, string> = {
'是': 'Yes',
'否': 'No',
'采集间隔(分钟)': 'Collection interval (minutes)',
'存储策略': 'Storage policy',
'单份增量': 'Single copy (incremental)',
'年末对比': 'Year-end comparison',
'历史快照': 'Historical snapshots',
'全局采集存储策略': 'Global collection storage policy',
'存储总控模式': 'Storage master control mode',
'全部单份': 'All single-copy',
'默认推荐': 'Recommended default',
'全部历史': 'All history',
'保留天数': 'Retention days',
'自动清理': 'Auto prune',
'应用': 'Apply',
'存储与快照策略': 'Storage & snapshot policy',
'单源存储策略': 'Collector storage mode',
'自定义覆盖(独立于全局默认)': 'Custom override (independent from global default)',
'继承全局默认策略': 'Inherits global default policy',
'切换为全部单份': 'Switch all to single copy',
'应用默认推荐策略': 'Apply recommended default policy',
'切换为全部历史快照': 'Switch all to historical snapshots',
'确认开启全部历史快照': 'Enable historical snapshots for all collectors?',
'确认全部开启': 'Confirm enable all',
'确认开启超期自动清理': 'Enable automatic expiration pruning?',
'确认开启': 'Confirm enable',
'关闭自动清理': 'Disable auto prune',
'开启自动清理': 'Enable auto prune',
'更新保留天数': 'Update retention days',
'与「采集管理 → 采集调度」中的历史保留天数保持同步;仅在开启自动清理时回收超期历史。': 'Synchronized with retention days in Collection Management → Schedule; expired history is pruned only when auto-prune is enabled.',
'无时间': 'No timestamp',
'自动刷新': 'Auto refresh',
'会话超时(分钟)': 'Session timeout (minutes)',
-13
View File
@@ -29,19 +29,6 @@
gap: 14px;
}
.earth-desktop-handoff__badge {
display: inline-flex;
align-items: center;
gap: 8px;
width: fit-content;
padding: 5px 10px;
border: 1px solid rgba(96, 165, 250, 0.32);
background: rgba(59, 130, 246, 0.14);
color: #93c5fd;
font-size: 12px;
font-weight: 600;
}
.earth-desktop-handoff__title {
font-size: 22px;
font-weight: 600;
@@ -1,4 +1,4 @@
import { ArrowLeft, ExternalLink, Globe2 } from 'lucide-react'
import { ArrowLeft, Download, ExternalLink } from 'lucide-react'
import { Link } from 'react-router-dom'
import { useLocale } from '../../i18n/locale'
@@ -11,17 +11,13 @@ export default function EarthDesktopRedirect() {
return (
<main className="earth-desktop-handoff">
<section className="earth-desktop-handoff__panel">
<div className="earth-desktop-handoff__badge">
<Globe2 size={14} aria-hidden="true" />
<span>{isEnglish ? 'Admin Container Mode' : '独立控制台容器模式'}</span>
</div>
<h1 className="earth-desktop-handoff__title">
{isEnglish ? 'Open Intelligent Planet Desktop' : '请在桌面客户端打开智能星球'}
{isEnglish ? 'Open Planet Earth' : '打开 Planet Earth'}
</h1>
<p className="earth-desktop-handoff__desc">
{isEnglish
? 'This container serves the Admin Console and Docs only. Launch the native Electron Planet Earth client for hardware-accelerated 3D rendering, or run ./planet.sh earth locally.'
: '当前容器仅承载运维控制台与系统文档服务。请启动原生 Planet Earth 桌面客户端观看硬件加速 3D 地球,或在本地运行 ./planet.sh earth。'}
? 'First visit? Download Planet Earth and start it once from the location where you plan to keep it. Then use the button below to open your globe.'
: '首次使用请下载客户端,放到常用位置并启动一次。之后点击下方按钮即可打开地球。'}
</p>
<div className="earth-desktop-handoff__actions">
<a
@@ -29,7 +25,11 @@ export default function EarthDesktopRedirect() {
href="planet-earth://open"
>
<ExternalLink size={15} aria-hidden="true" />
<span>{isEnglish ? 'Launch Planet Earth' : '唤起桌面端 Earth'}</span>
<span>{isEnglish ? 'Launch desktop app' : '打开桌面客户端'}</span>
</a>
<a className="earth-desktop-handoff__btn" href="https://rclaw.top/">
<Download size={15} aria-hidden="true" />
<span>{isEnglish ? 'Download latest version' : '下载最新版'}</span>
</a>
<Link className="earth-desktop-handoff__btn" to="/admin">
<ArrowLeft size={15} aria-hidden="true" />
+2 -2
View File
@@ -58,8 +58,8 @@ function Register() {
setFeedback(null)
try {
const response = await axios.post(`${API_URL}/auth/verify-email`, { email, code })
const { access_token, user } = response.data
useAuthStore.setState({ token: access_token, user })
const { access_token, refresh_token, user } = response.data
useAuthStore.setState({ token: access_token, refreshToken: refresh_token ?? null, user })
axios.defaults.headers.common.Authorization = `Bearer ${access_token}`
navigate('/admin', { replace: true })
} catch (error) {
@@ -37,8 +37,8 @@ function VerifyEmail() {
setFeedback(null)
try {
const response = await axios.post(`${API_URL}/auth/verify-email`, { email, code })
const { access_token, user } = response.data
useAuthStore.setState({ token: access_token, user })
const { access_token, refresh_token, user } = response.data
useAuthStore.setState({ token: access_token, refreshToken: refresh_token ?? null, user })
axios.defaults.headers.common.Authorization = `Bearer ${access_token}`
navigate('/admin', { replace: true })
} catch (error) {
+90 -8
View File
@@ -1,6 +1,6 @@
import axios, { AxiosError, type InternalAxiosRequestConfig } from 'axios'
import { create } from 'zustand'
import { persist, createJSONStorage } from 'zustand/middleware'
import axios from 'axios'
import { createJSONStorage, persist } from 'zustand/middleware'
interface User {
id: number
@@ -11,18 +11,25 @@ interface User {
interface AuthState {
token: string | null
refreshToken: string | null
user: User | null
login: (username: string, password: string) => Promise<void>
logout: () => void
clearAuth: () => void
}
interface RetryableRequestConfig extends InternalAxiosRequestConfig {
_authRetried?: boolean
}
const API_URL = import.meta.env.VITE_API_URL || '/api/v1'
let pendingRefresh: Promise<string | null> | null = null
export const useAuthStore = create<AuthState>()(
persist(
(set) => ({
(set, get) => ({
token: null,
refreshToken: null,
user: null,
async login(username: string, password: string) {
@@ -34,18 +41,30 @@ export const useAuthStore = create<AuthState>()(
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
})
const { access_token, user } = response.data
set({ token: access_token, user })
const { access_token, refresh_token, user } = response.data
set({ token: access_token, refreshToken: refresh_token ?? null, user })
axios.defaults.headers.common['Authorization'] = `Bearer ${access_token}`
},
logout() {
set({ token: null, user: null })
const { token, refreshToken } = get()
set({ token: null, refreshToken: null, user: null })
delete axios.defaults.headers.common['Authorization']
if (token || refreshToken) {
void axios
.post(
`${API_URL}/auth/logout`,
refreshToken ? { refresh_token: refreshToken } : {},
{
headers: token ? { Authorization: `Bearer ${token}` } : {},
}
)
.catch(() => undefined)
}
},
clearAuth() {
set({ token: null, user: null })
set({ token: null, refreshToken: null, user: null })
localStorage.removeItem('auth-storage')
delete axios.defaults.headers.common['Authorization']
},
@@ -59,8 +78,71 @@ export const useAuthStore = create<AuthState>()(
axios.interceptors.request.use((config) => {
const token = useAuthStore.getState().token
if (token) {
if (token && !config.headers.Authorization) {
config.headers.Authorization = `Bearer ${token}`
}
return config
})
async function refreshAccessToken(): Promise<string | null> {
const { refreshToken } = useAuthStore.getState()
if (!refreshToken) {
return null
}
if (!pendingRefresh) {
pendingRefresh = axios
.post(
`${API_URL}/auth/refresh`,
{},
{
headers: { Authorization: `Bearer ${refreshToken}` },
}
)
.then((response) => {
const { access_token, refresh_token, user } = response.data
useAuthStore.setState({
token: access_token,
refreshToken: refresh_token ?? refreshToken,
user,
})
axios.defaults.headers.common['Authorization'] = `Bearer ${access_token}`
return String(access_token)
})
.catch(() => {
useAuthStore.getState().clearAuth()
return null
})
.finally(() => {
pendingRefresh = null
})
}
return pendingRefresh
}
axios.interceptors.response.use(
(response) => response,
async (error: AxiosError) => {
const originalRequest = error.config as RetryableRequestConfig | undefined
const requestUrl = originalRequest?.url || ''
const isAuthLifecycleRequest =
requestUrl.includes('/auth/login') ||
requestUrl.includes('/auth/refresh') ||
requestUrl.includes('/auth/logout')
if (
error.response?.status === 401 &&
originalRequest &&
!originalRequest._authRetried &&
!isAuthLifecycleRequest &&
useAuthStore.getState().refreshToken
) {
originalRequest._authRetried = true
const nextToken = await refreshAccessToken()
if (nextToken) {
originalRequest.headers.Authorization = `Bearer ${nextToken}`
return axios(originalRequest)
}
}
return Promise.reject(error)
}
)