Commit 5cddd549 by liimin

feat: 新增错误处理与权限工具,优化录音和上传功能

- 新增 utils/error.uts 全局错误处理工具,统一错误日志格式
- 新增 utils/permission.uts 权限检查工具,简化权限管理
- 优化录音功能:修复录音开始回调类型,统一录音文件管理
- 优化上传功能:为上传策略添加类型别名,增强类型安全
- 修复登录和签名中的严格相等比较问题
- 优化数据库查询逻辑,移除冗余空值检查
- 为日志输出添加 ANSI 颜色,提升调试体验
- 优化分辨率适配模块,使用 logger 替代 console
- 重构录音相关类型定义,提升代码可维护性
1 parent 132ef2fa
Showing 32 changed files with 454 additions and 232 deletions
......@@ -98,29 +98,29 @@ function stringifyRecursive(
targetObj = new UTSJSONObject(processedObj);
}
} else {
if (processedObj !== null) {
if (Array.isArray(processedObj)) {
const arr = processedObj as any[];
for (let i = 0; i < arr.length; i++) {
objKeys.push(`${i}`);
}
} else if (processedObj instanceof UTSJSONObject) {
const objMap = (processedObj as UTSJSONObject).toMap();
objMap.forEach((_, key) => {
objKeys.push(key);
});
} else {
const json = new UTSJSONObject(processedObj);
targetObj = json;
const objMap = json.toMap();
objMap.forEach((_, key) => {
objKeys.push(key);
});
}
if (sort !== null) {
objKeys = objKeys.sort(sort);
// if (processedObj !== null) {
if (Array.isArray(processedObj)) {
const arr = processedObj as any[];
for (let i = 0; i < arr.length; i++) {
objKeys.push(`${i}`);
}
} else if (processedObj instanceof UTSJSONObject) {
const objMap = (processedObj as UTSJSONObject).toMap();
objMap.forEach((_, key) => {
objKeys.push(key);
});
} else {
const json = new UTSJSONObject(processedObj);
targetObj = json;
const objMap = json.toMap();
objMap.forEach((_, key) => {
objKeys.push(key);
});
}
if (sort !== null) {
objKeys = objKeys.sort(sort);
}
// }
}
for (const key of objKeys) {
......
......@@ -31,7 +31,7 @@ export function sign(params: UTSJSONObject, secret: string, noSignAttr: string[]
const realObj: UTSJSONObject = {};
for (const item of objVal) {
const idx = item.indexOf("=");
if (idx === -1) {
if (idx == -1) {
continue;
}
const key = item.slice(0, Math.max(0, idx));
......
import { logger } from "@/services/logger/index.uts";
import { IResolutionAdapter, resolutionAdapters } from "./adapter.uts";
import { initRegistry, isRegistryInitialized } from "./registry.uts";
import { resolutionState } from "./store.uts";
......@@ -8,29 +10,23 @@ import { AppResolutionConfig, ResponsiveImage } from "./types/index.uts";
// ========================================================================
export function updateResolutionConfig() {
initRegistry();
const info = uni.getWindowInfo();
console.log("🚀 ~ updateResolutionConfig ~ info:", info);
// 优先取 windowWidth,如果为 0 则取 screenWidth (物理屏幕宽)
let w = info.windowWidth;
let h = info.windowHeight;
const pr = info.pixelRatio;
// 兜底逻辑...
if (w === 0 && info.screenWidth > 0) {
if (w == 0 && info.screenWidth > 0) {
w = info.screenWidth;
if (info.screenHeight > 0) h = info.screenHeight;
console.warn(`[ResolutionAdapt] windowWidth is 0, fallback to screenWidth: ${w}x${h}`);
}
if (w === 0 || h === 0) {
console.error(`[ResolutionAdapt] Failed to get valid window size: ${w}x${h}`);
if (w == 0 || h == 0) {
return;
}
const key = `${Math.round(w)}x${Math.round(h)}`;
console.log(`[ResolutionAdapt] Window: ${w}x${h} @${pr}x, Key: ${key}`);
// 使用适配器模式匹配
let adapter: IResolutionAdapter | null = null;
......@@ -42,10 +38,10 @@ export function updateResolutionConfig() {
}
if (adapter === null) {
console.error(`[ResolutionAdapt] No adapter matched for ${w}x${h}`);
// 使用 logger 服务记录日志
logger.debug(`[ResolutionAdapt] 未找到适配器,跳过配置更新`);
return;
}
// 执行适配
let target = adapter.getConfig(key);
let usedKey = key;
......@@ -64,7 +60,7 @@ export function updateResolutionConfig() {
resolutionState.pixelRatio = pr;
resolutionState.windowWidth = w;
resolutionState.windowHeight = h;
console.log(`[ResolutionAdapt] Applied config: ${usedKey}, cssClass: ${resolutionState.cssClass}`);
logger.info(`[ResolutionAdapt] Applied config: ${usedKey}, cssClass: ${resolutionState.cssClass}`);
}
}
......
......@@ -179,8 +179,7 @@ const doLogin = async (): Promise<void> => {
const resCode = res !== null ? res.code : null;
const data = res !== null ? (res.data as any | null) : null;
const message = res !== null ? (res.message as null | string) : null;
if (`${resCode}` === "0" && data !== null) {
if (`${resCode}` == "0" && data !== null) {
jump(data, remember);
} else {
uni.showModal({
......
......@@ -128,9 +128,9 @@ export default class DBBase implements IDBBase {
// if (!isOpen) {
await this.db.init();
// }
if (this.table_name == null) {
throw new Error("DBBase: table_name is null");
}
// if (this.table_name == null) {
// throw new Error("DBBase: table_name is null");
// }
const isTableExists = await this.db.isTableExists(this.table_name);
logger.warn(`数据库是否存在isTableExists: ${isTableExists}`, "DBBase");
......
......@@ -326,10 +326,10 @@ export default class SQLite {
// 如果 result 为空,再降级使用 data
const rows = result.result ?? result.data;
if (rows == null) {
resolve([] as any[]);
return;
}
// if (rows == null) {
// resolve([] as any[]);
// return;
// }
const processedRows: any[] = [];
const rowsArray = rows as any[]; // 此时 rowsArray 可能是 UTSJSONObject[] 或 any[]
......
......@@ -67,7 +67,7 @@ export class Logger {
serverUrl: targetUrl,
headers: headers ?? this.uploadConfig.headers,
include: true,
days: (days === 0 ? this.uploadConfig.days : days) ?? 7,
days: (days == 0 ? this.uploadConfig.days : days) ?? 7,
suffix
} as IUpload;
......@@ -86,7 +86,22 @@ export class Logger {
const message = this.formatMsg(msg);
const fullMessage = `[${level}][${tag}] ${message}`;
action.console(fullMessage);
// Add ANSI color codes for console output
let consoleMessage = fullMessage;
const ESC = "\u001B";
const RESET = `${ESC}[0m`;
if (level == "DEBUG") {
consoleMessage = `${ESC}[34m${fullMessage}${RESET}`; // Blue
} else if (level == "INFO") {
consoleMessage = `${ESC}[32m${fullMessage}${RESET}`; // Green
} else if (level == "WARN") {
consoleMessage = `${ESC}[93m${fullMessage}${RESET}`; // Bright Yellow
} else if (level == "ERROR") {
consoleMessage = `${ESC}[31m${fullMessage}${RESET}`; // Red
}
action.console(consoleMessage);
action.file(fullMessage);
this.remote?.let((r) => {
......
import { getRecorderManagerX, IRecorderManagerFail, RecorderManager, RecorderManagerOnStopResult, RecorderManagerStartOptions } from "@/uni_modules/uni-recorder-x/utssdk/interface.uts";
import { logger } from "../logger";
/*
* @Description:
......@@ -7,10 +5,18 @@ import { logger } from "../logger";
* @Author: limin
* @Date: 2024-12-04 18:17:23
* @LastEditors: limin
* @LastEditTime: 2026-03-12 21:09:44
* @LastEditTime: 2026-03-13 12:58:42
* @FilePath: \venus\apps\uniappx\uniapp-x-tape\services\recorder\AudioManager.uts
*/
import { AudioEvents, AudioStartOptions, OnErrorCallback, OnStartCallback, OnStopCallback } from "./types";
import { AudioEvents, AudioStartOptions, OnErrorCallback, OnStartCallback, OnStopCallback, RecorderManager, RecorderManagerOnStopResult, RecorderManagerStartOptions } from "./types/audio.uts";
interface IRecorderManagerLoose {
start(options: any): void;
stop(): void;
onStart(callback: (res: any) => void): void;
onStop(callback: (res: any) => void): void;
onError(callback: (res: any) => void): void;
}
class AudioManager {
__counter: number = 0;
......@@ -20,7 +26,8 @@ class AudioManager {
startOptions: AudioStartOptions = {
// duration: 10 * 60 * 1000, // uts-recorder 暂不支持 duration 自动停止
sampleRate: 16_000,
numberOfChannels: 1
numberOfChannels: 1,
format:"mp3"
};
/**
......@@ -59,19 +66,19 @@ class AudioManager {
onStop,
onError
};
this.recorderManager = getRecorderManagerX();
this.recorderManager = uni.getRecorderManagerX() as RecorderManager;
this.initListeners();
}
initListeners() {
this.recorderManager.onStart((res: any) => {
this.onStart(res);
this.recorderManager.onStart((res) => {
this.onStart(res as RecorderManagerOnStartResult);
});
this.recorderManager.onStop((res: RecorderManagerOnStopResult) => {
this.onStop(res);
this.recorderManager.onStop((res) => {
this.onStop(res as RecorderManagerOnStopResult);
});
this.recorderManager.onError((err: IRecorderManagerFail) => {
this.onError(err as UniError);
this.recorderManager.onError((err) => {
this.onError(err as IRecorderManagerFail);
});
}
......@@ -83,31 +90,30 @@ class AudioManager {
*
* @param {Error} err - 发生的错误对象
*/
async onError(err: UniError) {
async onError(err: any) {
logger.info(`〖录音管理Audio〗 == 录音错误回调 ${JSON.stringify(err)}`);
// 重置录音状态
this.reset();
await this.events.onError(err);
}
/**
* 录音开始成功的回调
*/
async onStart(res: any) {
// 记录录音开始的信息到日志
logger.info(`〖录音管理Audio〗 == 开启录音回调 ${JSON.stringify(res)}`);
// 等待事件的onStart方法执行完成
await this.events.onStart(res);
// 内部计数器增加,用于跟踪录音开始的次数
this.__counter++;
// 设置录音状态标志为true,表示当前正在录音
this.__isRecording = true;
// 等待事件的onStart方法执行完成
}
/**
* 录音停止成功的回调
*/
async onStop(res: RecorderManagerOnStopResult) {
logger.info("〖录音管理Audio〗 == 停止录音回调 ");
async onStop(res: any) {
logger.info(`〖录音管理Audio〗 == 停止录音回调 ${JSON.stringify(res)}`);
// 重置录音状态
this.reset();
await this.events.onStop(res);
}
/**
......@@ -136,7 +142,7 @@ class AudioManager {
const options = {
sampleRate: this.startOptions.sampleRate,
numberOfChannels: this.startOptions.numberOfChannels,
format: "aac"
format: this.startOptions.format
} as RecorderManagerStartOptions;
this.recorderManager.start(options);
}
......
......@@ -6,7 +6,7 @@ import type { IDBRecord, RecordData } from "./types";
* @Author: limin
* @Date: 2025-01-02 18:34:39
* @LastEditors: limin
* @LastEditTime: 2026-03-06 12:40:15
* @LastEditTime: 2026-03-13 19:52:30
* @FilePath: \venus\apps\uniappX\uniapp-x-tape\services\recorder\DBRecord.uts
*/
import DBBase from "../db/DBBase.uts";
......@@ -116,12 +116,12 @@ class DBRecord extends DBBase implements IDBRecord {
// 更好的做法是:
// 1. setStrategy 改为 async (但这会破坏接口签名,如果有接口的话)
// 2. 在内部启动一个 async 任务,并捕获错误
if (this.db !== null) {
// 使用 IIFE 或 then/catch 处理异步
this.ensureColumns().catch(error => {
logger.error(`DBRecord: setStrategy ensureColumns failed: ${error}`, "DBRecord");
});
}
// if (this.db !== null) {
// // 使用 IIFE 或 then/catch 处理异步
this.ensureColumns().catch(error => {
logger.error(`DBRecord: setStrategy ensureColumns failed: ${error}`, "DBRecord");
});
// }
}
/**
......
......@@ -2,6 +2,7 @@ import type { RecordData } from "./types";
import { saveRecCustomer, searchRecordingEndTime } from "@/api/receiption.uts";
import { handleError } from "../../utils/error.uts";
// import dayjs from 'dayjs'
import { replaceAll } from "../../utils/index.uts";
/*
......@@ -10,7 +11,7 @@ import { replaceAll } from "../../utils/index.uts";
* @Author: limin
* @Date: 2026-01-28 20:57:12
* @LastEditors: limin
* @LastEditTime: 2026-03-06 16:51:40
* @LastEditTime: 2026-03-13 19:54:16
* @FilePath: \venus\apps\uniappX\uniapp-x-tape\services\recorder\RecordSave.uts
*/
import Queue from "../../utils/Queue.uts";
......@@ -300,9 +301,8 @@ class RecordSave {
const dbRecord = await this.getDbRecord();
await dbRecord.removeRecord(recordId);
logger.info(`【接待记录保存服务】 == 删除接待记录成功: recordId ->${recordId}`, "RecordSave");
} catch (error) {
const errorMsg = typeof error === "string" ? error : `${error}`;
logger.error(`【接待记录保存服务】 == 删除接待记录异常: error ->${errorMsg}`, "RecordSave");
} catch (error: any) {
handleError(error, "RecordSave", "【接待记录保存服务】 == 删除接待记录异常: error ->");
}
}
......@@ -314,9 +314,8 @@ class RecordSave {
await this._removeFileOnClient(file);
}
logger.info(`【接待记录保存服务】 == 删除接待文件完成!`, "RecordSave");
} catch (error) {
const errorMsg = typeof error === "string" ? error : `${error}`;
logger.error(`【接待记录保存服务】 == 删除接待文件异常: error ->${errorMsg}`, "RecordSave");
} catch (error: any) {
handleError(error, "RecordSave", "【接待记录保存服务】 == 删除接待文件异常: error ->");
}
}
......@@ -391,10 +390,9 @@ class RecordSave {
// 成功:立即处理下一个任务
this._scheduleNext(0);
} catch (error) {
const recordId = record !== null ? record.recordId as string : null;
const errorMsg = typeof error === "string" ? error : `${error}`;
logger.error(`【接待记录保存服务】 == 异常,error->${errorMsg}, recordId: ${recordId}`, "RecordSave");
} catch (error: any) {
const recordId = record !== null ? record.getString("recordId") : null;
const errorMsg = handleError(error, "RecordSave", `【接待记录保存服务】 == 异常, recordId: ${recordId}, error->`);
// 如果任务已经 dequeue,将其加入黑名单防止死循环
if (recordId !== null) {
this._addToBlackList(recordId, `Scheduler error: ${errorMsg}`);
......@@ -466,9 +464,8 @@ class RecordSave {
const _snapshot = await this.getRecordsSnapshotFlatten();
this.snapshot = new Queue(_snapshot);
logger.warn(`【接待记录保存服务】 == 创建快照成功! ${JSON.stringify(this.snapshot.items)} 快照数: ${this.snapshot.size} `, "RecordSave");
} catch (error) {
const errorMsg = typeof error === "string" ? error : `${error}`;
logger.error(`【接待记录保存服务】 == 获取快照失败 error:${errorMsg}`, "RecordSave");
} catch (error: any) {
handleError(error, "RecordSave", "【接待记录保存服务】 == 获取快照失败 error:");
if (this.snapshot === null) {
this.snapshot = new Queue([]);
}
......@@ -515,17 +512,16 @@ class RecordSave {
file2Up.status = FileStatus.NotExist;
}
result.push(file2Up);
} catch (error) {
const errorMsg = typeof error === "string" ? error : `${error}`;
logger.error(`【接待记录保存服务】 == 解析处理文件异常 error: ${errorMsg}, recordId: ${recordId}, file: ${JSON.stringify(file)}`, "RecordSave");
} catch (error: any) {
const errorMsg = handleError(error, "RecordSave", `【接待记录保存服务】 == 解析处理文件异常, recordId: ${recordId}, file: ${JSON.stringify(file)} error:`);
this._addToBlackList(recordId, `Parse error: ${errorMsg}`);
continue;
}
}
}
return result;
} catch (error) {
logger.error(`【接待记录保存服务】 == 处理文件列表异常: ${error}`, "RecordSave");
} catch (error: any) {
handleError(error, "RecordSave", "【接待记录保存服务】 == 处理文件列表异常:");
return result;
}
}
......@@ -569,8 +565,8 @@ class RecordSave {
uni.onNetworkStatusChange(this._networkHandler);
logger.info("【接待记录保存服务】初始化成功", "RecordSave");
} catch (error) {
logger.error(`【接待记录保存服务】初始化失败 error:${error}`, "RecordSave");
} catch (error: any) {
handleError(error, "RecordSave", "【接待记录保存服务】初始化失败 error:");
}
}
......@@ -631,7 +627,7 @@ class RecordSave {
logger.info(`【接待记录保存服务】 == 解析结果: recordId=${recordId}, status=${status}`, "RecordSave");
const callbackKey = this._getTaskKey(recordId, fileName);
const isCurrentTask = this._currentKey !== null && callbackKey === this._currentKey;
const isCurrentTask = this._currentKey !== null && callbackKey == this._currentKey;
if (!isCurrentTask) {
logger.warn(`【接待记录保存服务】 == 收到非当前任务回调: ${callbackKey} (当前: ${this._currentKey}),仅更新状态`, "RecordSave");
......@@ -651,14 +647,14 @@ class RecordSave {
logger.info("【接待记录保存服务】 == 本次任务完成,开启下一次上传任务!", "RecordSave");
this.endTask();
}
} catch (error) {
} catch (error: any) {
if (this._currentKey !== null) {
this._addToBlackList(this._currentKey.split("_")[0], `Save failed: ${error}`);
}
const recordId = data.recordId as string;
const filePath = data.filePath as string;
const fileName = data.fileName as string;
logger.error(`【接待记录保存服务】 == 保存记录(save)异常 error: ${error}, recordId: ${recordId}, filePath: ${filePath + fileName}`, "RecordSave");
const recordId = data.getString("recordId");
const filePath = data.getString("filePath");
const fileName = data.getString("fileName");
handleError(error, "RecordSave", `【接待记录保存服务】 == 保存记录(save)异常, recordId: ${recordId}, filePath: ${(filePath ?? "") + (fileName ?? "")} error:`);
this.endTask();
}
}
......@@ -726,10 +722,9 @@ class RecordSave {
return;
}
await this.uploadRecord(record);
} catch (error) {
const errorMsg = typeof error === "string" ? error : `${error}`;
} catch (error: any) {
const errorMsg = handleError(error, "RecordSave", `上传文件时发生异常(uploadRecord), recordId: ${recordId}, error:`);
this._addToBlackList(recordId, `上传文件时发生异常(uploadRecord): ${errorMsg}`);
logger.error(`上传文件时发生异常(uploadRecord): ${errorMsg}, recordId: ${recordId}`, "RecordSave");
this.endTask();
}
};
......@@ -808,10 +803,9 @@ class RecordSave {
};
this.handleUploadResult(result);
} catch (error) {
logger.error(`【接待记录保存服务】 == 上传失败: ${error}`, "RecordSave");
} catch (error: any) {
const errorMsg = handleError(error, "RecordSave", "【接待记录保存服务】 == 上传失败:");
const errorMsg = typeof error === "string" ? error : `${error}`;
const errorResult = {
detail: {
data: [{
......
......@@ -2,6 +2,7 @@
import { commit } from "@/store/index.uts";
import { checkPermission, requestPermissions } from "@/uni_modules/permission-handler-plus";
import { handleError } from "../../utils/error.uts";
// import TimeoutService from './TimeoutService.uts'
import { logger } from "../logger/index.uts";
// import { sleep } from './helper.uts' // 文件不存在,先注释掉
......@@ -62,16 +63,7 @@ export class RecordService {
this.triggerTempNumber();
} catch (error) {
console.error(`RecordService init error raw: ${error}`);
let errorMsg = "";
if (typeof error === "string") {
errorMsg = error;
} else if (error instanceof Error) {
errorMsg = error.message;
} else {
errorMsg = `${ error}`;
}
logger.error({ msg: `【录音服务RecordService】 == 初始化异常: ${errorMsg}` }, "RecordService");
handleError(error, "RecordService", "【录音服务RecordService】 == 初始化异常:");
}
}
initDto() {
......@@ -114,7 +106,7 @@ export class RecordService {
}
},
fail: (err) => {
logger.error({ msg: `【录音服务RecordService】 == 请求录音权限失败: ${err}` }, "RecordService");
handleError(err, "RecordService", "【录音服务RecordService】 == 请求录音权限失败:");
resolve(false);
}
});
......@@ -128,8 +120,7 @@ export class RecordService {
}
onAudioError(error: any) {
const message = JSON.stringify(error);
this.reportError(`录音异常: error: ${message}`, message);
handleError(error, "RecordService", "【录音服务RecordService】 == 录音异常:");
}
async onAudioStart(res: any) {
......@@ -143,8 +134,8 @@ export class RecordService {
logger.warn("〖RecordService〗 == onAudioStart called but record is null", "RecordService");
return;
}
const resObj = res as UTSJSONObject;
const recordFile: RecordFile = { filePath: resObj.getString("tempFilePath") ?? "" };
const resObj = res as RecorderManagerOnStartResult;
const recordFile: RecordFile = { filePath: resObj.filePath };
if (this.audioManager.counter === 0) {
logger.info("〖RecordService〗 == First audio segment, adding record...", "RecordService");
// Use single-element array if add expects array, OR if add accepts single item, adjust accordingly.
......@@ -155,28 +146,7 @@ export class RecordService {
await this.record.addAudio(recordFile);
}
} catch (error) {
// Improved error logging
let errorMsg = "";
if (error === null) {
errorMsg = "Unknown error (null)";
} else if (typeof error === "string") {
errorMsg = error;
} else if (error instanceof Error) {
errorMsg = error.message;
if (errorMsg === "") {
errorMsg = `Error with empty message: ${error.name} ${error.toString()}`;
}
} else {
try {
errorMsg = JSON.stringify(error);
if (errorMsg === "{}" || errorMsg === '""') {
errorMsg = `${error}`;
}
} catch {
errorMsg = `Stringify failed: ${error}`;
}
}
logger.error({ msg: `〖RecordService〗 == onAudioStart error: ${errorMsg}` }, "RecordService");
handleError(error, "RecordService", "〖RecordService〗 == onAudioStart error:");
}
}
......@@ -195,10 +165,6 @@ export class RecordService {
this.stopAudioRecord();
}
reportError(msg: string, error: any) {
logger.error({ msg: `【录音服务RecordService】 == ${msg} error: ${error}` }, "RecordService");
}
reset() {
// this.flushAllDebounceTimers();
this.audioManager = null;
......@@ -249,7 +215,7 @@ export class RecordService {
// this.timeoutService!.start()
return true; // 返回 true 表示成功启动
} catch (error) {
logger.error({ msg: `【录音服务RecordService】 == startAudio 异常: ${error}` }, "RecordService");
handleError(error, "RecordService", "【录音服务RecordService】 == startAudio 异常:");
return false;
} finally {
this._startAudioPromise = null;
......@@ -277,16 +243,7 @@ export class RecordService {
logger.warn("【录音服务RecordService】 == 结束接待时 record 为空", "RecordService");
}
} catch (error) {
let errorMsg = "";
if (typeof error === "string") {
errorMsg = error;
} else if (error instanceof Error) {
errorMsg = error.message;
} else {
errorMsg = JSON.stringify(error);
}
logger.error({ msg: `【录音服务RecordService】 == 结束接待保存失败: ${errorMsg}` }, "RecordService");
this.reportError("结束接待保存失败", `${errorMsg}`);
handleError(error, "RecordService", "【录音服务RecordService】 == 结束接待保存失败:");
}
}
......
......@@ -216,14 +216,14 @@ class TempRecord {
logger.warn("〖接待记录Record〗 == 尝试添加录音片段但 record 为空", "TempRecord");
return;
}
const recordUrlList = (record!.recordUrlList as RecordFile[]) ?? [];
const recordUrlList = (record.recordUrlList as RecordFile[]) ?? [];
recordUrlList.push(item);
// 更新 record 对象中的列表,防止不同步
record!.recordUrlList = recordUrlList;
record.recordUrlList = recordUrlList;
// 更新数据库中的 recordUrlList
const id = record!.id;
const id = record.id;
try {
// Cast RecordFile[] to UTSJSONObject[] or any for updateRecord
// updateRecord takes UTSJSONObject for items
......
......@@ -54,7 +54,7 @@ export class DefaultRecorderStrategy implements IRecorderStrategy {
}
getBussinessType(sceneType: any | null): number {
return sceneType === 0 ? 1 : 2; // sceneType 0延保 1精品。 bussinessType 1.延保 2.轻改
return sceneType == 0 ? 1 : 2; // sceneType 0延保 1精品。 bussinessType 1.延保 2.轻改
}
/**
......@@ -140,7 +140,7 @@ export class DefaultRecorderStrategy implements IRecorderStrategy {
// 直接在这里进行缓存写入
const result = this.processMaterialPoints(data as UTSJSONObject[]);
// 检查是否需要缓存
if (result.getBoolean("_isCache") === true) {
if (result.getBoolean("_isCache") == true) {
const key = result.getString("key");
const val = result.get("value");
if (key !== null && val !== null) {
......
......@@ -30,11 +30,11 @@ export class RecorderStrategyFactory {
strategy = new DefaultRecorderStrategy();
break;
}
default: {
console.warn(`Unknown strategy type: ${type}, using default.`);
strategy = new DefaultRecorderStrategy();
break;
}
// default: {
// console.warn(`Unknown strategy type: ${type}, using default.`);
// strategy = new DefaultRecorderStrategy();
// break;
// }
}
// 更新当前策略
this.currentStrategy = strategy;
......
import { RecorderManagerOnStopResult, RecorderManagerStartOptions } from "@/uni_modules/uni-recorder-x/utssdk/interface.uts";
import { IRecorderManagerFail, RecorderManagerOnStartResult, RecorderManagerOnStopResult, RecorderManagerStartOptions } from "@/uni_modules/uni-recorder-x/utssdk/interface.uts";
export { getRecorderManagerX, IRecorderManagerFail, RecorderManager, RecorderManagerOnStartResult, RecorderManagerOnStopResult, RecorderManagerStartOptions } from "@/uni_modules/uni-recorder-x/utssdk/interface.uts";
export type AudioStartOptions = RecorderManagerStartOptions
export type RecorderManagerOnErrorResult = IRecorderManagerFail
export type OnStartCallback = (res: any) => Promise<void> | void
export type OnStopCallback = (res: RecorderManagerOnStopResult) => Promise<void> | void
export type OnStopCallback = (res: any) => Promise<void> | void
export type OnErrorCallback = (err: any) => Promise<void> | void
export type AudioEvents = {
......@@ -16,5 +19,3 @@ export type RecordFile = {
filePath: string
status?: number
}
// 移除 RecorderStrategy,因为不再使用策略模式
import { RecordFile } from './audio'
import { RecordFile } from "./audio";
export type RecordData = {
id: string
staffUuid?: string | null
staffName?: string | null
serviceMerchantId?: number | null
carModel?: string | null
endReasonType?: number | null
customerName?: string | null
phoneNumber?: string | null
appCode?: string | null
loginPhone?: string | null
salesName?: string | null
salesUuid?: string | null
receptionStatus?: number | null
receptionStartTime?: string | null
receptionEndTime?: string | null
receptionCustomerPaySourceList?: any[] | null
merchantId?: number | null
merchantName?: string | null
bussinessType?: number | null
channelType?: number | null
receptionCustomerMaterialPointList?: any[] | null
recordUrlList?: RecordFile[] | null
carBrand?: string | null
carBrandId?: number | null
oneCarBrand?: string | null
oneCarBrandId?: number | null
recordStatus?: number | null // 0: recording, 1: completed
appCode?: null | string
bussinessType?: null | number
carBrand?: null | string
carBrandId?: null | number
carModel?: null | string
channelType?: null | number
customerName?: null | string
endReasonType?: null | number
fileName?: null | string
filePath?: null | string
id: string
loginPhone?: null | string
merchantId?: null | number
merchantName?: null | string
oneCarBrand?: null | string
oneCarBrandId?: null | number
phoneNumber?: null | string
receptionCustomerMaterialPointList?: any[] | null
receptionCustomerPaySourceList?: any[] | null
receptionEndTime?: null | string
receptionStartTime?: null | string
receptionStatus?: null | number
recordId?: null | string
recordStatus?: null | number // 0: recording, 1: completed
recordUrlList?: null | RecordFile[]
salesName?: null | string
salesUuid?: null | string
serviceMerchantId?: null | number
staffName?: null | string
staffUuid?: null | string
// Upload task fields
status?: number | null
}
export type FileInfo = {
clientPath: string
error?: string
fileName: string
recordId: string
serverPath: null | string
status: number
}
export type UploadOssResponse = {
requestUrls?: null | string[]
}
export type UploadOssData = {
res?: null | UploadOssResponse
}
export type UploadPayloadData = {
oss?: null | UploadOssData
}
export type UploadResultPayload = {
code?: null | number
data?: null | UploadPayloadData
fileName?: null | string
filePath?: null | string
message?: null | string
recordId?: null | string
status?: number | null
}
export type UploadResultDetail = {
data?: null | UploadResultPayload[]
}
export type UploadResult = {
detail?: null | UploadResultDetail
fileName?: null | string
filePath?: null | string
recordId?: null | string
status?: number | null
}
......@@ -10,7 +10,7 @@ import { logger } from "../logger/index.uts";
import { AliOSSUploadStrategy } from "./strategies/AliOSSUploadStrategy.uts";
import { AliUniUploadStrategy } from "./strategies/AliUniUploadStrategy.uts";
import { UniUploadStrategy } from "./strategies/UniUploadStrategy.uts";
import { UploadStrategyType } from "./types/index.uts";
import { UploadOptions, UploadResult, UploadStrategyType } from "./types/index.uts";
import { IUploadStrategy } from "./types/IUploadStrategy.uts";
/**
......@@ -63,9 +63,9 @@ class FileUploadService {
/**
* 上传文件
* @param options 配置对象
* @returns Promise<UTSJSONObject> 返回上传结果
* @returns Promise<UploadResult> 返回上传结果
*/
async upload(options: UTSJSONObject): Promise<UTSJSONObject> {
async upload(options: UploadOptions): Promise<UploadResult> {
return this.strategy.upload(options);
}
}
......
......@@ -5,6 +5,7 @@ import { OSS_CONFIG } from "@/config/oss.config.uts";
import { logger } from "../../logger/index.uts";
import { IUploadStrategy } from "../types/IUploadStrategy.uts";
import { UploadOptions, UploadResult } from "../types/index.uts";
/**
* 阿里云 OSS 上传策略基类
......@@ -19,14 +20,14 @@ export abstract class AliOSSBaseStrategy implements IUploadStrategy {
* @param token OSS Token 数据
* @param options 原始配置选项
*/
abstract doUpload(filePath: string, objectKey: string, token: OssTokenData, options: UTSJSONObject): Promise<UTSJSONObject>
abstract doUpload(filePath: string, objectKey: string, token: OssTokenData, options: UploadOptions): Promise<UploadResult>
/**
* 获取策略名称
*/
abstract getStrategyName(): string
async upload(options: UTSJSONObject): Promise<UTSJSONObject> {
async upload(options: UploadOptions): Promise<UploadResult> {
const filePath = options.getString("filePath");
if (filePath === null || filePath === "") {
throw new Error("filePath is required");
......
import type { OssTokenData } from "../types/oss.uts";
import { logger } from "../../logger/index.uts";
import { UploadOptions, UploadResult } from "../types/index.uts";
import { AliOSSBaseStrategy } from "./AliOSSBaseStrategy.uts";
/**
......@@ -12,7 +12,7 @@ export class AliOSSUploadStrategy extends AliOSSBaseStrategy {
super();
}
override async doUpload(filePath: string, objectKey: string, token: OssTokenData, options: UTSJSONObject): Promise<UTSJSONObject> {
override async doUpload(filePath: string, objectKey: string, token: OssTokenData, options: UploadOptions): Promise<UploadResult> {
throw new Error("AliOSSUploadStrategy is not implemented because uts-alioss plugin has been removed.");
}
......
import type { OssTokenData } from "../types/oss.uts";
import { logger } from "../../logger/index.uts";
import { AliOSSBaseStrategy } from "./AliOSSBaseStrategy.uts";
import { UploadOptions, UploadResult } from "../types/index.uts";
import { base64Encode, hmacSha1 } from "../utils/PureCrypto.uts";
import { AliOSSBaseStrategy } from "./AliOSSBaseStrategy.uts";
/**
* 阿里云 OSS 上传策略 (使用 uni.uploadFile)
......@@ -15,7 +16,7 @@ export class AliUniUploadStrategy extends AliOSSBaseStrategy {
super();
}
override async doUpload(filePath: string, objectKey: string, token: OssTokenData, options: UTSJSONObject): Promise<UTSJSONObject> {
override async doUpload(filePath: string, objectKey: string, token: OssTokenData, options: UploadOptions): Promise<UploadResult> {
const accessKeyId = token.lsaccessKeyId ?? "";
const accessKeySecret = token.lsaccessKeySecret ?? "";
const securityToken = token.securityToken ?? "";
......@@ -67,11 +68,12 @@ export class AliUniUploadStrategy extends AliOSSBaseStrategy {
const url = `${host}/${objectKey}`;
resolve({
const resObj = {
url,
objectKey,
strategy: "aliuni"
} as UTSJSONObject);
};
resolve(JSON.parse(JSON.stringify(resObj)) as UploadResult);
} else {
logger.error(`[AliUniUploadStrategy] 上传失败: statusCode=${res.statusCode}`, "FileUploadService");
reject(new Error(`Upload failed with status ${res.statusCode}`));
......
import { logger } from "../../logger/index.uts";
import { UploadOptions, UploadResult } from "../types/index.uts";
import { IUploadStrategy } from "../types/IUploadStrategy.uts";
/**
* uni.uploadFile 上传策略
*/
export class UniUploadStrategy implements IUploadStrategy {
async upload(options: UTSJSONObject): Promise<UTSJSONObject> {
async upload(options: UploadOptions): Promise<UploadResult> {
const filePath = options.getString("filePath");
if (filePath === null || filePath === "") {
throw new Error("filePath is required");
......@@ -29,12 +30,12 @@ export class UniUploadStrategy implements IUploadStrategy {
success: (res) => {
logger.info(`[UniUploadStrategy] 上传成功: ${res.statusCode}`, "FileUploadService");
let data: UTSJSONObject;
let data: UploadResult;
try {
if (typeof res.data === "string") {
data = JSON.parse(res.data as string) as UTSJSONObject;
data = JSON.parse(res.data as string) as UploadResult;
} else {
data = res.data as UTSJSONObject;
data = res.data as UploadResult;
}
} catch {
data = { rawData: res.data };
......
import { UploadOptions, UploadResult } from "./upload.uts";
/**
* 上传策略接口
*/
export interface IUploadStrategy {
upload(options: UTSJSONObject): Promise<UTSJSONObject>
upload(options: UploadOptions): Promise<UploadResult>
}
......@@ -3,6 +3,16 @@
*/
export enum UploadStrategyType {
ALI_OSS = "alioss",
UNI_UPLOAD = "uni",
ALI_UNI = "aliuni"
ALI_UNI = "aliuni",
UNI_UPLOAD = "uni"
}
/**
* 上传配置选项 (别名 UTSJSONObject 以保持灵活性)
*/
export type UploadOptions = UTSJSONObject;
/**
* 上传结果 (别名 UTSJSONObject 以保持灵活性)
*/
export type UploadResult = UTSJSONObject;
import { API_GET_RECORDER_MANAGER } from '../protocol.uts';
import { GetRecorderManager, RecorderManager, RecorderManagerOnStopResult, RecorderManagerStartOptions, IRecorderManagerFail } from '../interface.uts';
import { GetRecorderManager, RecorderManager, RecorderManagerOnStopResult, RecorderManagerOnStartResult, RecorderManagerStartOptions, IRecorderManagerFail } from '../interface.uts';
import { createFile } from './utils.uts';
export { RecorderManagerFailImpl } from "../unierror.uts"
import LogSelfV2 from "io.dcloud.uts.log.LogSelfV2";
import { RecorderManagerFailImpl, RecorderManagerUniErrors } from '../unierror.uts';
import { AudioRecorder, RecordingListener, RecordingFormat } from "uts.sdk.modules.uniRecorder";
export { RecorderManagerFailImpl }
// NOTE 避免被 vue Proxy 污染
const DEFAULT_DURATION = 1000 * 60
const MAX_DURATION = DEFAULT_DURATION * 10
......@@ -25,7 +26,6 @@ class RecorderManagerImpl implements RecorderManager, RecordingListener {
})
}
innerStart(options : RecorderManagerStartOptions) : void {
if (options == null) options = {} as RecorderManagerStartOptions
if (options.format == null) options.format = DEFAULT_FORMAT
if (options.duration == null) {
......@@ -85,8 +85,8 @@ class RecorderManagerImpl implements RecorderManager, RecordingListener {
this.manager.stopRecording()
}
startCallback : ((result : any) => void) | null = null
override onStart(options : (result : any) => void) : void {
startCallback : ((result : RecorderManagerOnStartResult) => void) | null = null
override onStart(options : (result : RecorderManagerOnStartResult) => void) : void {
this.startCallback = options
}
// override offStart() : void {
......@@ -149,7 +149,7 @@ class RecorderManagerImpl implements RecorderManager, RecordingListener {
// }
override onRecordingStarted() {
let res = new RecorderManagerOnStopResultCallback(this.manager.getFilePath()!)
let res = new RecorderManagerOnStartResultCallback(this.manager.getFilePath()!)
this.startCallback?.(res)
}
override onRecordingStopped() {
......@@ -172,6 +172,26 @@ class RecorderManagerImpl implements RecorderManager, RecordingListener {
}
}
class RecorderManagerOnStartResultCallback implements RecorderManagerOnStartResult, IJSONStringify, LogSelfV2 {
override filePath : string = ""
constructor(filePath : string) {
this.filePath = filePath
}
override toJSON() : Any {
var result : UTSJSONObject = new UTSJSONObject()
result.set("filePath", this.filePath)
return result
}
override toLogMap() : Map<String, Any> {
var map : Map<String, Any> = new Map<String, Any>()
map.set("filePath", this.filePath)
return map
}
}
class RecorderManagerOnStopResultCallback implements RecorderManagerOnStopResult, IJSONStringify, LogSelfV2 {
override tempFilePath : string = ""
......
import { API_GET_RECORDER_MANAGER } from '../protocol.uts';
import { GetRecorderManager, RecorderManager, RecorderManagerOnStopResult, RecorderManagerStartOptions, IRecorderManagerFail } from '../interface.uts';
import { GetRecorderManager, RecorderManager, RecorderManagerOnStopResult, RecorderManagerOnStartResult, RecorderManagerStartOptions, IRecorderManagerFail } from '../interface.uts';
import AVRecorder, { supportFormats as avRecorderSupportFormats, SupportFormat } from './AVRecorder.uts';
import { onRecorderStateChange, setRecordStateCallback, deleteRecordStateCallback } from './utils.uts';
import { RecorderManagerFailImpl } from '../unierror.uts'
......@@ -37,7 +37,7 @@ class RecorderManagerImpl implements RecorderManager {
RECORDER_MANAGER = null
}
}
onStart(options: (result: any) => void): void {
onStart(options: (result: RecorderManagerOnStartResult) => void): void {
setRecordStateCallback('start', options)
}
// onPause(options: (result: any) => void): void {
......
......@@ -14,8 +14,9 @@ import DCloudUniappRuntime
@objc(StateChangeRes)
@objcMembers
public class StateChangeRes : NSObject, RecorderManagerOnStopResult {
public class StateChangeRes : NSObject, RecorderManagerOnStopResult, RecorderManagerOnStartResult {
public var tempFilePath: String = ""
public var filePath: String = ""
public var errMsg: String?
public var frameBuffer: ArrayBuffer?
public var isLastFrame: Bool = false
......@@ -58,6 +59,7 @@ public enum UniAudioRecorderEvent {
}
typealias UniAudioRecorderEventCallback = (_ result: Any) -> Void
typealias UniAudioRecorderStartEventCallback = (_ result: RecorderManagerOnStartResult) -> Void
typealias UniAudioRecorderStopEventCallback = (_ result: RecorderManagerOnStopResult) -> Void
typealias UniAudioRecorderErrorEventCallback = (_ result: IRecorderManagerFail) -> Void
......@@ -89,6 +91,7 @@ public class UniAudioRecorderManager: NSObject, RecorderManager {
private var sampleRates: [Int32] = [8000, 11025, 12000, 16000, 22050, 24000, 32000, 44100, 48000]
private var eventCallbacks: [String: UniAudioRecorderEventCallback] = [:]
private var startEventCallback: UniAudioRecorderStartEventCallback?
private var stopEventCallback: UniAudioRecorderStopEventCallback?
private var errorEventCallBack: UniAudioRecorderErrorEventCallback?
......@@ -175,15 +178,17 @@ public class UniAudioRecorderManager: NSObject, RecorderManager {
dispatchEvent(event: .resume)
}
public func onStart(_ options: @escaping (Any) -> Void) {
addEvent(event: .start, eventCallback: options)
}
public func onPause(_ options: @escaping (Any) -> Void) {
addEvent(event: .pause, eventCallback: options)
}
public func onStop(_ options: @escaping (any RecorderManagerOnStopResult) -> Void) {
public func onStart(_ options: @escaping (RecorderManagerOnStartResult) -> Void) {
addStartEvent(event: .start, eventCallback: options)
}
public func onStop(_ options: @escaping (RecorderManagerOnStopResult) -> Void) {
addStopEvent(event: .stop, eventCallback: options)
}
......@@ -315,7 +320,8 @@ extension UniAudioRecorderManager {
let result = StateChangeRes()
result.tempFilePath = audioRecorder?.url.absoluteString ?? ""
dispatchEvent(event: .start, result: result)
result.filePath = audioRecorder?.url.absoluteString ?? ""
dispatchStartEvent(event: .start, result: result)
} else {
failedAction(1107604, errMsg: "录音启动失败,请对比采样率与编码码率是否匹配")
}
......@@ -443,6 +449,12 @@ extension UniAudioRecorderManager {
eventCallbacks.set(event.rawValue, eventCallback)
}
private func addStartEvent(event: UniAudioRecorderEvent, eventCallback: @escaping UniAudioRecorderStartEventCallback) {
if event.rawValue == UniAudioRecorderEvent.start.rawValue {
startEventCallback = eventCallback
}
}
private func addStopEvent(event: UniAudioRecorderEvent, eventCallback: @escaping UniAudioRecorderStopEventCallback) {
if event.rawValue == UniAudioRecorderEvent.stop.rawValue {
stopEventCallback = eventCallback
......@@ -456,6 +468,12 @@ extension UniAudioRecorderManager {
}
}
private func dispatchStartEvent(event: UniAudioRecorderEvent, result: RecorderManagerOnStartResult) {
if event.rawValue == UniAudioRecorderEvent.start.rawValue {
startEventCallback?(result)
}
}
private func dispatchStopEvent(event: UniAudioRecorderEvent, result: RecorderManagerOnStopResult) {
guard let _ = audioRecorder else { return }
if event.rawValue == UniAudioRecorderEvent.stop.rawValue {
......
import { GetRecorderManager, RecorderManager } from "../interface.uts"
import { GetRecorderManager, RecorderManager, RecorderManagerOnStopResult, RecorderManagerOnStartResult, RecorderManagerStartOptions, IRecorderManagerFail } from '../interface.uts';
export { RecorderManagerFailImpl } from '../unierror.uts'
export const getRecorderManagerX : GetRecorderManager = function () : RecorderManager {
......
......@@ -18,10 +18,13 @@ export type RecorderManagerStartOptions = {
export interface RecorderManagerOnStopResult {
tempFilePath : string
};
export interface RecorderManagerOnStartResult {
filePath : string
};
export interface RecorderManager {
start(options : RecorderManagerStartOptions) : void;
stop() : void;
onStart(options : (result : any) => void) : void;
onStart(options : (result : RecorderManagerOnStartResult) => void) : void;
onStop(options : (result : RecorderManagerOnStopResult) => void) : void;
onError(options: (result: IRecorderManagerFail) => void): void;
}
......
import { logger } from "@/services/logger/index.uts";
/**
* 全局错误处理函数
* @param error 错误对象
* @param module 模块名称,默认为 "Global"
* @param prefix 错误信息前缀,用于描述错误上下文
* @returns 格式化后的错误信息
*/
export function handleError(error: any | null, module: string = "Global", prefix: string = ""): string {
let errorMsg = "";
if (error === null) {
errorMsg = "Unknown error (null)";
} else if (typeof error === "string") {
errorMsg = error;
} else if (error instanceof Error) {
const msg = error.message;
errorMsg = msg === "" ? `Error with empty message: ${error.name}` : msg;
} else {
// 优先使用 toString() 获取错误信息,避免 JSON.stringify() 返回 "{}" (如 Java 异常对象)
const str = `${error}`;
if (str !== "[object Object]" && str !== "{}" && str !== "") {
errorMsg = str;
} else {
try {
const json = JSON.stringify(error);
errorMsg = (json === "{}" || json === '""') ? str : json;
} catch {
errorMsg = `Stringify failed: ${str}`;
}
}
}
const logMsg = prefix !== "" ? `${prefix} ${errorMsg}` : `Error: ${errorMsg}`;
// 记录错误日志
logger.error({ msg: logMsg }, module);
return errorMsg;
}
export * from "./storage.uts";
export * from "./common.uts";
export * from "./parse.uts";
export * from "./error.uts";
export * from "./permission.uts";
import { checkPermission, requestPermissions } from "@/uni_modules/permission-handler-plus";
import { handleError } from "./error.uts";
/**
* 确保已获取指定权限
* @param permissionName 权限名称 (如 "Microphone")
* @param hintText 权限被拒绝时的提示文本
* @returns Promise<boolean> true: 已获取权限, false: 未获取权限
*/
export async function ensurePermission(permissionName: string, hintText: string): Promise<boolean> {
return new Promise((resolve) => {
try {
checkPermission(permissionName, (result) => {
if (result === "granted") {
resolve(true);
} else {
requestPermissions({
names: [permissionName],
success: (res) => {
let granted = false;
// res is string[]
const resList = res as string[];
resList.forEach((v: string) => {
if (v == "granted") {
granted = true;
}
});
if (granted) {
resolve(true);
} else {
uni.showToast({
title: hintText,
icon: "none"
});
resolve(false);
}
},
fail: (err) => {
handleError(err, "PermissionUtils", `请求权限失败 (${permissionName}):`);
resolve(false);
}
});
}
});
} catch (error) {
handleError(error, "PermissionUtils", `检查权限异常 (${permissionName}):`);
resolve(false);
}
});
}
/**
* 确保已获取多个指定权限
* @param permissionNames 权限名称列表
* @param hintText 权限被拒绝时的提示文本
* @returns Promise<boolean> true: 已获取所有权限, false: 未获取权限
*/
export async function ensurePermissions(permissionNames: string[], hintText: string): Promise<boolean> {
if (permissionNames.length === 0) return true;
// 简单实现:逐个检查/请求,或者一次性请求
// 这里的 requestPermissions 似乎支持数组,所以我们可以直接调用 requestPermissions
// 但是 checkPermission 似乎只支持单个 string (根据 index.uts 的签名)
// export function checkPermission(permission: string, complete: (result: string) => void): void
// 如果需要检查多个,可能需要先检查一遍,如果有未授权的,再统一请求
// 简化策略:直接调用 requestPermissions 请求所有,它内部应该会处理已授权的情况?
// 或者我们可以先 check 第一个,如果没授权就请求所有。
// 但 permission-handler-plus 的 requestPermissions 似乎是请求弹窗。
return new Promise((resolve) => {
try {
requestPermissions({
names: permissionNames,
success: (res) => {
let allGranted = true;
const resList = res as string[];
// 假设 resList 顺序对应 permissionNames 或者只是结果列表
// 如果有一个不是 granted,则失败
for (let i = 0; i < resList.length; i++) {
if (resList[i] != "granted") {
allGranted = false;
break;
}
}
if (allGranted) {
resolve(true);
} else {
uni.showToast({
title: hintText,
icon: "none"
});
resolve(false);
}
},
fail: (err) => {
handleError(err, "PermissionUtils", `请求权限失败 (${permissionNames.join(", ")}):`);
resolve(false);
}
});
} catch (error) {
handleError(error, "PermissionUtils", `请求权限异常 (${permissionNames.join(", ")}):`);
resolve(false);
}
});
}
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!