nex_buddy/web/src/api.ts

414 lines
14 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

// 后端契约的唯一出口:所有请求都走这里,方便统一处理 401 与错误文案。
const TOKEN_KEY = 'nx.token'
const USER_KEY = 'nx.user'
export type SignInfo = { code: string; name: string; symbol: string; element: string; degree: number; date_range: string }
export type User = {
id: string
email?: string | null
phone?: string | null
nickname: string
real_name?: string | null
birthday?: string | null
birth_time?: string | null
birth_city?: string | null
birth_region_code?: string | null
birth_place?: string | null
residence_region_code?: string | null
residence_city?: string | null
residence_place?: string | null
timezone?: string | null
sun_sign?: string | null
sun_sign_name?: string | null
sun_symbol?: string | null
sun_degree?: number | null
moon_sign?: string | null
moon_sign_name?: string | null
moon_symbol?: string | null
moon_degree?: number | null
role: 'user' | 'admin'
status: string
created_at?: string
}
export type Device = {
id: string
chip_id: string
model: string
fw_version: string
bound_at?: string | null
last_active_at?: string | null
}
export type RegionNode = { code: string; name: string; level: number; children?: RegionNode[] }
export type RegionRow = {
code: string
name: string
level: number
parent_code?: string | null
timezone: string
enabled: boolean
sort_order: number
}
export type Zodiac = {
code: string
name_cn: string
name_en: string
symbol: string
element: string
start_month: number
start_day: number
end_month: number
end_day: number
date_range?: string
intro: string
sort_order: number
enabled: boolean
}
export type AstroPreview = {
sun: SignInfo
moon: SignInfo
birth_place?: string | null
timezone: string
utc_time: string
}
export type Fortune = {
scope: 'month' | 'ym' | 'generic'
period?: string
title: string
content: string
updated_at?: string | null
}
export type MyFortune = {
period: string
timezone: string
sign?: string | null
fortune?: Fortune | null
}
export type FortuneRow = {
id: number
zodiac_code: string
scope: 'month' | 'ym'
period: string
title: string
title_en: string
content: string
content_en: string
enabled: boolean
}
export type AdminUser = User & { devices: Device[] }
// 天气连通性自检:后端把一次请求拆成 DNS/TCP/TLS/HTTP 四步各自计时
export type WeatherProbeStep = { name: string; ok: boolean; ms: number | null; detail: string }
export type WeatherProbe = {
ok: boolean
city: string
host?: string
port?: number
key_kind?: string
resolved?: string[]
proxy?: string
steps: WeatherProbeStep[]
hint?: string
}
export type Firmware = {
id: string
model: string
version: string
channel: 'stable' | 'beta'
size_bytes: number
sha256: string
notes: string
notes_en: string
min_version: string
published: boolean
download_count: number
created_at?: string | null
published_at?: string | null
device_count: number
}
export type DeviceUpgrade = {
id: string
chip_id: string
model: string
fw_version: string
target_version: string
upgrade_state: '' | 'pending' | 'downloading' | 'success' | 'failed' | 'canceled'
upgrade_error: string
upgrade_at?: string | null
boot_slot: string
fw_updated_at?: string | null
bound_user_id?: string | null
user_label: string
last_active_at?: string | null
}
// TF 卡媒体:网页上传 → 服务端处理 → 用户点「同步」后设备增量写入(music 原样透传;image 服务端已转 JPEG)
export type MediaItem = {
id: string
kind: 'music' | 'image'
name: string
size: number
crc32: number
width: number
height: number
original_name: string
created_at: string
synced_devices: number
// MP3 内嵌封面(上传时服务端已抽出);无封面时前端显示音符图标
has_cover: boolean
}
// 单台设备的待同步状态:pending 是待下载数量,rev 与 synced_rev 不同说明
// 还有删除/改名这类不体现在数量上的变更。
export type MediaPending = {
device_id: string
seq: number
ack: number
pending: number
rev: string
synced_rev: string
items: { id: string; kind: 'music' | 'image'; name: string; size: number }[]
}
export type UpgradesInfo = { total: number
by_version: Record<string, number>
latest: string
pending: number
items: DeviceUpgrade[]
}
export class ApiError extends Error {
status: number
constructor(message: string, status: number) {
super(message)
this.status = status
}
}
export const auth = {
get token() {
return localStorage.getItem(TOKEN_KEY)
},
get user(): User | null {
try {
return JSON.parse(localStorage.getItem(USER_KEY) || 'null')
} catch {
return null
}
},
save(token: string, user: User) {
localStorage.setItem(TOKEN_KEY, token)
localStorage.setItem(USER_KEY, JSON.stringify(user))
},
saveUser(user: User) {
localStorage.setItem(USER_KEY, JSON.stringify(user))
},
clear() {
localStorage.removeItem(TOKEN_KEY)
localStorage.removeItem(USER_KEY)
},
}
async function req<T>(path: string, init: RequestInit = {}): Promise<T> {
const headers: Record<string, string> = {
'Content-Type': 'application/json',
...((init.headers as Record<string, string>) || {}),
}
if (auth.token) headers.Authorization = `Bearer ${auth.token}`
const res = await fetch(path, { ...init, headers })
const body = await res.json().catch(() => ({}))
// 只有「带着会话 token 打普通接口被打回」才是过期;登录/注册/扫码的 401
// 是业务错误(密码错、票据失效),必须把后端 detail 透传给页面展示。
if (res.status === 401 && auth.token && !path.startsWith('/api/auth/')) {
auth.clear()
throw new ApiError('登录已过期,请重新登录', 401)
}
if (!res.ok) {
const detail = typeof body.detail === 'string' ? body.detail : `请求失败(${res.status})`
throw new ApiError(detail, res.status)
}
return body as T
}
/** multipart 专用:不能手动设 Content-Type,否则浏览器不会带 boundary。 */
async function reqForm<T>(path: string, form: FormData): Promise<T> {
const headers: Record<string, string> = {}
if (auth.token) headers.Authorization = `Bearer ${auth.token}`
const res = await fetch(path, { method: 'POST', body: form, headers })
const body = await res.json().catch(() => ({}))
if (res.status === 401 && auth.token) {
auth.clear()
throw new ApiError('登录已过期,请重新登录', 401)
}
if (!res.ok) {
const detail = typeof body.detail === 'string' ? body.detail : `请求失败(${res.status})`
throw new ApiError(detail, res.status)
}
return body as T
}
const qs = (params: Record<string, unknown>) => {
const sp = new URLSearchParams()
Object.entries(params).forEach(([k, v]) => {
if (v !== undefined && v !== null && v !== '') sp.set(k, String(v))
})
const s = sp.toString()
return s ? `?${s}` : ''
}
export const api = {
register: (account: string, password: string, nickname = '') =>
req<{ token: string; user: User }>('/api/auth/register', {
method: 'POST',
body: JSON.stringify({ account, password, nickname }),
}),
login: (account: string, password: string) =>
req<{ token: string; user: User }>('/api/auth/login', {
method: 'POST',
body: JSON.stringify({ account, password }),
}),
/** 设备屏二维码里的一次性票据 → 会话(免密,一码一用) */
qrLogin: (code: string) =>
req<{ token: string; user: User }>('/api/auth/qr-login', {
method: 'POST',
body: JSON.stringify({ code }),
}),
logout: () => req<{ ok: boolean }>('/api/auth/logout', { method: 'POST' }),
profile: () => req<User>('/api/user/profile'),
updateProfile: (patch: Partial<User>) =>
req<User>('/api/user/profile', { method: 'PUT', body: JSON.stringify(patch) }),
devices: () => req<Device[]>('/api/devices'),
pair: (code: string) =>
req<Device>('/api/devices/pair', { method: 'POST', body: JSON.stringify({ code }) }),
unbind: (id: string) => req<{ ok: boolean; detail?: string }>(`/api/devices/${id}`, { method: 'DELETE' }),
health: () => req<{ ok: boolean; db: boolean; redis: boolean; weather_ready: boolean }>('/healthz'),
// 码表
regionsTree: () => req<{ items: RegionNode[]; count: number }>('/api/meta/regions/tree'),
zodiacs: () => req<{ items: Zodiac[]; count: number }>('/api/meta/zodiacs'),
astroPreview: (payload: { birthday: string; birth_time?: string | null; birth_region_code?: string | null }) =>
req<AstroPreview>('/api/meta/astro/preview', { method: 'POST', body: JSON.stringify(payload) }),
myFortune: (lang: 'zh' | 'en') =>
req<MyFortune>(`/api/meta/fortune?lang=${lang}`),
// TF 卡媒体库
media: {
list: () => req<MediaItem[]>('/api/media'),
upload: (file: File) => {
const fd = new FormData()
fd.append('file', file)
return reqForm<MediaItem>('/api/media', fd)
},
remove: (id: string) => req<unknown>(`/api/media/${id}`, { method: 'DELETE' }),
// 设备侧:进模块时查一次待同步,用户点确认才下发
pending: (deviceId: string) => req<MediaPending>(`/api/devices/${deviceId}/media/pending`),
// <img>/<audio> 带不了 Authorization 头,token 走 query(后端只对这一条路径放宽)
fileUrl: (id: string) => `/api/media/${id}/file${auth.token ? `?t=${encodeURIComponent(auth.token)}` : ''}`,
coverUrl: (id: string) => `/api/media/${id}/cover${auth.token ? `?t=${encodeURIComponent(auth.token)}` : ''}`,
},
// 管理端
admin: {
users: () => req<{ total: number; items: AdminUser[] }>('/api/admin/users'),
setUserStatus: (userId: string, status: 'active' | 'disabled') =>
req<{ ok: boolean }>(`/api/admin/users/${userId}/status?status=${status}`, { method: 'POST' }),
unbindDevice: (deviceId: string) =>
req<{ ok: boolean; detail?: string }>(`/api/admin/devices/${deviceId}`, { method: 'DELETE' }),
revokeDevice: (deviceId: string) =>
req<{ ok: boolean; detail?: string }>(`/api/admin/devices/${deviceId}/revoke`, { method: 'POST' }),
fortunes: (params?: { zodiac_code?: string; scope?: string; year?: number }) =>
req<{ items: FortuneRow[] }>(`/api/admin/fortunes${qs(params || {})}`),
createFortune: (body: Omit<FortuneRow, 'id'>) =>
req<{ ok: boolean }>('/api/admin/fortunes', { method: 'POST', body: JSON.stringify(body) }),
updateFortune: (id: number, body: Partial<FortuneRow>) =>
req<{ ok: boolean }>(`/api/admin/fortunes/${id}`, { method: 'PUT', body: JSON.stringify(body) }),
deleteFortune: (id: number) =>
req<{ ok: boolean }>(`/api/admin/fortunes/${id}`, { method: 'DELETE' }),
settings: () =>
req<{ items: { key: string; value: unknown; updated_at?: string | null }[] }>('/api/admin/settings'),
saveSetting: (key: string, value: string) =>
req<{ ok: boolean }>('/api/admin/settings', { method: 'PUT', body: JSON.stringify({ key, value }) }),
testWeather: (city?: string) =>
req<WeatherProbe>(`/api/admin/settings/weather/test${qs({ city })}`, { method: 'POST' }),
regions: (params: { q?: string; level?: number; page?: number; page_size?: number }) =>
req<{ total: number; page: number; page_size: number; items: RegionRow[] }>(`/api/admin/regions${qs(params)}`),
createRegion: (body: Omit<RegionRow, 'sort_order'> & { sort_order?: number }) =>
req<{ ok: boolean; detail?: string }>('/api/admin/regions', { method: 'POST', body: JSON.stringify(body) }),
updateRegion: (code: string, body: Partial<RegionRow>) =>
req<{ ok: boolean }>(`/api/admin/regions/${code}`, { method: 'PUT', body: JSON.stringify(body) }),
deleteRegion: (code: string) => req<{ ok: boolean }>(`/api/admin/regions/${code}`, { method: 'DELETE' }),
importRegions: (mode: 'missing' | 'upsert' = 'missing') =>
req<{ ok: boolean; detail?: string }>(`/api/admin/regions/import?mode=${mode}`, { method: 'POST' }),
zodiacs: () => req<{ items: Zodiac[] }>('/api/admin/zodiacs'),
updateZodiac: (code: string, body: Partial<Zodiac>) =>
req<{ ok: boolean }>(`/api/admin/zodiacs/${code}`, { method: 'PUT', body: JSON.stringify(body) }),
createZodiac: (body: Zodiac) =>
req<{ ok: boolean }>('/api/admin/zodiacs', { method: 'POST', body: JSON.stringify(body) }),
deleteZodiac: (code: string) => req<{ ok: boolean }>(`/api/admin/zodiacs/${code}`, { method: 'DELETE' }),
// 固件
firmwares: () =>
req<{ items: Firmware[]; storage: string; max_size: number }>('/api/admin/firmwares'),
uploadFirmware: (file: File, fields: Record<string, string>) => {
const fd = new FormData()
fd.append('file', file)
Object.entries(fields).forEach(([k, v]) => fd.append(k, v))
return reqForm<{ ok: boolean; detail?: string }>('/api/admin/firmwares', fd)
},
updateFirmware: (id: string, patch: Partial<Firmware>) =>
req<{ ok: boolean }>(`/api/admin/firmwares/${id}`, { method: 'PUT', body: JSON.stringify(patch) }),
deleteFirmware: (id: string) => req<{ ok: boolean }>(`/api/admin/firmwares/${id}`, { method: 'DELETE' }),
rolloutFirmware: (id: string, deviceIds?: string[]) =>
req<{ ok: boolean; detail?: string }>(`/api/admin/firmwares/${id}/rollout`, {
method: 'POST',
body: JSON.stringify({ firmware_id: id, device_ids: deviceIds ?? null }),
}),
// 下载要带 Bearer,直接 <a href> 不行,只能 fetch 成 blob 再点一下
downloadFirmware: async (fw: Firmware) => {
const res = await fetch(`/api/admin/firmwares/${fw.id}/download`, {
headers: auth.token ? { Authorization: `Bearer ${auth.token}` } : {},
})
if (!res.ok) throw new ApiError(`下载失败(${res.status})`, res.status)
const blob = await res.blob()
const url = URL.createObjectURL(blob)
const a = document.createElement('a')
a.href = url
a.download = `knob_os-${fw.version}.bin`
a.click()
URL.revokeObjectURL(url)
},
deviceUpgrades: (q?: string) =>
req<UpgradesInfo>(`/api/admin/devices/upgrades${qs({ q })}`),
pushUpgrade: (deviceId: string, firmwareId: string) =>
req<{ ok: boolean; detail?: string }>(`/api/admin/devices/${deviceId}/upgrade`, {
method: 'POST',
body: JSON.stringify({ firmware_id: firmwareId }),
}),
cancelUpgrade: (deviceId: string) =>
req<{ ok: boolean; detail?: string }>(`/api/admin/devices/${deviceId}/upgrade`, { method: 'DELETE' }),
},
}