From 192de36036f80a2e2abd570e6fb1f351139550dd Mon Sep 17 00:00:00 2001 From: Luk Date: Wed, 18 Sep 2024 13:14:47 +0800 Subject: [PATCH] uni.setStorageSync('_passtoken/uni_id_token/_clid') automatically for callBase() calls --- unitool.js | 188 +++++++++++++++++++++++++++++++++++------------------ 1 file changed, 125 insertions(+), 63 deletions(-) diff --git a/unitool.js b/unitool.js index ea49324..c500fec 100644 --- a/unitool.js +++ b/unitool.js @@ -18,7 +18,7 @@ const my = { }, isVideoFile (ext = '') { return (wo.envar.videoExtensionList || ['avi', 'mp4', 'mov', 'wmv', 'video']).includes(ext.replace(/^\./, '').toLowerCase()) - } + }, } module.exports = { @@ -73,20 +73,16 @@ module.exports = { const navibarTitle = this.localizeText( pageTitle || - pageNow?.$vm?.$data?.i18nPageTitle || // 页面.vue 的 i18nPageTitle 变量 - pageNow?.$vm?.$data?.i18nText?.[langNow]?.tPageTitle || // 页面.vue 的 i18nText 对象 - pageNow?.$vm?.$data?.pageTitle || - wo?.pageSet?.[pageNow?.route?.substring?.(6)]?.i18nPageTitle || - wo?.pagesJson?.pages?.find((page) => page.path === pageNow?.route)?.i18nPageTitle || // pages.json 的页面配置里 - '' + pageNow?.$vm?.$data?.i18nPageTitle || // 页面.vue 的 i18nPageTitle 变量 + pageNow?.$vm?.$data?.i18nText?.[langNow]?.tPageTitle || // 页面.vue 的 i18nText 对象 + pageNow?.$vm?.$data?.pageTitle || + wo?.pageSet?.[pageNow?.route?.substring?.(6)]?.i18nPageTitle || + wo?.pagesJson?.pages?.find((page) => page.path === pageNow?.route)?.i18nPageTitle || // pages.json 的页面配置里 + '' ) windowTitle = - windowTitle || - wo?.envar?.callnames?.[langNow] || - wo?.pagesJson?.appInfo?.i18nText?.[langNow] || - wo?.pagesJson?.globalStyle?.navigationBarTitleText || - '' + windowTitle || wo?.envar?.callnames?.[langNow] || wo?.pagesJson?.appInfo?.i18nText?.[langNow] || wo?.pagesJson?.globalStyle?.navigationBarTitleText || '' if (wo.envar.clientInfo.deviceType === 'pc') { uni.setNavigationBarTitle({ title: windowTitle + (navibarTitle ? ` - ${navibarTitle}` : '') }) @@ -189,7 +185,7 @@ module.exports = { ...globalThis.wo?.envar?.clientInfo, lang: globalThis.wo?.ss?.i18n?.mylang, // #ifdef WEB - requrl: globalThis.location?.href + requrl: globalThis.location?.href, // #endif } apiWhat._passtoken = uni.getStorageSync('_passtoken') @@ -253,18 +249,30 @@ module.exports = { } else { result = { _state: 'CLIENT_WOBASE_TYPE_UNKNOWN' } } + + if (result?._passtoken) { + uni.setStorageSync('_passtoken', result._passtoken) + } + if (result?.uni_id_token) { + uni.setStorageSync('uni_id_token', result.uni_id_token) + } + if (result?._clid) { + uni.setStorageSync('_clid', result._clid) + } + // 注意1,resultServer 和 resultCloud 推荐遵循同样的格式 { _state, error | data },这样方便前端做统一判断。 // 注意2,虽然预设了 resultServer 和 resultCloud = {},但如果后台返回了 null,那么 resultServer/resultCloud 也是 null。 if (process.env.NODE_ENV !== 'production') { - console.log({ - _at: startTime, - _io: 'CREQ', - _path: `${thisRoute} => ${apiWho}/${apiTodo}`, - apiurl, - baseType, - apiWhat, - timeout, - } + console.log( + { + _at: startTime, + _io: 'CREQ', + _path: `${thisRoute} => ${apiWho}/${apiTodo}`, + apiurl, + baseType, + apiWhat, + timeout, + } // `%c ${startTime} (IN) ${thisRoute} :: ${apiTodo}`, // 'background: #87cefa; border-radius: 0.5em;color: white; font-weight: bold; padding: 2px 0.5em;', // { @@ -276,12 +284,13 @@ module.exports = { // apiurl, // } ) - console.log({ - _at: new Date().toJSON(), - _io: 'CRES', - _path: `${thisRoute} => ${apiWho}/${apiTodo}`, - result - } + console.log( + { + _at: new Date().toJSON(), + _io: 'CRES', + _path: `${thisRoute} => ${apiWho}/${apiTodo}`, + result, + } // `%c ${new Date().toJSON()} (OUT) ${thisRoute} :: ${apiTodo}`, // 'background: #4169e1; border-radius: 0.5em;color: white; font-weight: bold; padding: 2px 0.5em;', // result @@ -306,15 +315,21 @@ module.exports = { if (mediaType === 'image') { let [errorChoose, { tempFilePaths, tempFiles } = {}] = await uni.chooseImage({ count, sizeType, sourceType }) if (errorChoose) { - return { _state: 'CER_FAIL_CHOOSE', _msg: { zhCN: '图像选择失败。请稍后再试,或向客服投诉。', enUS: 'Image choose failed. Please try again later, or report to customer service.' } } + return { + _state: 'CER_FAIL_CHOOSE', + _msg: { zhCN: '图像选择失败。请稍后再试,或向客服投诉。', enUS: 'Image choose failed. Please try again later, or report to customer service.' }, + } } fileSize = tempFiles?.[0]?.size filePicked = tempFiles?.[0] filePath = tempFilePaths?.[0] } else if (mediaType === 'video') { - let [errorChoose, { tempFilePath, tempFile, size, duration, }] = await uni.chooseVideo({ sourceType }) + let [errorChoose, { tempFilePath, tempFile, size, duration }] = await uni.chooseVideo({ sourceType }) if (errorChoose) { - return { _state: 'CER_FAIL_CHOOSE', _msg: { zhCN: '视频选择失败。请稍后再试,或向客服投诉。', enUS: 'Video choose failed. Please try again later, or report to customer service.' } } + return { + _state: 'CER_FAIL_CHOOSE', + _msg: { zhCN: '视频选择失败。请稍后再试,或向客服投诉。', enUS: 'Video choose failed. Please try again later, or report to customer service.' }, + } } fileSize = size filePicked = tempFile @@ -322,9 +337,16 @@ module.exports = { } else { // #ifdef WEB // https://uniapp.dcloud.net.cn/api/media/file.html - let [errorChoose, { tempFilePaths, tempFiles } = {}] = await uni.chooseFile({ count, extension: Array.isArray(mediaType) ? mediaType : undefined, type: Array.isArray(mediaType) ? undefined : 'all' }) // 20240429 但是测试下来 extension 参数无效 + let [errorChoose, { tempFilePaths, tempFiles } = {}] = await uni.chooseFile({ + count, + extension: Array.isArray(mediaType) ? mediaType : undefined, + type: Array.isArray(mediaType) ? undefined : 'all', + }) // 20240429 但是测试下来 extension 参数无效 if (errorChoose) { - return { _state: 'CER_FAIL_CHOOSE', _msg: { zhCN: '文件选择失败。请稍后再试,或向客服投诉。', enUS: 'File choose failed. Please try again later, or report to customer service.' } } + return { + _state: 'CER_FAIL_CHOOSE', + _msg: { zhCN: '文件选择失败。请稍后再试,或向客服投诉。', enUS: 'File choose failed. Please try again later, or report to customer service.' }, + } } fileSize = tempFiles?.[0]?.size filePicked = tempFiles?.[0] @@ -339,7 +361,10 @@ module.exports = { return { _state: 'CER_EMPTY_FILE', _msg: { zhCN: '文件为空,无法上传。', enUS: 'Empty files cannot be uploaded.' } } } else if (fileSize > (globalThis.wo?.envar?.fileSizeLimit || 10485760)) { let sizeLimitMB = parseInt((globalThis.wo?.envar?.fileSizeLimit || 10485760) / 1048576) + 'MB' - return { _state: 'CER_FILE_TOO_LARGE', _msg: { zhCN: `文件大于 ${sizeLimitMB} MB,无法上传`, enUS: `The file exceeds ${sizeLimitMB} MB and cannot be uploaded` } } + return { + _state: 'CER_FILE_TOO_LARGE', + _msg: { zhCN: `文件大于 ${sizeLimitMB} MB,无法上传`, enUS: `The file exceeds ${sizeLimitMB} MB and cannot be uploaded` }, + } } const fileName = filePicked?.name || filePath?.split?.('/')?.pop?.() // filePicked.name is available in WEB only. on the other hand, filePath 在 WEB 上并不是文件路径名,而是类似 "blob:http://localhost:8080/f0d3e54d-0694-4803-8097-641d76a10b0d“。在 iOS 上是 "_doc/uniapp_temp_1598593902955/compressed/1598593925815.png", 有时还包含从 file:/// 开始的完整路径名。 @@ -348,14 +373,19 @@ module.exports = { if ( // #ifndef APP // 20240830 luk: 在 App 上,就相信 iOS/Android,不检查文件后缀名。 - mediaType === 'image' && !my.isImageFile(fileExt) || mediaType === 'video' && !my.isVideoFile(fileExt) || + (mediaType === 'image' && !my.isImageFile(fileExt)) || + (mediaType === 'video' && !my.isVideoFile(fileExt)) || // #endif - Array.isArray(mediaType) && !mediaType?.includes?.('.' + fileExt)) { + (Array.isArray(mediaType) && !mediaType?.includes?.('.' + fileExt)) + ) { return { _state: 'UNSUPPORTED_FILETYPE', _msg: { zhCN: '不支持的文件类型:\n' + fileName, enUS: 'Unsupported file type:\n' + fileName } } } if (!filePath) { - return { _state: 'BER_FAIL_CHOOSE_FILE', _msg: { zhCN: '文件选择失败。请稍后再试,或向客服投诉。', enUS: 'File choose failed. Please try again later, or report to customer service.' } } + return { + _state: 'BER_FAIL_CHOOSE_FILE', + _msg: { zhCN: '文件选择失败。请稍后再试,或向客服投诉。', enUS: 'File choose failed. Please try again later, or report to customer service.' }, + } } for (let key in formData) { @@ -376,7 +406,10 @@ module.exports = { try { data = JSON.parse(data) } catch (exp) { - return { _state: 'BER_FAIL_RESPONSE_JSON_MALFORMED', _msg: { zhCN: '文件上传失败。请稍后再试,或向客服投诉。', enUS: 'File upload failed. Please try again later, or report to customer service.' } } + return { + _state: 'BER_FAIL_RESPONSE_JSON_MALFORMED', + _msg: { zhCN: '文件上传失败。请稍后再试,或向客服投诉。', enUS: 'File upload failed. Please try again later, or report to customer service.' }, + } } } @@ -384,7 +417,11 @@ module.exports = { // 后台送来的 baseUrl 在开发环境下,不一定符合前端实际,因为后台只知道预设的 servUrl 例如 https://pexserver.test.tic.cc:7739/... ,而开发环境下实际上是 http://localhost:7739/... 所以再设置一个 fileUrl 来根据 location.origin 调整。// todo: 改名叫 clientUrl 或 userUrl 或 baseUrl4Client,与 baseUrl 对应 return { _state: 'SUCCESS', fileUrl: this.make_server_url(data.path), ...data } // { path, destination, filename, fileUrl, cid?, ipfsUrl?, baseUrl?, ...file } 注意,data.path 不包含起头的 '/' } else { - return { _state: 'BER_FAIL_UPLOAD_FILE', _msg: { zhCN: '文件上传失败。请稍后再试,或向客服投诉。', enUS: 'File upload failed. Please try again later, or report to customer service.' }, error: errorUpload } + return { + _state: 'BER_FAIL_UPLOAD_FILE', + _msg: { zhCN: '文件上传失败。请稍后再试,或向客服投诉。', enUS: 'File upload failed. Please try again later, or report to customer service.' }, + error: errorUpload, + } } }, @@ -398,7 +435,10 @@ module.exports = { if (mediaType === 'image') { let [errorChoose, { tempFilePaths, tempFiles } = {}] = await uni.chooseImage({ count, sizeType, sourceType }) if (errorChoose) { - return { _state: 'CER_FAIL_CHOOSE', _msg: { zhCN: '图像选择失败。请稍后再试,或向客服投诉。', enUS: 'Image choose failed. Please try again later, or report to customer service.' } } + return { + _state: 'CER_FAIL_CHOOSE', + _msg: { zhCN: '图像选择失败。请稍后再试,或向客服投诉。', enUS: 'Image choose failed. Please try again later, or report to customer service.' }, + } } fileSize = tempFiles?.[0]?.size filePicked = tempFiles?.[0] @@ -416,7 +456,10 @@ module.exports = { } else if (mediaType === 'video') { let [errorChoose, { tempFilePath, tempFile, duration, size, width, height, name }] = await uni.chooseVideo({ sourceType, maxDuration }) if (errorChoose) { - return { _state: 'CER_FAIL_CHOOSE', _msg: { zhCN: '视频选择失败。请稍后再试,或向客服投诉。', enUS: 'Video choose failed. Please try again later, or report to customer service.' } } + return { + _state: 'CER_FAIL_CHOOSE', + _msg: { zhCN: '视频选择失败。请稍后再试,或向客服投诉。', enUS: 'Video choose failed. Please try again later, or report to customer service.' }, + } } fileSize = size filePicked = tempFile @@ -443,7 +486,10 @@ module.exports = { // onUploadProgress: ({ index, loaded, total, tempFilePath, tempFile }) => { } }) if (errMsg !== 'chooseAndUploadFile:ok') { - return { _state: 'CER_FAIL_CHOOSE', _msg: { zhCN: '文件选择失败。请稍后再试,或向客服投诉。', enUS: 'File choose failed. Please try again later, or report to customer service.' } } + return { + _state: 'CER_FAIL_CHOOSE', + _msg: { zhCN: '文件选择失败。请稍后再试,或向客服投诉。', enUS: 'File choose failed. Please try again later, or report to customer service.' }, + } } fileSize = tempFiles?.[0]?.size filePicked = tempFiles?.[0] @@ -457,7 +503,10 @@ module.exports = { return { _state: 'CER_EMPTY_FILE', _msg: { zhCN: '文件为空,无法上传。', enUS: 'Empty files cannot be uploaded.' } } } else if (fileSize > (globalThis.wo?.envar?.fileSizeLimit || 10485760)) { let sizeLimitMB = parseInt((globalThis.wo?.envar?.fileSizeLimit || 10485760) / 1048576) + 'MB' - return { _state: 'CER_FILE_TOO_LARGE', _msg: { zhCN: `文件大于 ${sizeLimitMB} MB,无法上传`, enUS: `The file exceeds ${sizeLimitMB} MB and cannot be uploaded` } } + return { + _state: 'CER_FILE_TOO_LARGE', + _msg: { zhCN: `文件大于 ${sizeLimitMB} MB,无法上传`, enUS: `The file exceeds ${sizeLimitMB} MB and cannot be uploaded` }, + } } const fileName = filePicked?.name || filePath?.split?.('/')?.pop?.() // filePicked.name is available in WEB only. on the other hand, filePath 在 WEB 上并不是文件路径名,而是类似 "blob:http://localhost:8080/f0d3e54d-0694-4803-8097-641d76a10b0d“。在 iOS 上是 "_doc/uniapp_temp_1598593902955/compressed/1598593925815.png", 有时还包含从 file:/// 开始的完整路径名。 @@ -466,18 +515,24 @@ module.exports = { if ( // #ifndef APP // 20240830 luk: 在 App 上,就相信 iOS/Android,不检查文件后缀名。 - mediaType === 'image' && !my.isImageFile(fileExt) || mediaType === 'video' && !my.isVideoFile(fileExt) || + (mediaType === 'image' && !my.isImageFile(fileExt)) || + (mediaType === 'video' && !my.isVideoFile(fileExt)) || // #endif - Array.isArray(mediaType) && !mediaType?.includes?.('.' + fileExt)) { + (Array.isArray(mediaType) && !mediaType?.includes?.('.' + fileExt)) + ) { return { _state: 'UNSUPPORTED_FILETYPE', _msg: { zhCN: '不支持的文件类型:\n' + fileName, enUS: 'Unsupported file type:\n' + fileName } } } - if (mediaType !== 'video' && mediaType !== 'image') { // 这一句应该在上面的 uniCloud.chooseAndUploadFile() 分支里,不过为了合用 fileSize 和 fileExt 的判断,就放在这里。 + if (mediaType !== 'video' && mediaType !== 'image') { + // 这一句应该在上面的 uniCloud.chooseAndUploadFile() 分支里,不过为了合用 fileSize 和 fileExt 的判断,就放在这里。 return { _state: 'SUCCESS', fileUrl: filePicked?.url } } if (!filePath) { - return { _state: 'BER_FAIL_CHOOSE_FILE', _msg: { zhCN: '文件上传失败。请稍后再试,或向客服投诉。', enUS: 'File upload failed. Please try again later, or report to customer service.' } } + return { + _state: 'BER_FAIL_CHOOSE_FILE', + _msg: { zhCN: '文件上传失败。请稍后再试,或向客服投诉。', enUS: 'File upload failed. Please try again later, or report to customer service.' }, + } } this.showLoading() @@ -494,7 +549,10 @@ module.exports = { if (fileID) { return { _state: 'SUCCESS', fileUrl: fileID, requestId } } else { - return { _state: 'BER_FAIL_UPLOAD_FILE', _msg: { zhCN: '文件上传失败。请稍后再试,或向客服投诉。', enUS: 'File upload failed. Please try again later, or report to customer service.' } } + return { + _state: 'BER_FAIL_UPLOAD_FILE', + _msg: { zhCN: '文件上传失败。请稍后再试,或向客服投诉。', enUS: 'File upload failed. Please try again later, or report to customer service.' }, + } } }, @@ -565,16 +623,16 @@ module.exports = { return /msie/.test(userAgent) && !/opera/.test(userAgent) ? 'msie' : /opera/.test(userAgent) - ? 'opera' - : /version.*safari/.test(userAgent) - ? 'safari' - : /chrome/.test(userAgent) - ? 'chrome' - : /gecko/.test(userAgent) && !/webkit/.test(userAgent) - ? 'firefox' - : /micromessenger/.test(userAgent) - ? 'wechat' - : 'unknown' // 只要在 H5, 即使不认识也要返回一个名称。 + ? 'opera' + : /version.*safari/.test(userAgent) + ? 'safari' + : /chrome/.test(userAgent) + ? 'chrome' + : /gecko/.test(userAgent) && !/webkit/.test(userAgent) + ? 'firefox' + : /micromessenger/.test(userAgent) + ? 'wechat' + : 'unknown' // 只要在 H5, 即使不认识也要返回一个名称。 // #endif return '' // 如果不在 H5。 }, @@ -622,7 +680,8 @@ module.exports = { showModal (option = {}) { option.title = this.localizeText(option.title) - option.content = (uni.getSystemInfoSync().uniPlatform === 'app' ? '\n' : '') + this.localizeText(option.content)?.substring?.(0, option.contentLength || 300) + option.content = + (uni.getSystemInfoSync().uniPlatform === 'app' ? '\n' : '') + this.localizeText(option.content)?.substring?.(0, option.contentLength || 300) if (option.content) option.content += '\n\n' option.cancelText = this.localizeText(option.cancelText || { zhCN: '取消', enUS: 'Cancel' }) option.confirmText = this.localizeText(option.confirmText || { zhCN: '好的', enUS: 'OK' }) @@ -670,11 +729,13 @@ module.exports = { }, formatDate (date, format) { - if (typeof date === 'string' && date) { // new Date('') ==> Invalid Date + if (typeof date === 'string' && date) { + // new Date('') ==> Invalid Date if (/^\d\d\d\d-\d\d-\d\d \d\d:\d\d:\d\d\.\d\d\d$/.test(date)) { // 这是从 typeorm 数据库得到的Date类型的值 date = date.replace(/-/g, '/') // safari 不支持 yyyy-mm-dd,必须改成 yyyy/mm/dd - } else if (/^\d{13}$/.test(date)) { // new Date('1702179364450') ==> Invalid Date,所以要先转成纯数字 + } else if (/^\d{13}$/.test(date)) { + // new Date('1702179364450') ==> Invalid Date,所以要先转成纯数字 date = parseInt(date) } else if (/^\d{10}$/.test(date)) { date = parseInt(date) * 1000 @@ -738,7 +799,7 @@ module.exports = { (res) => { pc.setLocalDescription(res) }, - () => { } + () => {} ) //延迟,让一切都能完成 setTimeout(() => { @@ -769,7 +830,8 @@ module.exports = { next_focus (currentFocus, focusList) { focusList = focusList || getCurrentPages()?.pop()?.focusList if (focusList) { - for (let n in focusList) { // 不论对数组或对象都有效,n 是数组的index 或对象的key + for (let n in focusList) { + // 不论对数组或对象都有效,n 是数组的index 或对象的key focusList[n] = false } setTimeout(() => {