/** * 本机软件 HTTP 客户端(17300) * * 现在 HTTP 只负责**低频、无状态**的事,剩三个接口: * - `GET /api/query/{code}` 查信息,**同时返回服务/登录状态**(没登录回 401 `state:need-login`) * - `POST /api/activate-login` 把本机软件的登录窗/主界面叫到前台 * - `POST /api/playback/download` 按运单下载录像 * * ⚠️ 海康相关(拉通道 / 实时预览 / 云台 / 满帧率窗口)**全部走 WebSocket 17301**, * 见 {@link ./localWs.ts};这里只留通道列表的类型,供那边的返回值复用。 * * 为什么不再单独做探活接口:探活通过 ≠ 真正查询时软件还在(用户可能中途退了), * 两次请求之间的状态可能已经变了。合并成一个接口后,页面只发一次请求就能决定 * 「展示结果」还是「提示可以唤起」。 * * ⚠️ 这是**跨域**请求(页面同源是我们的站点,目标是 localhost:17300): * 本机软件必须允许 CORS(`Access-Control-Allow-Origin` 放行站点来源),否则浏览器会拦掉, * 表现和「软件没启动」一样 —— 页面统一提示「服务暂不可用」。 * * 地址可用 `VITE_LOCAL_SERVICE` 覆盖(换端口 / 换 127.0.0.1 时用)。 */ /** 本机服务地址(去掉末尾斜杠) */ export const LOCAL_BASE = ((import.meta.env.VITE_LOCAL_SERVICE as string | undefined) || 'http://localhost:17300') .replace(/\/+$/, ''); /** 本机服务返回非 2xx / 超时 / 跨域失败时抛它 */ export class LocalServiceError extends Error { /** HTTP 状态码(网络层失败时为 0) */ status: number; constructor(message: string, status = 0) { super(message); this.name = 'LocalServiceError'; this.status = status; } } /** 带超时的请求;**非 2xx 且返回了 JSON(带 state)时也原样返回**,交给调用方判状态 */ async function request(path: string, timeoutMs: number, method: 'GET' | 'POST' | 'DELETE' = 'GET', requestBody?: unknown): Promise { const controller = new AbortController(); const timer = setTimeout(() => controller.abort(), timeoutMs); try { let res: Response; try { res = await fetch(`${LOCAL_BASE}${path}`, { method, headers: { Accept: 'application/json', ...(requestBody === undefined ? {} : { 'Content-Type': 'application/json' }), }, body: requestBody === undefined ? undefined : JSON.stringify(requestBody), signal: controller.signal, }); } catch (err) { // 连不上本机软件(没启动 / 没安装 / 被拦):统一成 status=0,调用方据此提示唤起或下载 const aborted = err instanceof DOMException && err.name === 'AbortError'; throw new LocalServiceError(aborted ? '连接本机软件超时' : '无法连接本机软件', 0); } const text = await res.text(); let body: unknown = null; if (text) { try { body = JSON.parse(text); } catch { body = text; } } if (!res.ok) { // 本机软件的错误响应也是统一的 JSON(带 state/loggedIn),原样交给调用方 if (body && typeof body === 'object' && 'state' in (body as Record)) { return body as T; } throw new LocalServiceError(`本地服务返回 ${res.status}`, res.status); } return (body ?? null) as T; } finally { clearTimeout(timer); } } /** 查询接口返回的业务状态 */ export type LocalQueryState = 'ok' | 'need-login' | 'bad-request' | 'not-found' | 'error'; /** * `GET /api/query/{code}` 的统一响应 * * 不论成败都带 `loggedIn` / `user` / `env` / `server`,所以: * - 收到任何响应(200/400/401/404)= 软件在跑; * - 只有**网络失败**(连不上/超时/被 CORS 拦)= 软件没启动。 */ export interface LocalQueryResult { ok: boolean; state: LocalQueryState; /** 本次查询的运单号(原样回来,方便排查) */ code?: string; loggedIn: boolean; user: string | null; /** 构建环境:Development / Production */ env?: string; /** 当前后端地址(排障用) */ server?: string; /** 失败原因 */ message?: string; /** 成功时的数据(键值对,直接渲染) */ data?: Record | null; } /** * 查信息 —— **同时拿到服务/登录状态** * * 连不上 / 超时 / 被 CORS 拦 → 抛 {@link LocalServiceError}(页面提示「服务暂不可用」); * 其余情况都正常返回,看 `state` */ export async function queryLocal(code: string): Promise { return request(`/api/query/${encodeURIComponent(code)}`, 8000); } /** * 请求本机软件把登录窗叫到前台(`POST /api/activate-login`) * * `navigator.userActivation` 限定?不需要 —— 但必须用 POST:GET 会被链接预取 / 预渲染误触发。 */ export function requestLocalLogin(): Promise<{ ok?: boolean; loggedIn?: boolean; message?: string }> { return request('/api/activate-login', 4000, 'POST'); } /** * 叫醒已安装的本机软件:**自定义 URL Scheme**(安装包写进注册表的那种,像 `thunder://`、 * `baiduyunguanjia://` 一样) * * 网页**无法直接执行 exe**:只能让浏览器去打开 `xxx://…`,由系统按注册表找到 exe 并拉起( * Chrome/Edge 会先弹「要打开 xxx 吗?」)。 * * ⚠️ 浏览器**不会告诉我们成功与否**:能唤起、没安装、用户点「取消」在网页侧看起来一模一样。 * 所以调用方必须配合超时兑底(轮询 `queryLocal` 等软件起来,超时就展示下载安装提示)。 * * 协议名用 `VITE_APP_PROTOCOL` 配(默认 `yuncang`),必须与安装包里注册的一致。 */ export const APP_PROTOCOL = (import.meta.env.VITE_APP_PROTOCOL as string | undefined) || 'yuncang'; /** 拼出唤醒地址(把 code 一并带过去,软件起来后可以直接定位到该运单) */ export function appLaunchUrl(code?: string): string { const query = code ? `?code=${encodeURIComponent(code)}` : ''; return `${APP_PROTOCOL}://open${query}`; } /** * 触发唤醒。用隐藏 iframe 而不是 `location.href`: * 协议没注册时 Chrome 会直接在当前标签报错页,用 iframe 就只是静默失败。 * * 只能在**用户手势**里调(点击 / 回车),否则 Chrome 会拦掉外部协议。 */ export function launchApp(code?: string): void { const iframe = document.createElement('iframe'); iframe.style.display = 'none'; iframe.src = appLaunchUrl(code); document.body.appendChild(iframe); setTimeout(() => iframe.remove(), 1500); } /** * 轮询查询:直到不再是「未登录」为止 * * 用途: * - 软件没登录 → 唤起登录窗后,等用户登录完(登录成功后同一个接口就直接返回数据); * - 刚被协议唤起 → 等软件把 HTTP 服务拉起来。 * * @returns `offline: true` = 申请不到(软件中途退了/没起来);`result` = 最后一次拿到的响应 */ export async function waitForQuery( code: string, timeoutMs = 30000, intervalMs = 1000, ): Promise<{ result?: LocalQueryResult; offline: boolean }> { const deadline = Date.now() + timeoutMs; let last: LocalQueryResult | undefined; while (Date.now() < deadline) { try { last = await queryLocal(code); } catch { return { result: last, offline: true }; } if (last.state !== 'need-login') return { result: last, offline: false }; await new Promise(resolve => setTimeout(resolve, intervalMs)); } return { result: last, offline: false }; } // ---------------- 按运单下载录像(本机软件 POST /api/playback/download) ---------------- /** 下载录像的结果 */ export interface LocalPlaybackDownloadResult { ok: boolean; state?: 'ok' | 'need-login' | 'bad-request' | 'unsupported' | 'error'; code?: string; /** 最终存放目录(本机软件里设置的录像根目录 + 年/月/日) */ folder?: string; /** 合并后的成片路径(单路时就是那一路) */ merged?: string | null; /** 各路段文件(合并失败时会有多个) */ segments?: string[]; /** 非致命提示(某路没下到 / 合并失败等) */ warnings?: string[]; elapsedMs?: number; message?: string; } /** * 让本机软件按运单号下载这段时间的录像(多路自动合并) * * 走的是 `POST /api/playback/download { code }`: * - 录像存到**这台电脑自己设置的目录**(默认 `~/packVideo/年/月/日/`), * 跟「是不是设备服务器」无关 —— 任何装了本机软件的电脑都能下; * - 下载 + 合并可能要几十秒,所以超时给到 **180 秒**。 */ export function downloadPlayback(code: string): Promise { return request('/api/playback/download', 180000, 'POST', { code }); } // ---------------- 海康设备通道(本机软件 POST /api/hik/channels) ---------------- /** 本机软件返回的单个通道 */ export interface HikChannelItem { channel: number; type: 'analog' | 'digital'; enabled: boolean; /** 设备上的通道名(8000 协议不返回,通常为空) */ name?: string | null; ip?: string | null; port?: number | null; user?: string | null; } /** 本机软件拉通道的返回体(失败时 state=hik-error,并带 lastError) */ export interface HikChannelsPayload { ok: boolean; state?: string; lastError?: number; message?: string; data?: { endpoint: string; serialNumber: string; diskCount: number; analogChannelCount: number; digitalChannelCount: number; startChannel: number; startDigitalChannel: number; channels: HikChannelItem[]; warning?: string | null; userId: number; sessionReused: boolean; elapsedMs: number; }; } // ---------------- 实时预览 / 云台 / 拉通道已全部改走 WebSocket(见 api/localWs.ts) ----------------