Commit 22119ae0 by liimin

feat(uploader): 新增阿里云OSS上传策略基类和uni.uploadFile直传策略

重构上传模块,提取公共逻辑到AliOSSBaseStrategy基类
新增AliUniUploadStrategy使用uni.uploadFile直传OSS,避免原生SDK兼容性问题
完善类型定义,统一导出上传服务接口
更新manifest版本号至112
1 parent 39bfb0f6
Showing 44 changed files with 1239 additions and 209 deletions
import * as receiption from "./receiption.uts";
export {
receiption
}
import http from '@/api/request/http.uts' import http from '@/api/request/http.uts'
import type { OssTokenData } from '../composables/uploader/types/oss.uts'
export function getToken(params: UTSJSONObject): Promise<UTSJSONObject> { export async function getToken(params: UTSJSONObject): Promise<UTSJSONObject> {
const data: UTSJSONObject = { const data: UTSJSONObject = {
projectName: 'boutique', projectName: 'boutique',
...params ...params
} }
return http.fetch('dj.api.smartcarlife.recepiton.customer.oss.getToken', data) as Promise<UTSJSONObject> const d = http.fetch('dj.api.smartcarlife.recepiton.customer.oss.getToken', data,false, 'dj')
// console.log("🚀 ~ getToken ~ d:", d)
return d
} }
...@@ -9,12 +9,13 @@ ...@@ -9,12 +9,13 @@
*/ */
import SQLite from './sqlite.uts' import SQLite from './sqlite.uts'
import { logger } from '../logger/index.uts' import { logger } from '../logger/index.uts'
import type { IDBBase } from '../recorder/types/db.uts'
/** /**
* 记录管理器基类 * 记录管理器基类
* 用于管理记录列表 * 用于管理记录列表
*/ */
class DBBase { export default class DBBase implements IDBBase {
db: SQLite | null = null db: SQLite | null = null
db_name = 'zyzs' db_name = 'zyzs'
db_version = '1.0' db_version = '1.0'
...@@ -67,7 +68,7 @@ class DBBase { ...@@ -67,7 +68,7 @@ class DBBase {
* @param {Object} record - 要添加的新记录对象 * @param {Object} record - 要添加的新记录对象
* @returns {Array} - 包含新记录的更新后的记录列表 * @returns {Array} - 包含新记录的更新后的记录列表
*/ */
async addRecord(record: UTSJSONObject) { async addRecord(record: UTSJSONObject): Promise<void> {
await this.db!.insert(this.table_name, record) await this.db!.insert(this.table_name, record)
} }
...@@ -123,7 +124,7 @@ class DBBase { ...@@ -123,7 +124,7 @@ class DBBase {
* @param {Array} records - 要设置的记录列表 * @param {Array} records - 要设置的记录列表
* @returns {void} - 此函数不返回任何值 * @returns {void} - 此函数不返回任何值
*/ */
async setRecords(records: UTSJSONObject[]) { async setRecords(records: UTSJSONObject[]): Promise<void> {
// 串行执行还是并行?forEach 是同步的,里面的 async 不会阻塞 // 串行执行还是并行?forEach 是同步的,里面的 async 不会阻塞
// 应该用 for of 或者 Promise.all // 应该用 for of 或者 Promise.all
for (const record of records) { for (const record of records) {
...@@ -177,7 +178,7 @@ class DBBase { ...@@ -177,7 +178,7 @@ class DBBase {
* *
* @returns {void} - 此函数不返回任何值 * @returns {void} - 此函数不返回任何值
*/ */
async clearRecords() { async clearRecords(): Promise<void> {
// delete 需要 where 参数,这里可能是清空表 // delete 需要 where 参数,这里可能是清空表
// sqlite.uts 的 delete 实现:`DELETE FROM ${tabName} WHERE ${whereStr}` // sqlite.uts 的 delete 实现:`DELETE FROM ${tabName} WHERE ${whereStr}`
// 如果 where 为空,SQL 会变成 `DELETE FROM ${tabName} WHERE ` -> 语法错误 // 如果 where 为空,SQL 会变成 `DELETE FROM ${tabName} WHERE ` -> 语法错误
...@@ -212,4 +213,3 @@ class DBBase { ...@@ -212,4 +213,3 @@ class DBBase {
this.db!.drop(this.table_name) this.db!.drop(this.table_name)
} }
} }
export default DBBase
...@@ -4,14 +4,14 @@ ...@@ -4,14 +4,14 @@
* @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-01 02:56:19 * @LastEditTime: 2026-03-01 17:38:52
* @FilePath: \venus\apps\uniappX\uniapp-x-tape\composables\recorder\DBRecord.uts * @FilePath: \venus\apps\uniappX\uniapp-x-tape\composables\recorder\DBRecord.uts
*/ */
import DBBase from '../db/DBBase.uts' import DBBase from '../db/DBBase.uts'
import { logger } from '../logger/index.uts' import { logger } from '../logger/index.uts'
import type { RecordData, IDBRecord } from './types'
const TABLE_NAME = 'records' const TABLE_NAME = 'records'
const TABLE_COLUMNS = [ const TABLE_COLUMNS = [
`id TEXT PRIMARY KEY`, `id TEXT PRIMARY KEY`,
`staffUuid TEXT`, `staffUuid TEXT`,
`staffName TEXT`, `staffName TEXT`,
...@@ -42,7 +42,7 @@ const TABLE_COLUMNS = [ ...@@ -42,7 +42,7 @@ const TABLE_COLUMNS = [
'recordStatus INTEGER DEFAULT 1' // 0: recording, 1: completed 'recordStatus INTEGER DEFAULT 1' // 0: recording, 1: completed
] ]
class DBRecord extends DBBase { class DBRecord extends DBBase implements IDBRecord {
private _initPromise: Promise<boolean> | null = null private _initPromise: Promise<boolean> | null = null
private static instance: DBRecord | null = null private static instance: DBRecord | null = null
...@@ -81,7 +81,7 @@ class DBRecord extends DBBase { ...@@ -81,7 +81,7 @@ class DBRecord extends DBBase {
/** /**
* 确保表字段存在(用于版本升级) * 确保表字段存在(用于版本升级)
*/ */
async ensureColumns() { async ensureColumns(): Promise<void> {
try { try {
// 优化:只查询一次表结构 // 优化:只查询一次表结构
const columnInfo = await this.db!.selectSql(`PRAGMA table_info(${this.table_name})`) const columnInfo = await this.db!.selectSql(`PRAGMA table_info(${this.table_name})`)
...@@ -128,15 +128,73 @@ class DBRecord extends DBBase { ...@@ -128,15 +128,73 @@ class DBRecord extends DBBase {
/** /**
* 获取已完成的接待记录 (recordStatus = 1) * 获取已完成的接待记录 (recordStatus = 1)
*/ */
async getCompletedRecords(): Promise<any[]> { async getCompletedRecords(): Promise<RecordData[]> {
return this.getRecordsByWhere({ recordStatus: 1 }) const records = await this.getRecordsByWhere({ recordStatus: 1 })
const res: RecordData[] = []
records.forEach((item: any) => {
try {
const itemObj = item as UTSJSONObject
// Handle JSON string fields
const listFields = ['receptionCustomerPaySourceList', 'receptionCustomerMaterialPointList', 'recordUrlList']
listFields.forEach(field => {
const val = itemObj[field]
if (typeof val === 'string') {
try {
itemObj[field] = JSON.parse(val)
} catch (e) {
logger.error(`DBRecord: Failed to parse field ${field}: ${val}`, "DBRecord")
itemObj[field] = null
}
}
})
const record = JSON.parse<RecordData>(JSON.stringify(itemObj))
if (record != null) {
res.push(record)
}
} catch (e) {
logger.error(`DBRecord: Failed to parse record: ${JSON.stringify(item)} error: ${e}`, "DBRecord")
}
})
return res
} }
/** /**
* 获取进行中/临时的接待记录 (recordStatus = 0) * 获取进行中/临时的接待记录 (recordStatus = 0)
*/ */
async getTempRecords(): Promise<any[]> { async getTempRecords(): Promise<RecordData[]> {
return this.getRecordsByWhere({ recordStatus: 0 }) const records = await this.getRecordsByWhere({ recordStatus: 0 })
const res: RecordData[] = []
records.forEach((item: any) => {
try {
const itemObj = item as UTSJSONObject
// Handle JSON string fields
const listFields = ['receptionCustomerPaySourceList', 'receptionCustomerMaterialPointList', 'recordUrlList']
listFields.forEach(field => {
const val = itemObj[field]
if (typeof val === 'string') {
try {
itemObj[field] = JSON.parse(val)
} catch (e) {
logger.error(`DBRecord: Failed to parse field ${field}: ${val}`, "DBRecord")
itemObj[field] = null
}
}
})
const record = JSON.parse<RecordData>(JSON.stringify(itemObj))
if (record != null) {
res.push(record)
}
} catch (e) {
logger.error(`DBRecord: Failed to parse record: ${JSON.stringify(item)} error: ${e}`, "DBRecord")
}
})
return res
} }
} }
export default DBRecord export default DBRecord
...@@ -4,7 +4,7 @@ ...@@ -4,7 +4,7 @@
* @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-01 11:30:48 * @LastEditTime: 2026-03-01 18:34:16
* @FilePath: \venus\apps\uniappX\uniapp-x-tape\composables\recorder\RecordSave.uts * @FilePath: \venus\apps\uniappX\uniapp-x-tape\composables\recorder\RecordSave.uts
*/ */
import Queue from '../../utils/Queue.uts' import Queue from '../../utils/Queue.uts'
...@@ -15,7 +15,7 @@ import { convertDateTimeFormat } from '../../utils/index.uts' ...@@ -15,7 +15,7 @@ import { convertDateTimeFormat } from '../../utils/index.uts'
import FileUploadService from '../uploader/FileUploadService.uts' import FileUploadService from '../uploader/FileUploadService.uts'
import { logger } from '../logger/index.uts' import { logger } from '../logger/index.uts'
import DBRecord from './DBRecord.uts' import DBRecord from './DBRecord.uts'
// import Record from './types' import type { RecordData } from './types'
// 模拟 utils // 模拟 utils
function deepClone(obj: any | null): any | null { function deepClone(obj: any | null): any | null {
if (obj == null) return null if (obj == null) return null
...@@ -292,7 +292,7 @@ class RecordSave { ...@@ -292,7 +292,7 @@ class RecordSave {
_isTargetFile(item: UTSJSONObject, fileInfo: UTSJSONObject): boolean { _isTargetFile(item: UTSJSONObject, fileInfo: UTSJSONObject): boolean {
const fileName = fileInfo['fileName'] as string const fileName = fileInfo['fileName'] as string
const clientPath = fileInfo['clientPath'] as string const clientPath = fileInfo['clientPath'] as string
const itemFile = item['file'] as string const itemFile = (item['file'] ?? item['filePath']) as string
if (!this.isLegalFile(fileName)) return !this.isLegalFile(itemFile) if (!this.isLegalFile(fileName)) return !this.isLegalFile(itemFile)
return itemFile == clientPath || itemFile.endsWith(fileName) return itemFile == clientPath || itemFile.endsWith(fileName)
...@@ -347,9 +347,9 @@ class RecordSave { ...@@ -347,9 +347,9 @@ class RecordSave {
async getRecordsSnapshotFlatten(): Promise<UTSJSONObject[]> { async getRecordsSnapshotFlatten(): Promise<UTSJSONObject[]> {
// await uni.$dbReady // UTS 中没有 $dbReady // await uni.$dbReady // UTS 中没有 $dbReady
const dbRecord = await this.getDbRecord() const dbRecord = await this.getDbRecord()
let _records = await dbRecord.getCompletedRecords() let _records: RecordData[] = await dbRecord.getCompletedRecords()
return await this.flattenData(_records ?? []) return await this.flattenData(_records ?? [])
} }
/** /**
* 上传文件记录 * 上传文件记录
...@@ -576,17 +576,17 @@ class RecordSave { ...@@ -576,17 +576,17 @@ class RecordSave {
return key != "" && this._blackList.has(key) return key != "" && this._blackList.has(key)
} }
async flattenData(records: any[]): Promise<UTSJSONObject[]> { async flattenData(records: RecordData[]): Promise<UTSJSONObject[]> {
console.log("🚀 ~ RecordSave ~ flattenData ~ records:", records)
const result: UTSJSONObject[] = [] const result: UTSJSONObject[] = []
try { try {
for (const cur of records) { for (const cur of records) {
const curObj = cur as UTSJSONObject // const curObj = cur as UTSJSONObject // Removed cast
const recordUrlListRaw = curObj['recordUrlList'] as UTSJSONObject[] const recordUrlListRaw = cur.recordUrlList ?? []
const recordUrlList = this.urlListFilter(recordUrlListRaw) // Filter RecordFile[]
const recordUrlList = recordUrlListRaw.filter(item => (item.file != null && item.file !== "") || (item.filePath !== ""))
// 1. 记录级别的黑名单检查 (针对空文件等整条记录的问题) // 1. 记录级别的黑名单检查 (针对空文件等整条记录的问题)
const recordId = curObj['id'] as string const recordId = cur.id
if (this._isInBlackList(recordId)) { if (this._isInBlackList(recordId)) {
continue continue
} }
...@@ -597,10 +597,10 @@ class RecordSave { ...@@ -597,10 +597,10 @@ class RecordSave {
} }
for (const file of recordUrlList) { for (const file of recordUrlList) {
try { try {
const fileStatus = file['status'] as number const fileStatus = file.status ?? 0
if (fileStatus === FileStatus.Uploaded || fileStatus === FileStatus.Completed) continue if (fileStatus === FileStatus.Uploaded || fileStatus === FileStatus.Completed) continue
const fileUrl = file['file'] as string const fileUrl = (file.file ?? file.filePath)
const aFullPath = fileUrl.split('/') const aFullPath = fileUrl.split('/')
const fileName = aFullPath.pop()! const fileName = aFullPath.pop()!
const filePath = aFullPath.join('/') + '/' const filePath = aFullPath.join('/') + '/'
...@@ -611,7 +611,6 @@ class RecordSave { ...@@ -611,7 +611,6 @@ class RecordSave {
file2Up['filePath'] = filePath file2Up['filePath'] = filePath
const fileExists = await this.checkFileExists(fileUrl) const fileExists = await this.checkFileExists(fileUrl)
console.log("🚀 ~ RecordSave ~ flattenData ~ fileExists:", fileExists)
if (!fileExists) { if (!fileExists) {
logger.error(`【接待记录保存服务】 == 记录中有语音文件地址,但是文件不存在, recordId: ${recordId}, fileUrl: ${fileUrl}`, "RecordSave") logger.error(`【接待记录保存服务】 == 记录中有语音文件地址,但是文件不存在, recordId: ${recordId}, fileUrl: ${fileUrl}`, "RecordSave")
file2Up['status'] = FileStatus.NotExist file2Up['status'] = FileStatus.NotExist
...@@ -619,7 +618,7 @@ class RecordSave { ...@@ -619,7 +618,7 @@ class RecordSave {
result.push(file2Up) result.push(file2Up)
} catch (error) { } catch (error) {
const errorMsg = typeof error === 'string' ? error : `${error}` const errorMsg = typeof error === 'string' ? error : `${error}`
logger.error(`【接待记录保存服务】 == 解析处理文件异常 error: ${errorMsg}, recordId: ${recordId}, file: ${file}`, "RecordSave") 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
} }
...@@ -637,7 +636,7 @@ class RecordSave { ...@@ -637,7 +636,7 @@ class RecordSave {
if (!Array.isArray(urlList)) { if (!Array.isArray(urlList)) {
return [] return []
} }
const __list = urlList.filter(item => item['file'] != null && item['file'] != "") const __list = urlList.filter(item => (item['file'] != null && item['file'] != "") || (item['filePath'] != null && item['filePath'] != ""))
return __list return __list
} }
......
...@@ -7,7 +7,7 @@ import { logger } from '../logger/index.uts' ...@@ -7,7 +7,7 @@ import { logger } from '../logger/index.uts'
import { checkPermission, requestPermissions } from '@/uni_modules/permission-handler-plus' import { checkPermission, requestPermissions } from '@/uni_modules/permission-handler-plus'
import { watch } from 'vue' import { watch } from 'vue'
import { storage } from '../../utils/storage.uts' import { storage } from '../../utils/storage.uts'
import { RecordFile } from './types' import { RecordFile, RecordData } from './types'
import { StartRecordSuccess, StopRecordSuccess, StartRecordOptions } from '@/uni_modules/uts-recorder' import { StartRecordSuccess, StopRecordSuccess, StartRecordOptions } from '@/uni_modules/uts-recorder'
type DebounceTimer = { type DebounceTimer = {
fn: () => void fn: () => void
...@@ -25,7 +25,7 @@ class RecordService { ...@@ -25,7 +25,7 @@ class RecordService {
audioManager: AudioManager | null = null audioManager: AudioManager | null = null
record: TempRecord | null = null record: TempRecord | null = null
tempRecordDto: UTSJSONObject | null = null tempRecordDto: RecordData | null = null
debounceTimers: Map<string, DebounceTimer> = new Map() debounceTimers: Map<string, DebounceTimer> = new Map()
_startAudioPromise: Promise<boolean> | null = null _startAudioPromise: Promise<boolean> | null = null
...@@ -165,7 +165,7 @@ class RecordService { ...@@ -165,7 +165,7 @@ class RecordService {
} }
return dynamicAttrs return dynamicAttrs
} catch (e) { } catch (e) {
console.log("🚀 ~ RecordService ~ attributesProvider ~ e:", e) logger.error({ msg: `【录音服务RecordService】 == attributesProvider 异常: ${e}` }, "RecordService")
return {} return {}
} }
} }
...@@ -302,7 +302,7 @@ class RecordService { ...@@ -302,7 +302,7 @@ class RecordService {
} }
isReceptioning(): boolean { isReceptioning(): boolean {
return (this.audioManager?.isRecording ?? false) || (this.record?.currentRecord?.getNumber('endReasonType') == 1) return (this.audioManager?.isRecording ?? false) || (this.record?.currentRecord?.endReasonType == 1)
} }
reset() { reset() {
...@@ -312,52 +312,8 @@ class RecordService { ...@@ -312,52 +312,8 @@ class RecordService {
} }
initDto() { initDto() {
const userInfoRaw = storage.get('userInfo') // initialize as RecordData or null
let userInfo: UTSJSONObject | null = null this.tempRecordDto = null
if (userInfoRaw != null) {
if (typeof userInfoRaw === 'string') {
const userInfoStr = userInfoRaw as string
if (userInfoStr.length > 0) {
try {
const parsed = JSON.parse(userInfoStr)
if (parsed != null) {
userInfo = parsed as UTSJSONObject
}
} catch (e) {
console.error(`RecordService initDto parse error: ${e}`)
userInfo = null
}
}
} else {
userInfo = userInfoRaw as UTSJSONObject
}
}
const shopMerchantId = userInfo?.getString('shopMerchantId')
const phone = userInfo?.getString('phone')
const sceneType = userInfo?.getNumber('sceneType')
const uuid = userInfo?.getString('uuid')
const name = userInfo?.getString('name')
const merchantId = userInfo?.getString('merchantId')
const channelType = userInfo?.getNumber('channelType')
const merchantName = userInfo?.getString('merchantName')
const deviceInfo = uni.getDeviceInfo()
const appCode = deviceInfo.deviceId
this.tempRecordDto = {
staffUuid: uuid,
staffName: name,
serviceMerchantId: merchantId,
endReasonType: 0, //原因 1.异常 0.正常
loginPhone: phone,
appCode,
merchantId: shopMerchantId,
merchantName,
bussinessType: this.getBussinessType(sceneType),
channelType: channelType ?? 1 //1问界 2 比亚迪 3 其他
}
} }
debounce(key: string, fn: () => void, delay: number) { debounce(key: string, fn: () => void, delay: number) {
...@@ -430,9 +386,9 @@ class RecordService { ...@@ -430,9 +386,9 @@ class RecordService {
const track = receptionTrack as UTSJSONObject const track = receptionTrack as UTSJSONObject
if (track == null) return if (track == null) return
const merchantId = this.tempRecordDto?.getString('merchantId') const merchantId = this.tempRecordDto?.merchantId
const staffUuid = this.tempRecordDto?.getString('staffUuid') const staffUuid = this.tempRecordDto?.staffUuid
const staffName = this.tempRecordDto?.getString('staffName') const staffName = this.tempRecordDto?.staffName
const userInfo = storage.get('userInfo') as UTSJSONObject | null const userInfo = storage.get('userInfo') as UTSJSONObject | null
const sceneType = userInfo?.getNumber('sceneType') const sceneType = userInfo?.getNumber('sceneType')
...@@ -442,14 +398,21 @@ class RecordService { ...@@ -442,14 +398,21 @@ class RecordService {
const map = track.toMap() const map = track.toMap()
map.forEach((v, k) => { map.forEach((v, k) => {
const point = v as UTSJSONObject const point = v as UTSJSONObject
// Convert to JSON object to allow dynamic property assignment
const newPoint = { const newPoint = {
...point,
merchantId, merchantId,
staffUuid, staffUuid,
staffName, staffName,
businessScene: sceneType businessScene: sceneType
} }
receptionCustomerMaterialPointList.push(newPoint) const newPointJson = JSON.parse(JSON.stringify(newPoint)) as UTSJSONObject
const pMap = point.toMap()
pMap.forEach((pv, pk) => {
newPointJson[pk] = pv
})
receptionCustomerMaterialPointList.push(newPointJson)
}) })
if (this.record != null) { if (this.record != null) {
......
/**
* 录音功能模块入口
* 统一导出录音服务、音频管理、记录保存等核心功能
*/
// 导出录音服务单例
export { default as RecordService } from './RecordService.uts'
// 导出音频管理器
export { default as AudioManager } from './AudioManager.uts'
// 导出记录保存服务
export { default as RecordSave } from './RecordSave.uts'
// 导出临时记录管理
export { default as TempRecord } from './TempRecord.uts'
// 导出数据库记录管理
export { default as DBRecord } from './DBRecord.uts'
// 导出相关类型定义
export * from './types/index.uts'
// 导出常量定义
export * from './common/constants.uts'
...@@ -13,6 +13,8 @@ export type AudioEvents = { ...@@ -13,6 +13,8 @@ export type AudioEvents = {
} }
export type RecordFile = { export type RecordFile = {
filePath: string filePath: string
file?: string
status?: number
} }
// 移除 RecorderStrategy,因为不再使用策略模式 // 移除 RecorderStrategy,因为不再使用策略模式
import { RecordData } from './record'
export interface IDBBase {
init(): Promise<boolean>
addRecord(record: UTSJSONObject): Promise<void>
removeRecord(id: any): Promise<any>
getRecordById(id: any): Promise<UTSJSONObject | null>
getRecordsByWhere(where: UTSJSONObject): Promise<any[]>
getRecords(): Promise<any[]>
setRecords(records: UTSJSONObject[]): Promise<void>
updateRecord(setData: UTSJSONObject, where: UTSJSONObject | null): Promise<any>
isOpen(): Promise<boolean>
clearRecords(): Promise<void>
}
export interface IDBRecord extends IDBBase {
ensureColumns(): Promise<void>
getCompletedRecords(): Promise<RecordData[]>
getTempRecords(): Promise<RecordData[]>
}
export * from './audio' export * from './audio'
export * from './record'
export * from './db'
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
}
import { logger } from '../logger/index.uts'
import { IUploadStrategy } from './IUploadStrategy.uts'
import { getToken } from '@/api/receiption.uts'
import type { OssTokenResponse, OssTokenData } from './types/oss.uts'
/**
* 阿里云 OSS 上传策略基类
* 封装了获取 Token、解析 Token、生成 objectKey 等公共逻辑
*/
export abstract class AliOSSBaseStrategy implements IUploadStrategy {
async upload(options: UTSJSONObject): Promise<UTSJSONObject> {
const filePath = options.getString('filePath')
if (filePath == null || filePath == "") {
throw new Error("filePath is required")
}
const strategyName = this.getStrategyName()
logger.info(`[${strategyName}] 开始上传文件: ${filePath}`, "FileUploadService")
try {
// 1. 获取 OSS Token
const responseJson = await getToken({})
let token: OssTokenData | null = null
// 手动解析 JSON,避免 Gson 强类型检查导致的 "non-nullable member" 错误
const dataObj = responseJson['data']
if (dataObj != null && typeof dataObj == 'object') {
// 标准结构: { code, msg, data: {...} }
const data = dataObj as UTSJSONObject
token = {
lsaccessKeyId: data.getString('lsaccessKeyId'),
lsaccessKeySecret: data.getString('lsaccessKeySecret'),
securityToken: data.getString('securityToken'),
bucketName: data.getString('bucketName'),
region: data.getString('region')
} as OssTokenData
} else {
// 尝试直接映射: { lsaccessKeyId, ... }
const lsaccessKeyId = responseJson.getString('lsaccessKeyId')
if (lsaccessKeyId != null) {
token = {
lsaccessKeyId: lsaccessKeyId,
lsaccessKeySecret: responseJson.getString('lsaccessKeySecret'),
securityToken: responseJson.getString('securityToken'),
bucketName: responseJson.getString('bucketName'),
region: responseJson.getString('region')
} as OssTokenData
}
}
if (token == null || token.lsaccessKeyId == null || token.lsaccessKeyId == "") {
// 记录原始响应以便调试 (使用 console.error 避免 logger 可能的异常)
console.error(`[${strategyName}] Token响应无效:`, JSON.stringify(responseJson))
throw new Error("Token response is invalid or null")
}
// 2. 确定 objectKey
let objectKey = options.getString('objectKey')
if (objectKey == null || objectKey == "") {
const fileName = filePath.substring(filePath.lastIndexOf('/') + 1)
objectKey = `uploads/${Date.now()}/${fileName}`
}
// 3. 执行具体上传逻辑
console.log(`[${strategyName}] Token获取成功,准备上传: ${objectKey}`)
return await this.doUpload(filePath, objectKey, token, options)
} catch (error) {
const errorMsg = typeof error === 'string' ? error : `${error}`
console.error(`[${strategyName}] 上传异常: ${errorMsg}`)
// logger.error(`[${strategyName}] 上传异常: ${errorMsg}`, "FileUploadService")
throw error
}
}
/**
* 获取策略名称
*/
abstract getStrategyName(): string
/**
* 执行具体上传逻辑
* @param filePath 文件路径
* @param objectKey OSS 对象键
* @param token OSS Token 数据
* @param options 原始配置选项
*/
abstract doUpload(filePath: string, objectKey: string, token: OssTokenData, options: UTSJSONObject): Promise<UTSJSONObject>
}
import { UploadOptions, upload, initConfig, OSSConfig, UploadSuccessResult, UploadFailResult } from "@/uni_modules/uts-alioss"; import { UploadOptions, upload, initConfig, OSSConfig, UploadSuccessResult, UploadFailResult } from "@/uni_modules/uts-alioss";
import { logger } from '../logger/index.uts' import { logger } from '../logger/index.uts'
import { getToken } from '@/api/receiption.uts' import { AliOSSBaseStrategy } from './AliOSSBaseStrategy.uts'
import { IUploadStrategy } from './IUploadStrategy.uts' import type { OssTokenData } from './types/oss.uts'
/** /**
* 阿里云 OSS 上传策略 * 阿里云 OSS 上传策略 (原生 SDK)
*/ */
export class AliOSSUploadStrategy implements IUploadStrategy { export class AliOSSUploadStrategy extends AliOSSBaseStrategy {
async upload(options: UTSJSONObject): Promise<UTSJSONObject> {
const filePath = options.getString('filePath') constructor() {
super()
if (filePath == null || filePath == "") { }
throw new Error("filePath is required")
}
logger.info(`[AliOSSUploadStrategy] 开始上传文件: ${filePath}`, "FileUploadService") override getStrategyName(): string {
return "AliOSSUploadStrategy"
}
try { override async doUpload(filePath: string, objectKey: string, token: OssTokenData, options: UTSJSONObject): Promise<UTSJSONObject> {
// 获取 OSS Token const lsaccessKeySecret:string = token.lsaccessKeySecret ?? ""
const token = await getToken({}) const securityToken:string = token.securityToken ?? ""
const lsaccessKeyId:string = token.lsaccessKeyId ?? ""
const lsaccessKeySecret = token.getString('lsaccessKeySecret') // 使用默认值如果未定义
const securityToken = token.getString('securityToken') const defaultBucket:string = token.bucketName ?? 'glsk-oss'
const lsaccessKeyId = token.getString('lsaccessKeyId') const defaultRegion:string = token.region ?? 'oss-cn-shenzhen'
const bucketName = token.getString('bucketName') ?? 'your-bucket-name'
const region = token.getString('region') ?? 'oss-cn-hangzhou'
// 允许 options 覆盖默认配置 // 允许 options 覆盖默认配置
const targetBucket = options.getString('bucketName') ?? bucketName const bucketName:string = options.getString('bucketName') ?? defaultBucket
const targetRegion = options.getString('region') ?? region const region:string = options.getString('region') ?? defaultRegion
// 配置 OSS // 配置 OSS
const ossConfig = { const ossConfig = {
endpoint: `https://${targetRegion}.aliyuncs.com`, endpoint: `https://${region}.aliyuncs.com`,
bucketName: targetBucket, bucketName: bucketName,
accessKeyId: lsaccessKeyId ?? '', // 必填 accessKeyId: lsaccessKeyId , // 必填
accessKeySecret: lsaccessKeySecret ?? '', // 必填 accessKeySecret: lsaccessKeySecret , // 必填
securityToken: securityToken // 选填 securityToken: securityToken // 选填
} as OSSConfig } as OSSConfig
initConfig(ossConfig) initConfig(ossConfig)
// 确定 objectKey
let objectKey = options.getString('objectKey')
if (objectKey == null || objectKey == "") {
// 如果未指定,使用文件名
const fileName = filePath.substring(filePath.lastIndexOf('/') + 1)
objectKey = `uploads/${Date.now()}/${fileName}`
}
// 使用 await 等待 Promise 结果 // 使用 await 等待 Promise 结果
const result = await new Promise<UTSJSONObject>((resolve, reject) => { const result = await new Promise<UTSJSONObject>((resolve, reject) => {
const uploadOptions = { const uploadOptions = {
...@@ -72,11 +63,5 @@ export class AliOSSUploadStrategy implements IUploadStrategy { ...@@ -72,11 +63,5 @@ export class AliOSSUploadStrategy implements IUploadStrategy {
}) })
return result return result
} catch (error) {
const errorMsg = typeof error === 'string' ? error : `${error}`
logger.error(`[AliOSSUploadStrategy] 上传异常: ${errorMsg}`, "FileUploadService")
throw error
}
} }
} }
import { logger } from '../logger/index.uts'
import { AliOSSBaseStrategy } from './AliOSSBaseStrategy.uts'
import type { OssTokenData } from './types/oss.uts'
import { base64Encode, hmacSha1 } from './utils/PureCrypto.uts'
/**
* 阿里云 OSS 上传策略 (使用 uni.uploadFile)
* 替代原生 SDK 方案,避免兼容性问题
* 使用纯 UTS 实现的加密工具,支持全平台
*/
export class AliUniUploadStrategy extends AliOSSBaseStrategy {
constructor() {
super()
}
override getStrategyName(): string {
return "AliUniUploadStrategy"
}
override async doUpload(filePath: string, objectKey: string, token: OssTokenData, options: UTSJSONObject): Promise<UTSJSONObject> {
const accessKeyId = token.lsaccessKeyId ?? ""
const accessKeySecret = token.lsaccessKeySecret ?? ""
const securityToken = token.securityToken ?? ""
// 默认配置
const defaultBucket = token.bucketName ?? 'glsk-oss'
const defaultRegion = token.region ?? 'oss-cn-shenzhen'
// 允许 options 覆盖
const bucketName = options.getString('bucketName') ?? defaultBucket
const region = options.getString('region') ?? defaultRegion
// 3. 生成 Policy 和 Signature
const host = `https://${bucketName}.${region}.aliyuncs.com`
// 构造 policy
const expiration = new Date(Date.now() + 30 * 60 * 1000).toISOString() // 30分钟后过期
const policyObj = {
expiration: expiration,
conditions: [
{ bucket: bucketName },
["content-length-range", 0, 1048576000], // 限制大小 1GB
["eq", "$key", objectKey],
["eq", "$x-oss-security-token", securityToken]
]
}
console.log("🚀 ~ AliUniUploadStrategy ~ doUpload ~ policyObj:", policyObj)
const policyBase64 = this.getPolicyBase64(policyObj)
// 增加 null 检查
if (accessKeySecret == null) {
console.error("[AliUniUploadStrategy] accessKeySecret is null")
throw new Error("accessKeySecret is null")
}
const signature = this.getSignature(policyBase64, accessKeySecret)
console.log(`[AliUniUploadStrategy] policyBase64: ${policyBase64}, signature: ${signature}`)
// 4. 构造表单数据
const formData = {
key: objectKey,
policy: policyBase64,
OSSAccessKeyId: accessKeyId,
success_action_status: '200',
signature: signature,
'x-oss-security-token': securityToken
}
console.log("🚀 ~ AliUniUploadStrategy ~ doUpload ~ formData:", formData)
// 5. 执行上传
const result = await new Promise<UTSJSONObject>((resolve, reject) => {
uni.uploadFile({
url: host,
filePath: filePath,
name: 'file',
formData: formData as UTSJSONObject,
success: (res) => {
if (res.statusCode == 200 || res.statusCode == 204) {
logger.info(`[AliUniUploadStrategy] 上传成功: ${objectKey}`, "FileUploadService")
const url = `${host}/${objectKey}`
resolve({
url: url,
objectKey: objectKey,
strategy: 'aliuni'
} as UTSJSONObject)
} else {
logger.error(`[AliUniUploadStrategy] 上传失败: statusCode=${res.statusCode}`, "FileUploadService")
reject(new Error(`Upload failed with status ${res.statusCode}`))
}
},
fail: (err) => {
logger.error(`[AliUniUploadStrategy] 上传失败: ${err.errMsg}`, "FileUploadService")
reject(new Error(err.errMsg))
}
})
})
return result
}
/**
* 生成 Policy Base64 字符串
*/
getPolicyBase64(policyObj: any): string {
const policyStr = JSON.stringify(policyObj)
if (policyStr == null) return ""
return base64Encode(policyStr).replace(/\n/g, '')
}
/**
* 生成签名
*/
getSignature(policyBase64: string, accessKeySecret: string): string {
return hmacSha1(policyBase64, accessKeySecret).replace(/\n/g, '')
}
}
...@@ -10,6 +10,8 @@ import { logger } from '../logger/index.uts' ...@@ -10,6 +10,8 @@ import { logger } from '../logger/index.uts'
import { IUploadStrategy } from './IUploadStrategy.uts' import { IUploadStrategy } from './IUploadStrategy.uts'
import { AliOSSUploadStrategy } from './AliOSSUploadStrategy.uts' import { AliOSSUploadStrategy } from './AliOSSUploadStrategy.uts'
import { UniUploadStrategy } from './UniUploadStrategy.uts' import { UniUploadStrategy } from './UniUploadStrategy.uts'
import { AliUniUploadStrategy } from './AliUniUploadStrategy.uts'
import { UploadStrategyType } from './types/index.uts'
/** /**
* 文件上传服务 * 文件上传服务
...@@ -20,8 +22,8 @@ class FileUploadService { ...@@ -20,8 +22,8 @@ class FileUploadService {
private strategy: IUploadStrategy private strategy: IUploadStrategy
private constructor() { private constructor() {
// 默认使用 OSS 策略 // 默认使用 AliUni 策略 (uni.uploadFile 直传 OSS)
this.strategy = new AliOSSUploadStrategy() this.strategy = new AliUniUploadStrategy()
} }
static getInstance(): FileUploadService { static getInstance(): FileUploadService {
...@@ -33,15 +35,18 @@ class FileUploadService { ...@@ -33,15 +35,18 @@ class FileUploadService {
/** /**
* 切换上传策略 * 切换上传策略
* @param type 策略类型: 'alioss' | 'uni' * @param type 策略类型
*/ */
setStrategy(type: string) { setStrategy(type: UploadStrategyType) {
if (type == 'alioss') { if (type == UploadStrategyType.ALI_OSS) {
this.strategy = new AliOSSUploadStrategy() this.strategy = new AliOSSUploadStrategy()
logger.info(`[FileUploadService] 切换策略为: AliOSS`, "FileUploadService") logger.info(`[FileUploadService] 切换策略为: AliOSS (Native SDK)`, "FileUploadService")
} else if (type == 'uni') { } else if (type == UploadStrategyType.UNI_UPLOAD) {
this.strategy = new UniUploadStrategy() this.strategy = new UniUploadStrategy()
logger.info(`[FileUploadService] 切换策略为: uni.uploadFile`, "FileUploadService") logger.info(`[FileUploadService] 切换策略为: uni.uploadFile (Generic)`, "FileUploadService")
} else if (type == UploadStrategyType.ALI_UNI) {
this.strategy = new AliUniUploadStrategy()
logger.info(`[FileUploadService] 切换策略为: AliUni (uni.uploadFile -> OSS)`, "FileUploadService")
} else { } else {
logger.warn(`[FileUploadService] 未知策略: ${type}, 保持当前策略`, "FileUploadService") logger.warn(`[FileUploadService] 未知策略: ${type}, 保持当前策略`, "FileUploadService")
} }
......
/**
* 文件上传模块入口
* 统一导出服务实例、接口定义和相关类型
*/
// 导出单例服务实例
export { default as FileUploadService } from './FileUploadService.uts'
// 导出策略接口 (用于自定义策略实现)
export * from './IUploadStrategy.uts'
// 导出相关类型定义 (枚举、Token结构等)
export * from './types/index.uts'
export * from './oss'
export * from './upload'
export type OssTokenData = {
lsaccessKeyId?: string
lsaccessKeySecret?: string
securityToken?: string
bucketName?: string
region?: string
}
export type OssTokenResponse = {
code: string
msg: string
data: OssTokenData
}
/**
* 上传策略类型枚举
*/
export enum UploadStrategyType {
ALI_OSS = "alioss",
UNI_UPLOAD = "uni",
ALI_UNI = "aliuni"
}
/**
* 纯 UTS 实现的加密工具类
* 包含 Base64 编码和 HMAC-SHA1 签名
* 支持全平台 (Android, iOS, Web)
*/
// Base64 索引表
const BASE64_CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
/**
* 将字符串转为 UTF-8 字节数组
*/
function stringToUtf8Bytes(str: string): number[] {
const bytes: number[] = [];
let i = 0;
while (i < str.length) {
const code = str.charCodeAt(i);
const c = code ?? 0;
if (c < 0x80) {
bytes.push(c);
} else if (c < 0x800) {
bytes.push(0xc0 + ((c >> 6) & 0x1f));
bytes.push(0x80 + (c & 0x3f));
} else {
const x = c ^ 0xd800;
if (x >> 10 == 0) { // High surrogate
// 增加边界检查
if (i + 1 >= str.length) {
// 异常情况:不完整的 surrogate pair,当作普通字符处理或跳过
break;
}
const nextCode = str.charCodeAt(i + 1);
const next = (nextCode ?? 0) ^ 0xdc00;
const codePoint = (x << 10) + next + 0x10000;
bytes.push(0xf0 + ((codePoint >> 18) & 0x7));
bytes.push(0x80 + ((codePoint >> 12) & 0x3f));
bytes.push(0x80 + ((codePoint >> 6) & 0x3f));
bytes.push(0x80 + (codePoint & 0x3f));
i++;
} else {
bytes.push(0xe0 + ((c >> 12) & 0xf));
bytes.push(0x80 + ((c >> 6) & 0x3f));
bytes.push(0x80 + (c & 0x3f));
}
}
i++;
}
return bytes;
}
/**
* Base64 编码
*/
export function base64Encode(input: string): string {
const bytes = stringToUtf8Bytes(input);
return base64EncodeBytes(bytes);
}
/**
* Base64 编码 (输入字节数组)
*/
export function base64EncodeBytes(bytes: number[]): string {
let output = "";
let i = 0;
while (i < bytes.length) {
const byte1 = bytes[i++];
const byte2 = i < bytes.length ? bytes[i++] : NaN;
const byte3 = i < bytes.length ? bytes[i++] : NaN;
const enc1 = byte1 >> 2;
const enc2 = ((byte1 & 3) << 4) | (Number.isNaN(byte2) ? 0 : byte2 >> 4);
const enc3 = Number.isNaN(byte2) ? 64 : ((byte2 & 15) << 2) | (Number.isNaN(byte3) ? 0 : byte3 >> 6);
const enc4 = Number.isNaN(byte3) ? 64 : byte3 & 63;
output += BASE64_CHARS.charAt(enc1) + BASE64_CHARS.charAt(enc2) +
(enc3 == 64 ? "=" : BASE64_CHARS.charAt(enc3)) +
(enc4 == 64 ? "=" : BASE64_CHARS.charAt(enc4));
}
return output;
}
/**
* SHA1 核心算法 (支持 number[])
*/
function sha1Compute(data: number[]): number[] {
// Padding
const messageLen = data.length * 8; // bit length
const paddedData: number[] = []
// 手动复制,避免 spread syntax 问题
for (let k = 0; k < data.length; k++) {
paddedData.push(data[k])
}
paddedData.push(0x80);
while ((paddedData.length * 8 + 64) % 512 !== 0) {
paddedData.push(0);
}
// Append length (64-bit big-endian)
// High 32 bits
const highLen = Math.floor(messageLen / 0x100000000); // messageLen >>> 32
paddedData.push((highLen >>> 24) & 0xff);
paddedData.push((highLen >>> 16) & 0xff);
paddedData.push((highLen >>> 8) & 0xff);
paddedData.push(highLen & 0xff);
// Low 32 bits
paddedData.push((messageLen >>> 24) & 0xff);
paddedData.push((messageLen >>> 16) & 0xff);
paddedData.push((messageLen >>> 8) & 0xff);
paddedData.push(messageLen & 0xff);
// Initial hash values
let h0 = 0x67452301;
let h1 = 0xEFCDAB89;
let h2 = 0x98BADCFE;
let h3 = 0x10325476;
let h4 = 0xC3D2E1F0;
// Process 512-bit chunks
for (let i = 0; i < paddedData.length; i += 64) {
// 使用明确的数组初始化
const w: number[] = []
for(let k = 0; k < 80; k++) { w.push(0) }
for (let j = 0; j < 16; j++) {
const idx = i + j * 4;
// 确保索引不越界
const b0 = idx < paddedData.length ? paddedData[idx] : 0;
const b1 = idx + 1 < paddedData.length ? paddedData[idx + 1] : 0;
const b2 = idx + 2 < paddedData.length ? paddedData[idx + 2] : 0;
const b3 = idx + 3 < paddedData.length ? paddedData[idx + 3] : 0;
w[j] = (b0 << 24) | (b1 << 16) | (b2 << 8) | b3;
}
for (let j = 16; j < 80; j++) {
const temp = w[j - 3] ^ w[j - 8] ^ w[j - 14] ^ w[j - 16];
w[j] = (temp << 1) | (temp >>> 31);
}
let a = h0;
let b = h1;
let c = h2;
let d = h3;
let e = h4;
for (let j = 0; j < 80; j++) {
let f = 0;
let k = 0;
if (j < 20) {
f = (b & c) | ((~b) & d);
k = 0x5A827999;
} else if (j < 40) {
f = b ^ c ^ d;
k = 0x6ED9EBA1;
} else if (j < 60) {
f = (b & c) | (b & d) | (c & d);
k = 0x8F1BBCDC;
} else {
f = b ^ c ^ d;
k = 0xCA62C1D6;
}
const temp = ((a << 5) | (a >>> 27)) + f + e + k + w[j];
e = d;
d = c;
c = (b << 30) | (b >>> 2);
b = a;
a = temp | 0; // Force to 32-bit int
}
h0 = (h0 + a) | 0;
h1 = (h1 + b) | 0;
h2 = (h2 + c) | 0;
h3 = (h3 + d) | 0;
h4 = (h4 + e) | 0;
}
// Produce result (20 bytes)
const result: number[] = [];
const appendInt = (n: number) => {
result.push((n >>> 24) & 0xff);
result.push((n >>> 16) & 0xff);
result.push((n >>> 8) & 0xff);
result.push(n & 0xff);
};
appendInt(h0);
appendInt(h1);
appendInt(h2);
appendInt(h3);
appendInt(h4);
return result;
}
/**
* HMAC-SHA1 签名
* @param key 密钥字符串
* @param message 消息字符串
* @returns Base64 编码的签名
*/
export function hmacSha1(message: string, key: string): string {
let keyBytes = stringToUtf8Bytes(key);
const messageBytes = stringToUtf8Bytes(message);
const blockSize = 64; // SHA-1 block size
// If key is longer than block size, hash it
if (keyBytes.length > blockSize) {
keyBytes = sha1Compute(keyBytes);
}
// 确保 keyBytes 长度为 blockSize (通过填充 0)
// 注意:如果 keyBytes 被 hash 过,它现在的长度是 20,需要填充到 64
// 如果 keyBytes 本来就小于 64,也需要填充
while (keyBytes.length < blockSize) {
keyBytes.push(0);
}
// const oPad = new Array<number>(blockSize);
// const iPad = new Array<number>(blockSize);
const oPad: number[] = []
const iPad: number[] = []
for(let k = 0; k < blockSize; k++) {
oPad.push(0)
iPad.push(0)
}
for (let i = 0; i < blockSize; i++) {
oPad[i] = keyBytes[i] ^ 0x5c;
iPad[i] = keyBytes[i] ^ 0x36;
}
// Inner hash: H(K XOR ipad, text)
const innerMsg: number[] = []
for(let k = 0; k < iPad.length; k++) { innerMsg.push(iPad[k]) }
for(let k = 0; k < messageBytes.length; k++) { innerMsg.push(messageBytes[k]) }
const innerHash = sha1Compute(innerMsg);
// Outer hash: H(K XOR opad, innerHash)
const outerMsg: number[] = []
for(let k = 0; k < oPad.length; k++) { outerMsg.push(oPad[k]) }
for(let k = 0; k < innerHash.length; k++) { outerMsg.push(innerHash[k]) }
const outerHash = sha1Compute(outerMsg);
return base64EncodeBytes(outerHash);
}
...@@ -3,7 +3,7 @@ ...@@ -3,7 +3,7 @@
"appid": "__UNI__B602BFA", "appid": "__UNI__B602BFA",
"description": "", "description": "",
"versionName": "1.0.0", "versionName": "1.0.0",
"versionCode": "111", "versionCode": "112",
"uni-app-x": { "uni-app-x": {
"flex-direction": "row" "flex-direction": "row"
}, },
......
...@@ -72,14 +72,14 @@ export function upload(options: any) { ...@@ -72,14 +72,14 @@ export function upload(options: any) {
// } // }
// const request = new ResumableUploadRequest(bucketName, objectKey, filePath, recordDir); // const request = new ResumableUploadRequest(bucketName, objectKey, filePath, recordDir);
// ossClient!.asyncResumableUpload(request, new OSSCompletedCallback<ResumableUploadRequest, ResumableUploadResult>({ // ossClient!.asyncResumableUpload(request, new OSSCompletedCallback<ResumableUploadRequest, ResumableUploadResult>({
// onSuccess: (request: ResumableUploadRequest, result: ResumableUploadResult) => { // onSuccess: (request: ResumableUploadRequest, result: ResumableUploadResult) => {
// let endpoint = currentConfig!.endpoint; // let endpoint = currentConfig!.endpoint;
// if (!endpoint.startsWith("http")) { // if (!endpoint.startsWith("http")) {
// endpoint = "https://" + endpoint; // endpoint = "https://" + endpoint;
// } // }
// let url = ""; // let url = "";
// if (endpoint.includes("://")) { // if (endpoint.includes("://")) {
// const parts = endpoint.split("://"); // const parts = endpoint.split("://");
...@@ -92,7 +92,7 @@ export function upload(options: any) { ...@@ -92,7 +92,7 @@ export function upload(options: any) {
// url: url, // url: url,
// objectKey: objectKey // objectKey: objectKey
// } as UploadSuccessResult; // } as UploadSuccessResult;
// options.success?.(successRes); // options.success?.(successRes);
// options.complete?.(successRes); // options.complete?.(successRes);
// }, // },
...@@ -105,12 +105,12 @@ export function upload(options: any) { ...@@ -105,12 +105,12 @@ export function upload(options: any) {
// if (serviceException != null) { // if (serviceException != null) {
// errMsg += " " + serviceException.getErrorCode() + " " + serviceException.getRequestId() + " " + serviceException.getHostId() + " " + serviceException.getRawMessage(); // errMsg += " " + serviceException.getErrorCode() + " " + serviceException.getRequestId() + " " + serviceException.getHostId() + " " + serviceException.getRawMessage();
// } // }
// const failRes = { // const failRes = {
// errCode: -2, // errCode: -2,
// errMsg: errMsg // errMsg: errMsg
// } as UploadFailResult; // } as UploadFailResult;
// options.fail?.(failRes); // options.fail?.(failRes);
// options.complete?.(failRes); // options.complete?.(failRes);
// } // }
...@@ -126,7 +126,7 @@ export function upload(options: any) { ...@@ -126,7 +126,7 @@ export function upload(options: any) {
// if (!endpoint.startsWith("http")) { // if (!endpoint.startsWith("http")) {
// endpoint = "https://" + endpoint; // endpoint = "https://" + endpoint;
// } // }
// let url = ""; // let url = "";
// if (endpoint.includes("://")) { // if (endpoint.includes("://")) {
// const parts = endpoint.split("://"); // const parts = endpoint.split("://");
...@@ -141,7 +141,7 @@ export function upload(options: any) { ...@@ -141,7 +141,7 @@ export function upload(options: any) {
// url: url, // url: url,
// objectKey: objectKey // objectKey: objectKey
// } as UploadSuccessResult; // } as UploadSuccessResult;
// options.success?.(successRes); // options.success?.(successRes);
// options.complete?.(successRes); // options.complete?.(successRes);
// }, // },
...@@ -153,12 +153,12 @@ export function upload(options: any) { ...@@ -153,12 +153,12 @@ export function upload(options: any) {
// if (serviceException != null) { // if (serviceException != null) {
// errMsg += " " + serviceException.getErrorCode() + " " + serviceException.getRequestId() + " " + serviceException.getHostId() + " " + serviceException.getRawMessage(); // errMsg += " " + serviceException.getErrorCode() + " " + serviceException.getRequestId() + " " + serviceException.getHostId() + " " + serviceException.getRawMessage();
// } // }
// const failRes = { // const failRes = {
// errCode: -2, // errCode: -2,
// errMsg: errMsg // errMsg: errMsg
// } as UploadFailResult; // } as UploadFailResult;
// options.fail?.(failRes); // options.fail?.(failRes);
// options.complete?.(failRes); // options.complete?.(failRes);
// } // }
......
...@@ -4,97 +4,97 @@ ...@@ -4,97 +4,97 @@
"compiler_version": "4.87" "compiler_version": "4.87"
}, },
"files": { "files": {
"components/evaluationForm/TypeTabComponent.kt": { "pages/demo/gl-tape-demo/index.kt": {
"class": "GenComponentsEvaluationFormTypeTabComponent", "md5": "0aae13f9001ec4f53db18f232da3b9816d12d620",
"md5": "0c65870c54770c8dfebb843dc83b547ef7d25a50" "class": "GenPagesDemoGlTapeDemoIndex"
}, },
"pages/demo/old/index.kt": { "pages/demo/permission/index.kt": {
"class": "GenPagesDemoOldIndex", "class": "GenPagesDemoPermissionIndex",
"md5": "8b8d4a1b49e2ef7592d4e2f958b222392cf46fe8" "md5": "18cb329597e3254e8c67cefdc1f196e3a1260273"
}, },
"uni_modules/z-paging-x/components/z-paging-x/components/z-paging-load-more.kt": { "uni_modules/z-paging-x/components/z-paging-x/components/z-paging-load-more.kt": {
"class": "GenUniModulesZPagingXComponentsZPagingXComponentsZPagingLoadMore", "md5": "1e3f265be090ef72c9841a36e09d19bb3abc1a93",
"md5": "1e3f265be090ef72c9841a36e09d19bb3abc1a93" "class": "GenUniModulesZPagingXComponentsZPagingXComponentsZPagingLoadMore"
},
"pages/demo/local-store/index.kt": {
"class": "GenPagesDemoLocalStoreIndex",
"md5": "6360b2df10619a70490f9f6f126d91728741e2c2"
},
"components/PublishPopup.kt": {
"class": "GenComponentsPublishPopup",
"md5": "b0c3be2d9836f013bc4b67bbf5fe08a456f6ce18"
},
"pages/common/components/NoData.kt": {
"class": "GenPagesCommonComponentsNoData",
"md5": "0608111022dbb7da0f7c3e452b7409d1ec7f5735"
}, },
"pages/demo/echarts/index.kt": { "pages/demo/echarts/index.kt": {
"md5": "e9c323efac81c50aa4eca12e75586263bacd95fb", "md5": "e9c323efac81c50aa4eca12e75586263bacd95fb",
"class": "GenPagesDemoEchartsIndex" "class": "GenPagesDemoEchartsIndex"
}, },
"pages/demo/tailwindcss/index.kt": {
"md5": "c427026081cb75ed3d462c5ebf8a3ac0750bfa34",
"class": "GenPagesDemoTailwindcssIndex"
},
"pages/common/components/AccountList.kt": { "pages/common/components/AccountList.kt": {
"md5": "d78e30a9fd29b1bd3fc6451b74a39845095f79ee", "class": "GenPagesCommonComponentsAccountList",
"class": "GenPagesCommonComponentsAccountList" "md5": "d78e30a9fd29b1bd3fc6451b74a39845095f79ee"
}, },
"pages/demo/media/index.kt": { "pages/demo/record/index.kt": {
"md5": "d76917918ad2397c0cd8429328b52ab77a83ff4f", "md5": "46db702d44876c630d91abbce66cfca7cf3b20e9",
"class": "GenPagesDemoMediaIndex" "class": "GenPagesDemoRecordIndex"
},
"uni_modules/z-paging-x/components/z-paging-x/components/z-paging-refresher.kt": {
"md5": "fc38688c293b8de58280ea7094b45716e5c5d262",
"class": "GenUniModulesZPagingXComponentsZPagingXComponentsZPagingRefresher"
}, },
"uni_modules/z-paging-x/components/z-paging-x/z-paging-x.kt": { "uni_modules/z-paging-x/components/z-paging-x/z-paging-x.kt": {
"md5": "790b2fe11f0d1a339b2a255af60a133b90113a36", "md5": "790b2fe11f0d1a339b2a255af60a133b90113a36",
"class": "GenUniModulesZPagingXComponentsZPagingXZPagingX" "class": "GenUniModulesZPagingXComponentsZPagingXZPagingX"
}, },
"pages/demo/record/index.kt": { "pages/demo/old/index.kt": {
"md5": "46db702d44876c630d91abbce66cfca7cf3b20e9", "class": "GenPagesDemoOldIndex",
"class": "GenPagesDemoRecordIndex" "md5": "8b8d4a1b49e2ef7592d4e2f958b222392cf46fe8"
},
"pages/common/accountItems/index.kt": {
"class": "GenPagesCommonAccountItemsIndex",
"md5": "ce7b7aebc25c812bc76446384be7b4ae423373da"
}, },
"pages/common/login/index.kt": { "pages/common/login/index.kt": {
"class": "GenPagesCommonLoginIndex", "md5": "165659590e28e0663c371d8606710e0c7fd36859",
"md5": "165659590e28e0663c371d8606710e0c7fd36859" "class": "GenPagesCommonLoginIndex"
},
"uni_modules/z-paging-x/components/z-paging-x-empty/z-paging-x-empty.kt": {
"md5": "e8fa2621d20e3d4183965c604b60282e40ce5932",
"class": "GenUniModulesZPagingXComponentsZPagingXEmptyZPagingXEmpty"
}, },
"uni_modules/z-paging-x/components/z-paging-x/components/z-paging-loading.kt": { "pages/common/components/NoData.kt": {
"md5": "bc2c0931a10ad4eea405d60556ee5e702cc28f62", "class": "GenPagesCommonComponentsNoData",
"class": "GenUniModulesZPagingXComponentsZPagingXComponentsZPagingLoading" "md5": "0608111022dbb7da0f7c3e452b7409d1ec7f5735"
}, },
"uni_modules/z-paging-x/components/z-paging-x/components/z-paging-refresher.kt": { "index.kt": {
"class": "GenUniModulesZPagingXComponentsZPagingXComponentsZPagingRefresher", "md5": "eea29e723be30ffc425911e50ea2a80ea6bfbf75",
"md5": "fc38688c293b8de58280ea7094b45716e5c5d262" "class": ""
}, },
"pages/demo/permission/index.kt": { "components/evaluationForm/TypeTabComponent.kt": {
"class": "GenPagesDemoPermissionIndex", "md5": "0c65870c54770c8dfebb843dc83b547ef7d25a50",
"md5": "18cb329597e3254e8c67cefdc1f196e3a1260273" "class": "GenComponentsEvaluationFormTypeTabComponent"
}, },
"pages/demo/tailwindcss/index.kt": { "pages/demo/media/index.kt": {
"md5": "c427026081cb75ed3d462c5ebf8a3ac0750bfa34", "md5": "d76917918ad2397c0cd8429328b52ab77a83ff4f",
"class": "GenPagesDemoTailwindcssIndex" "class": "GenPagesDemoMediaIndex"
}, },
"pages/demo/gl-tape-demo/index.kt": { "uni_modules/z-paging-x/components/z-paging-x-empty/z-paging-x-empty.kt": {
"md5": "0aae13f9001ec4f53db18f232da3b9816d12d620", "md5": "e8fa2621d20e3d4183965c604b60282e40ce5932",
"class": "GenPagesDemoGlTapeDemoIndex" "class": "GenUniModulesZPagingXComponentsZPagingXEmptyZPagingXEmpty"
}, },
"index.kt": { "pages/demo/local-store/index.kt": {
"md5": "8fedb508a381a1f5a963a7042637c3bba0946696", "class": "GenPagesDemoLocalStoreIndex",
"class": "" "md5": "6360b2df10619a70490f9f6f126d91728741e2c2"
}, },
"pages/index/index.kt": { "pages/index/index.kt": {
"md5": "d8d028fdb9eab322150af58a90c2361ddfea3f18", "md5": "d8d028fdb9eab322150af58a90c2361ddfea3f18",
"class": "GenPagesIndexIndex" "class": "GenPagesIndexIndex"
}, },
"pages/common/accountItems/index.kt": {
"md5": "ce7b7aebc25c812bc76446384be7b4ae423373da",
"class": "GenPagesCommonAccountItemsIndex"
},
"uni_modules/uni-icons/components/uni-icons/uni-icons.kt": { "uni_modules/uni-icons/components/uni-icons/uni-icons.kt": {
"md5": "95aae1ef2b0e8906a602ca5d24eea964329fab31", "class": "GenUniModulesUniIconsComponentsUniIconsUniIcons",
"class": "GenUniModulesUniIconsComponentsUniIconsUniIcons" "md5": "95aae1ef2b0e8906a602ca5d24eea964329fab31"
},
"uni_modules/z-paging-x/components/z-paging-x/components/z-paging-loading.kt": {
"md5": "bc2c0931a10ad4eea405d60556ee5e702cc28f62",
"class": "GenUniModulesZPagingXComponentsZPagingXComponentsZPagingLoading"
}, },
"uni_modules/lime-echart/components/l-echart/l-echart.kt": { "uni_modules/lime-echart/components/l-echart/l-echart.kt": {
"md5": "23c5a52d57071d3771477b55f910fbe9ccac83fc", "md5": "23c5a52d57071d3771477b55f910fbe9ccac83fc",
"class": "GenUniModulesLimeEchartComponentsLEchartLEchart" "class": "GenUniModulesLimeEchartComponentsLEchartLEchart"
},
"components/PublishPopup.kt": {
"md5": "b0c3be2d9836f013bc4b67bbf5fe08a456f6ce18",
"class": "GenComponentsPublishPopup"
} }
} }
} }
\ No newline at end of file \ No newline at end of file
@file:Suppress("UNCHECKED_CAST", "USELESS_CAST", "INAPPLICABLE_JVM_NAME", "UNUSED_ANONYMOUS_PARAMETER", "NAME_SHADOWING", "UNNECESSARY_NOT_NULL_ASSERTION")
package uts.sdk.modules.permissionHandlerPlus
import io.dcloud.uniapp.*
import io.dcloud.uniapp.extapi.*
import io.dcloud.uniapp.framework.*
import io.dcloud.uniapp.runtime.*
import io.dcloud.uniapp.vue.*
import io.dcloud.uniapp.vue.shared.*
import io.dcloud.unicloud.*
import io.dcloud.uts.*
import io.dcloud.uts.Map
import io.dcloud.uts.Set
import kotlin.properties.Delegates
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Deferred
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.async
import io.dcloud.uts.UTSAndroid
fun permissionStatusName(status: Int): String {
when (status) {
0 ->
return "denied"
1 ->
return "granted"
2 ->
return "restricted"
3 ->
return "limited"
4 ->
return "permanentlyDenied"
5 ->
return "provisional"
else ->
return "unkonwn"
}
}
fun permissionIdByName(name: String): Int {
when (name) {
"Calendar" ->
return 0
"Camera" ->
return 1
"Contacts" ->
return 2
"Location" ->
return 3
"LocationAlways" ->
return 4
"LocationWhenInUse" ->
return 5
"MediaLibrary" ->
return 6
"Microphone" ->
return 7
"Phone" ->
return 8
"Photos" ->
return 9
"PhotosAddOnly" ->
return 10
"Reminders" ->
return 11
"Sensors" ->
return 12
"Sms" ->
return 13
"Speech" ->
return 14
"Storage" ->
return 15
"IgnoreBatteryOptimizations" ->
return 16
"Notification" ->
return 17
"AccessMediaLocation" ->
return 18
"ActivityRecognition" ->
return 19
"Unknown" ->
return 20
"Bluetooth" ->
return 21
"ManageExternalStorage" ->
return 22
"SystemAlertWindow" ->
return 23
"RequestInstallPackages" ->
return 24
"AppTrackingTransparency" ->
return 25
"RriticalAlerts" ->
return 26
"AccessNotificationPolicy" ->
return 27
"BluetoothScan" ->
return 28
"BluetoothAdvertise" ->
return 29
"BluetoothConnect" ->
return 30
"NearbyWifiDevices" ->
return 31
"Videos" ->
return 32
"Audio" ->
return 33
"ScheduleExactAlarm" ->
return 34
"SensorsAlways" ->
return 35
"CalendarWriteOnly" ->
return 36
"CalendarFullAccess" ->
return 37
"Assistant" ->
return 38
"BackgroundRefresh" ->
return 39
else ->
return -1
}
}
fun permissionNameById(id: Int): String {
when (id) {
0 ->
return "Calendar"
1 ->
return "Camera"
2 ->
return "Contacts"
3 ->
return "Location"
4 ->
return "LocationAlways"
5 ->
return "LocationWhenInUse"
6 ->
return "MediaLibrary"
7 ->
return "Microphone"
8 ->
return "Phone"
9 ->
return "Photos"
10 ->
return "PhotosAddOnly"
11 ->
return "Reminders"
12 ->
return "Sensors"
13 ->
return "Sms"
14 ->
return "Speech"
15 ->
return "Storage"
16 ->
return "IgnoreBatteryOptimizations"
17 ->
return "Notification"
18 ->
return "AccessMediaLocation"
19 ->
return "ActivityRecognition"
20 ->
return "Unknown"
21 ->
return "Bluetooth"
22 ->
return "ManageExternalStorage"
23 ->
return "SystemAlertWindow"
24 ->
return "RequestInstallPackages"
25 ->
return "AppTrackingTransparency"
26 ->
return "RriticalAlerts"
27 ->
return "AccessNotificationPolicy"
28 ->
return "BluetoothScan"
29 ->
return "BluetoothAdvertise"
30 ->
return "BluetoothConnect"
31 ->
return "NearbyWifiDevices"
32 ->
return "Videos"
33 ->
return "Audio"
34 ->
return "ScheduleExactAlarm"
35 ->
return "SensorsAlways"
36 ->
return "CalendarWriteOnly"
37 ->
return "CalendarFullAccess"
38 ->
return "Assistant"
39 ->
return "BackgroundRefresh"
else ->
return "Unknown"
}
}
typealias SuccessCallBack = (result: Any) -> Unit
typealias FailCallBack = (error: Any) -> Unit
open class PermissionObject (
@JsonNotNull
open var names: UTSArray<String>,
@JsonNotNull
open var success: SuccessCallBack,
@JsonNotNull
open var fail: FailCallBack,
) : UTSObject(), IUTSSourceMap {
override fun `__$getOriginalPosition`(): UTSSourceMapPosition? {
return UTSSourceMapPosition("PermissionObject", "uni_modules/permission-handler-plus/utssdk/interface.uts", 237, 13)
}
}
fun checkPermission(permission: String, complete: (result: String) -> Unit) {
var permissionId = permissionIdByName(permission)
if (permissionId == -1) {
complete("unkown permission")
return
}
var handler = PermissionHandlerKt()
handler.checkPermissionStatus(permissionId, UTSAndroid.getAppContext()!!, UTSAndroid.getUniActivity()!!, fun(result: Int){
complete(permissionStatusName(result))
}
)
}
fun requestPermissions(permission: PermissionObject) {
var permissionIds: UTSArray<Int> = _uA()
for(pm in resolveUTSKeyIterator(permission.names)){
var permissionId = permissionIdByName(pm)
if (permissionId == -1) {
continue
}
permissionIds.push(permissionId)
}
if (permissionIds.size == 0) {
var error = Map<String, String>()
error.set("code", "-1")
error.set("msg", "unkown permission")
permission.fail(error)
return
}
var handler = PermissionHandlerKt()
handler.requestPermissions(permissionIds, UTSAndroid.getAppContext()!!, UTSAndroid.getUniActivity()!!, fun(result: kotlin.collections.Map<Int, Int>?, error: kotlin.collections.Map<String, String>?): Unit {
console.log(result, error, " at uni_modules/permission-handler-plus/utssdk/app-android/index.uts:49")
if (error != null) {
var errorMap = Map<String, String>()
error.forEach(fun(k, v){
var name = k
var value = v
errorMap.set(name, value)
}
)
permission.fail(errorMap)
return
}
var nameMap = Map<String, String>()
result?.forEach(fun(k, v){
var name = permissionNameById(k)
var status = permissionStatusName(v)
nameMap.set(name, status)
}
)
permission.success(nameMap)
}
)
}
@file:Suppress("UNCHECKED_CAST", "USELESS_CAST", "INAPPLICABLE_JVM_NAME", "UNUSED_ANONYMOUS_PARAMETER", "NAME_SHADOWING", "UNNECESSARY_NOT_NULL_ASSERTION")
package uts.sdk.modules.uniGetbatteryinfo
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.os.BatteryManager
import io.dcloud.uniapp.*
import io.dcloud.uniapp.extapi.*
import io.dcloud.uniapp.framework.*
import io.dcloud.uniapp.runtime.*
import io.dcloud.uniapp.vue.*
import io.dcloud.uniapp.vue.shared.*
import io.dcloud.unicloud.*
import io.dcloud.uts.*
import io.dcloud.uts.Map
import io.dcloud.uts.Set
import io.dcloud.uts.UTSAndroid
import kotlin.properties.Delegates
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Deferred
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.async
open class GetBatteryInfoSuccess (
@JsonNotNull
open var errMsg: String,
@JsonNotNull
open var level: Number,
@JsonNotNull
open var isCharging: Boolean = false,
) : UTSObject(), IUTSSourceMap {
override fun `__$getOriginalPosition`(): UTSSourceMapPosition? {
return UTSSourceMapPosition("GetBatteryInfoSuccess", "uni_modules/uni-getbatteryinfo/utssdk/interface.uts", 1, 13)
}
}
open class GetBatteryInfoOptions (
open var success: ((res: GetBatteryInfoSuccess) -> Unit)? = null,
open var fail: ((res: UniError) -> Unit)? = null,
open var complete: ((res: Any) -> Unit)? = null,
) : UTSObject(), IUTSSourceMap {
override fun `__$getOriginalPosition`(): UTSSourceMapPosition? {
return UTSSourceMapPosition("GetBatteryInfoOptions", "uni_modules/uni-getbatteryinfo/utssdk/interface.uts", 12, 13)
}
}
open class GetBatteryInfoResult (
@JsonNotNull
open var level: Number,
@JsonNotNull
open var isCharging: Boolean = false,
) : UTSObject(), IUTSSourceMap {
override fun `__$getOriginalPosition`(): UTSSourceMapPosition? {
return UTSSourceMapPosition("GetBatteryInfoResult", "uni_modules/uni-getbatteryinfo/utssdk/interface.uts", 26, 13)
}
}
typealias GetBatteryInfoErrorCode = Number
interface GetBatteryInfoFail : IUniError {
override var errCode: GetBatteryInfoErrorCode
}
typealias GetBatteryInfo = (options: GetBatteryInfoOptions) -> Unit
typealias GetBatteryInfoSync = () -> GetBatteryInfoResult
val UniErrorSubject = "uni-getBatteryInfo"
val UniErrors: Map<GetBatteryInfoErrorCode, String> = Map(_uA(
_uA(
1001,
"getBatteryInfo:fail getAppContext is null"
),
_uA(
1002,
"getBatteryInfo:fail not support"
)
))
open class GetBatteryInfoFailImpl : UniError, GetBatteryInfoFail, IUTSSourceMap {
override fun `__$getOriginalPosition`(): UTSSourceMapPosition? {
return UTSSourceMapPosition("GetBatteryInfoFailImpl", "uni_modules/uni-getbatteryinfo/utssdk/unierror.uts", 20, 14)
}
override lateinit var errCode: GetBatteryInfoErrorCode
constructor(errCode: GetBatteryInfoErrorCode) : super() {
this.errSubject = UniErrorSubject
this.errCode = errCode
this.errMsg = UniErrors[errCode] ?: ""
}
}
val getBatteryInfo: GetBatteryInfo = fun(options: GetBatteryInfoOptions) {
val context = UTSAndroid.getAppContext()
if (context != null) {
val manager = context.getSystemService(Context.BATTERY_SERVICE) as BatteryManager
val level = manager.getIntProperty(BatteryManager.BATTERY_PROPERTY_CAPACITY)
var ifilter = IntentFilter(Intent.ACTION_BATTERY_CHANGED)
var batteryStatus = context.registerReceiver(null, ifilter)
var status = batteryStatus?.getIntExtra(BatteryManager.EXTRA_STATUS, -1)
var isCharging = status == BatteryManager.BATTERY_STATUS_CHARGING || status == BatteryManager.BATTERY_STATUS_FULL
val res = GetBatteryInfoSuccess(errMsg = "getBatteryInfo:ok", level = level, isCharging = isCharging)
options.success?.invoke(res)
options.complete?.invoke(res)
} else {
var res = GetBatteryInfoFailImpl(1001)
options.fail?.invoke(res)
options.complete?.invoke(res)
}
}
val getBatteryInfoSync: GetBatteryInfoSync = fun(): GetBatteryInfoResult {
val context = UTSAndroid.getAppContext()
if (context != null) {
val manager = context.getSystemService(Context.BATTERY_SERVICE) as BatteryManager
val level = manager.getIntProperty(BatteryManager.BATTERY_PROPERTY_CAPACITY)
var ifilter = IntentFilter(Intent.ACTION_BATTERY_CHANGED)
var batteryStatus = context.registerReceiver(null, ifilter)
var status = batteryStatus?.getIntExtra(BatteryManager.EXTRA_STATUS, -1)
var isCharging = status == BatteryManager.BATTERY_STATUS_CHARGING || status == BatteryManager.BATTERY_STATUS_FULL
val res = GetBatteryInfoResult(level = level, isCharging = isCharging)
return res
} else {
val res = GetBatteryInfoResult(level = -1, isCharging = false)
return res
}
}
{"version":3,"sources":["uni_modules/uni-getbatteryinfo/utssdk/app-android/index.uts","uni_modules/uni-getbatteryinfo/utssdk/interface.uts","uni_modules/uni-getbatteryinfo/utssdk/unierror.uts"],"sourcesContent":["import Context from \"android.content.Context\";\nimport BatteryManager from \"android.os.BatteryManager\";\n\nimport { GetBatteryInfo, GetBatteryInfoOptions, GetBatteryInfoSuccess, GetBatteryInfoResult,GetBatteryInfoSync } from '../interface.uts'\nimport IntentFilter from 'android.content.IntentFilter';\nimport Intent from 'android.content.Intent';\n\nimport { GetBatteryInfoFailImpl } from '../unierror';\n\n/**\n * 异步获取电量\n */\nexport const getBatteryInfo : GetBatteryInfo = function (options : GetBatteryInfoOptions) {\n\n\n const context = UTSAndroid.getAppContext();\n if (context != null) {\n const manager = context.getSystemService(\n Context.BATTERY_SERVICE\n ) as BatteryManager;\n const level = manager.getIntProperty(\n BatteryManager.BATTERY_PROPERTY_CAPACITY\n );\n\n let ifilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);\n let batteryStatus = context.registerReceiver(null, ifilter);\n let status = batteryStatus?.getIntExtra(BatteryManager.EXTRA_STATUS, -1);\n let isCharging = status == BatteryManager.BATTERY_STATUS_CHARGING || status == BatteryManager.BATTERY_STATUS_FULL;\n\n const res : GetBatteryInfoSuccess = {\n errMsg: 'getBatteryInfo:ok',\n level,\n isCharging: isCharging\n }\n options.success?.(res)\n options.complete?.(res)\n } else {\n\t\tlet res = new GetBatteryInfoFailImpl(1001);\n options.fail?.(res)\n options.complete?.(res)\n }\n}\n\n/**\n * 同步获取电量示例\n */\nexport const getBatteryInfoSync : GetBatteryInfoSync = function (): GetBatteryInfoResult {\n\n const context = UTSAndroid.getAppContext();\n if (context != null) {\n\n\n const manager = context.getSystemService(\n Context.BATTERY_SERVICE\n ) as BatteryManager;\n const level = manager.getIntProperty(\n BatteryManager.BATTERY_PROPERTY_CAPACITY\n );\n \n let ifilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);\n let batteryStatus = context.registerReceiver(null, ifilter);\n let status = batteryStatus?.getIntExtra(BatteryManager.EXTRA_STATUS, -1);\n let isCharging = status == BatteryManager.BATTERY_STATUS_CHARGING || status == BatteryManager.BATTERY_STATUS_FULL;\n \n const res : GetBatteryInfoResult = {\n level: level,\n isCharging: isCharging\n };\n\n return res;\n }\n else {\n /**\n * 无有效上下文\n */\n const res : GetBatteryInfoResult = {\n level: -1,\n isCharging: false\n };\n return res;\n }\n\n\n}\n","export type GetBatteryInfoSuccess = {\n errMsg: string,\n /**\n * 设备电量,范围1 - 100\n */\n level: number,\n /**\n * 是否正在充电中\n */\n isCharging: boolean\n}\n\nexport type GetBatteryInfoOptions = {\n /**\n * 接口调用结束的回调函数(调用成功、失败都会执行)\n */\n success?: (res: GetBatteryInfoSuccess) => void\n /**\n * 接口调用失败的回调函数\n */\n fail?: (res: UniError) => void\n /**\n * 接口调用成功的回调\n */\n complete?: (res: any) => void\n}\n\nexport type GetBatteryInfoResult = {\n /**\n * 设备电量,范围1 - 100\n */\n level: number,\n /**\n * 是否正在充电中\n */\n isCharging: boolean\n}\n\n/**\n * 错误码\n * - 1001 getAppContext is null\n */\nexport type GetBatteryInfoErrorCode = 1001 | 1002;\n/**\n * GetBatteryInfo 的错误回调参数\n */\nexport interface GetBatteryInfoFail extends IUniError {\n errCode: GetBatteryInfoErrorCode\n};\n\n/**\n* 获取电量信息\n* @param {GetBatteryInfoOptions} options\n*\n*\n* @tutorial https://uniapp.dcloud.net.cn/api/system/batteryInfo.html\n* @platforms APP-IOS = ^9.0,APP-ANDROID = ^22\n* @since 3.6.11\n*\n* @assert () => success({errCode: 0, errSubject: \"uni-getBatteryInfo\", errMsg: \"getBatteryInfo:ok\", level: 60, isCharging: false })\n* @assert () => fail({errCode: 1001, errSubject: \"uni-getBatteryInfo\", errMsg: \"getBatteryInfo:fail getAppContext is null\" })\n*/\nexport type GetBatteryInfo = (options: GetBatteryInfoOptions) => void\n\n\nexport type GetBatteryInfoSync = () => GetBatteryInfoResult\n\ninterface Uni {\n\n /**\n * 获取电池电量信息\n *\n * @example\n * ```typescript\n * uni.getBatteryInfo({\n *\t\tsuccess(res) {\n *\t\t\t__f__('log','at uni_modules/uni-getbatteryinfo/utssdk/interface.uts:77',res);\n *\t\t}\n * })\n * ```\n * @remark\n * - 该接口需要同步调用\n * @uniPlatform {\n * \"app\": {\n * \"android\": {\n * \"osVer\": \"4.4.4\",\n * \"uniVer\": \"3.6.11\",\n * \"unixVer\": \"3.9.0\"\n * },\n * \"ios\": {\n * \"osVer\": \"12.0\",\n * \"uniVer\": \"3.6.11\",\n * \"unixVer\": \"4.11\"\n * },\n * \"harmony\": {\n * \"osVer\": \"3.0\",\n * \"uniVer\": \"4.23\",\n * \"unixVer\": \"x\"\n * }\n * },\n * \"web\": {\n * \"uniVer\": \"3.6.11\",\n * \"unixVer\": \"4.0\"\n * }\n * }\n * @uniVueVersion 2,3 //支持的vue版本\n *\n */\n getBatteryInfo(options: GetBatteryInfoOptions): void,\n /**\n * 同步获取电池电量信息\n *\n * @example\n * ```typescript\n * uni.getBatteryInfo()\n * ```\n * @remark\n * - 该接口需要同步调用\n * @uniPlatform {\n * \"app\": {\n * \"android\": {\n * \"osVer\": \"4.4.4\",\n * \"uniVer\": \"3.6.11\",\n * \"unixVer\": \"3.9.0\"\n * },\n * \"ios\": {\n * \"osVer\": \"12.0\",\n * \"uniVer\": \"3.6.11\",\n * \"unixVer\": \"4.11\"\n * },\n * \"harmony\": {\n * \"osVer\": \"3.0\",\n * \"uniVer\": \"4.23\",\n * \"unixVer\": \"x\"\n * }\n * },\n * \"web\": {\n * \"uniVer\": \"3.6.11\",\n * \"unixVer\": \"4.0\"\n * }\n * }\n * @uniVueVersion 2,3 //支持的vue版本\n *\n */\n getBatteryInfoSync(): GetBatteryInfoResult\n\n}\n","import { GetBatteryInfoErrorCode, GetBatteryInfoFail } from \"./interface.uts\"\n/**\n * 错误主题\n */\nexport const UniErrorSubject = 'uni-getBatteryInfo';\n\n\n/**\n * 错误信息\n * @UniError\n */\nexport const UniErrors : Map<GetBatteryInfoErrorCode, string> = new Map([\n /**\n * 错误码及对应的错误信息\n */\n [1001, 'getBatteryInfo:fail getAppContext is null'],\n [1002, 'getBatteryInfo:fail not support'],\n]);\n\n\n/**\n * 错误对象实现\n */\nexport class GetBatteryInfoFailImpl extends UniError implements GetBatteryInfoFail {\n override errCode : GetBatteryInfoErrorCode;\n /**\n * 错误对象构造函数\n */\n constructor(errCode : GetBatteryInfoErrorCode) {\n super();\n this.errSubject = UniErrorSubject;\n this.errCode = errCode;\n this.errMsg = UniErrors[errCode] ?? \"\";\n }\n}\n"],"names":[],"mappings":";;AAAA,OAAoB,uBAAyB,AAAC;AAK9C,OAAmB,sBAAwB,AAAC;AAD5C,OAAyB,4BAA8B,AAAC;AAHxD,OAA2B,yBAA2B,AAAC;;;;;;;;;;;;;;;;;ACDnB,WAAxB;IACV;qBAAQ,MAAM,CAAC;IAIf;oBAAO,MAAM,CAAC;IAId;yBAAY,OAAO,SAAA;;;;;;AAGe,WAAxB;IAIV,oBAAW,KAAK,0BAA0B,IAAI,UAAA;IAI9C,iBAAQ,KAAK,aAAa,IAAI,UAAA;IAI9B,qBAAY,KAAK,GAAG,KAAK,IAAI,UAAA;;;;;;AAGI,WAAvB;IAIV;oBAAO,MAAM,CAAC;IAId;yBAAY,OAAO,SAAA;;;;;;UAOT,0BAA0B,MAAI;UAIzB,qBAA2B;aAC1C,GAAgC,CAAhC,SAAS;;UAeC,kBAAkB,SAAS,0BAA0B,IAAI;UAGzD,2BAA2B;AC7DhC,IAAM,kBAAkB;AAOxB,IAAM,WAAY,6BAA6B,MAAM,IAAI,AAAI,IAAI;IAItE;AAAC,YAAI;QAAE;KAA4C;IACnD;AAAC,YAAI;QAAE;KAAkC;CAC1C;AAMK,WAAO,yBAA+B;;;;IAC1C,sBAAS,gCAAkC;IAI3C,YAAY,gCAAiC,IAC3C,KAAK,GADsC;QAE3C,IAAI,CAAC,UAAU,GAAG;QAClB,IAAI,CAAC,OAAO,GAAG;QACf,IAAI,CAAC,MAAM,GAAG,SAAS,CAAC,QAAQ,CAAA,EAAA,CAAI;IACtC;;AFrBK,IAAM,iCAAkC,IAAU,8BAA+B,EAAA;IAGpF,IAAM,UAAU,WAAW,aAAa;IACxC,IAAI,QAAO,EAAA,CAAI,IAAI,EAAE;QACjB,IAAM,UAAU,QAAQ,gBAAgB,CACpC,QAAQ,eAAe,EAC1B,EAAA,CAAI;QACL,IAAM,QAAQ,QAAQ,cAAc,CAChC,eAAe,yBAAyB;QAG5C,IAAI,UAAU,AAAI,aAAa,OAAO,sBAAsB;QAC5D,IAAI,gBAAgB,QAAQ,gBAAgB,CAAC,IAAI,EAAE;QACnD,IAAI,SAAS,eAAe,YAAY,eAAe,YAAY,EAAE,CAAC,CAAC;QACvE,IAAI,aAAa,OAAM,EAAA,CAAI,eAAe,uBAAuB,CAAA,EAAA,CAAI,OAAM,EAAA,CAAI,eAAe,mBAAmB;QAEjH,IAAM,MAAM,sBACR,SAAQ,qBACR,QAAA,OACA,aAAY;QAEhB,QAAQ,OAAO,SAAG;QAClB,QAAQ,QAAQ,SAAG;MAChB,IAIN,CAJM;QACT,IAAI,MAAM,uBAA2B,IAAI;QACnC,QAAQ,IAAI,SAAG;QACf,QAAQ,QAAQ,SAAG;;AAE3B;AAKO,IAAM,yCAA0C,4BAAiC;IAEpF,IAAM,UAAU,WAAW,aAAa;IACxC,IAAI,QAAO,EAAA,CAAI,IAAI,EAAE;QAGjB,IAAM,UAAU,QAAQ,gBAAgB,CACpC,QAAQ,eAAe,EAC1B,EAAA,CAAI;QACL,IAAM,QAAQ,QAAQ,cAAc,CAChC,eAAe,yBAAyB;QAG5C,IAAI,UAAU,AAAI,aAAa,OAAO,sBAAsB;QAC5D,IAAI,gBAAgB,QAAQ,gBAAgB,CAAC,IAAI,EAAE;QACnD,IAAI,SAAS,eAAe,YAAY,eAAe,YAAY,EAAE,CAAC,CAAC;QACvE,IAAI,aAAa,OAAM,EAAA,CAAI,eAAe,uBAAuB,CAAA,EAAA,CAAI,OAAM,EAAA,CAAI,eAAe,mBAAmB;QAEjH,IAAM,MAAM,qBACR,QAAO,OACP,aAAY;QAGhB,OAAO;MAEN,IASJ,CATI;QAID,IAAM,MAAM,qBACR,QAAO,CAAC,CAAC,EACT,aAAY,KAAK;QAErB,OAAO;;AAIf"}
\ No newline at end of file \ No newline at end of file
...@@ -5,7 +5,7 @@ ...@@ -5,7 +5,7 @@
}, },
"files": { "files": {
"utssdk/app-android/index.uts": { "utssdk/app-android/index.uts": {
"md5": "7702ee53c2669e07b8bf16a7880023f1" "md5": "5ff9b02c4fece5ac95431b4a5ad5afc0"
}, },
"utssdk/index.uts": { "utssdk/index.uts": {
"md5": "01104f37b0e6512bad0c3b39b302c93d" "md5": "01104f37b0e6512bad0c3b39b302c93d"
......
@file:Suppress("UNCHECKED_CAST", "USELESS_CAST", "INAPPLICABLE_JVM_NAME", "UNUSED_ANONYMOUS_PARAMETER", "NAME_SHADOWING", "UNNECESSARY_NOT_NULL_ASSERTION")
package uts.sdk.modules.utsOpenSchema
import android.content.Intent
import android.net.Uri
import io.dcloud.uniapp.*
import io.dcloud.uniapp.extapi.*
import io.dcloud.uniapp.framework.*
import io.dcloud.uniapp.runtime.*
import io.dcloud.uniapp.vue.*
import io.dcloud.uniapp.vue.shared.*
import io.dcloud.unicloud.*
import io.dcloud.uts.*
import io.dcloud.uts.Map
import io.dcloud.uts.Set
import io.dcloud.uts.UTSAndroid
import kotlin.properties.Delegates
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Deferred
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.async
typealias OpenSchema = (url: String) -> Unit
typealias CanOpenURL = (url: String) -> Boolean
val openSchema: OpenSchema = fun(url: String) {
if (canOpenURL(url)) {
val context = UTSAndroid.getUniActivity()!!
val uri = Uri.parse(url)
val intent = Intent(Intent.ACTION_VIEW, uri)
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
intent.setData(uri)
context.startActivity(intent)
} else {
console.error("[uts-openSchema] url param Error:", JSON.stringify(url), " at uni_modules/uts-openSchema/utssdk/app-android/index.uts:14")
}
}
val canOpenURL: CanOpenURL = fun(url: String): Boolean {
if (UTSAndroid.`typeof`(url) === "string" && url.length > 0) {
val context = UTSAndroid.getUniActivity()!!
val uri = Uri.parse(url)
val intent = Intent(Intent.ACTION_VIEW, uri)
return if (intent.resolveActivity(context.packageManager) != null) {
true
} else {
false
}
} else {
return false
}
}
{"version":3,"sources":["uni_modules/uts-openSchema/utssdk/app-android/index.uts","uni_modules/uts-openSchema/utssdk/interface.uts"],"sourcesContent":["import Intent from 'android.content.Intent'\nimport Uri from 'android.net.Uri'\nimport { OpenSchema, CanOpenURL } from '../interface.uts'\n\nexport const openSchema : OpenSchema = function (url : string) {\n if (canOpenURL(url)) {\n const context = UTSAndroid.getUniActivity()!\n const uri = Uri.parse(url)\n const intent = new Intent(Intent.ACTION_VIEW, uri)\n intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK)\n intent.setData(uri)\n context.startActivity(intent)\n } else {\n __f__('error','at uni_modules/uts-openSchema/utssdk/app-android/index.uts:14','[uts-openSchema] url param Error:', JSON.stringify(url))\n }\n}\n\nexport const canOpenURL : CanOpenURL = function (url : string) : boolean {\n if (typeof url === 'string' && url.length > 0) {\n const context = UTSAndroid.getUniActivity()!\n const uri = Uri.parse(url)\n const intent = new Intent(Intent.ACTION_VIEW, uri)\n return intent.resolveActivity(context.packageManager) != null ? true : false\n } else {\n return false\n }\n}\n","export type OpenSchema = (url : string) => void\nexport type CanOpenURL = (url : string) => boolean\n"],"names":[],"mappings":";;AAAA,OAAmB,sBAAwB;AAC3C,OAAgB,eAAiB;;;;;;;;;;;;;;;;;UCDrB,cAAc,KAAM,MAAM,KAAK,IAAI;UACnC,cAAc,KAAM,MAAM,KAAK,OAAO;ADG3C,IAAM,yBAA0B,IAAU,KAAM,MAAM,EAAA;IAC3D,IAAI,WAAW,MAAM;QACnB,IAAM,UAAU,WAAW,cAAc;QACzC,IAAM,MAAM,IAAI,KAAK,CAAC;QACtB,IAAM,SAAS,AAAI,OAAO,OAAO,WAAW,EAAE;QAC9C,OAAO,QAAQ,CAAC,OAAO,sBAAsB;QAC7C,OAAO,OAAO,CAAC;QACf,QAAQ,aAAa,CAAC;MACjB,IAEN,CAFM;QACL,cAA8E,qCAAqC,KAAK,SAAS,CAAC;;AAEtI;AAEO,IAAM,yBAA0B,IAAU,KAAM,MAAM,GAAI,OAAO,CAAA;IACtE,IAAI,oBAAO,KAAG,GAAA,CAAK,SAAQ,EAAA,CAAI,IAAI,MAAM,CAAA,CAAA,CAAG,CAAC,EAAE;QAC7C,IAAM,UAAU,WAAW,cAAc;QACzC,IAAM,MAAM,IAAI,KAAK,CAAC;QACtB,IAAM,SAAS,AAAI,OAAO,OAAO,WAAW,EAAE;QAC9C,OAAO,IAAA,OAAO,eAAe,CAAC,QAAQ,cAAc,EAAC,EAAA,CAAI,IAAI,EAAG;YAAA,IAAI;QAAJ,EAAO,IAAK,CAAL;YAAA,KAAK;QAAL,CAAK;MACvE,IAEN,CAFM;QACL,OAAO,KAAK;;AAEhB"}
\ No newline at end of file \ No newline at end of file
{"duts":["uni-actionSheet","uni-theme","uni-getSystemInfo","uni-base64ToArrayBuffer","uni-arrayBufferToBase64","uni-crash","uni-storage","uni-dialogPage","uni-event","uni-exit","uni-form","uni-getAccessibilityInfo","uni-getAppAuthorizeSetting","uni-getAppBaseInfo","uni-getDeviceInfo","uni-getElementById","uni-getSystemSetting","uni-modal","uni-openAppAuthorizeSetting","uni-privacy","uni-progress","uni-prompt","uni-rpx2px","uni-rich-text","uni-barcode-scanning","uni-camera","uni-media","permission-handler-plus","uni-location","uni-location-system","lime-sqlite","uts-recorder","uni-getNetworkType","uni-createInnerAudioContext","uni-fileSystemManager","uni-clipboard","uni-previewImage","uni-network","uni-video"]}
\ No newline at end of file \ No newline at end of file
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!