| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778 |
- /**
- * 取阿里云 NLS 的 token(实时语音识别用)。
- *
- * 2026-10-28 起**不再走 `/api` 反向代理**,直接请求 HTTPS 地址
- * `https://kdyjs-proxy.metamaker.cn/proxy_proxy/proxy/verify/getALYToken`
- * (该地址带 `Access-Control-Allow-Origin: *`,浏览器可跨域直连)。
- * 返回形态:`{ code: 200, message: "成功", content: "<32 位 token>" }`。
- *
- * **前端不持有任何阿里云凭据**:签名要 AccessKeySecret,而前端 bundle 是公开的,
- * 签名在网关侧做,前端只拿结果。网关**不返回过期时间**,按官方文档的 24 小时估。
- *
- * 缓存策略:缓存到**过期前 5 分钟**;并发调用共用同一个在途请求。
- */
- import { getNlsAppkey, getNlsTokenApiUrl } from "@/utils/runtime-config";
- export interface NlsTokenResult {
- token: string;
- /** 过期时间(epoch 毫秒)—— 网关不给,按 24 小时估 */
- expireAt: number;
- }
- /** NLS token 的有效期(官方文档 24 小时;网关不返回,所以按它估) */
- const TOKEN_LIFETIME_MS = 24 * 60 * 60 * 1000;
- /** 提前多久视为过期(留出换 token + 重连的余量) */
- const REFRESH_AHEAD_MS = 5 * 60 * 1000;
- let cached: NlsTokenResult | null = null;
- let inflight: Promise<NlsTokenResult> | null = null;
- const isValid = () => !!cached && cached.expireAt - Date.now() > REFRESH_AHEAD_MS;
- export const fetchNlsToken = async (): Promise<NlsTokenResult> => {
- if (isValid()) {
- return cached as NlsTokenResult;
- }
- if (inflight) {
- return inflight;
- }
- inflight = (async () => {
- const response = await fetch(getNlsTokenApiUrl(), { method: "GET" });
- let body: any = null;
- try {
- body = await response.json();
- } catch {
- /* 非 JSON 时按状态码报错 */
- }
- if (!response.ok) {
- throw new Error(body?.message || `获取语音识别 token 失败(HTTP ${response.status})`);
- }
- // 网关用 code 表达业务结果(HTTP 200 也可能是失败)
- if (Number(body?.code) !== 200 || !body?.content) {
- throw new Error(body?.message || "获取语音识别 token 失败:响应里没有 token");
- }
- cached = {
- token: String(body.content).trim(),
- expireAt: Date.now() + TOKEN_LIFETIME_MS,
- };
- return cached;
- })();
- try {
- return await inflight;
- } finally {
- inflight = null;
- }
- };
- /** NLS 的 appkey(识别请求要带)—— 见 `getNlsAppkey` 的说明 */
- export const getNlsTokenAppkey = (): string => getNlsAppkey();
- /** 丢掉缓存(怀疑 token 失效时强制重取) */
- export const clearNlsTokenCache = (): void => {
- cached = null;
- };
|