// 后端契约的唯一出口:所有请求都走这里,方便统一处理 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 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(path: string, init: RequestInit = {}): Promise { const headers: Record = { 'Content-Type': 'application/json', ...((init.headers as Record) || {}), } 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(path: string, form: FormData): Promise { const headers: Record = {} 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) => { 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('/api/user/profile'), updateProfile: (patch: Partial) => req('/api/user/profile', { method: 'PUT', body: JSON.stringify(patch) }), devices: () => req('/api/devices'), pair: (code: string) => req('/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('/api/meta/astro/preview', { method: 'POST', body: JSON.stringify(payload) }), myFortune: (lang: 'zh' | 'en') => req(`/api/meta/fortune?lang=${lang}`), // TF 卡媒体库 media: { list: () => req('/api/media'), upload: (file: File) => { const fd = new FormData() fd.append('file', file) return reqForm('/api/media', fd) }, remove: (id: string) => req(`/api/media/${id}`, { method: 'DELETE' }), // 设备侧:进模块时查一次待同步,用户点确认才下发 pending: (deviceId: string) => req(`/api/devices/${deviceId}/media/pending`), // /