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